summaryrefslogtreecommitdiff
path: root/src/kare.c
diff options
context:
space:
mode:
authorCharlie Root <root@dangofactory.local>2026-10-25 10:15:31 +0900
committerCharlie Root <root@dangofactory.local>2026-10-25 10:15:31 +0900
commit7318435b737394904bb1c5ce9fe013b0eee1882f (patch)
tree41adf14909f5f8d15c8e1c5db361e6ea0ac97598 /src/kare.c
downloadmpegcap-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/kare.c')
-rw-r--r--src/kare.c5340
1 files changed, 5340 insertions, 0 deletions
diff --git a/src/kare.c b/src/kare.c
new file mode 100644
index 0000000..f505873
--- /dev/null
+++ b/src/kare.c
@@ -0,0 +1,5340 @@
+/*
+ * main.c - kare command line capture tool
+ *
+ * Cross-platform (Linux / Windows / FreeBSD / macOS) capture program for
+ * CX23416 + EZ-USB FX2 based USB2 MPEG capture modules.
+ *
+ * Output is an MPEG-2 program stream, directly playable in VLC
+ * (and any other MPEG-2 capable player) on Windows, Linux and macOS.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <math.h>
+#include <string.h>
+#include <signal.h>
+#include <time.h>
+
+#if defined(_WIN32)
+#include <windows.h>
+#include <io.h>
+#include <fcntl.h>
+#define strcasecmp _stricmp
+#else
+#include <pthread.h>
+#include <unistd.h>
+#include <fcntl.h> /* F_SETFL / O_NONBLOCK for the PCM pipe */
+#include <pwd.h>
+#include <grp.h>
+#include <sys/types.h>
+#endif
+
+#include "pvrusb2.h"
+#include "capture.h"
+#include "hm12.h"
+
+#if !defined(_WIN32)
+static double now_sec(void)
+{
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return (double)ts.tv_sec + (double)ts.tv_nsec / 1e9;
+}
+#endif
+
+extern int vsync_lines; /* encoder frame-buffer depth (encoder.c) */
+
+static FILE *out_fp = NULL;
+static unsigned long long total_bytes = 0;
+static pvr2_capture_t *g_cap = NULL;
+static volatile int g_stop = 0;
+static int mpeg_synced = 0; /* seen the first 00 00 01 ba pack header */
+
+/* Raw (HM12) mode: accumulate incoming bytes into whole frames, convert
+ * to I420 and write a YUV4MPEG2 (.y4m) stream. */
+/* -P [user] : run the player as another user, feeding it a real pipe. */
+static const char *player_user = NULL;
+static int auto_player = 0; /* -W: actually start the player */
+#if !defined(_WIN32)
+
+/* Drop privileges to `name` in the forked child. */
+static int setuid_name(const char *name)
+{
+ struct passwd *pw = getpwnam(name);
+ if (!pw)
+ return -1;
+ if (setgid(pw->pw_gid) < 0)
+ return -1;
+ if (initgroups(name, pw->pw_gid) < 0)
+ return -1;
+ if (setuid(pw->pw_uid) < 0)
+ return -1;
+ return 0;
+}
+#endif
+
+static int raw_mode = 0;
+/* ==================================================================
+ * ★ CTLFILE - live parameter control (2026-10-16).
+ *
+ * The user asked to be able to TWEAK the NEC/decoder parameters while the
+ * picture runs, without recompiling or replugging ("パラメーターがいじれるように
+ * mpegviewで"). kare owns the device, so the control point is here:
+ * CTLFILE=<path> names a text file that mpegview appends one command per
+ * line to (its keyboard front-end). Every new line is executed against the
+ * live device and echoed with the resulting state.
+ *
+ * Commands (all printed with what they did):
+ * W <dev> <reg> <val> 1-byte-register I2C write (0x12/0x5c/0x5b/0x1a)
+ * W44 <reg16> <val> CX25837 (0x44) register write
+ * R <dev> <reg> read one byte and print (0x12 -> RD00 status)
+ * YC <lc> <lg> <cc> <cg> uPD64084GC coring/gain: reg 0x04 = lc<<4|lg,
+ * reg 0x05 = cc<<4|cg (coring = the noise
+ * reduction; 0 = bypass, yacxm's YC_LCORE..)
+ * YC0 coring BYPASS preset (cores 0, vendor gains)
+ * YCV <vg> <vc> reg 0x0a = vg<<5|vc (vertical gain/convergence)
+ * GR <0|1|2> uPD64031A reg 0x00 GRMD: 0=ON 1=OFF 2=THROUGH
+ * (+ the CH strobe that starts/stops the op)
+ * IN <hex103> CX25837 0x103 (input mux)
+ * MODE <hex401> 0x401 INPUT_MODE (00 composite/01 Y-C/11 YPbPr)
+ * Q stop the capture
+ * Unknown commands are reported, never silently ignored.
+ * ================================================================== */
+static FILE *ctl_fp = NULL; /* stdio only: portable to Windows/Linux */
+static off_t ctl_pos = 0;
+static char ctl_line[256];
+static size_t ctl_len = 0;
+static int ctl_rd00 = -1; /* last RD00 read from 0x12 */
+static int ctl_argn = 0; /* YC argument counter */
+/* shadow of the parameters we set, so SHOW can print the live state:
+ * [0..3] = 0x12 regs 00,02,08,09 [4..11] = 0x5c regs 00,02,04,05,06,0a,0b,15 */
+/* ---- unknown-register identification sweep -------------------------------
+ * The vendor app's 64084 parameters that we have NOT mapped yet
+ * (ノイズ除去レベル, 動き検出, 空間軸/時間軸ノイズ除去) live in registers we
+ * cannot name from the datasheet (there is no uPD64084 datasheet) or from
+ * yacxm (which only documents 04/05/0a). The honest way to find them is to
+ * walk a register and watch the picture: SWEEP <dev> <reg> [from to step ms].
+ * Non-blocking: one step per data callback, so the stream keeps running.
+ * ------------------------------------------------------------------------*/
+static int sw_active = 0, sw_dev = 0x5c, sw_reg = 0;
+static int sw_val = 0, sw_to = 0xff, sw_step = 1, sw_ms = 150, sw_base = 0;
+static uint64_t sw_last = 0;
+static uint8_t ctl_shadow[12] = { 0x00, 0x58, 0xef, 0x7f,
+ 0x1d, 0x80, 0x29, 0x36,
+ 0x11, 0x43, 0x39, 0xe0 };
+static pvr2_dev *g_dev; /* device handle for ctl_poll() */
+
+static const char *ctl_path = NULL;
+
+static void ctl_open(void)
+{
+ ctl_path = getenv("CTLFILE");
+ if (!ctl_path)
+ return;
+ /* stdio, not open()/read(): the same code then builds on Windows
+ * (MinGW/MSVC) and Linux as well as FreeBSD. */
+ ctl_fp = fopen(ctl_path, "rb");
+ if (!ctl_fp) {
+ fprintf(stderr, "CTLFILE: cannot open %s\n", ctl_path);
+ return;
+ }
+ fseek(ctl_fp, 0, SEEK_END); /* ignore pre-existing lines */
+ fprintf(stderr, "CTLFILE: live control on %s (append commands)\n",
+ ctl_path);
+}
+
+/* forward: the split-PCM low-pass lives further down, but the live control
+ * command "LP" (ctl_do) has to be able to retune it mid-capture. */
+static int pcm_lp_on;
+static double g_pcm_din;
+static void pcm_lp_init(double fs, double fc);
+static void pcm_notch_init(double fs, double f0, double bw);
+static int pcm_notch_n;
+static int pcm_notch_on;
+static void pcm_pad_set(double db);
+
+static void ctl_do(char *s)
+{
+ char *c = strtok(s, " \t\r\n");
+ if (!c)
+ return;
+
+ if (!strcmp(c, "W") || !strcmp(c, "W44") || !strcmp(c, "R")) {
+ char *a = strtok(NULL, " \t\r\n"), *b = strtok(NULL, " \t\r\n");
+ int dev, reg, val = 0;
+ if (!a || !b) { fprintf(stderr, "CTL: %s needs 2 args\n", c); return; }
+ dev = (int)strtol(a, NULL, 0);
+ reg = (int)strtol(b, NULL, 0);
+ if (c[0] == 'R') {
+ uint8_t v = 0;
+ int rc = pvr2_i2c_read(g_dev, (uint8_t)dev,
+ (uint16_t)reg, &v, 1);
+ if (dev == 0x12 && rc == 0) {
+ ctl_rd00 = v;
+ fprintf(stderr, "CTL R 0x%02x 0x%04x = 0x%02x "
+ "[KILF=%d HNC=%d GCON=%d GCR=%d "
+ "DVG=%d INTM=%d]\n", dev, reg, v,
+ (v>>7)&1, (v>>6)&1, (v>>5)&1,
+ (v>>4)&1, (v>>3)&1, v&7);
+ } else {
+ fprintf(stderr, "CTL R 0x%02x 0x%04x = %s0x%02x\n",
+ dev, reg, rc < 0 ? "NACK " : "", v);
+ }
+ return;
+ }
+ { char *d = strtok(NULL, " \t\r\n");
+ if (!d) { fprintf(stderr, "CTL: %s needs 3 args\n", c); return; }
+ val = (int)strtol(d, NULL, 0); }
+ if (c[1] == '4') { /* W44: 16-bit register + data byte */
+ uint8_t v = (uint8_t)val;
+ int rc = pvr2_i2c_write(g_dev, (uint8_t)dev,
+ (uint16_t)reg, &v, 1);
+ fprintf(stderr, "CTL W44 0x%04x = 0x%02x -> %s\n",
+ reg, v, rc < 0 ? "NACK" : "ok");
+ } else {
+ uint16_t w = (uint16_t)((reg << 8) | (val & 0xff));
+ int rc;
+ if (dev == 0x12 && (reg == 0x00 || reg == 0x02 || reg == 0x08 ||
+ reg == 0x09))
+ ctl_shadow[(reg == 0x00) ? 0 : (reg == 0x02) ? 1
+ : (reg == 0x08) ? 2 : 3] = (uint8_t)val;
+ if (dev == 0x5c)
+ ctl_shadow[(reg == 0x00) ? 4 : (reg == 0x02) ? 5
+ : (reg == 0x04) ? 6 : (reg == 0x05) ? 7
+ : (reg == 0x06) ? 8 : (reg == 0x0a) ? 9
+ : (reg == 0x0b) ? 10
+ : (reg == 0x15) ? 11 : 4] = (uint8_t)val;
+ rc = pvr2_i2c_write(g_dev, (uint8_t)dev, w, NULL, 0);
+ fprintf(stderr, "CTL W 0x%02x 0x%02x = 0x%02x -> %s\n",
+ dev, reg, val & 0xff, rc < 0 ? "NACK" : "ok");
+ }
+ return;
+ }
+ /*
+ * ★ "WM" - re-send the WM8739 bring-up sequence DURING a capture.
+ *
+ * The raw audio degrades between runs (10-15 kHz loses ~13 dB, a USB
+ * port reset restores it) and every readable register is identical in
+ * both states, so the suspect is the WM8739's internal state - which is
+ * write-only and therefore can only be tested by writing it again.
+ * These are the exact values this tool already sends at startup, so
+ * re-sending them is a no-op if the part is fine:
+ * echo WM >> /tmp/kare-<uid>.ctl
+ * Measured: see the notes (state flips / does not flip).
+ */
+ if (!strcmp(c, "WM")) {
+ static const struct { uint8_t r, v; } seq[] = {
+ { 15, 0x00 }, { 0, 0x17 }, { 1, 0x17 }, { 5, 0x00 },
+ { 6, 0x5a }, { 7, 0x49 }, { 8, 0x02 }, { 9, 0x01 },
+ };
+ size_t k;
+ fprintf(stderr, "CTL WM: re-sending WM8739 bring-up\n");
+ for (k = 0; k < sizeof(seq) / sizeof(seq[0]); k++) {
+ int rc = pvr2_wm873x_write(g_dev, 0x1a, seq[k].r,
+ seq[k].v);
+ fprintf(stderr, " R%u = 0x%02x -> %s\n", seq[k].r,
+ seq[k].v, rc < 0 ? "NACK" : "ACK");
+ }
+ return;
+ }
+ /*
+ * ★ "ARESET" - re-send CX2341X_ENC_MISC 12 (reset audio interface)
+ * DURING a capture, and "MR <addr>" to watch the audio DSP state.
+ *
+ * MISC(12) is documented as "reset audio interface after channel change
+ * or input switch" and this tool already sends it once at init, so
+ * re-sending it is the low-risk way to test whether the degraded audio
+ * state is the audio interface needing that reset after the mux and
+ * clock have settled:
+ * echo ARESET >> /tmp/kare-<uid>.ctl
+ *
+ * MR reads one CX23416 memory word - 0xa058 is the word that differs
+ * between the good and the bad state (high half 0x00da in the bad one).
+ */
+ if (!strcmp(c, "ARESET")) {
+ uint32_t p4[4];
+ p4[0] = 12; p4[1] = 0; p4[2] = 0; p4[3] = 0;
+ {
+ int rc = pvr2_enc_cmd(g_dev, CX2341X_ENC_MISC, p4, 4);
+ fprintf(stderr, "CTL ARESET: MISC(12) -> %s\n",
+ rc < 0 ? "failed" : "ok");
+ }
+ return;
+ }
+ if (!strcmp(c, "MR")) {
+ char *a = strtok(NULL, " \r\n");
+ uint32_t addr, v = 0;
+ if (!a) { fprintf(stderr, "CTL: MR needs an address\n"); return; }
+ addr = (uint32_t)strtoul(a, NULL, 0);
+ /*
+ * pvr2_read_reg, NOT pvr2_mbox_read: they address DIFFERENT
+ * spaces. The APU/AO blocks (0xa000, 0x2d00) are only visible
+ * through the register command; a MBOX read of 0xa058 returns
+ * 0xe8000611, which is unrelated to the value REGDUMP reports
+ * (0x00dae11a). Measured, so this cannot mislead later.
+ */
+ if (pvr2_read_reg(g_dev, (uint16_t)addr, &v) == 0)
+ fprintf(stderr, "CTL MR 0x%04x = 0x%08x\n", addr, v);
+ else
+ fprintf(stderr, "CTL MR 0x%04x = read failed\n", addr);
+ return;
+ }
+ /*
+ * PCMDUMP=<prefix>: write the pre-filter and post-filter samples of the
+ * first 2 s to <prefix>.pre / <prefix>.post (16-bit LE mono-interleaved
+ * exactly as the filter sees them). This is the only way to compare the
+ * filter's effect on IDENTICAL data - the source changes between
+ * captures, so two separate runs cannot be compared.
+ */
+ if (!strcmp(c, "LP")) {
+ /*
+ * "LP <hz|0>" - change the split-PCM low-pass DURING a capture.
+ * This is the only honest way to A/B the filter: the source
+ * keeps changing, so two separate captures cannot be compared
+ * (measuring 1-3 kHz rise by 2 dB between "filter on" and
+ * "filter off" captures proved the point - a low-pass cannot
+ * add energy).
+ */
+ char *a = strtok(NULL, " \r\n");
+ double hz = a ? atof(a) : 10000.0;
+ if (hz <= 0.0) {
+ pcm_lp_on = 0;
+ fprintf(stderr, "CTL LP: low-pass OFF\n");
+ } else {
+ pcm_lp_init(48000.0, hz);
+ fprintf(stderr, "CTL LP: low-pass on at %.0f Hz\n", hz);
+ }
+ return;
+ }
+ /*
+ * "PAD <db>" and "NTCH <hz>|0" - live audio knobs for the spoon bar.
+ * "LP <hz>|0" already exists just above. All three act on the split
+ * PCM in this process, so the viewer can change them without restarting
+ * the capture.
+ */
+ if (!strcmp(c, "PAD")) {
+ char *a = strtok(NULL, " \t\r\n");
+ pcm_pad_set(a ? atof(a) : 0.0);
+ return;
+ }
+ if (!strcmp(c, "NTCH")) {
+ char *a = strtok(NULL, " \t\r\n");
+ double hz = a ? atof(a) : 0.0;
+ pcm_notch_n = 0;
+ pcm_notch_on = 0;
+ if (hz > 0.0) {
+ pcm_notch_init(48000.0, hz, 8.0);
+ fprintf(stderr, "CTL NTCH: %.0f Hz\n", hz);
+ } else {
+ fprintf(stderr, "CTL NTCH: off\n");
+ }
+ return;
+ }
+ if (!strcmp(c, "YC") || !strcmp(c, "YC0")) {
+ unsigned lc = 2, lg = 9, cc = 3, cg = 6, vg = 2, vc = 3;
+ char *a;
+ if (c[2] == '0') { lc = 0; cc = 0; } /* coring bypass */
+ while ((a = strtok(NULL, " \t\r\n")) != NULL) {
+ unsigned *t = NULL;
+ switch (ctl_argn++) {
+ case 0: t = &lc; break; case 1: t = &lg; break;
+ case 2: t = &cc; break; case 3: t = &cg; break;
+ case 4: t = &vg; break; case 5: t = &vc; break;
+ }
+ if (!t) break;
+ *t = (unsigned)strtoul(a, NULL, 0);
+ }
+ ctl_argn = 0;
+ {
+ unsigned r4 = ((lc & 0xf) << 4) | (lg & 0xf);
+ unsigned r5 = ((cc & 0xf) << 4) | (cg & 0xf);
+ unsigned ra = ((vg & 0x7) << 5) | (vc & 0x1f);
+ pvr2_i2c_write(g_dev, 0x5c, (uint16_t)((0x04 << 8) | r4), NULL, 0);
+ pvr2_i2c_write(g_dev, 0x5c, (uint16_t)((0x05 << 8) | r5), NULL, 0);
+ pvr2_i2c_write(g_dev, 0x5c, (uint16_t)((0x0a << 8) | ra), NULL, 0);
+ ctl_shadow[6] = (uint8_t)r4; ctl_shadow[7] = (uint8_t)r5;
+ ctl_shadow[9] = (uint8_t)ra;
+ fprintf(stderr, "CTL %s: 0x5c 04=0x%02x 05=0x%02x 0a=0x%02x "
+ "(luma core=%u gain=%u, chroma core=%u gain=%u%s)\n",
+ c, r4, r5, ra, lc, lg, cc, cg,
+ (lc == 0 && cc == 0) ? " <- coring BYPASS" : "");
+ }
+ return;
+ }
+ if (!strcmp(c, "YCV")) {
+ char *a = strtok(NULL, " \t\r\n"), *b = strtok(NULL, " \t\r\n");
+ unsigned vg = a ? (unsigned)strtoul(a, NULL, 0) : 2;
+ unsigned vc = b ? (unsigned)strtoul(b, NULL, 0) : 3;
+ unsigned ra = ((vg & 7) << 5) | (vc & 0x1f);
+ pvr2_i2c_write(g_dev, 0x5c, (uint16_t)((0x0a << 8) | ra), NULL, 0);
+ fprintf(stderr, "CTL YCV: 0x5c 0a=0x%02x (vgain=%u vcnvg=%u)\n",
+ ra, vg, vc);
+ return;
+ }
+ if (!strcmp(c, "GR")) {
+ char *a = strtok(NULL, " \t\r\n");
+ unsigned m = a ? (unsigned)strtoul(a, NULL, 0) : 0;
+ /* GRMD = bits 7:6: 00 ON, 01 OFF, 1x THROUGH (datasheet table 2-3;
+ * ON also needs the GRSW pin low). The CH strobe (bit 4) is what
+ * actually starts/stops the operation (datasheet 2.4). */
+ unsigned v = (m == 2) ? 0x80 : (m == 1) ? 0x40 : 0x00;
+ pvr2_i2c_write(g_dev, 0x12, (uint16_t)((0x00 << 8) | v), NULL, 0);
+ pvr2_i2c_write(g_dev, 0x12, 0x0010, NULL, 0);
+ pvr2_i2c_write(g_dev, 0x12, 0x0000, NULL, 0);
+ fprintf(stderr, "CTL GR: 0x12 00=0x%02x + CH strobe (%s)\n", v,
+ m == 2 ? "THROUGH" : m == 1 ? "OFF" : "ON (needs GRSW low)");
+ return;
+ }
+ if (!strcmp(c, "IN") || !strcmp(c, "MODE")) {
+ char *a = strtok(NULL, " \t\r\n");
+ unsigned v = a ? (unsigned)strtoul(a, NULL, 0) : 0;
+ uint16_t reg = (c[0] == 'I') ? 0x0103 : 0x0401;
+ uint8_t b = (uint8_t)v;
+ pvr2_i2c_write(g_dev, CX2584X_I2C_ADDR, reg, &b, 1);
+ fprintf(stderr, "CTL %s: 0x%04x = 0x%02x\n", c, reg, v & 0xff);
+ return;
+ }
+ if (!strcmp(c, "PRE")) {
+ /*
+ * 64031A 前ゴースト処理範囲 (datasheet SA02h D4 = PREGHSTS):
+ * 0 = -1.0 us, 1 = -2.6 us (standard 1).
+ * The datasheet requires a CHANNEL CHANGE (or CPU reset) after
+ * changing it -- "この設定はデータ変更後,チャネル変更または CPU
+ * リセットを…" -- so the CH strobe follows.
+ * The app's 映像入力設定 tab has exactly this pair
+ * (前ゴースト処理範囲: -1usまで / -2.6usまで).
+ */
+ char *a = strtok(NULL, " \t\r\n");
+ unsigned v = a ? (unsigned)strtoul(a, NULL, 0) : 1;
+ uint8_t cur = 0x58;
+ unsigned r2;
+ (void)pvr2_i2c_read(g_dev, 0x12, 0x0002, &cur, 1); /* RD00-ish
+ path is meaningless here; keep the vendor
+ value as the base */
+ cur = 0x58;
+ r2 = (cur & (uint8_t)~0x10) | ((v & 1) << 4)
+ | (v ? 0 : 0); /* D4 = PREGHSTS */
+ pvr2_i2c_write(g_dev, 0x12, (uint16_t)((0x02 << 8) | r2), NULL, 0);
+ pvr2_i2c_write(g_dev, 0x12, 0x0010, NULL, 0); /* channel change */
+ pvr2_i2c_write(g_dev, 0x12, 0x0000, NULL, 0);
+ fprintf(stderr, "CTL PRE: 0x12 02=0x%02x (前ゴースト処理範囲 %s) "
+ "+ CH strobe\n", r2, v ? "-2.6usまで" : "-1.0usまで");
+ return;
+ }
+ if (!strcmp(c, "YCMODE")) {
+ /*
+ * 64084 動作モード. The app's 映像入力設定 tab offers exactly
+ * two: 3次元Y/C分離 / 2次元Y/C分離+ノイズ除去. The pcap
+ * writes 0x5c reg0x00 = 0x1d in 4 sessions and 0x5d in 2 --
+ * a single bit (0x40) apart, i.e. that bit IS the 2D/3D (plus
+ * noise-removal) selection. YCMODE 0 = 0x1d (3D, vendor
+ * default), 1 = 0x5d (2D Y/C + noise removal).
+ */
+ char *a = strtok(NULL, " \t\r\n");
+ unsigned v = a ? (unsigned)strtoul(a, NULL, 0) : 0;
+ unsigned r0 = v ? 0x5d : 0x1d;
+ pvr2_i2c_write(g_dev, 0x5c, (uint16_t)((0x00 << 8) | r0), NULL, 0);
+ fprintf(stderr, "CTL YCMODE: 0x5c 00=0x%02x (%s)\n", r0,
+ v ? "2D Y/C + noise removal" : "3D Y/C separation");
+ return;
+ }
+ if (!strcmp(c, "SHOW")) {
+ fprintf(stderr,
+ "CTL SHOW: 64031A(0x12) 00(GRMD)=%02x 02(PREGHSTS/others)=%02x "
+ "08(DIR3DYC/DCPAG)=%02x 09(DCPEN)=%02x\n",
+ ctl_shadow[0], ctl_shadow[1], ctl_shadow[2], ctl_shadow[3]);
+ fprintf(stderr,
+ "CTL SHOW: 64084(0x5c) 00(mode)=%02x 02=%02x 04(lcore/gain)=%02x "
+ "05(ccore/gain)=%02x 06=%02x 0a(vgain/cnvg)=%02x 0b=%02x 15=%02x\n",
+ ctl_shadow[4], ctl_shadow[5], ctl_shadow[6], ctl_shadow[7],
+ ctl_shadow[8], ctl_shadow[9], ctl_shadow[10],
+ ctl_shadow[11]);
+ return;
+ }
+ if (!strcmp(c, "SWEEP")) {
+ char *a = strtok(NULL, " \t\r\n");
+ char *b = strtok(NULL, " \t\r\n");
+ if (!a || !b) {
+ fprintf(stderr, "CTL: SWEEP <dev> <reg> [from to step ms]\n");
+ return;
+ }
+ sw_dev = (int)strtol(a, NULL, 0);
+ sw_reg = (int)strtol(b, NULL, 0);
+ {
+ char *v;
+ v = strtok(NULL, " \t\r\n"); if (v) sw_val = (int)strtol(v, NULL, 0);
+ v = strtok(NULL, " \t\r\n"); if (v) sw_to = (int)strtol(v, NULL, 0);
+ v = strtok(NULL, " \t\r\n"); if (v) sw_step = (int)strtol(v, NULL, 0);
+ v = strtok(NULL, " \t\r\n"); if (v) sw_ms = (int)strtol(v, NULL, 0);
+ }
+ if (sw_step <= 0) sw_step = 1;
+ if (sw_ms < 20) sw_ms = 20;
+ sw_base = sw_val;
+ sw_active = 1;
+ sw_last = 0;
+ fprintf(stderr, "CTL SWEEP: dev=0x%02x reg=0x%02x %02x..%02x step %d "
+ "every %d ms -- WATCH THE PICTURE (SWEEPSTOP to end)\n",
+ sw_dev, sw_reg, sw_val, sw_to, sw_step, sw_ms);
+ return;
+ }
+ if (!strcmp(c, "SWEEPSTOP")) {
+ sw_active = 0;
+ /* put the register back to the value it had before the sweep */
+ pvr2_i2c_write(g_dev, (uint8_t)sw_dev,
+ (uint16_t)((sw_reg << 8) | sw_base), NULL, 0);
+ fprintf(stderr, "CTL SWEEPSTOP: dev=0x%02x reg=0x%02x restored to 0x%02x\n",
+ sw_dev, sw_reg, sw_base);
+ return;
+ }
+ if (!strcmp(c, "SWEEPALL")) {
+ /* walk every register of the uPD64084GC once, 8 values each */
+ sw_dev = 0x5c; sw_reg = 0; sw_val = 0; sw_to = 0x17; sw_step = 0;
+ sw_ms = 800; sw_active = 2; /* 2 = register index walk */
+ fprintf(stderr, "CTL SWEEPALL: 0x5c regs 0x00..0x17 (values 00,55,aa,ff "
+ "each) -- WATCH THE PICTURE\n");
+ return;
+ }
+ if (!strcmp(c, "Q")) {
+ fprintf(stderr, "CTL Q: stopping\n");
+ if (g_cap) pvr2_capture_stop(g_cap);
+ return;
+ }
+ fprintf(stderr, "CTL: unknown command '%s'\n", c);
+}
+
+static unsigned now_ms(void)
+{
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return (unsigned)((ts.tv_sec * 1000u) + (ts.tv_nsec / 1000000u));
+}
+
+static void ctl_sweep_tick(void)
+{
+ static const uint8_t probe4[4] = { 0x00, 0x55, 0xaa, 0xff };
+ unsigned t;
+
+ if (!sw_active || !g_dev)
+ return;
+ t = now_ms();
+ if (sw_last && (t - (unsigned)sw_last) < (unsigned)sw_ms)
+ return;
+ sw_last = t;
+ if (sw_active == 1) {
+ pvr2_i2c_write(g_dev, (uint8_t)sw_dev,
+ (uint16_t)((sw_reg << 8) | (sw_val & 0xff)), NULL, 0);
+ fprintf(stderr, "CTL SWEEP 0x%02x 0x%02x = 0x%02x\n",
+ sw_dev, sw_reg, sw_val & 0xff);
+ sw_val += sw_step;
+ if (sw_val > sw_to) {
+ sw_active = 0;
+ fprintf(stderr, "CTL SWEEP done (register left at 0x%02x)\n",
+ (sw_val - sw_step) & 0xff);
+ }
+ return;
+ }
+ /* SWEEPALL: for each register, write 00/55/aa/ff */
+ if (sw_base >= 4) {
+ sw_base = 0; sw_reg++;
+ if (sw_reg > (int)sw_to) {
+ sw_active = 0;
+ fprintf(stderr, "CTL SWEEPALL done\n");
+ return;
+ }
+ }
+ if (sw_base == 0)
+ fprintf(stderr, "CTL SWEEPALL reg 0x%02x:\n", sw_reg);
+ pvr2_i2c_write(g_dev, 0x5c, (uint16_t)((sw_reg << 8) | probe4[sw_base]),
+ NULL, 0);
+ fprintf(stderr, " CTL SWEEPALL 0x5c %02x = %02x\n", sw_reg,
+ probe4[sw_base]);
+ sw_base++;
+}
+
+static void ctl_poll(void)
+{
+ static char buf[512];
+ size_t n;
+
+ if (!ctl_fp || !g_dev)
+ return;
+ ctl_sweep_tick();
+ n = fread(buf, 1, sizeof(buf), ctl_fp);
+ if (n == 0) {
+ clearerr(ctl_fp); /* the file grows: retry next callback */
+ return;
+ }
+ ctl_pos += (off_t)n;
+ {
+ size_t i;
+ for (i = 0; i < n; i++) {
+ char ch = buf[i];
+ if (ch == '\n' || ctl_len >= sizeof(ctl_line) - 1) {
+ ctl_line[ctl_len] = 0;
+ ctl_argn = 0;
+ if (ctl_len)
+ ctl_do(ctl_line);
+ ctl_len = 0;
+ } else {
+ ctl_line[ctl_len++] = ch;
+ }
+ }
+ }
+}
+
+/* ==================================================================
+ * ★ Audio-only capture: WAV writer (2026-10-16).
+ *
+ * Measured: raw capture with subtype 0x02 (PCM only, captype 1 or 2 --
+ * NOT captype 0, where it really is empty) delivers the encoder's PCM
+ * directly: ~183 KB/s of 16-bit little-endian stereo at 48 kHz, i.e. the
+ * same audio the MPEG path carries inside its MP2 frames, but uncompressed.
+ * (The HM12 32-bit word swap that the VIDEO path needs must NOT be applied
+ * here -- reading it swapped gives an alternating +/-15000 pattern.)
+ *
+ * --pcm FILE write that PCM straight out as a RIFF/WAVE file
+ * PCMRATE=<n> sample rate for the header (default 48000)
+ * PCMCH=<n> channels for the header (default 2)
+ *
+ * The video path is bypassed entirely when --pcm is used, so nothing gets
+ * framed as y4m.
+ * ================================================================== */
+static const char *pcm_path = NULL;
+static FILE *pcm_fp = NULL;
+/*
+ * ★ --pcmfd <n>: write the encoder PCM to an already-open descriptor.
+ * This is how mpegview gets raw YUV *and* PCM at the same time -- the same
+ * split ivtv does by exposing raw YUV on /dev/video32 and PCM on
+ * /dev/video24 while the device streams subtype 0x03. Raw PCM on a pipe:
+ * no WAV header, no seeking (a pipe cannot be patched at the end).
+ */
+static int pcm_fd = -1;
+static int pcm_raw;
+static unsigned long pcm_drops;
+static void pcm_write_rec(const uint8_t *p, size_t n);
+static uint64_t pcm_bytes = 0;
+static unsigned long split_recs = 0;
+static int split_started = 0;
+static uint64_t split_tot = 0, split_last_i = 0;
+static uint64_t sp_abs = 0; /* stream bytes consumed so far */
+static uint64_t sp_last_rec = 0; /* absolute offset of the last record */
+static int sp_have_rec = 0;
+static uint64_t sp_resync_at = 0;
+static uint64_t sp_prev_rec_end = 0;
+ /* first record seen = frame boundary */ /* PCM records split out (SPLITAV) */
+static unsigned pcm_rate = 48000;
+static unsigned pcm_ch = 2;
+
+static void pcm_wr32(uint32_t v)
+{
+ unsigned char b[4];
+ b[0] = v & 0xff; b[1] = (v >> 8) & 0xff;
+ b[2] = (v >> 16) & 0xff; b[3] = (v >> 24) & 0xff;
+ fwrite(b, 1, 4, pcm_fp);
+}
+static void pcm_wr16(uint16_t v)
+{
+ unsigned char b[2];
+ b[0] = v & 0xff; b[1] = (v >> 8) & 0xff;
+ fwrite(b, 1, 2, pcm_fp);
+}
+
+static int pcm_open(const char *path)
+{
+ unsigned rate = pcm_rate, ch = pcm_ch;
+ const char *e;
+
+ if ((e = getenv("PCMRATE")) != NULL) rate = (unsigned)strtoul(e, NULL, 0);
+ if ((e = getenv("PCMCH")) != NULL) ch = (unsigned)strtoul(e, NULL, 0);
+ pcm_rate = rate ? rate : 48000;
+ pcm_ch = ch ? ch : 2;
+ if (pcm_fd >= 0) {
+ pcm_fp = fdopen(pcm_fd, "wb");
+ if (!pcm_fp) {
+ fprintf(stderr, "PCM: cannot fdopen(%d)\n", pcm_fd);
+ return -1;
+ }
+ pcm_raw = 1;
+ fcntl(pcm_fd, F_SETFL, fcntl(pcm_fd, F_GETFL) | O_NONBLOCK);
+ fprintf(stderr, "PCM: fd %d raw (%u Hz, %u ch, s16le, no header)\n",
+ pcm_fd, pcm_rate, pcm_ch);
+ return 0;
+ }
+ pcm_fp = fopen(path, "wb");
+ if (!pcm_fp) {
+ fprintf(stderr, "PCM: cannot open %s\n", path);
+ return -1;
+ }
+ /* RIFF/WAVE header; the two size fields are patched at the end. */
+ fwrite("RIFF", 1, 4, pcm_fp);
+ /*
+ * Placeholder sizes: the file GROWS while it is written, and a WAV
+ * demuxer that sees data size 0 refuses to read anything. A large
+ * placeholder makes it stream instead (the real sizes are patched in
+ * pcm_close()).
+ */
+ pcm_wr32(0x7ffffff0u); /* RIFF size -> patched */
+ fwrite("WAVEfmt ", 1, 8, pcm_fp);
+ pcm_wr32(16);
+ pcm_wr16(1); /* PCM */
+ pcm_wr16((uint16_t)pcm_ch);
+ pcm_wr32(pcm_rate);
+ pcm_wr32(pcm_rate * pcm_ch * 2); /* byte rate */
+ pcm_wr16((uint16_t)(pcm_ch * 2)); /* block align */
+ pcm_wr16(16); /* bits per sample */
+ fwrite("data", 1, 4, pcm_fp);
+ pcm_wr32(0x7ffffff0u); /* data size -> patched */
+ fprintf(stderr, "PCM: %s (%u Hz, %u ch, 16-bit LE)\n", path,
+ pcm_rate, pcm_ch);
+ return 0;
+}
+
+/*
+ * ★ The PCM fd is a pipe shared with the live viewer. If the viewer is busy
+ * (SDL repainting) the pipe fills, and a blocking write would stall the VIDEO
+ * path with it -- measured as mpegview reporting "video=-1" (no frames at all).
+ * So write non-blocking and DROP audio on EAGAIN: the picture must never wait
+ * for the sound.
+ */
+/* PCM record layout (see the SPLITAV section): 12-byte header + payload.
+ * Declared here because pcm_write_split() below sizes its swap buffer with it. */
+#define PCM_REC_PAYLOAD 4608
+#define PCM_REC_HDR 12
+
+static void pcm_write_rec(const uint8_t *p, size_t n)
+{
+ if (!pcm_fp)
+ return;
+ if (pcm_raw) {
+ ssize_t w = write(pcm_fd, p, n);
+ if (w < 0 || (size_t)w != n)
+ pcm_drops++;
+ if (w > 0)
+ pcm_bytes += (uint64_t)w;
+ } else {
+ fwrite(p, 1, n, pcm_fp);
+ pcm_bytes += n;
+ }
+}
+
+/*
+ * ★ 2026-10-23: the SPLIT path's PCM is byte-swapped per 16-bit word.
+ *
+ * Mixed-mode (subtype 0x03) record payloads carry their two bytes the other
+ * way round; written unswapped they are not noise from the input, they are
+ * the programme with the halves of every sample exchanged - the "sandstorm"
+ * when BGM plays. Measured upstream on one 4,608-byte record before this
+ * change: mean |adjacent sample difference| 27,351 (samples like -14595,
+ * 8702, -13827) against 69 once swapped (-570, -479, -567). The audio-only
+ * mode (subtype 0x02) is the OPPOSITE way round and a swap destroys it
+ * (19,139 against 84), so only the split path is converted.
+ *
+ * PCMNOSWAP=1 restores the unswapped bytes for an A/B.
+ */
+/*
+ * ★ PCMLP=<Hz> - low-pass on the split PCM (default 10000, 0 = off).
+ *
+ * The raw path carries roughly 14 dB more energy above 10 kHz than the
+ * encoder's own mp2 of the same programme (measured on this unit: 10-15 kHz
+ * at -20.4 dB relative for the split PCM against -34.2 dB for the mp2, and
+ * the earlier note measured +24 dB at 16-23 kHz). Nothing above the
+ * programme band is wanted there, and on a listening test that extra top end
+ * is what makes the raw audio sound harsh/"crushed" compared with the MPEG
+ * audio. Four cascaded 2nd-order sections = 8th order, which keeps the
+ * audible band flat and drops the junk.
+ *
+ * This is a treatment, not a diagnosis: it hides the junk rather than
+ * explaining it (the source of that band is still open).
+ */
+struct pcm_bq { double b0, b1, b2, a1, a2; };
+/*
+ * ★ One state set PER CHANNEL (2026-10-24).
+ *
+ * The split PCM is interleaved stereo, and the filters used to run over it as
+ * one sample stream: every "60 Hz" notch then landed at 30 Hz per channel and
+ * the two channels shared one filter state, so L and R leaked into each other
+ * and every corner frequency was half of what it claimed. Measured symptom:
+ * a notch at 120 Hz removed the 60 Hz hum while the 15.7 kHz notch did nothing
+ * (it was sitting at 7.9 kHz per channel).
+ */
+static double lp_st[4][2][4]; /* [section][channel][x1,x2,y1,y2] */
+static double nt_st[32][2][4];
+static struct pcm_bq pcm_lp[4];
+
+static void pcm_lp_init(double fs, double fc)
+{
+ int i;
+ if (fc <= 0.0 || fc >= fs / 2.0)
+ return;
+ for (i = 0; i < 4; i++) {
+ /* Butterworth 8th order = 4 sections, Q = 0.5098, 0.6013,
+ * 0.8999, 2.5629 */
+ static const double q[4] = { 0.5098, 0.6013, 0.8999, 2.5629 };
+ double w0 = 2.0 * M_PI * fc / fs;
+ double cw = cos(w0), sw = sin(w0);
+ double alpha = sw / (2.0 * q[i]);
+ double a0 = 1.0 + alpha;
+ pcm_lp[i].b0 = (1.0 - cw) / 2.0 / a0;
+ pcm_lp[i].b1 = (1.0 - cw) / a0;
+ pcm_lp[i].b2 = (1.0 - cw) / 2.0 / a0;
+ pcm_lp[i].a1 = -2.0 * cw / a0;
+ pcm_lp[i].a2 = (1.0 - alpha) / a0;
+ memset(lp_st[i], 0, sizeof(lp_st[i]));
+ }
+ pcm_lp_on = 1;
+ fprintf(stderr, "PCM low-pass: 8th order at %.0f Hz\n", fc);
+}
+
+static FILE *g_dp, *g_dq; /* PCMDUMP .pre / .post */
+
+/*
+ * ★ PCMNOTCH=<hz>[,<hz>...] - narrow notches on the split PCM (default:
+ * 15734 Hz, the NTSC line rate).
+ *
+ * Measured on this unit with the low-pass already at 6 kHz: the raw PCM's
+ * LEFT channel carries a 15,735 Hz component at amplitude 679,000, i.e. LOUDER
+ * than the whole audio band (the 6 kHz band measures 198,000). It is the
+ * video line rate leaking into the audio input, and an 8th-order 6 kHz
+ * low-pass only takes it down by 28 dB (measured), which is why it still
+ * dominates. A notch is the right tool: it removes that one line without
+ * dulling the programme, and the line is at a known, fixed frequency.
+ *
+ * PCMNOTCH=0 disables; PCMNOTCH=<hz> replaces the default.
+ */
+static struct pcm_bq pcm_notch[32];
+static int pcm_notch_n;
+static int pcm_notch_on;
+
+/*
+ * ★ bw is a BANDWIDTH in Hz, not a Q (2026-10-24).
+ *
+ * A fixed Q makes the notch width grow with frequency (BW = f0/Q), so a series
+ * of 60 Hz-spaced notches at Q=3 overlaps completely above ~300 Hz: measured,
+ * 960 Hz fell -50 dB and 1,000 Hz -34.5 dB, i.e. the whole 60-1200 Hz range was
+ * being removed. That is audible as "the sound is cut". A fixed bandwidth
+ * keeps every notch 8 Hz wide whatever its frequency.
+ */
+static void pcm_notch_init(double fs, double f0, double bw)
+{
+ struct pcm_bq *n = &pcm_notch[pcm_notch_n];
+ double w0, cw, sw, alpha, a0, q;
+
+ if (f0 <= 0.0 || f0 >= fs / 2.0 || bw <= 0.0 ||
+ pcm_notch_n >= (int)(sizeof(pcm_notch) / sizeof(pcm_notch[0])))
+ return;
+ q = f0 / bw; /* Q = f0 / bandwidth */
+ w0 = 2.0 * M_PI * f0 / fs;
+ cw = cos(w0);
+ sw = sin(w0);
+ alpha = sw / (2.0 * q);
+ a0 = 1.0 + alpha;
+ n->b0 = 1.0 / a0;
+ n->b1 = -2.0 * cw / a0;
+ n->b2 = 1.0 / a0;
+ n->a1 = -2.0 * cw / a0;
+ n->a2 = (1.0 - alpha) / a0;
+ memset(nt_st[pcm_notch_n], 0, sizeof(nt_st[0]));
+ pcm_notch_n++;
+ pcm_notch_on = 1;
+ fprintf(stderr, "PCM notch: %.0f Hz (%.1f Hz wide, Q=%.0f)\n",
+ f0, bw, q);
+}
+
+/* live-adjustable from the control file (the spoon bar drives these) */
+static double g_pcm_pad = 1.0;
+static int g_pcm_pad_db;
+static int g_pcm_pad_init;
+
+static void pcm_pad_set(double db)
+{
+ g_pcm_pad = pow(10.0, db / 20.0);
+ g_pcm_pad_db = (int)db;
+ if (g_pcm_pad <= 0.0)
+ g_pcm_pad = 1.0;
+ fprintf(stderr, "PCM pad: %d dB (x%.3f)\n", g_pcm_pad_db, g_pcm_pad);
+}
+
+static void pcm_lp_apply(int16_t *p, size_t nfr)
+{
+ size_t k;
+ int s, m, ch;
+ double pad;
+
+ if (!g_pcm_pad_init) {
+ const char *e = getenv("PCMPAD");
+ g_pcm_pad_init = 1;
+ if (e && *e)
+ pcm_pad_set(atof(e));
+ }
+ pad = g_pcm_pad;
+ if (!pcm_lp_on && pad == 1.0 && !pcm_notch_on)
+ return;
+ for (k = 0; k < nfr; k++) {
+ for (ch = 0; ch < 2; ch++) {
+ double v = (double)p[2 * k + ch];
+ if (pad != 1.0)
+ v *= pad;
+ for (s = 0; s < 4 && pcm_lp_on; s++) {
+ struct pcm_bq *q = &pcm_lp[s];
+ double *st = lp_st[s][ch];
+ double y = q->b0 * v + q->b1 * st[0] +
+ q->b2 * st[1] -
+ q->a1 * st[2] - q->a2 * st[3];
+ st[1] = st[0]; st[0] = v;
+ st[3] = st[2]; st[2] = y;
+ v = y;
+ }
+ for (m = 0; m < pcm_notch_n && pcm_notch_on; m++) {
+ struct pcm_bq *q = &pcm_notch[m];
+ double *st = nt_st[m][ch];
+ double y = q->b0 * v + q->b1 * st[0] +
+ q->b2 * st[1] -
+ q->a1 * st[2] - q->a2 * st[3];
+ st[1] = st[0]; st[0] = v;
+ st[3] = st[2]; st[2] = y;
+ v = y;
+ }
+ if (v > 32767.0) v = 32767.0;
+ if (v < -32768.0) v = -32768.0;
+ p[2 * k + ch] = (int16_t)v;
+ }
+ }
+}
+
+static void pcm_write_split(const uint8_t *p, size_t n)
+{
+ static unsigned char sw[PCM_REC_PAYLOAD];
+ static int noswap = -1;
+ static int lp_init;
+ size_t i;
+
+ if (!lp_init) {
+ /*
+ * ★ Default OFF (2026-10-24). The historical measurement
+ * (commit c945409, 2026-10-17) is the reason: a 10 kHz corner
+ * takes the 16-23 kHz junk down by 27 dB but ALSO drops the
+ * 4-8 kHz band by 4.5 dB, and on a listening test that reads as
+ * "the sound is cut". Nothing is filtered unless asked:
+ * PCMLP=<hz> 8th-order low-pass at <hz>
+ * PCMNOTCH=<hz[,hz]> narrow notches (8 Hz wide)
+ */
+ const char *e = getenv("PCMLP");
+ double fc = e ? atof(e) : 0.0;
+ lp_init = 1;
+ if (fc > 0.0)
+ pcm_lp_init(48000.0, fc);
+ if (!getenv("PCMNOT")) {
+ const char *q = getenv("PCMNOTCH");
+ if (q && *q && strcmp(q, "0") != 0) {
+ char buf[128];
+ char *tok, *save;
+ snprintf(buf, sizeof(buf), "%s", q);
+ for (tok = strtok_r(buf, ",", &save); tok;
+ tok = strtok_r(NULL, ",", &save))
+ pcm_notch_init(48000.0, atof(tok), 8.0);
+ }
+ }
+ }
+ if (n > sizeof(sw)) {
+ pcm_write_rec(p, n);
+ return;
+ }
+ if (noswap < 0) {
+ const char *e = getenv("PCMNOSWAP");
+ noswap = (e && *e && *e != '0');
+ }
+ if (noswap) {
+ pcm_write_rec(p, n);
+ return;
+ }
+ /*
+ * ★★★ POSTARESET (default ON): re-send CX2341X_ENC_MISC 12 once ~1 s of
+ * PCM has flowed, i.e. AFTER START_CAPTURE.
+ *
+ * Measured 2026-10-24: the audio state is bimodal per run (fixed for the
+ * whole run), BRIGHT = the CX25837 ADC path is +7 dB at the top end and
+ * loses the 15.7 kHz line, dull = it matches the WM8739 reference path
+ * within 1-2 dB. Nothing readable differs (1426 registers identical at
+ * both start and end), but MISC(12) - documented as "reset audio interface
+ * after channel change or input switch" - FLIPS a live capture out of the
+ * BRIGHT state:
+ *
+ * ar1: t=0..4 BRIGHT (line -49) -> ARESET at 6 s -> dull (line -23)
+ * ar3: t=0..4 BRIGHT (line -46) -> ARESET at 6 s -> dull (line -23)
+ * ar2: already dull -> stays dull
+ *
+ * So the encoder latches the audio interface at START_CAPTURE and can
+ * latch it wrong; the tool only sent MISC(12) BEFORE the start (in
+ * pvr2_encoder_config), which cannot fix a latch made afterwards.
+ * POSTARESET=0 disables it for an A/B.
+ */
+ for (i = 0; i + 1 < n; i += 2) {
+ sw[i] = p[i + 1];
+ sw[i + 1] = p[i];
+ }
+ if (n & 1)
+ sw[n - 1] = p[n - 1];
+ /*
+ * ★★★ PCMGATE (default ON): do not let the wrong audio state be heard.
+ *
+ * Measured 2026-10-24: the CX25837 audio path latches into one of two
+ * states per run and the state can sit BRIGHT (5-8 dB more top end than
+ * the WM8739 reference path, and the 15,734 Hz line gone) for the first
+ * moments of a capture before something turns it over. The user's
+ * report is exactly that: "the first few hundred ms are the correct
+ * sound and then it reverts".
+ *
+ * The line level is a content-independent indicator of the state:
+ * dull/correct line/total -23 .. -25 dB
+ * BRIGHT line/total -46 .. -53 dB
+ * so a Goertzel bin at 15,734 Hz over each 96 ms block tells us which
+ * state we are in. While the state is wrong this does two things:
+ * - re-sends CX2341X_ENC_MISC 12 (the audio-interface reset, which was
+ * measured to flip a live capture out of BRIGHT), rate limited;
+ * - mutes the PCM with a 5 ms ramp, so the listener hears nothing
+ * rather than the wrong sound, and it comes back the instant the
+ * state is right.
+ *
+ * PCMGATE=0 disables.
+ */
+ if (!getenv("PCMGATE") || *getenv("PCMGATE") != '0') {
+ static double coeff = 2.0 * 0.0, gate = 1.0;
+ static int init, bright_run, n_retry;
+ static double t_retry;
+ size_t nfr = n / 4, k;
+ double sp = 0.0, sq = 0.0;
+
+ if (!init) {
+ double w0 = 2.0 * M_PI * 15734.0 / 48000.0;
+ coeff = 2.0 * cos(w0);
+ init = 1;
+ if (getenv("PCMGATE_LOG"))
+ fprintf(stderr, "PCMGATE: on, bin %.0f Hz\n",
+ 15734.0);
+ }
+ /* Goertzel on the left channel plus the broadband power */
+ {
+ double s1 = 0.0, s2 = 0.0;
+ for (k = 0; k < nfr; k++) {
+ double v = (double)((int16_t *)sw)[2 * k];
+ double s0 = v + coeff * s1 - s2;
+ s2 = s1;
+ s1 = s0;
+ sq += v * v;
+ }
+ sp = s1 * s1 + s2 * s2 - coeff * s1 * s2;
+ }
+ if (nfr > 0 && sq > 0.0 && sp > 0.0) {
+ /*
+ * Fraction of the block's energy that sits in the line
+ * bin. Parseval: sum_k |X_k|^2 = N * sum x^2, and the
+ * Goertzel value is |X_k|^2, so the fraction is
+ * sp / (nfr * sq). (The first version divided by sq^2
+ * and the answer moved with the level, which read as a
+ * flickering state - measured, so it is fixed here.)
+ */
+ static double ema = -100.0;
+ double db = 10.0 * log10(sp / (sq * (double)nfr + 1e-9));
+ int ok;
+ if (ema < -99.0)
+ ema = db;
+ else
+ ema = 0.90 * ema + 0.10 * db; /* ~1 s: 96 ms/block */
+ /* hysteresis: 6 dB, so the gate cannot chatter */
+ ok = (ema > -33.0) || (ema > -39.0 && gate > 0.5);
+ {
+ static int lg = -1;
+ if (lg < 0)
+ lg = getenv("PCMGATE_LOG") != NULL;
+ if (lg)
+ fprintf(stderr, "PCMGATE blk line %.1f "
+ "ema %.1f %s\n", db, ema,
+ ok ? "OK" : "BRIGHT");
+ }
+ if (!ok) {
+ bright_run++;
+ t_retry += (double)nfr / 48000.0;
+ if (n_retry < 20 && t_retry > 0.5) {
+ uint32_t pp[4];
+ pp[0] = 12; pp[1] = 0;
+ pp[2] = 0; pp[3] = 0;
+ t_retry = 0.0;
+ n_retry++;
+ (void)pvr2_enc_cmd(g_dev,
+ CX2341X_ENC_MISC, pp, 4);
+ fprintf(stderr, "PCMGATE: state BRIGHT "
+ "(line %.1f/%.1f dB) -> MISC(12) "
+ "retry %d, muting\n", db, ema,
+ n_retry);
+ }
+ } else if (bright_run) {
+ fprintf(stderr, "PCMGATE: state OK (line %.1f/%.1f "
+ "dB) after %d blocks\n", db, ema,
+ bright_run);
+ bright_run = 0;
+ }
+ /* ramp 5 ms so the gate cannot click */
+ {
+ double tgt = ok ? 1.0 : 0.0;
+ double step = 1.0 / (0.005 * 48000.0);
+ for (k = 0; k < nfr * 2; k++) {
+ int16_t *s = (int16_t *)sw;
+ if (gate < tgt)
+ gate = gate + step > tgt ?
+ tgt : gate + step;
+ else if (gate > tgt)
+ gate = gate - step < tgt ?
+ tgt : gate - step;
+ s[k] = (int16_t)((double)s[k] * gate);
+ }
+ }
+ }
+ }
+ {
+ /* PCMDUMP: pre-filter samples of the same data, for A/B. */
+ static int dump_init, dumped;
+ if (!dump_init) {
+ const char *e = getenv("PCMDUMP");
+ dump_init = 1;
+ if (e && *e) {
+ char fn[256];
+ snprintf(fn, sizeof(fn), "%s.pre", e);
+ g_dp = fopen(fn, "wb");
+ snprintf(fn, sizeof(fn), "%s.post", e);
+ g_dq = fopen(fn, "wb");
+ fprintf(stderr, "PCMDUMP: %s.pre / .post\n", e);
+ }
+ }
+ if (g_dp && dumped < 96000) {
+ fwrite(sw, 1, n, g_dp);
+ dumped += (int)(n / 2);
+ if (dumped >= 96000) {
+ fclose(g_dp); g_dp = NULL;
+ }
+ }
+ }
+ pcm_lp_apply((int16_t *)sw, n / 4); /* n bytes = n/4 stereo frames */
+ if (g_dq) {
+ static int dumped2;
+ if (dumped2 < 96000) {
+ fwrite(sw, 1, n, g_dq);
+ dumped2 += (int)(n / 2);
+ if (dumped2 >= 96000) {
+ fclose(g_dq); g_dq = NULL;
+ }
+ }
+ }
+ {
+ static int wr;
+ static int wdbg = -1;
+ if (wdbg < 0) {
+ const char *e = getenv("PCMDBG");
+ wdbg = (e && *e && *e != '0');
+ }
+ if (wdbg && wr < 4) {
+ int16_t *o = (int16_t *)sw;
+ fprintf(stderr, "WRITE rec %d: %d %d %d %d\n", wr,
+ o[0], o[1], o[2], o[3]);
+ wr++;
+ }
+ }
+ pcm_write_rec(sw, n);
+}
+
+static void pcm_close(void)
+{
+ if (!pcm_fp)
+ return;
+ if (!pcm_raw) {
+ fseek(pcm_fp, 4, SEEK_SET);
+ pcm_wr32((uint32_t)(pcm_bytes + 36));
+ fseek(pcm_fp, 40, SEEK_SET);
+ pcm_wr32((uint32_t)pcm_bytes);
+ }
+ fflush(pcm_fp);
+ fclose(pcm_fp);
+ pcm_fp = NULL;
+ fprintf(stderr, "PCM: %lu records, wrote %llu bytes (%.1f s at %u Hz/%u ch)\n",
+ split_recs, (unsigned long long)pcm_bytes,
+ (double)pcm_bytes / (double)(pcm_rate * pcm_ch * 2),
+ pcm_rate, pcm_ch);
+ if (pcm_drops)
+ fprintf(stderr, "PCM: dropped %lu records (pipe full)\n",
+ pcm_drops);
+}
+
+/* Encoder start state, kept so the capture context can send
+ * CX2341X_ENC_STOP_CAPTURE (0x82) with the same (type, subtype) the capture
+ * was started with -- see pvr2_encoder_stop(). */
+static int enc_started = 0;
+static uint32_t enc_captype = 0, enc_subtype = 0x13;
+/* -Y : print the wall-clock time of each raw frame, to measure where the
+ * pipeline delay sits (steady-state vs start-up backlog). */
+static int raw_timing = 0;
+/* Effective frame-rate check: the encoder sometimes drops to half rate,
+ * which interleaves two different moments into one 518400-byte block
+ * and shreds the picture. Measured so it can be reported rather than
+ * silently written out. */
+static unsigned long raw_frame_count = 0;
+static int raw_rate_warned = 0;
+/* -B/--planes PFX: also dump Y, U and V as separate PGM files. */
+static const char *planes_prefix = NULL;
+/* -L FILE: write the luma plane on its own as a greyscale y4m, so any
+ * vertical-line artefact can be judged without colour confusing it. */
+static const char *luma_path = NULL;
+/* -R FILE: dump the raw (still macroblock-tiled) HM12 stream, before
+ * any de-macroblocking, so the layout can be analysed offline. */
+static const char *raw_hm12_path = NULL;
+static FILE *raw_hm12_fp = NULL;
+static int raw_tframes = 0;
+static double raw_t0 = 0.0;
+/* -A <sec> : drop the first SEC seconds of raw (HM12) backlog. Measured:
+ * the encoder holds ~1.5 s of raw frames, so playback runs 1.5 s behind
+ * unless we discard that much. */
+static double raw_drop_sec = 0.0;
+static uint64_t raw_drop_bytes = 0;
+static uint64_t raw_drop_seen = 0;
+static uint8_t raw_acc[720 * 480 * 3 / 2 * 2]; /* up to 2 frames of slack */
+static size_t raw_acc_len = 0;
+static size_t raw_phase, raw_phase_left;
+static int raw_phase_init;
+static int y4m_hdr_done = 0;
+
+/*
+ * Live segment mode (-L): write to a numbered series of files that the
+ * player can follow with a normal file, instead of a FIFO.
+ *
+ * Why: a FIFO is S_IFIFO with a reported size of 0. Players stat() the
+ * source and treat a zero-length, non-seekable input as "a file with no
+ * content yet", so they sit on a read buffer and fall behind. A regular
+ * file is seekable and has a real size, so the player reads exactly as much
+ * as exists and the latency collapses to the segment rotation interval.
+ *
+ * Each segment is a self-contained MPEG-2 PS: it starts at a pack header
+ * and ends with a flush, so a player can start on any of them.
+ */
+static int live_mode = 0; /* 0 = off */
+static char live_path[512] = "";
+static FILE *live_fp = NULL;
+/* A single regular file, written continuously. It is seekable and has a
+ * real size, so a player reading it consumes exactly what exists and stays
+ * at the live edge - unlike a FIFO (S_IFIFO, stat size 0), which makes
+ * players sit on a read buffer and fall seconds behind. */
+
+static void on_sigint(int sig)
+{
+ (void)sig;
+ g_stop = 1;
+ if (g_cap)
+ pvr2_capture_stop(g_cap);
+}
+
+/* MPEG audio PES carry start code 0xC0. Counting them is the only
+ * objective way to tell whether an audio-clock register change actually
+ * made a difference. */
+static unsigned long audio_pes_count, video_pes_count, other_pes_count;
+static int raw_audio_rate;
+
+/* CX2584x identification: 0x0100 = low byte, 0x0101 = high byte. */
+static void print_chip_id(unsigned int v)
+{
+ const char *n = "unknown";
+ if (v == 0x0370) n = "CX25836";
+ else if (v == 0x0371) n = "CX25837";
+ else if (v == 0x038f) n = "CX25838";
+ else if (v == 0x0398) n = "CX25839";
+ else if (v == 0x03a0) n = "CX25840";
+ else if (v == 0x03a1) n = "CX25841";
+ else if (v == 0x03b0) n = "CX25842";
+ else if (v == 0x03b1) n = "CX25843";
+ else if (v == 0x03b4) n = "CX25844";
+ else if (v == 0x03b5) n = "CX25845";
+ fprintf(stderr, "CHIPID: 0x%04x %s\n", v, n);
+}
+
+static void count_pes(const uint8_t *buf, size_t len)
+{
+ size_t i;
+ for (i = 0; i + 3 < len; i++) {
+ if (buf[i] != 0x00 || buf[i + 1] != 0x00 || buf[i + 2] != 0x01)
+ continue;
+ if (buf[i + 3] >= 0xC0 && buf[i + 3] <= 0xDF)
+ audio_pes_count++;
+ else if (buf[i + 3] == 0xE0)
+ video_pes_count++;
+ else
+ other_pes_count++;
+ }
+}
+
+/*
+ * ★ SPLITAV=1 - one-pass raw YUV + PCM split (2026-10-16).
+ *
+ * Measured record format of the raw stream (captype 1/2, subtype 0x03)
+ * with a hardware-static picture (I2CW=0x404:0xf6, blue field):
+ *
+ * [518400 bytes HM12 video frame]
+ * then K x [12-byte header][4608 bytes PCM], K = 1 or 2
+ *
+ * header = 00 00 00 00 00 00 tt tt 00 00 12 00
+ * - bytes 0-5 are zero and bytes 8-11 are 00 00 12 00: ten fixed
+ * bytes, so the signature is effectively unique in the stream.
+ * - tt tt counts 2160 per record = 90 kHz ticks = 24 ms, and
+ * 4608 bytes = 1152 stereo sample-frames at 48 kHz = 24 ms, so
+ * the PCM payload size is fixed and the counter is an mpg-style
+ * PTS (its low 16 bits, wrapping).
+ *
+ * The splitter emits everything that is not a PCM payload to the normal
+ * raw video writer and the payload to the WAV writer, both in one pass:
+ * SPLITAV=1 RAWCAPTYPE=1 RAWAUDIO=0x03 ./kare ... -r \
+ * -o out.y4m --pcm out.wav -C -t 10
+ */
+static int split_av = 0;
+static int in_split_child = 0;
+static unsigned char sp_buf[65536];
+static size_t sp_len = 0;
+
+static void data_cb(const uint8_t *buf, size_t len, void *user);
+
+
+/*
+ * ★ HM12 のフレーム境界は「PCM レコードの位置」で決まる。
+ * 固定 518400 バイト切りだと、キャプチャ開始位相が毎回ランダム(実測 10,045 / 512 / 0)で
+ * de-macroblock が回転し、色が入れ替わって上下左右にずれた絵になる。
+ * そこで「レコード間の映像」を蓄積し、518400 バイト貯まった時点で 1 フレームとして出す。
+ * 最初のレコードより前(=欠けたフレーム)は破棄する。
+ */
+static unsigned char sp_fr[518400 * 4];
+static size_t sp_fr_len = 0;
+static size_t sp_seg_log = 0;
+
+static void split_emit_frame(void)
+{
+ if (sp_fr_len >= 518400u) {
+ in_split_child = 1;
+ data_cb(sp_fr, 518400u, NULL);
+ in_split_child = 0;
+ sp_fr_len = 0;
+ }
+}
+
+static void split_video(const uint8_t *p, size_t n)
+{
+ if (!split_started) {
+ sp_seg_log += n; /* 先頭の欠けたフレーム: 捨てる */
+ return;
+ }
+ while (n) {
+ size_t space = sizeof(sp_fr) - sp_fr_len;
+ size_t take = n < space ? n : space;
+ memcpy(sp_fr + sp_fr_len, p, take);
+ sp_fr_len += take;
+ p += take;
+ n -= take;
+ if (sp_fr_len >= sizeof(sp_fr))
+ split_emit_frame();
+ }
+}
+
+/*
+ * ★ A record always sits on a frame boundary, so the video bytes since the
+ * previous record are a WHOLE number of 518,400-byte frames (measured:
+ * 518,400 or 0, and 2x518,400 + the bytes of any record the parser missed).
+ * Emitting round(len / 518,400) frames and DISCARDING the remainder makes the
+ * demux self-correcting: a missed record costs at most one duplicated frame
+ * instead of shifting every later frame (which is the visible drift).
+ */
+static void split_frame_end(void)
+{
+ size_t n, rem, k;
+ /*
+ * ★ 2026-10-23: whole frames out, and the remainder is CARRIED.
+ *
+ * Two corrections to this function, both measured upstream:
+ *
+ * 1. Emit only whole frames. The old code rounded to the NEAREST
+ * frame, so a segment off the record grid by k bytes still
+ * produced a "frame" built from shifted bytes - in HM12 a
+ * k-byte shift rotates every 16-byte block line, which is a
+ * horizontal displacement of the picture.
+ * 2. Do NOT throw the remainder away. When two PCM records belong
+ * to one frame the video between them is only half a frame
+ * (259,200 bytes); discarding it loses frames forever (measured
+ * upstream: "zero frames per segment, so the window never
+ * appeared"). Keep it and let the next segment complete it -
+ * the accumulator then behaves as one continuous video stream
+ * emitted in whole frames.
+ *
+ * SPLITNEAREST=1 restores the old rounding-and-discard for an A/B.
+ */
+ if (getenv("SPLITNEAREST")) {
+ n = (sp_fr_len + 518400u / 2) / 518400u;
+ rem = 0;
+ } else {
+ n = sp_fr_len / 518400u;
+ rem = sp_fr_len - n * 518400u;
+ }
+ if (getenv("SPLITLOG"))
+ fprintf(stderr, "SPLITLOG segment %zu -> %zu frame(s), "
+ "carry %zu\n", sp_fr_len, n, rem);
+ for (k = 0; k < n; k++) {
+ in_split_child = 1;
+ data_cb(sp_fr + k * 518400u, 518400u, NULL);
+ in_split_child = 0;
+ }
+ if (n) {
+ memmove(sp_fr, sp_fr + n * 518400u, rem);
+ sp_fr_len = rem;
+ } else {
+ sp_fr_len = 0;
+ }
+ (void)sp_seg_log;
+}
+
+static void split_process(void);
+
+static void split_feed(const uint8_t *buf, size_t len)
+{
+ /*
+ * Append -> process -> append again. Processing after every append
+ * leaves at most one partial record (<= 4620+12 bytes) in the buffer,
+ * so a 64 KB buffer never needs an emergency flush (an earlier version
+ * flushed a PREFIX as video when it ran out of room and silently cut
+ * records in half).
+ */
+ while (len) {
+ size_t space = sizeof(sp_buf) - sp_len;
+ size_t take = len < space ? len : space;
+
+ memcpy(sp_buf + sp_len, buf, take);
+ sp_len += take;
+ buf += take;
+ len -= take;
+ split_process();
+ if (len && sp_len >= sizeof(sp_buf)) {
+ in_split_child = 1;
+ data_cb(sp_buf, sp_len, NULL);
+ in_split_child = 0;
+ sp_len = 0;
+ }
+ }
+}
+
+static void split_process(void)
+{
+ static uint32_t prev_cnt;
+ static int have_prev;
+ size_t i = 0;
+
+ while (sp_len - i >= PCM_REC_HDR + PCM_REC_PAYLOAD) {
+ size_t k = i, found = (size_t)-1;
+ for (; k + PCM_REC_HDR + PCM_REC_PAYLOAD <= sp_len; k++) {
+ uint32_t cnt;
+ /*
+ * Header (measured): 12 bytes, of which the LAST four
+ * are the invariant 00 00 12 00. The first eight are a
+ * monotonically increasing counter -- reading them as
+ * zero only works for the first ~24 records of a
+ * capture, which is exactly why the earlier
+ * six-zero-prefix detector lost 86% of the audio.
+ * So: match the invariant tail AND require the counter
+ * to advance, which no video payload reproduces.
+ */
+ if (sp_buf[k+8] || sp_buf[k+9] ||
+ sp_buf[k+10] != 0x12 || sp_buf[k+11])
+ continue;
+ /* bytes 4..7 are a BIG-endian counter (bytes 6..7
+ * are its low half: 0x3980, 0x41f0, 0x4a60 ... ) */
+ cnt = ((uint32_t)sp_buf[k+4] << 24) |
+ ((uint32_t)sp_buf[k+5] << 16) |
+ ((uint32_t)sp_buf[k+6] << 8) |
+ (uint32_t)sp_buf[k+7];
+ /*
+ * The counter advances by a modest amount per record
+ * (~2160 for 24 ms records). Requiring 0 < delta <
+ * 0x100000 kills the false positives that a bare
+ * "tail matches" test lets through from video data
+ * (each one used to hijack the parser and cost a real
+ * record: 45% extraction instead of ~100%).
+ */
+ /*
+ * ★ Records sit on a fixed grid relative to the video
+ * frames (measured: a record starts either 4,620 bytes
+ * after the previous one -- a second record for the same
+ * frame -- or 523,020 bytes later, i.e. one 518,400-byte
+ * frame plus one record). Restricting the search to
+ * that grid removes essentially all false positives; a
+ * false positive used to hijack prev_cnt and made every
+ * later real record fail the counter test, which left
+ * 4,620 bytes of audio inside the video of every frame
+ * -> the picture drifted. That was the live symptom.
+ */
+ {
+ uint64_t abs = sp_abs + k;
+ if (sp_have_rec && !getenv("NOGRID")) {
+ uint64_t a = sp_last_rec + PCM_REC_HDR +
+ PCM_REC_PAYLOAD;
+ uint64_t b = a + 518400u;
+ /*
+ * ★ Accept anything from the earliest
+ * possible next record onwards. The
+ * invariant 4-byte tail plus that
+ * monotonic constraint was measured to
+ * give exactly the audio rate on real
+ * video (167 matches in 4 s = 41.75/s,
+ * i.e. zero false positives), while the
+ * strict grid windows dropped ~10% of the
+ * records and left their bytes inside the
+ * video -> drift.
+ */
+ int ok0 = (abs + 8 >= a);
+ int ok1 = (abs + 8 >= a);
+ (void)b;
+ /*
+ * ★ Only reject candidates that are TOO
+ * EARLY: a record cannot start before the
+ * grid. Candidates later than the grid
+ * mean we missed one (so we resync here
+ * rather than reject every real record and
+ * desync for good -- that bug left most of
+ * the audio inside the video).
+ */
+ int late = (abs > b + 512 + 65536);
+ if (!ok0 && !ok1 && !late)
+ continue;
+ if (!ok0 && !ok1 && getenv("SPLITLOG"))
+ fprintf(stderr, "SPLITLOG resync at "
+ "%llu (expected %llu)\n",
+ (unsigned long long)abs,
+ (unsigned long long)b);
+ }
+ }
+ if (getenv("DBGREC"))
+ fprintf(stderr, "DBGREC tail at abs=%llu (grid %s)\n",
+ (unsigned long long)(sp_abs + k),
+ sp_have_rec ? "on" : "off");
+ /*
+ * The counter check is only needed while acquiring the
+ * grid (it rejects look-alikes in video data). Once the
+ * grid is known it must NOT reject anything on-grid: a
+ * strict counter test silently dropped ~8% of the
+ * records, leaving 4,620 audio bytes inside each affected
+ * frame, which is exactly the drift the user sees.
+ */
+ if (!sp_have_rec && have_prev) {
+ uint32_t d = cnt - prev_cnt;
+ if (d == 0 || d > 0x10000000u)
+ continue;
+ }
+ found = k;
+ prev_cnt = cnt;
+ have_prev = 1;
+ if (getenv("RECLOG"))
+ fprintf(stderr, "REC %llu %u %llu\n",
+ (unsigned long long)(sp_abs + k), cnt,
+ (unsigned long long)(sp_abs + k - sp_last_rec));
+ if (getenv("SPLITLOG"))
+ fprintf(stderr, "SPLITLOG seg %llu\n",
+ (unsigned long long)(sp_abs + k -
+ sp_prev_rec_end));
+ sp_prev_rec_end = sp_abs + k + PCM_REC_HDR +
+ PCM_REC_PAYLOAD;
+ sp_last_rec = sp_abs + k;
+ sp_have_rec = 1;
+ break;
+ }
+ if (found == (size_t)-1) {
+ size_t have = sp_len - i;
+ /*
+ * ★★★ Keep a whole record's worth, not just the header
+ * (2026-10-23, measured).
+ *
+ * The scan needs HDR+PAYLOAD bytes from a record's start,
+ * so a record that straddles the end of this 64 KB buffer
+ * cannot be seen yet. With only 12 bytes kept, its other
+ * 4,608 bytes were emitted as VIDEO: the record is lost
+ * from the audio AND 4,620 bytes are inserted into the
+ * picture, which is why the picture and the sound break at
+ * the same instant. Measured on a 156 MB raw dump replayed
+ * through this exact logic: keep=12 loses 17 of 417 records
+ * (one every ~1,100 frames), keep=4,619 loses none.
+ */
+ size_t need = PCM_REC_HDR + PCM_REC_PAYLOAD - 1;
+ size_t keep = have > need ? need : have;
+ size_t emit = have - keep;
+ if (emit)
+ split_video(sp_buf + i, emit);
+ i += emit;
+ break;
+ }
+ if (found > i)
+ split_video(sp_buf + i, found - i);
+ i = found;
+ if (!split_started)
+ split_started = 1;
+ split_frame_end();
+ if (getenv("SPLITLOG")) {
+ static uint64_t last_pos;
+ split_tot += i - split_last_i;
+ split_last_i = i;
+ fprintf(stderr, "SPLITLOG rec %lu at %llu (間隔 %llu)\n",
+ split_recs, (unsigned long long)split_tot,
+ (unsigned long long)(split_tot - last_pos));
+ last_pos = split_tot;
+ }
+ if (pcm_fp) {
+ pcm_write_split(sp_buf + i + PCM_REC_HDR,
+ PCM_REC_PAYLOAD);
+ split_recs++;
+ }
+ split_tot += PCM_REC_HDR + PCM_REC_PAYLOAD;
+ split_last_i = i + PCM_REC_HDR + PCM_REC_PAYLOAD;
+ i += PCM_REC_HDR + PCM_REC_PAYLOAD;
+ }
+ if (i) {
+ sp_abs += i;
+ memmove(sp_buf, sp_buf + i, sp_len - i);
+ sp_len -= i;
+ }
+}
+
+static void split_flush(void)
+{
+ if (sp_len) {
+ in_split_child = 1;
+ data_cb(sp_buf, sp_len, NULL);
+ in_split_child = 0;
+ sp_len = 0;
+ }
+}
+
+/*
+ * ★ POSTARESET, shared by both callbacks (2026-10-24).
+ *
+ * It used to live in pcm_write_split(), so it only fired when the split PCM
+ * was being written - i.e. never for video-only runs. Measured: six runs with
+ * PCM flowing came out correct in BOTH respects (audio state dull, video
+ * band-boundary row diff / interior = 1.22-1.23, i.e. no 16-line line),
+ * while five video-only runs had one with the line (ratio 8.03). Driving it
+ * from either callback makes the reset happen whatever the output mode.
+ */
+static void post_reset_tick(size_t bytes)
+{
+ static int done;
+ static unsigned long long tot;
+ uint32_t pp[4];
+
+ if (getenv("POSTARESET") && *getenv("POSTARESET") == '0')
+ return;
+ if (done)
+ return;
+ tot += bytes;
+ if (tot < 1500000ULL) /* ~1 s of raw video or 5 s of PCM */
+ return;
+ done = 1;
+ pp[0] = 12; pp[1] = 0; pp[2] = 0; pp[3] = 0;
+ if (pvr2_enc_cmd(g_dev, CX2341X_ENC_MISC, pp, 4) == 0)
+ fprintf(stderr, "POSTARESET: MISC(12) after start -> ok\n");
+ else
+ fprintf(stderr, "POSTARESET: MISC(12) failed\n");
+}
+
+static void data_cb(const uint8_t *buf, size_t len, void *user)
+{
+ (void)user;
+ ctl_poll(); /* live register/parameter commands (CTLFILE) */
+ post_reset_tick(len);
+ /*
+ * RATELOG=1: one line per USB transfer (time, length, cumulative) so
+ * the stream's structure can be seen -- e.g. whether the raw PCM
+ * arrives as its own small transfers next to the 128 KB video ones.
+ */
+ if (getenv("RATELOG")) {
+ static uint64_t tl_acc;
+ tl_acc += len;
+ fprintf(stderr, "TL %8.3f %7zu %12llu\n", now_sec(), len,
+ (unsigned long long)tl_acc);
+ }
+ /*
+ * Order matters: the splitter must be asked FIRST (it writes the
+ * PCM records itself), and the audio-only branch must not swallow
+ * the video bytes when splitting. In a split child call
+ * (in_split_child) both are skipped and the bytes go to the video
+ * writer, which is what the splitter wants for the video parts.
+ */
+ if (!in_split_child) {
+ /*
+ * SPLITRAWDUMP=<path>: write the stream BEFORE the splitter.
+ * -R dumps the post-split video, which contains no PCM
+ * records at all, so the record layout can only be studied
+ * from here.
+ */
+ {
+ static FILE *rd;
+ static int rd_init;
+ if (!rd_init) {
+ const char *q = getenv("SPLITRAWDUMP");
+ rd_init = 1;
+ if (q && *q)
+ rd = fopen(q, "wb");
+ }
+ if (rd && len)
+ fwrite(buf, 1, len, rd);
+ }
+ if (split_av && raw_mode) {
+ split_feed(buf, len);
+ return;
+ }
+ if (pcm_fp) {
+ /* audio only: the stream IS the PCM, no framing */
+ if (len) {
+ fwrite(buf, 1, len, pcm_fp);
+ pcm_bytes += len;
+ }
+ return;
+ }
+ }
+ if (!out_fp)
+ return;
+ if (!raw_mode)
+ count_pes(buf, len);
+ if (raw_mode) {
+ const size_t frame_sz = 720u * 480u * 3u / 2u;
+ /*
+ * ★ HM12PHASE=<n>: the raw stream may start n bytes into a
+ * frame (the phase is random per run: measured 10045 / 512 / 1
+ * across runs). A wrong phase rotates the de-macroblocking,
+ * which shows up as swapped green/red/blue bands drifting down
+ * the screen plus a left/right shift. Drop n bytes first.
+ */
+ if (!raw_phase_init) {
+ const char *ph = getenv("HM12PHASE");
+ raw_phase = raw_phase_left = ph ? (size_t)atoi(ph) : 0u;
+ raw_phase_init = 1;
+ if (raw_phase)
+ fprintf(stderr, "hm12 phase: skipping first %zu bytes\n",
+ raw_phase);
+ }
+ double t = now_sec();
+ static unsigned char scratch[720 * 480 * 3 / 2];
+ size_t off = 0;
+ /* --live with -r used to write to out_fp (usually /dev/null)
+ * and never to live_fp, so "raw + live" produced an empty
+ * live file. Send the y4m stream to the live file when live
+ * mode is on, exactly like the MPEG path does. */
+ FILE *dst = live_mode ? live_fp : out_fp;
+ if (!dst)
+ return;
+ if (!y4m_hdr_done) {
+ hm12_write_y4m_header(dst, 720, 480, 30000, 1001);
+ y4m_hdr_done = 1;
+ }
+ if (raw_hm12_fp) {
+ /* Raw dump is taken before any frame assembly so the
+ * macroblock layout can be examined as it comes.
+ * Count the bytes too, otherwise the summary reports
+ * "captured 0 bytes" even though the stream is fine. */
+ fwrite(buf, 1, len, raw_hm12_fp);
+ total_bytes += len;
+ return;
+ }
+ /* drop the encoder's initial backlog if requested */
+ if (raw_drop_sec > 0.0) {
+ size_t n = len - off;
+ if (raw_drop_bytes == 0)
+ raw_drop_bytes = (uint64_t)(raw_drop_sec *
+ 30.0 * 720.0 * 480.0 * 1.5);
+ if (n > raw_drop_bytes - raw_drop_seen)
+ n = (size_t)(raw_drop_bytes - raw_drop_seen);
+ raw_drop_seen += n;
+ off += n;
+ if (raw_drop_seen >= raw_drop_bytes) {
+ fprintf(stderr, "dropped %.1f s of raw "
+ "backlog (%llu bytes)\n",
+ raw_drop_sec,
+ (unsigned long long)raw_drop_seen);
+ raw_drop_sec = 0.0;
+ }
+ if (off >= len)
+ return;
+ }
+ while (off < len) {
+ size_t n = len - off;
+ if (raw_phase_left) {
+ size_t d = n < raw_phase_left ? n : raw_phase_left;
+ raw_phase_left -= d;
+ off += d;
+ if (!raw_phase_left)
+ fprintf(stderr, "hm12 phase: dropped %zu bytes\n",
+ raw_phase);
+ continue;
+ }
+ if (n > sizeof(raw_acc) - raw_acc_len)
+ n = sizeof(raw_acc) - raw_acc_len;
+ memcpy(raw_acc + raw_acc_len, buf + off, n);
+ raw_acc_len += n;
+ off += n;
+ if (raw_acc_len >= frame_sz) {
+ if (raw_t0 == 0.0)
+ raw_t0 = t; /* needed for the rate check too */
+ if (raw_timing)
+ fprintf(stderr, "rawframe %d t=+%.3f\n",
+ raw_tframes++, t - raw_t0);
+ hm12_write_frame_y4m(dst, raw_acc, 720, 480,
+ scratch);
+ raw_frame_count++;
+ total_bytes += frame_sz;
+ if (raw_t0 > 0.0 && !raw_rate_warned) {
+ double el = now_sec() - raw_t0;
+ if (el > 2.0) {
+ double fps = raw_frame_count / el;
+ if (fps < 24.0) {
+ fprintf(stderr,
+ "\n*** WARNING: encoder is at %.1f fps,"
+ " expected 30 ***\n"
+ " The capture is not usable: at half"
+ " rate the encoder interleaves\n"
+ " two fields into one frame, which"
+ " tears the picture.\n"
+ " Stop, replug the device and try"
+ " again.\n",
+ fps);
+ raw_rate_warned = 1;
+ }
+ }
+ }
+ memmove(raw_acc, raw_acc + frame_sz,
+ raw_acc_len - frame_sz);
+ raw_acc_len -= frame_sz;
+ /* live: flush every frame so the viewer
+ * sees the edge immediately; a file write
+ * only needs the periodic flush. */
+ if (live_mode)
+ fflush(dst);
+ else if ((total_bytes & 0xfffff) < frame_sz)
+ fflush(dst);
+ }
+ }
+ return;
+ }
+ /* MPEG-2 PS: skip leading garbage until the first pack header
+ * (00 00 01 ba). The encoder emits ~1.5 KB of uninitialised bytes
+ * at stream start, which otherwise makes VLC/ffmpeg report
+ * "slice mismatch / ac-tex damaged" decode errors. */
+ if (!mpeg_synced) {
+ size_t i;
+ for (i = 0; i + 3 < len; i++) {
+ if (buf[i] == 0 && buf[i+1] == 0 && buf[i+2] == 1 &&
+ buf[i+3] == 0xba) {
+ mpeg_synced = 1;
+ break;
+ }
+ }
+ if (!mpeg_synced)
+ return;
+ buf += i;
+ len -= i;
+ }
+ {
+ FILE *dst = live_mode ? live_fp : out_fp;
+ if (!dst)
+ return;
+ if (fwrite(buf, 1, len, dst) != len) {
+ /*
+ * ★ The viewer may be gone (crash, kill -9): its read end
+ * of the pipe is closed and every write fails. Without
+ * this the process keeps the CX23416 (and the USB device)
+ * busy forever, because SIGPIPE is ignored on purpose.
+ */
+ fprintf(stderr, "output closed -> stopping\n");
+ g_stop = 1;
+ return;
+ }
+ total_bytes += len; /* counts the live file too, not just -o */
+ if (live_mode) {
+ /* flush often so the player sees bytes immediately */
+ fflush(dst);
+ } else {
+ if ((total_bytes & 0xfffff) < len) /* ~every MB */
+ fflush(dst);
+ }
+ }
+}
+
+/* ---- timed capture (portable worker thread) ---- */
+
+#if defined(_WIN32)
+static DWORD WINAPI capture_thread(LPVOID arg)
+{
+ pvr2_capture_run((pvr2_capture_t *)arg);
+ return 0;
+}
+
+static void run_capture_timed(pvr2_capture_t *cap, int seconds)
+{
+ HANDLE th = CreateThread(NULL, 0, capture_thread, cap, 0, NULL);
+ if (!th) {
+ pvr2_capture_run(cap);
+ return;
+ }
+ WaitForSingleObject(th, (DWORD)seconds * 1000);
+ pvr2_capture_stop(cap);
+ WaitForSingleObject(th, 3000);
+ CloseHandle(th);
+}
+#else
+static void *capture_thread(void *arg)
+{
+ pvr2_capture_run((pvr2_capture_t *)arg);
+ return NULL;
+}
+
+static void run_capture_timed(pvr2_capture_t *cap, int seconds)
+{
+ pthread_t th;
+ int i;
+
+ if (pthread_create(&th, NULL, capture_thread, cap) != 0) {
+ pvr2_capture_run(cap);
+ return;
+ }
+ for (i = 0; i < seconds && !g_stop; i++) {
+ struct timespec ts = { 1, 0 };
+ nanosleep(&ts, NULL);
+ }
+ pvr2_capture_stop(cap);
+ pthread_join(th, NULL);
+}
+#endif
+
+static void usage(const char *prog)
+{
+ printf(
+"kare - capture MPEG-2 from CX23416/FX2 USB capture modules\n"
+"\n"
+"usage: %s [options] -o <output.mpeg> -c <cx_firmware.bin>\n"
+"\n"
+"options:\n"
+" -o FILE output file; use \"-\" for stdout (for pipes)\n"
+" -c FILE CX23416 firmware image (raw, NOT pre-swapped)\n"
+" (firmware_out/cx23416/cx_<n>_raw.bin) [required]\n"
+" -f FILE FX2 firmware image (only for cold state devices; optional)\n"
+" -v VID:PID device id in hex (default 04bb:0514 = GV-MVP/RZ2)\n"
+"\n"
+"video input:\n"
+" -C, --composite composite (yellow RCA): In2 luma + In6 chroma,\n"
+" 0x103=0xe1 - this is the default, because the RCA\n"
+" is the only jack this unit has in use\n"
+" --svideo S-Video (4-pin): luma In1 + chroma In5, 0x103=0xd0\n"
+" (measured 2026-10-25 with a recorder in the S jack)\n"
+" -S <n> S-Video chroma input: 0=In5, 1=In6, 2=In7, 3=In8\n"
+" (luma is In1 in all four; only 0=In5 is measured)\n"
+" -I <hex> raw 0x103 value, overrides everything above\n"
+"\n"
+"output format:\n"
+" --mpeg MPEG-2 program stream (default)\n"
+" --hm12, -r raw YUV, YUV4MPEG2 (.y4m)\n"
+ " --pcm FILE audio only: write the encoder PCM as a WAV\n"
+ " (RAWCAPTYPE=1 RAWAUDIO=0x02)\n"
+ " SPLITAV=1 with RAWCAPTYPE=1 RAWAUDIO=0x03: one pass, split\n"
+ " video -> -o and PCM -> --pcm\n"
+"\n"
+"other:\n"
+" -J / -U audio carrier: EIAJ (Japan, default) / BTSC (US)\n"
+" -3/-4/-8 audio sample rate 32000 / 44100 / 48000 (default 48000)\n"
+" -t SECONDS stop after SECONDS (omit for a live pipe: Ctrl-C to stop)\n"
+" -s scan USB devices and exit\n"
+" -p probe only (load firmware, print version, no capture)\n"
+" --live FILE write continuously to FILE (a normal, seekable file, so a\n"
+" player can follow it; a FIFO makes players buffer and lag)\n"
+" -P USER stream to stdout for USER (unbuffered); starts no player\n"
+" -W USER start VLC as USER right now and stream to it over a pipe\n"
+" (one process, no restart loop, no lag from re-probing)\n"
+" -V <lines> encoder frame-buffer depth (default 0x140=320; smaller = less lag)\n"
+" -F p|t|b y4m interlace tag: p=progressive (default), t=top field\n"
+" first, b=bottom field first\n"
+" --vstep N vertical filter distance: 1 = neighbouring lines\n"
+" (progressive), 2 = same field (interlaced)\n"
+" -L FILE write the Y (luma) plane only, as a greyscale y4m, to judge\n"
+" vertical-line artefacts without colour in the way\n"
+" -R FILE dump the raw macroblock-tiled HM12 stream (for analysis)\n"
+" -B PFX also dump each plane separately as PFX.Y/U/V/uv.y4m\n"
+" -A <sec> drop SEC seconds of raw (HM12) encoder backlog first\n"
+" -d verbose/debug output\n"
+" -D use the official driver's encoder command sequence\n"
+" -T enable the recovered driver tables / audio PLL (experiments;\n"
+" these were found to break capture, so they are OFF by default)\n"
+" --codec ADDR WM873x audio codec 7-bit I2C address (default 0x1a). The\n"
+" codec bring-up (packed word format, R6=0x00, R7=0x49,\n"
+" R9=0x01) runs on every capture; 0x50-0x5f is refused (EEPROM)\n"
+" --no-codec do not touch the WM873x at all\n"
+" -h this help\n"
+"\n"
+"examples:\n"
+" # record to a file, then play\n"
+" %s -c firmware/cx23416/cx_1_raw.bin -o cap.mpeg -C -t 30\n"
+" vlc cap.mpeg\n"
+"\n"
+" # live pipe to VLC (do NOT use -t, or VLC stalls at EOF)\n"
+" mkfifo /tmp/mp.fifo; chmod a+rw /tmp/mp.fifo\n"
+" vlc --demux=ps /tmp/mp.fifo &\n"
+" %s -c firmware/cx23416/cx_1_raw.bin -o - -C > /tmp/mp.fifo\n"
+"\n"
+" # raw YUV (HM12) to a file\n"
+" %s -c firmware/cx23416/cx_1_raw.bin -o cap.y4m -r -C -t 10\n",
+ prog, prog, prog, prog);
+}
+
+/*
+ * wm8739_bringup - write the WM8739 (XWM8739) ADC bring-up sequence.
+ *
+ * Taken from yacxm 0.1f (dev/cxm/cxm_audio.c, ADC_XWM8739_init), the
+ * working reference for this exact codec on I-O DATA's own CX23416 cards
+ * (GV-MVP/RX / RX2 / RX2W). The register addresses and the wire format
+ * match ours exactly: yacxm sends [0x34][reg<<1][data] and
+ * pvr2_wm873x_write(reg, data) emits the same two bytes.
+ *
+ * The entries that matter, and that this tool was missing:
+ * R15 = 0x00 reset register: normal operation
+ * R0 = 0x17 LEFT line in, bit7=LINMUTE. The WM8739 powers up with
+ * R1 = 0x17 RIGHT line in both line inputs MUTED (default 0x97), so
+ * an ADC that is never told otherwise converts silence.
+ * 0x17 = unmuted at 0 dB.
+ * R5 = 0x00 digital audio path control
+ * R6 = 0x00 power down control: every block powered up
+ * R7 = 0x49 format: MASTER mode (bit0), 24-bit, MSB-first
+ * R8 = 0x00 sampling: normal, 256fs, 48 kHz
+ * R9 = 0x01 activate
+ */
+static void wm8739_bringup(pvr2_dev *p, int wa)
+{
+ static const struct { uint8_t r, v; } seq[] = {
+ { 15, 0x00 }, { 0, 0x17 }, { 1, 0x17 }, { 5, 0x00 },
+ /*
+ * ★ R8 = 0x02 (384 fs), not 0x00 (2026-10-24). This is the
+ * bring-up used by AUDSTART, and it carried the old 0x00
+ * (256 fs) value: on this board SA_MCLK is 18.43 MHz = 384 fs,
+ * so 0x00 makes LRCLK 72 kHz and the PCM record counter steps
+ * 1440 ticks (16 ms) instead of 2160 (24 ms) - measured. The
+ * main init later writes 0x02 so the final state was right,
+ * but any path where this runs last would stream at the wrong
+ * rate. The Windows driver writes 0x00 and still works
+ * because its MPEG encoder resamples; we do not.
+ */
+ { 6, 0x5a }, { 7, 0x49 }, { 8, 0x02 }, { 9, 0x01 },
+ };
+ size_t k;
+
+ for (k = 0; k < sizeof(seq) / sizeof(seq[0]); k++) {
+ uint16_t rb = 0;
+ int wrc = pvr2_wm873x_write(p, (uint8_t)wa, seq[k].r,
+ seq[k].v);
+ int rrc = pvr2_wm873x_read(p, (uint8_t)wa, seq[k].r, &rb);
+ /* The WM8739 is write-only (datasheet: "will only respond
+ * to the R/W bit indicating a write"), so a read NACK is
+ * NOT evidence it is absent -- report the write ACK. */
+ fprintf(stderr, " R%u = 0x%02x -> write %s, read %s\n",
+ seq[k].r, seq[k].v,
+ (wrc < 0) ? "NACK" : "ACK",
+ (rrc < 0) ? "NACK (write-only part)" :
+ (rb == seq[k].v) ? "ok" : "mismatch");
+ }
+}
+
+/*
+ * ------------------------------------------------------------------
+ * WINxxx: three differences between this tool and the Windows driver,
+ * each behind its own env var so they can be isolated.
+ *
+ * 1. WINMASK - the driver clears bit 30 of REGISTER 0x0048
+ * (CX_REG_INTR_MASK), not of MBOX word 0x48. From the USB capture
+ * (docs/xp-init-sequence.txt):
+ * #597 CMD 0x05 0500000000000048 <- read register 0x0048
+ * #598 CMD 0x04 04ffffffbf000048 <- write 0xbfffffff
+ * CMD 0x04/0x05 are register accesses, the same ones used for
+ * 0x9058/0xa064 -- not MBOX accesses. #82 wrote 0xffffffff to the
+ * same 0x0048. pvr2_enc_clear_flag() reads MBOX 0x48 instead, which
+ * is why the ENCDIAG dump shows 0x0048 still at 0xffffffff.
+ *
+ * 2. WINGPIO - the driver's GPIO direction/output values are
+ * 0x9020 = 0x0000c780 and 0x900c = 0x00000310 (capture #87-88,
+ * #171-172, ...). This tool writes 0x408/0x08 (firmware.c), leaving
+ * bits 4, 7, 8 and 9 different. Audio-ADC power, mute and analog
+ * switch control are commonly on GPIO.
+ *
+ * 3. WINI2C - the driver writes three I2C addresses this tool has never
+ * touched, right after the WM8739 init (capture #518-525):
+ * 0x5b: 0010
+ * 0x12: 08df 08ef 0000 0010 0000 (0000->0010->0000 = a strobe)
+ * 0x5c: 0280 0b39 15e0 001d 0429 0536 0a43 0611
+ * 0x1a: 0017 0217 (R0/R1 written again)
+ * Wire format is confirmed from the capture: every one of these is a
+ * single FX2 0x08 command with a 2-byte sub-address and NO data byte
+ * ([0x08][dev][len=2][sub_hi][sub_lo]); the trailing bytes in the
+ * captured packets are stale buffer content, not part of the write.
+ * ------------------------------------------------------------------
+ */
+static void win_i2c(pvr2_dev *p)
+{
+ static const struct { uint8_t dev; uint16_t w; } s[] = {
+ { 0x5b, 0x0010 },
+ { 0x12, 0x08df }, { 0x12, 0x08ef }, { 0x12, 0x0000 },
+ { 0x12, 0x0010 }, { 0x12, 0x0000 },
+ { 0x5c, 0x0280 }, { 0x5c, 0x0b39 }, { 0x5c, 0x15e0 },
+ { 0x5c, 0x001d }, { 0x5c, 0x0429 }, { 0x5c, 0x0536 },
+ { 0x5c, 0x0a43 }, { 0x5c, 0x0611 },
+ { 0x1a, 0x0017 }, { 0x1a, 0x0217 },
+ };
+ uint8_t nodata = 0;
+ size_t k;
+
+ for (k = 0; k < sizeof(s) / sizeof(s[0]); k++) {
+ /* len = 0, so the byte is not sent; a valid pointer keeps
+ * memcpy() well defined. */
+ int rc = pvr2_i2c_write(p, s[k].dev, s[k].w, &nodata, 0);
+ fprintf(stderr, "WINI2C dev=0x%02x %04x -> %s\n",
+ s[k].dev, s[k].w, rc < 0 ? "NACK" : "ACK");
+ }
+}
+
+/*
+ * ★ Full vendor register tables for the NEC pair (2026-10-16).
+ *
+ * The pcap shows the Windows driver writing ALL 24 registers (0x00-0x17) of
+ * both chips at every session start, then a 4-write fine-tune, then the CH
+ * strobe -- and the short block again afterwards. Our default only ever sent
+ * the short block, so 21 of the uPD64031A's 24 registers and 16 of the
+ * uPD64084GC's 24 stayed at their power-on defaults.
+ *
+ * What the datasheet says the missing uPD64031A registers do (S14778JJ4V0DS):
+ * SA01=0xb8 EXDAS=1 (digital output on) + N3D1STEN=1: drives the
+ * "3-D processing inhibit" control to the 3D Y/C IC on N3D --
+ * the datasheet notes this is only effective when used with
+ * NEC's own 3-D Y/C separator, i.e. exactly our uPD64084GC.
+ * SA09=0x7f DCPEN=1: digital clamp ENABLED. Without it DCPAG (SA08
+ * D5-D3), which the short block DOES set to 101 (pedestal shift
+ * + 1.625x), is documented as having no effect.
+ * SA0e/SA0f colour-killer (KILM/KILS/KILR) and sync-loss (HSSR/VSSR)
+ * thresholds -- picture-quality parameters left at defaults.
+ * SA02/03/04/06/07 PREGHSTS, analysis counts, ADC mode, hunting and
+ * vertical-sync-loss time constants.
+ * The uPD64084GC's table is not decodable here (no register datasheet), but
+ * the vendor writes 24 registers and the short block only 8, with DIFFERENT
+ * values for 02/06/0b/15 (a0/cc/37/60 vs 80/11/39/e0).
+ *
+ * NECFULL=0 keeps the old short-block-only behaviour for A/B.
+ */
+static void win_i2c_full(pvr2_dev *p)
+{
+ static const struct { uint8_t dev, reg, val; } t[] = {
+ /* uPD64031A (0x12) full table, pcap order */
+ { 0x12, 0x00, 0x00 }, { 0x12, 0x01, 0xb8 },
+ { 0x12, 0x02, 0x58 }, { 0x12, 0x03, 0x87 },
+ { 0x12, 0x04, 0x96 }, { 0x12, 0x05, 0x03 },
+ { 0x12, 0x06, 0x14 }, { 0x12, 0x07, 0x0b },
+ { 0x12, 0x08, 0x9f }, { 0x12, 0x09, 0x7f },
+ { 0x12, 0x0a, 0x00 }, { 0x12, 0x0b, 0x00 },
+ { 0x12, 0x0c, 0x1d }, { 0x12, 0x0d, 0x5e },
+ { 0x12, 0x0e, 0x00 }, { 0x12, 0x0f, 0xd0 },
+ { 0x12, 0x10, 0x00 }, { 0x12, 0x11, 0x00 },
+ { 0x12, 0x12, 0x00 }, { 0x12, 0x13, 0x00 },
+ { 0x12, 0x14, 0x00 }, { 0x12, 0x15, 0x00 },
+ { 0x12, 0x16, 0x00 }, { 0x12, 0x17, 0x00 },
+ /* fine-tune block (pcap) */
+ { 0x12, 0x01, 0xb8 }, { 0x12, 0x04, 0x96 },
+ { 0x12, 0x09, 0x70 }, { 0x12, 0x08, 0x9f },
+ /* CH strobe: datasheet 2.4 -- after the register setup the
+ * channel-change signal STARTS the ghost-reduction operation */
+ { 0x12, 0x00, 0x00 }, { 0x12, 0x00, 0x10 },
+ { 0x12, 0x00, 0x00 },
+ /* uPD64084GC (0x5c) full table, pcap order */
+ { 0x5c, 0x00, 0x1d }, { 0x5c, 0x01, 0x01 },
+ { 0x5c, 0x02, 0xa0 }, { 0x5c, 0x03, 0x24 },
+ { 0x5c, 0x04, 0x29 }, { 0x5c, 0x05, 0x36 },
+ { 0x5c, 0x06, 0xcc }, { 0x5c, 0x07, 0x01 },
+ { 0x5c, 0x08, 0x56 }, { 0x5c, 0x09, 0x48 },
+ { 0x5c, 0x0a, 0xff }, { 0x5c, 0x0b, 0x37 },
+ { 0x5c, 0x0c, 0xa0 }, { 0x5c, 0x0d, 0x05 },
+ { 0x5c, 0x0e, 0x08 }, { 0x5c, 0x0f, 0x44 },
+ { 0x5c, 0x10, 0x00 }, { 0x5c, 0x11, 0x08 },
+ { 0x5c, 0x12, 0x52 }, { 0x5c, 0x13, 0xf8 },
+ { 0x5c, 0x14, 0x53 }, { 0x5c, 0x15, 0x60 },
+ { 0x5c, 0x16, 0x10 }, { 0x5c, 0x17, 0x00 },
+ /* tail (pcap) */
+ { 0x5c, 0x02, 0xa0 }, { 0x5c, 0x0b, 0x37 },
+ { 0x5c, 0x15, 0x60 },
+ };
+ size_t k;
+ int nack = 0;
+
+ for (k = 0; k < sizeof(t) / sizeof(t[0]); k++) {
+ /* 1-byte-register parts: reg16 = (reg << 8) | data, len = 0
+ * -> the FX2 packet is [08][dev][02][reg][data], exactly the
+ * vendor's wire format. */
+ uint16_t w = (uint16_t)((t[k].reg << 8) | t[k].val);
+ if (pvr2_i2c_write(p, t[k].dev, w, NULL, 0) < 0)
+ nack++;
+ }
+ fprintf(stderr, "NEC full tables: %u writes to 0x12/0x5c, %d NACK%s\n",
+ (unsigned)(sizeof(t) / sizeof(t[0])), nack,
+ nack ? " <-- check the chips" : "");
+}
+
+static void win_gpio(pvr2_dev *p)
+{
+ /*
+ * ★ 0xc780 was wrong: bit0 must be an OUTPUT. The driver reads
+ * 0x9020 and walks it 0xc400 → 0xc500 → 0xc701 → 0xc780 → **0xc781**
+ * (measured, /ROM/rz2-usb.pcap: 0x9020 reads back those five values),
+ * i.e. the final direction has bit0 set. yacxm uses 0x0000c301 for
+ * its RX board, which also has bit0 as an output. If GPIO0 is a
+ * reset/enable for the audio ADC, leaving it an input (floating) means
+ * the part never comes up.
+ */
+ pvr2_gpio_dir(p, 0xffffffff, 0x0000c781);
+ pvr2_gpio_out(p, 0xffffffff, 0x00000310);
+ fprintf(stderr, "WINGPIO: dir=0xc781 out=0x0310\n");
+}
+
+/*
+ * POSTCAP=1 - the one I2C write the driver performs AFTER START_CAPTURE
+ * and before the stream begins (capture command #1186, immediately after
+ * START_CAPTURE 0x81 [0,19]): device 0x5b, register 0x00 = 0x00.
+ *
+ * 0x5b is the "audio control" chip yacxm addresses as 0xb6 (7-bit 0x5b);
+ * its comment there reads "GV-MVP/RX: audio control of tuner; deletion
+ * causes very small volume of tuner input". The driver sets reg 0 to 0x10
+ * during init and back to 0x00 here, i.e. a 0x10 → 0x00 transition that
+ * lands exactly between START_CAPTURE and the first stream packet.
+ * This tool has never written 0x5b at start time at all.
+ */
+/*
+ * Panasonic VP27s MPX (tuner audio multiplex) at 7-bit I2C 0x5b.
+ *
+ * ★ Identification: yacxm writes the three bytes {0x00, 0x00, 0x04} to the
+ * 8-bit address 0xb6 (= 7-bit 0x5b) with the comment "GV-MVP/RX: audio
+ * control of tuner", and that byte string is EXACTLY what Linux's
+ * vp27smpx.c sends (i2c_master_send of {0x00, mode, 0x04}, mode: 0 =
+ * mono/LANG1, 1 = stereo, 2 = LANG2). So 0x5b is the VP27s MPX, and the
+ * "audio control" register is reg 0x00.
+ *
+ * The Windows driver on this board writes only TWO bytes to 0x5b --
+ * reg 0x00 = 0x10 at init, then reg 0x00 = 0x00 right after START_CAPTURE
+ * (pcap) -- which is the default here (win_i2c / postcap). VPMODE=<mode>
+ * additionally sends the full vp27smpx 3-byte form so the documented audio
+ * mode control can be exercised:
+ * VPMODE=mono | stereo | lang2
+ * The RZ2 has no tuner, so this only matters if the MPX is in the line-in
+ * path; it is harmless either way (write ACK measured).
+ */
+static void vp27s_mode(pvr2_dev *p, const char *mode)
+{
+ uint8_t d = 0x04; /* the trailing byte vp27smpx sends */
+ uint16_t reg;
+ int rc;
+
+ if (!strcmp(mode, "stereo")) reg = 0x0001;
+ else if (!strcmp(mode, "lang2")) reg = 0x0002;
+ else reg = 0x0000; /* mono / LANG1 */
+ /* reg16 = (reg 0x00 << 8) | mode -> the FX2 sends [00][mode][04] */
+ rc = pvr2_i2c_write(p, 0x5b, reg, &d, 1);
+ fprintf(stderr, "VP27s MPX (0x5b): reg0=%s (vp27smpx 3-byte form) "
+ "-> %s\n", mode, rc < 0 ? "NACK" : "ACK");
+}
+
+static void postcap(pvr2_dev *p)
+{
+ uint8_t v = 0x00;
+
+ (void)pvr2_i2c_write(p, 0x5b, 0x0000, &v, 1);
+ fprintf(stderr, "POSTCAP: dev=0x5b reg=0x00 = 0x00 (driver's post-start write)\n");
+}
+
+static void win_mask(pvr2_dev *p)
+{
+ uint32_t v = 0;
+
+ pvr2_write_reg(p, 0x0048, 0xbfffffff);
+ if (pvr2_read_reg(p, 0x0048, &v) == 0)
+ fprintf(stderr, "WINMASK: 0x0048 = %08x\n", v);
+}
+
+/*
+ * ==================================================================
+ * REPLAY=1 - execute the captured Windows-driver sequence VERBATIM.
+ *
+ * Why this exists: every kare experiment env var (AUDIOEARLY, D0UPLOAD,
+ * HR1, POSTCAP, AUDIOBLK, ...) fires at a FIXED point in this file, so
+ * turning them all on does NOT reproduce the driver's order -- it produces
+ * THIS tool's order with extra writes sprinkled in. Ordering has decided
+ * two findings on this project already (0x0115=0x8c and the audio block
+ * writes only worked from the driver's position), so the faithful test is
+ * to replay the captured operations in captured order, with nothing of our
+ * own injected.
+ *
+ * The sequence is generated by scripts/gen_replay.py from
+ * /ROM/rz2-usb.pcap and read from ref/replay_seq.txt. Operations:
+ * SPEED/POWERON/FWPOST1/DEEPRESET/MEMSEL/EEPROMADDR single-byte FX2 cmds
+ * STREAMON/STREAMOFF FX2 0x36/0x37
+ * CMD_D0 <hex> / CMD_D1 the 0xd0/d1 pair
+ * I2CW <dev> <reg> <hex|-> I2C write (dash = none)
+ * REGW <reg> <val> CX23416 register write
+ * ENC <cmd> <6 args> MBOX encoder command
+ * FW_FX2 the 12982-byte 8051 image
+ * FW_BIG the CX23416 image (swab32)
+ * STREAM_START stop; start capturing
+ *
+ * The driver's MBOX handshake (write 0x03, poll for 0x07, clear) is left to
+ * pvr2_enc_cmd(), which reproduces it exactly; the sequence file's `MBOXW`
+ * lines are that handshake and are therefore ignored here.
+ * ==================================================================
+ */
+
+/* Bulk-write a firmware image to EP 0x02 with the CX23416's 32-bit swap,
+ * WITHOUT the prelude pvr2_upload_firmware2() adds (the replay sequence
+ * supplies its own ordering). */
+static int replay_fw_big(pvr2_dev *p, uint8_t *fw, size_t len)
+{
+ const size_t CHUNK = 0x2000;
+ uint8_t *buf;
+ size_t off, len4;
+ int total = 0;
+
+ if (!fw || len < 4)
+ return -1;
+ buf = malloc(CHUNK);
+ if (!buf)
+ return -1;
+ len4 = len & ~(size_t)3;
+ for (off = 0; off < len4; off += CHUNK) {
+ size_t chunk = (len4 - off) < CHUNK ? (len4 - off) : CHUNK;
+ int tr = 0;
+ int r;
+
+ memcpy(buf, fw + off, chunk);
+ pvr2_swap32_buf(buf, chunk / 4);
+ r = libusb_bulk_transfer(p->dev, EP_FW_OUT, buf, (int)chunk,
+ &tr, 5000);
+ if (r != 0 || tr != (int)chunk) {
+ fprintf(stderr, "REPLAY: big firmware chunk at 0x%zx "
+ "failed (r=%d tr=%d)\n", off, r, tr);
+ free(buf);
+ return -1;
+ }
+ total += (int)chunk;
+ }
+ free(buf);
+ fprintf(stderr, "REPLAY: CX23416 image %d bytes\n", total);
+ return 0;
+}
+
+/* Bulk-write the 12982-byte 8051 (FX2) image verbatim - no swap. */
+static int replay_fw_fx2(pvr2_dev *p, const char *path)
+{
+ uint8_t *img = NULL;
+ size_t len = 0;
+ size_t off;
+ int total = 0;
+
+ if (pvr2_load_file(path, &img, &len) < 0) {
+ fprintf(stderr, "REPLAY: cannot load %s\n", path);
+ return -1;
+ }
+ for (off = 0; off < len; off += 4096) {
+ int chunk = (int)((len - off) < 4096 ? (len - off) : 4096);
+ int tr = 0;
+ int r = libusb_bulk_transfer(p->dev, EP_FW_OUT,
+ img + off, chunk, &tr, 5000);
+ if (r != 0 || tr != chunk) {
+ fprintf(stderr, "REPLAY: FX2 image chunk at 0x%zx "
+ "failed (r=%d tr=%d)\n", off, r, tr);
+ free(img);
+ return -1;
+ }
+ total += chunk;
+ }
+ free(img);
+ fprintf(stderr, "REPLAY: FX2 image %d bytes\n", total);
+ return 0;
+}
+
+/* Drain the EP 0x81 response a single-byte FX2 command leaves queued.
+ * The Windows driver does this after every one of them (the capture shows an
+ * EP 0x81 completion per command); skipping it leaves stale data on the
+ * endpoint and the NEXT I2C write's status read then blocks on its timeout. */
+static void drain(pvr2_dev *p)
+{
+ uint8_t tmp[64];
+
+ memset(tmp, 0, sizeof(tmp));
+ (void)pvr2_raw_in(p, EP_CMD_IN, tmp, sizeof(tmp));
+}
+
+static int replay_run(pvr2_dev *p, const char *path,
+ uint8_t *cx_fw, size_t cx_len)
+{
+ FILE *fp = fopen(path, "r");
+ char line[512];
+ int n = 0;
+ int ndiff = 0;
+
+ if (!fp) {
+ fprintf(stderr, "REPLAY: cannot open %s\n", path);
+ return -1;
+ }
+ fprintf(stderr, "REPLAY: executing %s verbatim\n", path);
+ while (fgets(line, sizeof(line), fp)) {
+ char *nl = strchr(line, '\n');
+ unsigned int a, b, c, d, e, f, g;
+ char hex[64];
+ if (nl)
+ *nl = '\0';
+ if (!line[0] || line[0] == '#')
+ continue;
+ if (getenv("REPLAYTRACE")) {
+ fprintf(stderr, " REPLAY[%d] %s\n", n + 1, line);
+ fflush(stderr);
+ }
+
+ if (sscanf(line, "DELAY %u", &a) == 1) {
+ /*
+ * The driver's own inter-operation delay. These are
+ * part of the sequence: it waits 18.4 s after
+ * SET_OUTPUT_PORT, and polls the video-lock register
+ * 0x040e every ~62 ms. REPLAYNODELAY=1 skips them
+ * (to A/B whether the timing is what matters).
+ */
+ if (!getenv("REPLAYNODELAY")) {
+ struct timespec ts;
+ ts.tv_sec = a / 1000;
+ ts.tv_nsec = (long)(a % 1000) * 1000000L;
+ nanosleep(&ts, NULL);
+ }
+ n++;
+ continue;
+ }
+
+ if (!strcmp(line, "SPEED")) {
+ pvr2_simple_cmd(p, FX2CMD_GET_USB_SPEED, NULL, 0);
+ drain(p);
+ } else if (!strcmp(line, "POWERON")) {
+ pvr2_simple_cmd(p, FX2CMD_POWER_ON, NULL, 0);
+ drain(p);
+ } else if (!strcmp(line, "FWPOST1")) {
+ pvr2_simple_cmd(p, FX2CMD_FWPOST1, NULL, 0);
+ drain(p);
+ } else if (!strcmp(line, "DEEPRESET")) {
+ pvr2_simple_cmd(p, FX2CMD_DEEP_RESET, NULL, 0);
+ drain(p);
+ } else if (!strcmp(line, "EEPROMADDR")) {
+ pvr2_simple_cmd(p, FX2CMD_GET_EEPROM_ADDR, NULL, 0);
+ drain(p);
+ } else if (!strcmp(line, "MEMSEL")) {
+ uint8_t z = 0x00;
+ pvr2_simple_cmd(p, FX2CMD_MEMSEL, &z, 1);
+ drain(p);
+ } else if (!strcmp(line, "STREAMON")) {
+ pvr2_simple_cmd(p, FX2CMD_STREAMING_ON, NULL, 0);
+ drain(p);
+ } else if (!strcmp(line, "STREAMOFF")) {
+ pvr2_simple_cmd(p, FX2CMD_STREAMING_OFF, NULL, 0);
+ drain(p);
+ } else if (sscanf(line, "CMD_D0 %60s", hex) == 1) {
+ uint8_t arg[8];
+ int i, ln = (int)(strlen(hex) / 2);
+ for (i = 0; i < ln && i < 8; i++)
+ sscanf(hex + 2 * i, "%2x", &arg[i]);
+ pvr2_simple_cmd(p, 0xd0, arg, ln);
+ drain(p);
+ } else if (!strcmp(line, "CMD_D1")) {
+ pvr2_simple_cmd(p, 0xd1, NULL, 0);
+ drain(p);
+ } else if (sscanf(line, "I2CW %x %x %60s", &a, &b, hex) == 3) {
+ if (!strcmp(hex, "-")) {
+ uint8_t z = 0;
+ pvr2_i2c_write(p, (uint8_t)a, (uint16_t)b,
+ &z, 0);
+ } else {
+ uint8_t d[8];
+ int i, ln = (int)(strlen(hex) / 2);
+ for (i = 0; i < ln && i < 8; i++)
+ sscanf(hex + 2 * i, "%2x", &d[i]);
+ pvr2_i2c_write(p, (uint8_t)a, (uint16_t)b,
+ d, ln);
+ }
+ } else if (sscanf(line, "REGW %x %x", &a, &b) == 2) {
+ pvr2_write_reg(p, (uint16_t)a, (uint32_t)b);
+ } else if (sscanf(line, "REGR %x %60s", &a, hex) == 2) {
+ uint32_t got = 0;
+ if (pvr2_read_reg(p, (uint16_t)a, &got) == 0) {
+ if (strcmp(hex, "?") &&
+ got != (uint32_t)strtoul(hex, NULL, 16)) {
+ fprintf(stderr, " REPLAY-DIFF reg 0x%04x "
+ "expected=%s got=%08x\n",
+ a, hex, got);
+ ndiff++;
+ }
+ }
+ } else if (sscanf(line, "I2CR %x %x %60s", &a, &b, hex) == 3) {
+ uint8_t got = 0;
+ if (pvr2_i2c_read(p, (uint8_t)a, (uint16_t)b, &got, 1) == 0) {
+ if (strcmp(hex, "?") &&
+ got != (uint8_t)strtoul(hex, NULL, 16)) {
+ fprintf(stderr, " REPLAY-DIFF i2c dev=%02x "
+ "reg=0x%04x expected=%s got=%02x\n",
+ a, b, hex, got);
+ ndiff++;
+ }
+ }
+ } else if (sscanf(line, "ENC %x %x %x %x %x %x %x",
+ &a, &b, &c, &d, &e, &f, &g) == 7) {
+ uint32_t ar[6];
+ ar[0] = b; ar[1] = c; ar[2] = d;
+ ar[3] = e; ar[4] = f; ar[5] = g;
+ if (pvr2_enc_cmd(p, a, ar, 6) < 0)
+ fprintf(stderr, "REPLAY: ENC %02x failed\n", a);
+ } else if (!strcmp(line, "FW_FX2")) {
+ if (replay_fw_fx2(p, "ref/d0_upload_12982.bin") < 0)
+ goto fail;
+ } else if (!strcmp(line, "FW_BIG")) {
+ if (replay_fw_big(p, cx_fw, cx_len) < 0)
+ goto fail;
+ } else if (!strcmp(line, "ENCCFG")) {
+ /*
+ * Run THIS tool's full pvr2_encoder_config() at the
+ * captured driver's position: after the 18.4 s wait, the
+ * encoder command table and START_CAPTURE, right before
+ * the stream starts. The replay alone proved that a
+ * byte-exact software sequence still yields zero audio;
+ * this marker re-sends the tool's own encoder setup
+ * (including SET_AUDIO_ID/PROP, unmute, INITIALIZE_INPUT
+ * and MISC(12)) ON TOP of the matched device state, so
+ * "the encoder config block never ran against a
+ * correctly-clocked device" is ruled in or out in one run.
+ */
+ if (pvr2_encoder_config(p, 48000) < 0)
+ fprintf(stderr, "REPLAY: ENCCFG reported errors\n");
+ else
+ fprintf(stderr, "REPLAY: ENCCFG executed "
+ "(tool encoder config after driver seq)\n");
+ } else if (!strcmp(line, "STREAM_START")) {
+ break;
+ } else {
+ fprintf(stderr, "REPLAY: unknown op '%s'\n", line);
+ }
+ n++;
+ }
+ fclose(fp);
+ fprintf(stderr, "REPLAY: %d operations executed, %d read mismatches\n",
+ n, ndiff);
+ return 0;
+fail:
+ fclose(fp);
+ return -1;
+}
+
+/*
+ * ★ REGDUMP=<tag> - read-only snapshot of every register the audio path
+ * depends on (2026-10-23).
+ *
+ * Why: the raw audio DEGRADES between runs on this unit (10-15 kHz loses
+ * ~13 dB, the bass band does not move, and a USB port reset restores it)
+ * while kare's own log and the WM8739 write ACKs are byte-identical run to
+ * run. So the difference is device STATE, and the only way to see it is to
+ * read the state in both conditions and diff the two dumps.
+ *
+ * Nothing in here writes: this is the safe instrument the ledger asks for
+ * before touching any register.
+ *
+ * Ranges, chosen for the audio path:
+ * 0x0100-0x0140 decoder clocks / audio interface (0x103 input select,
+ * 0x115/0x116 serial enables, 0x127 SA_MCLK, 0x12b, 0x131)
+ * 0x0400-0x0420 video/audio routing and status
+ * 0x0800-0x08ff the audio block the XP driver writes 40 times and this
+ * tool never writes
+ * 0x0900-0x0921 audio input / AGC / ADC control
+ * MBOX 0x40-0x5f the encoder's own state (audio props, bitrate, ...)
+ */
+static void reg_dump(pvr2_dev *p, const char *tag)
+{
+ static const struct { uint16_t lo, hi; const char *what; } blk[] = {
+ { 0x0100, 0x0140, "decoder clocks / audio interface" },
+ { 0x0141, 0x01ff, "rest of the 0x01 block" },
+ { 0x0400, 0x0420, "routing + status" },
+ { 0x0421, 0x04ff, "rest of the 0x04 block" },
+ { 0x0800, 0x08ff, "audio block (XP writes this)" },
+ { 0x0900, 0x097f, "audio input / AGC / ADC" },
+ { 0x0a00, 0x0aff, "0x0a block" },
+ { 0x0b00, 0x0bff, "0x0b block" },
+ };
+ size_t b;
+ uint32_t a;
+
+ fprintf(stderr, "REGDUMP %s\n", tag);
+ for (b = 0; b < sizeof(blk) / sizeof(blk[0]); b++) {
+ uint16_t r;
+ fprintf(stderr, "# %s 0x%04x-0x%04x (%s)\n",
+ tag, blk[b].lo, blk[b].hi, blk[b].what);
+ for (r = blk[b].lo; r <= blk[b].hi; r++) {
+ uint8_t v;
+ if ((r & 0xf) == 0)
+ fprintf(stderr, " %04x:", r);
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, r, &v, 1) == 0)
+ fprintf(stderr, " %02x", v);
+ else
+ fprintf(stderr, " --");
+ if ((r & 0xf) == 0xf || r == blk[b].hi)
+ fprintf(stderr, "\n");
+ }
+ }
+ fprintf(stderr, "# %s MBOX 0x40-0x5f (encoder)\n", tag);
+ for (a = 0x40; a <= 0x5f; a++) {
+ uint32_t w = 0;
+ if ((a & 7) == 0)
+ fprintf(stderr, " %02x:", a);
+ if (pvr2_mbox_read(p, a, &w, 1) == 0)
+ fprintf(stderr, " %08x", w);
+ else
+ fprintf(stderr, " --------");
+ if ((a & 7) == 7)
+ fprintf(stderr, "\n");
+ }
+ /*
+ * ★ The 0x0800 and 0x0900 blocks read as all-zero with 1-byte access
+ * on this part (the ledger says so, and it reproduces here). The
+ * Linux cx25840 driver uses 4-byte accesses there, so try that: if a
+ * 4-byte read returns real data, these blocks become inspectable and
+ * they are exactly where the XP driver writes 40 values we never
+ * write.
+ */
+ {
+ uint16_t r;
+ uint8_t w4[4];
+ fprintf(stderr, "# %s WIDE (4-byte reads) 0x0800-0x08ff / 0x0900-0x0920\n",
+ tag);
+ for (r = 0x0800; r <= 0x08fc; r += 4) {
+ if ((r & 0x3c) == 0)
+ fprintf(stderr, " %04x:", r);
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, r, w4, 4) == 0)
+ fprintf(stderr, " %02x%02x%02x%02x",
+ w4[0], w4[1], w4[2], w4[3]);
+ else
+ fprintf(stderr, " --------");
+ if ((r & 0x3c) == 0x3c)
+ fprintf(stderr, "\n");
+ }
+ for (r = 0x0900; r <= 0x0920; r += 4) {
+ if ((r & 0x1c) == 0)
+ fprintf(stderr, " %04x:", r);
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, r, w4, 4) == 0)
+ fprintf(stderr, " %02x%02x%02x%02x",
+ w4[0], w4[1], w4[2], w4[3]);
+ else
+ fprintf(stderr, " --------");
+ if ((r & 0x1c) == 0x1c)
+ fprintf(stderr, "\n");
+ }
+ }
+ /*
+ * ★ CX23416 GPIO - the NJM2750 audio selector's CNT1/CNT2 are driven by
+ * GPIO[8]/[9] (see the audio notes), so a mux that came up on the wrong
+ * input is visible HERE and nowhere else. This is the prime suspect for
+ * "the raw audio sounds wrong but the same programme through the MPEG
+ * path is fine": a different NJM2750 input would explain both a level
+ * change and video-sync crosstalk appearing in the audio.
+ */
+ {
+ static const struct { uint16_t r; const char *n; } gr[] = {
+ { 0x900c, "GPIO_DIR" },
+ { 0x9020, "GPIO_OUT" },
+ { 0x9024, "GPIO_ISM" },
+ { 0x9028, "GPIO_CLR" },
+ };
+ size_t k;
+ fprintf(stderr, "# %s CX23416 GPIO\n", tag);
+ for (k = 0; k < sizeof(gr) / sizeof(gr[0]); k++) {
+ uint32_t v = 0;
+ if (pvr2_read_reg(p, gr[k].r, &v) == 0)
+ fprintf(stderr, " %s (0x%04x) = 0x%08x\n",
+ gr[k].n, gr[k].r, v);
+ else
+ fprintf(stderr, " %s (0x%04x) = read failed\n",
+ gr[k].n, gr[k].r);
+ }
+ }
+ /*
+ * ★ CX23416 audio DSP blocks (2026-10-23). These are CX23416 MEMORY,
+ * not I2C, and they are the last readable place the audio state can
+ * hide: the ledger already uses them to prove the audio encode block is
+ * or is not configured (APU 0xa000 receives configuration, AO 0x2d00
+ * does not). If the raw audio degrades between runs and every CX25837
+ * register and the WM8739 re-write are identical, the difference has to
+ * show here - or it is analogue.
+ */
+ {
+ uint32_t r;
+ int shown = 0;
+ fprintf(stderr, "# %s CX23416 APU 0xa000-0xa07f\n", tag);
+ for (r = 0xa000; r <= 0xa07f; r++) {
+ uint32_t v = 0;
+ if (pvr2_read_reg(p, (uint16_t)r, &v) == 0) {
+ if ((shown++ % 4) == 0)
+ fprintf(stderr, " %04x:", r);
+ fprintf(stderr, " %08x", v);
+ if ((shown % 4) == 0)
+ fprintf(stderr, "\n");
+ }
+ }
+ if (shown % 4)
+ fprintf(stderr, "\n");
+ shown = 0;
+ fprintf(stderr, "# %s CX23416 AO 0x2d00-0x2d3f\n", tag);
+ for (r = 0x2d00; r <= 0x2d3f; r++) {
+ uint32_t v = 0;
+ if (pvr2_read_reg(p, (uint16_t)r, &v) == 0) {
+ if ((shown++ % 4) == 0)
+ fprintf(stderr, " %04x:", r);
+ fprintf(stderr, " %08x", v);
+ if ((shown % 4) == 0)
+ fprintf(stderr, "\n");
+ }
+ }
+ if (shown % 4)
+ fprintf(stderr, "\n");
+ }
+ fflush(stderr);
+}
+
+int main(int argc, char **argv)
+{
+ pvr2_dev *p;
+ uint8_t *cx_fw = NULL, *fx2_fw = NULL;
+ size_t cx_len = 0, fx2_len = 0;
+ const char *out_path = NULL, *cx_path = NULL, *fx2_path = NULL;
+ uint16_t vid = DEFAULT_VID, pid = DEFAULT_PID;
+ int composite = 1; /* default = the yellow RCA. It used to
+ * default to S-Video (0xc3), which is the
+ * OLD composite pin from before the pcap
+ * correction (0xf3 = In4) relabelled: the
+ * S jack has never been plugged in on this
+ * unit, and 0xc3 was measured (2026-10-24)
+ * to show the composite picture anyway. */
+ int coldload = 0;
+
+ int use_driver_tables = 0;
+ int raw_input = -1; /* -I: explicit 0x103 value */
+ int no_codec = 0; /* --no-codec: leave the WM873x alone */
+ int codec_addr = 0x1a;/* --codec ADDR: WM873x 7-bit I2C address
+ * (0x1a = CSB low, the standard value) */
+ int svideo_idx = 0; /* S-Video chroma pin: 0=In5, 1=In6,
+ * 2=In7, 3=In8 (luma is In1 for all
+ * four). Only used with -S/--svideo.
+ * ★ MEASURED 2026-10-25 with a recorder
+ * in the S jack: luma In1 + chroma In5 =
+ * 0x103=0xd0 is the S jack; the old table
+ * (luma In4, 0xc3 first) was never measured
+ * with anything plugged in and shows black.
+ * The RCA is In2+In6 = 0xe1. */
+ int sample_rate = 48000;
+ int japan_audio = 1; /* this device is a JP model (EIAJ) */
+ (void)japan_audio;
+ int do_scan = 0, do_probe = 0, verbose = 0;
+ int replay_done = 0; /* REPLAY=1 already ran the driver's sequence */
+ int limit_sec = 0;
+ int i;
+ int ret = 0;
+ struct timespec t0;
+
+ p = calloc(1, sizeof(*p));
+ if (!p)
+ return 1;
+
+ for (i = 1; i < argc; i++) {
+ const char *a = argv[i];
+ if (!strcmp(a, "-o") && i + 1 < argc) out_path = argv[++i];
+ else if (!strcmp(a, "-c") && i + 1 < argc) cx_path = argv[++i];
+ else if (!strcmp(a, "-f") && i + 1 < argc) fx2_path = argv[++i];
+ else if (!strcmp(a, "-v") && i + 1 < argc) {
+ unsigned int v, d;
+ if (sscanf(argv[++i], "%x:%x", &v, &d) == 2) {
+ vid = (uint16_t)v; pid = (uint16_t)d;
+ }
+ }
+ else if (!strcmp(a, "-t") && i + 1 < argc) limit_sec = atoi(argv[++i]);
+ else if (!strcmp(a, "-C")) composite = 1;
+ else if (!strcmp(a, "-S")) {
+ /* -S <n>: S-Video chroma input (0=In4 .. 4=In8).
+ * Also switches to S-Video mode. */
+ if (i + 1 < argc) { svideo_idx = atoi(argv[++i]); composite = 0; }
+ }
+ else if (!strcmp(a, "--svideo") || !strcmp(a, "--S-Video")) composite = 0;
+ else if (!strcmp(a, "--composite")) composite = 1;
+ else if (!strcmp(a, "--mpeg")) raw_mode = 0; /* MPEG-2 PS (default) */
+ else if (!strcmp(a, "--hm12")) raw_mode = 1; /* raw YUV (HM12) */
+ else if (!strcmp(a, "--pcmfd") && i + 1 < argc) {
+ pcm_fd = atoi(argv[++i]); /* PCM to an open fd (raw) */
+ }
+ else if (!strcmp(a, "--pcm") && i + 1 < argc) {
+ pcm_path = argv[++i]; /* audio-only, see pcm_open() */
+ raw_mode = 1;
+ }
+ else if (!strcmp(a, "-J")) japan_audio = 1;
+ else if (!strcmp(a, "-U")) japan_audio = 0;
+ else if (!strcmp(a, "-3")) sample_rate = 32000;
+ else if (!strcmp(a, "-4")) sample_rate = 44100;
+ else if (!strcmp(a, "-8")) sample_rate = 48000;
+ else if (!strcmp(a, "-s")) do_scan = 1;
+ else if (!strcmp(a, "-p")) do_probe = 1;
+ else if (!strcmp(a, "-d")) verbose = 1;
+ else if (!strcmp(a, "-D")) { /* handled later */ }
+ else if (!strcmp(a, "-T")) use_driver_tables = 1;
+ else if (!strcmp(a, "-I") && i + 1 < argc) raw_input = (int)strtol(argv[++i], NULL, 0);
+ else if (!strcmp(a, "--live") && i + 1 < argc) {
+ live_mode = 1;
+ snprintf(live_path, sizeof(live_path), "%s", argv[++i]);
+ }
+ else if (!strcmp(a, "-P") && i + 1 < argc)
+ player_user = argv[++i];
+ else if (!strcmp(a, "-W") && i + 1 < argc) {
+ /* -W USER : start VLC as USER, once, over a real pipe.
+ * No restart loop, no FIFO, no file - so no lag. */
+ player_user = argv[++i];
+ auto_player = 1;
+ }
+ else if (!strcmp(a, "-V") && i + 1 < argc)
+ vsync_lines = (int)strtol(argv[++i], NULL, 0);
+ else if (!strcmp(a, "-Y")) raw_timing = 1;
+ else if (!strcmp(a, "-N")) hm12_filter = 0; /* no luma filter (A/B) */
+ else if (!strcmp(a, "-L") && i + 1 < argc)
+ luma_path = argv[++i];
+ else if (!strcmp(a, "-R") && i + 1 < argc)
+ raw_hm12_path = argv[++i];
+ else if (!strcmp(a, "-F") && i + 1 < argc) {
+ char c = argv[++i][0];
+ hm12_interlace = (c == 't' || c == 'T') ? 1 :
+ (c == 'b' || c == 'B') ? 2 : 0;
+ }
+ else if (!strcmp(a, "--vstep") && i + 1 < argc)
+ hm12_vstep = atoi(argv[++i]);
+ else if ((!strcmp(a, "--planes") || !strcmp(a, "-B")) && i + 1 < argc)
+ planes_prefix = argv[++i];
+ else if (!strcmp(a, "-A") && i + 1 < argc)
+ raw_drop_sec = atof(argv[++i]);
+ else if (!strcmp(a, "--no-codec")) no_codec = 1;
+ else if (!strcmp(a, "--codec") && i + 1 < argc)
+ codec_addr = (int)strtol(argv[++i], NULL, 0);
+ else if (!strcmp(a, "-r") || !strcmp(a, "--raw")) raw_mode = 1;
+ else if (!strcmp(a, "-h") || !strcmp(a, "--help")) { usage(argv[0]); goto out_free; }
+ else {
+ fprintf(stderr, "unknown option: %s\n", a);
+ usage(argv[0]);
+ ret = 1;
+ goto out_free;
+ }
+ }
+
+ /*
+ * -L (luma), -B (plane dumps) and -R (raw HM12 dump) are all fed by
+ * the HM12 frame writer, which only runs in raw mode. Asking for one
+ * of them without -r used to produce no output at all -- a 0-byte
+ * live file with MODE=luma. Make the intent explicit instead.
+ */
+ if (luma_path || planes_prefix || raw_hm12_path)
+ raw_mode = 1;
+
+ if (pvr2_init(p) < 0) {
+ ret = 1;
+ goto out_free;
+ }
+ p->verbose = verbose;
+ g_dev = p; /* for the CTLFILE live-control commands */
+ ctl_open();
+ if (getenv("SPLITAV"))
+ split_av = 1;
+ if ((pcm_path || pcm_fd >= 0) && pcm_open(pcm_path ? pcm_path : "fd") < 0) {
+ ret = 1;
+ goto outexit;
+ }
+
+ if (do_scan) {
+ pvr2_scan(p);
+ goto outexit;
+ }
+
+ if (!cx_path && !do_probe) {
+ fprintf(stderr, "error: -c <cx firmware> is required\n");
+ usage(argv[0]);
+ ret = 1;
+ goto outexit;
+ }
+ if (!out_path && !do_probe) {
+ fprintf(stderr, "error: -o <output> is required\n");
+ usage(argv[0]);
+ ret = 1;
+ goto outexit;
+ }
+
+ /*
+ * A unit whose own FX2 code came up from EEPROM enumerates as
+ * 04b4:8613 and stays there - the FX2 code is the CX23416 loader,
+ * and it holds that ID until the CX23416 image is pushed. That is
+ * the state this unit was in before any of this started, and it is
+ * recoverable: open 04b4:8613, skip the FX2 upload entirely, and go
+ * straight to the CX23416 load. COLDLOAD=1 asks for that.
+ */
+ /*
+ * EPDIAG: which endpoint is refusing what. The CX23416 load fails at
+ * offset 0 with -99, which is a stall on EP 0x01 rather than a dead
+ * device - the unit is back at 04b4:8613 with six endpoints, so the
+ * FX2 is running. A stall means the loader present does not
+ * implement the command being sent, so it is worth finding out which
+ * commands answer before assuming anything about the encoder.
+ */
+ /*
+ * FX2RESET: force the FX2's 8051 back to life without uploading
+ * anything. The unit is sitting at 04b4:8613 with its six
+ * endpoints present, but every command returns IO error - the USB
+ * engine enumerates in hardware while the CPU is stopped, so
+ * EP 0x81 never answers. That is what an earlier run leaves behind
+ * if the CPUCS release did not take: the CPU stays halted across a
+ * warm reset because the reset request never went through.
+ *
+ * CPUCS is 0xE600. Asserting then releasing it with no data stage
+ * is a plain CPU reset, so this touches nothing persistent.
+ */
+ /*
+ * FX2BOOT: interrogate the FX2's boot configuration. The chip
+ * answers vendor requests from its own ROM before any 8051 code is
+ * running, which is the only thing still responding here. AN17 low
+ * makes it read EEPROM; the 0xA0/0xA1 pair is the Cypress download
+ * path and 0xA2 is the EEPROM write path - if EEPROM is intact, the
+ * ROM's own GET_EEPROM should answer.
+ */
+ /*
+ * CLMDET: the CX23416 load fails with -99, which is a stall on EP 0x01
+ * rather than a dead unit. Report the interface and endpoint state
+ * before sending anything, so a refusal can be told apart from a
+ * device that is simply not there.
+ */
+ /*
+ * CLMDET: the CX23416 load fails with -99, a stall on EP 0x01 rather
+ * than a dead unit. Report the interface and its endpoints before
+ * sending anything, so a refusal can be told apart from an absence.
+ */
+ if (getenv("CLMDET")) {
+ const struct libusb_config_descriptor *cfg = NULL;
+ int ep;
+ fprintf(stderr, "CLMDET: kernel driver active = %d\n",
+ libusb_kernel_driver_active(p->dev, 0));
+ if (libusb_get_active_config_descriptor(p->dev, &cfg) == 0 &&
+ cfg != NULL && cfg->bNumInterfaces > 0) {
+ const struct libusb_interface_descriptor *ifd =
+ &cfg->interface[0].altsetting[0];
+ fprintf(stderr,
+ "CLMDET: iface %d alt %d endpoints %d\n",
+ ifd->bInterfaceNumber, ifd->bAlternateSetting,
+ ifd->bNumEndpoints);
+ for (ep = 0; ep < ifd->bNumEndpoints; ep++) {
+ const struct libusb_endpoint_descriptor *e =
+ &ifd->endpoint[ep];
+ fprintf(stderr, " ep 0x%02x %s %s\n",
+ e->bEndpointAddress,
+ (e->bmAttributes & 3) == 2 ? "bulk" : "?",
+ (e->bEndpointAddress & 0x80) ? "IN" : "OUT");
+ }
+ }
+ }
+
+ if (getenv("FX2BOOT")) {
+ static const struct { uint8_t req; uint16_t val; } probe[] = {
+ { 0xa0, 0xe600 }, /* CPUCS: read state */
+ { 0xaf, 0x0000 }, /* Cypress "get chip info" */
+ { 0xa2, 0x0000 }, /* EEPROM write path: read status */
+ { 0xa9, 0x0000 }, /* alternate info request */
+ { 0xac, 0x0000 },
+ { 0xad, 0x0000 },
+ };
+ size_t i;
+ for (i = 0; i < sizeof(probe)/sizeof(probe[0]); i++) {
+ uint8_t b[8] = { 0 };
+ int r = libusb_control_transfer(p->dev, 0xc0,
+ probe[i].req,
+ probe[i].val, 0, b,
+ sizeof(b), 1000);
+ fprintf(stderr, "FX2BOOT 0x%02x/0x%04x: r=%d (%s)",
+ probe[i].req, probe[i].val, r,
+ libusb_error_name(r));
+ if (r > 0) {
+ int k;
+ fprintf(stderr, " data:");
+ for (k = 0; k < r; k++)
+ fprintf(stderr, " %02x", b[k]);
+ }
+ fprintf(stderr, "\n");
+ }
+ }
+
+ if (getenv("FX2RESET")) {
+ uint8_t one = 1, zero = 0;
+ int ra, rb;
+ ra = libusb_control_transfer(p->dev, 0x40, 0xA0, 0xE600, 0,
+ &one, 1, 1000);
+ fprintf(stderr, "FX2RESET: assert CPUCS r=%d\n", ra);
+ {
+ struct timespec ts = { 0, 200000000 };
+ nanosleep(&ts, NULL);
+ }
+ rb = libusb_control_transfer(p->dev, 0x40, 0xA0, 0xE600, 0,
+ &zero, 1, 1000);
+ fprintf(stderr, "FX2RESET: release CPUCS r=%d\n", rb);
+ }
+
+ if (getenv("EPDIAG")) {
+ static const uint8_t cmds[] = { 0x0b, 0xeb, 0xde, 0xdd, 0x52, 0x06 };
+ size_t ci;
+ for (ci = 0; ci < sizeof(cmds); ci++) {
+ uint8_t s[16];
+ int r = pvr2_simple_cmd(p, cmds[ci], NULL, 0);
+ int n = pvr2_raw_in(p, EP_CMD_IN, s, sizeof(s));
+ fprintf(stderr,
+ "EPDIAG cmd 0x%02x: r=%d (%s) in n=%d (%s)%s\n",
+ cmds[ci], r, libusb_error_name(r), n,
+ libusb_error_name(n),
+ (n > 0) ? (sprintf(s, " val=0x%02x", s[0]), s) : "");
+ }
+ }
+
+ /*
+ * EPCHK: work out whether the FX2 is alive at all. If the loader in
+ * its own EEPROM is responding, the vendor requests answer and the
+ * bulk endpoints are present; if it is not, they will fail the same
+ * way the CX23416 load does. This tells "the loader is wedged" apart
+ * from "the encoder is wedged", which are different faults with
+ * different fixes.
+ */
+ if (getenv("EPCHK")) {
+ uint8_t b[64];
+ int i;
+ {
+ uint8_t s[16];
+ int r = pvr2_simple_cmd(p, 0x0b, NULL, 0);
+ int n = pvr2_raw_in(p, EP_CMD_IN, s, sizeof(s));
+ fprintf(stderr,
+ "EPCHK 0x0b (USB speed): r=%d n=%d val=0x%02x\n",
+ r, n, (n > 0) ? s[0] : 0);
+ r = pvr2_simple_cmd(p, 0xeb, NULL, 0);
+ n = pvr2_raw_in(p, EP_CMD_IN, s, sizeof(s));
+ fprintf(stderr,
+ "EPCHK 0xeb (EEPROM addr): r=%d n=%d val=0x%02x\n",
+ r, n, (n > 0) ? s[0] : 0);
+ }
+ for (i = 0; i < 4; i++) {
+ int n = pvr2_raw_in(p, EP_VIDEO_IN, b, 32);
+ fprintf(stderr, "EPCHK bulk 0x84: n=%d\n", n);
+ if (n <= 0)
+ break;
+ }
+ fprintf(stderr, "EPCHK done\n");
+ }
+
+ if (getenv("COLDLOAD")) {
+ if (pvr2_find_device(p, 0x04b4, 0x8613) == 0) {
+ fprintf(stderr,
+ "COLDLOAD: opened 04b4:8613, skipping the FX2 "
+ "upload and loading the CX23416 image\n");
+ coldload = 1;
+ } else {
+ fprintf(stderr, "COLDLOAD: 04b4:8613 not present\n");
+ }
+ }
+ if (!coldload && pvr2_find_device(p, vid, pid) < 0) {
+ /*
+ * No fallback to 04b4:8613 here. That ID is what the FX2
+ * shows mid-reset, and a unit in that state cannot be driven
+ * by anything kare does: there is no command table behind
+ * it. NOTES.md has said since the first capture that this is
+ * a warm unit whose firmware comes out of its own EEPROM, and
+ * that a failed load leaves the CX23416 wedged until the USB
+ * is unplugged for ten seconds. If the device is not at
+ * 04bb:0514, the fix is a power cycle, not a different ID.
+ */
+ fprintf(stderr,
+ "device 04bb:0514 not found.\n"
+ " If the unit is enumerating as 04b4:8613 the encoder is\n"
+ " wedged from a previous load: unplug power AND usb, wait\n"
+ " 10s, power up, then replug usb.\n");
+ fprintf(stderr, "device %04x:%04x not found. Is it connected and "
+ "does libusb have access to it?\n", vid, pid);
+ pvr2_scan(p);
+ ret = 1;
+ goto outexit;
+ }
+
+ /*
+ * WARNING: do not pass -f on a unit that is already enumerated.
+ *
+ * This was learned the hard way. The unit enumerates as
+ * 04bb:0514 / "Conexant I-O DATA GV-MVP/RZ2" (the INF's real ID is
+ * 0547:1002) once its own firmware is resident, and it works from
+ * there with nothing but -c. Uploading the FX2 image over the top
+ * resets the device out of that state, the CX23416 upload that has
+ * to follow then times out at offset 0, and the unit is left
+ * enumerating as 04b4:8613 - the Cypress default - with only half
+ * the firmware in place. Recovering needs a full power cycle.
+ *
+ * So -f is for a unit that only ever shows 04b4:8613, and never as a
+ * reflex when something else is going wrong. FX2WARN=1 prints this
+ * and refuses.
+ */
+ if (getenv("FX2WARN") && fx2_path)
+ fprintf(stderr,
+ "refusing -f: this unit is already enumerated, and "
+ "uploading the FX2 image over a live device loses its "
+ "firmware. power-cycle it if you truly mean to.\n");
+
+ /*
+ * This is a warm unit: its FX2 code comes out of its own EEPROM and
+ * the CX23416 image is pushed every run with -c. -f is disabled
+ * outright. Pushing the FX2 image at a live device resets it to
+ * 04b4:8613, and because nothing on this platform can drive a device
+ * in that state, the CX23416 load that has to follow times out and
+ * the unit is left needing a power cycle. NOTES.md has carried this
+ * warning since the first capture and it was ignored.
+ */
+ if (fx2_path && !getenv("FORCE_FX2")) {
+ fprintf(stderr,
+ "-f is disabled by default: this unit loads its own FX2 "
+ "firmware from EEPROM, and pushing one at a live device "
+ "wedges the encoder until it is power-cycled.\n"
+ " FORCE_FX2=1 overrides this.\n");
+ ret = 1;
+ goto outexit;
+ }
+ if (fx2_path) {
+ if (pvr2_load_file(fx2_path, &fx2_fw, &fx2_len) < 0) {
+ ret = 1;
+ goto outexit;
+ }
+ if (pvr2_upload_fx2(p, fx2_fw, fx2_len) < 0) {
+ ret = 1;
+ goto outexit;
+ }
+ /* Device re-enumerates: wait, then reopen */
+ pvr2_exit(p);
+ {
+#if defined(_WIN32)
+ Sleep(2000);
+#else
+ struct timespec ts = { 2, 0 };
+ nanosleep(&ts, NULL);
+#endif
+ }
+ pvr2_init(p);
+ if (pvr2_find_device(p, vid, pid) < 0) {
+ /*
+ * The FX2 image alone does not turn the unit into
+ * 04bb:0514; on a cold unit it re-enumerates as
+ * 04b4:8613 with the loader now resident, and the
+ * real ID only appears once the CX23416 firmware
+ * has been pushed to it. So accept the cold ID here
+ * and carry on - the firmware2 upload below is what
+ * completes the sequence.
+ */
+ if (pvr2_find_device(p, 0x04b4, 0x8613) == 0)
+ fprintf(stderr,
+ "re-enumerated as 04b4:8613; "
+ "continuing to CX23416 firmware\n");
+ else {
+ fprintf(stderr,
+ "device did not re-appear after FX2 load\n");
+ ret = 1;
+ goto outexit;
+ }
+ }
+ }
+
+ /* Load CX23416 firmware.
+ * IMPORTANT: the encoder-resume (0xde) and USB-speed/EEPROM
+ * handshake must happen at the very start of the firmware2 upload,
+ * so we do NOT issue any FX2 command before this point. */
+ if (pvr2_load_file(cx_path, &cx_fw, &cx_len) < 0) {
+ ret = 1;
+ goto outexit;
+ }
+ if (getenv("REPLAY")) {
+ /*
+ * REPLAY=1: do NOT use pvr2_upload_firmware2 (it injects its
+ * own prelude and ordering). Execute the captured sequence
+ * literally, which includes the firmware transfers, the
+ * encoder commands and START_CAPTURE.
+ */
+ const char *rp = getenv("REPLAYFILE");
+ if (!rp)
+ rp = "ref/replay_seq.txt";
+ if (replay_run(p, rp, cx_fw, cx_len) < 0) {
+ ret = 1;
+ goto outexit;
+ }
+ replay_done = 1;
+ } else if (pvr2_upload_firmware2(p, cx_fw, cx_len) < 0) {
+ ret = 1;
+ goto outexit;
+ }
+
+ /*
+ * AUDORDER=1 writes the audio-enable registers here, right after the
+ * firmware upload and before the encoder is configured.
+ *
+ * The USB capture of the Windows driver shows the order is:
+ * 0x0b (USB speed) -> 0xde00 (encoder resume)
+ * -> I2C 0x0115=0x8c, 0x0116=0x07, 0x0118=0x02
+ * -> 0x0c block writes (video + PLL + audio)
+ * -> firmware image
+ * -> capture start
+ * i.e. those three registers are set BEFORE the firmware image goes
+ * down, while this tool writes 0x0115/0x0116 after START_CAPTURE.
+ * Writing 0x0115=0x8c late wedges the stream (measured: 0 bytes), so
+ * the position matters and this is the earliest point that is still
+ * after the 0x0b/0xde handshake the firmware loader needs.
+ */
+ if (getenv("AUDORDER")) {
+ uint8_t a15 = 0x8c, a16 = 0x07, a18 = 0x02;
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0115, &a15, 1);
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0116, &a16, 1);
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0118, &a18, 1);
+ fprintf(stderr, "AUDORDER: 0x0115=0x8c 0x0116=0x07 0x0118=0x02 "
+ "(before encoder config)\n");
+ }
+
+ /* USB speed sanity check (warm device should be High Speed = 0x80) */
+ {
+ int spd = pvr2_get_usb_speed(p);
+ if (spd >= 0 && verbose)
+ fprintf(stderr, "USB speed byte: 0x%02x\n", spd);
+ if (spd >= 0 && spd != 0x80)
+ fprintf(stderr, "warning: device not in high-speed mode\n");
+ }
+
+ /* Probe */
+ if (pvr2_enc_ping(p) < 0) {
+ fprintf(stderr, "encoder PING (0x80) failed: firmware not running\n");
+ ret = 1;
+ goto outexit;
+ }
+ fprintf(stderr, "encoder alive (PING ok)\n");
+ {
+ uint32_t ver = 0;
+ if (pvr2_enc_get_version(p, &ver) == 0)
+ fprintf(stderr, "CX23416 firmware version %u.%u.%u\n",
+ (ver >> 24) & 0xff, (ver >> 16) & 0xff, ver & 0xffff);
+ else
+ fprintf(stderr, "GET_VERSION failed\n");
+ }
+
+ if (do_probe) {
+ fprintf(stderr, "probe done\n");
+ goto outexit;
+ }
+
+ /*
+ * CX25837 bring-up hooks -- run HERE, before any encoder/decoder
+ * config, because that is the order the Windows driver uses: the
+ * 308-entry table is its cold-boot decoder init, and everything
+ * else (input mux 0x103, serial enables 0x115/0x116, DLL start)
+ * layers on top of it. Applying the table later let it clobber
+ * the already-set mux (0x103 0xf3 -> 0x00) and produced a
+ * zero-byte stream on 2026-10-04.
+ *
+ * SERINIT : read-only compare of the 308-entry table (1 byte/reg;
+ * the CX25837 I2C is 1 byte wide with auto-increment,
+ * so u32 reads only produce shifted false DIFFs).
+ * SERAPPLY=1 : write the table (expanded to 1232 byte writes).
+ *
+ * SERTEST / SERAPPLY2 : the narrow 0x0400-0x040f slice.
+ * PLLTEST / PLLAPPLY : the 0x0130-0x014f clock/PLL slice.
+ *
+ * The table does NOT contain the 0x08xx/0x09xx audio-DSP registers
+ * (Linux is_cx2583x() skips them; a 0x0900 write killed video here).
+ */
+ if (getenv("SERINIT") || getenv("SERAPPLY")) {
+ int apply = getenv("SERAPPLY") != NULL;
+ fprintf(stderr, "SERINIT: %s (308 entries from p2usbRZ2.sys .data+0039a0)\n",
+ apply ? "WRITING to CX25837" : "read-only compare");
+ pvr2_cx25837_ser_init(p, apply);
+ }
+
+ /*
+ * RATETAB=1 : the p2usbRZ2.sys set_sample_rate slice
+ * (pvr2_cx2584x_audio_config: rate PLL 0x0108-0x0113, audio PLL
+ * 0x0900-0x0903, fractional words 0x0128-0x012e, DSP start).
+ * Windows applies this RIGHT AFTER the 308-entry table and its
+ * video survives -- the 0x0900 "poison" finding came from applying
+ * it on top of the minimal reference init instead. NO90X=1
+ * skips the four 0x0900-0x0903 writes to bisect if the picture
+ * dies again.
+ */
+ if (getenv("RATETAB")) {
+ int mask = 0;
+ if (getenv("NO90X")) mask |= AUD_SKIP_90X;
+ if (getenv("NOPLL")) mask |= AUD_SKIP_PLL;
+ if (getenv("NOFRAC")) mask |= AUD_SKIP_FRAC;
+ if (pvr2_cx2584x_audio_config_opt(p, sample_rate, mask) < 0)
+ fprintf(stderr, "warning: RATETAB reported errors\n");
+ else
+ fprintf(stderr, "RATETAB: rate table applied (skipmask=%d)%s\n",
+ mask, mask ? "" : " (full)");
+ }
+ if (getenv("SERTEST") || getenv("SERAPPLY2")) {
+ int apply = getenv("SERAPPLY2") != NULL;
+ pvr2_cx25837_ser_test(p, apply);
+ }
+ if (getenv("PLLTEST") || getenv("PLLAPPLY")) {
+ int apply = getenv("PLLAPPLY") != NULL;
+ pvr2_cx25837_pll_test(p, apply);
+ }
+
+ /* Choose encoder config: -D uses the official driver's sequence. */
+ int use_driver_seq = 0;
+ for (i = 1; i < argc; i++)
+ if (!strcmp(argv[i], "-D")) use_driver_seq = 1;
+
+ /* Configure encoder + decoder and start capture */
+ /* Encoder interrupt mask - only with -T (the plain reference
+ * sequence leaves it alone and captures cleanly). */
+ if (use_driver_tables)
+ pvr2_write_reg(p, CX_REG_INTR_MASK, 0xbfffffff);
+
+ /*
+ * CX2584x decoder bring-up. This was defined but never called, so
+ * the decoder had been running on whatever state it powers up in:
+ * only 0x103 (input select) and 0x115/0x116 were programmed, and the
+ * internal DLL that drives the video/audio clock tree was never
+ * started. An under-clocked decoder is a plausible cause of
+ * per-line horizontal jitter, which is what the "2-pixel pairing"
+ * measurement picks up.
+ *
+ * Off by default because it was never exercised on this hardware.
+ * CXINIT=1 runs the DLL start-up only; CXINIT=2 also applies the
+ * NTSC video mode and audio carrier (pvr2_cx2584x_input_change),
+ * which also touches the audio registers - hence the two levels.
+ */
+ {
+ const char *cxinit = getenv("CXINIT");
+ if (cxinit) {
+ int level = atoi(cxinit);
+ fprintf(stderr, "CXINIT=%d: running CX2584x decoder "
+ "bring-up\n", level);
+ if (pvr2_cx2584x_init(p) < 0)
+ fprintf(stderr, " cx2584x_init reported an "
+ "error\n");
+ else
+ fprintf(stderr, " cx2584x_init ok (DLL "
+ "started)\n");
+ if (level >= 2) {
+ if (pvr2_cx2584x_input_change(p,
+ japan_audio) < 0)
+ fprintf(stderr, " cx2584x_input_change "
+ "reported an error\n");
+ else
+ fprintf(stderr, " cx2584x_input_change ok"
+ " (NTSC mode + audio carrier)\n");
+ }
+ }
+ }
+
+ if (pvr2_encoder_preconfig(p) < 0)
+ fprintf(stderr, "warning: preconfig reported errors\n");
+
+ /*
+ * AUDIOINIT=1 runs pvr2_audio_init() BEFORE the encoder starts.
+ * Normally it is only called with -T, and after the encoder is
+ * running, because writing the Aux PLL (0x0108/0x0110/0x0127) then
+ * was found to break capture. Doing it first gives the PLL a
+ * chance to settle before the encoder locks onto it, which is the
+ * other half of the "no audio PES" problem.
+ */
+ if (getenv("AUDIOINIT")) {
+ if (pvr2_audio_init(p, sample_rate) < 0)
+ fprintf(stderr, "warning: AUDIOINIT audio_init failed\n");
+ else
+ fprintf(stderr, "AUDIOINIT: audio PLL configured before "
+ "encoder start\n");
+ }
+ /*
+ * ADCTAB=1 applies only the audio-ADC block (0x0914/0x0918 = 0xa0 to
+ * bring the ADC up, 0x0808 for the carrier standard). The full
+ * table write is known to destroy the picture, so the audio half is
+ * applied on its own; without this the ADC is never enabled and the
+ * encoder has no audio to multiplex no matter what the serial-path
+ * bits say.
+ */
+ /*
+ * SEREARLY=1 : apply the full p2usbRZ2 decoder table BEFORE the
+ * encoder is configured/started. The table contains 0x0109=0x04
+ * (audio clock source switch); written while a capture session is
+ * already up it wedges that session (measured 2026-10-04: a single
+ * byte write to 0x109 kills the stream even when the value is
+ * unchanged), yet the register state persists and every LATER run
+ * works with it. Windows applies this table at driver load, i.e.
+ * before any encoder session exists - replicate that order here.
+ * SERFROM/SERTO range filters also apply.
+ */
+ if (getenv("SEREARLY")) {
+ fprintf(stderr, "SEREARLY: applying CX25837 table before "
+ "encoder config\n");
+ pvr2_cx25837_ser_init(p, 1);
+ /* The table's 0x0109 write (audio clock source switch)
+ * glitches SA_MCLK and wedges the CX23416 session no
+ * matter WHEN it happens (measured: even applied before
+ * the encoder config the session stays dead). Windows
+ * applies this table at driver load and then brings the
+ * CX23416 up - so do the same: full firmware re-upload
+ * on top of the new decoder clock state. */
+ fprintf(stderr, "SEREARLY: re-uploading CX23416 firmware "
+ "on top of the new clock state\n");
+ if (pvr2_upload_firmware2(p, cx_fw, cx_len) < 0)
+ fprintf(stderr, "SEREARLY: firmware re-upload FAILED\n");
+ }
+ if (getenv("AUDDSP")) {
+ if (pvr2_cx2584x_write_audio_dsp(p, japan_audio) < 0)
+ fprintf(stderr, "warning: AUDDSP failed\n");
+ else
+ fprintf(stderr, "AUDDSP: audio DSP block 0x0808-0x081f "
+ "applied\n");
+ }
+ if (getenv("ADCTAB")) {
+ if (pvr2_cx2584x_write_audio_table(p, japan_audio) < 0)
+ fprintf(stderr, "warning: ADCTAB audio table failed\n");
+ else
+ fprintf(stderr, "ADCTAB: audio ADC block applied "
+ "(0x0914/0x0918=0xa0, 0x0808=0x%02x)\n",
+ japan_audio ? 0xf7 : 0xf6);
+ }
+ /*
+ * V808=<hex> overrides register 0x0808. The driver's capture shows
+ * 0x0808 = 0xf6 during setup but 0x0808 = 0x00 immediately before
+ * START_CAPTURE (capture #1104), and this tool has always left it at
+ * 0xf6. 0x0808 is in the audio-DSP block that is otherwise
+ * unreachable, so a wrong value there is a prime suspect.
+ */
+ if (getenv("V808")) {
+ uint8_t v = (uint8_t)strtoul(getenv("V808"), NULL, 0);
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0808, &v, 1);
+ fprintf(stderr, "V808: 0x0808 = 0x%02x\n", v);
+ }
+ /*
+ * V810=<hex> writes 0x0810, which the driver toggles around the
+ * audio block writes (0x01 before, 0x00 after).
+ */
+ if (getenv("V810")) {
+ uint8_t v = (uint8_t)strtoul(getenv("V810"), NULL, 0);
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0810, &v, 1);
+ fprintf(stderr, "V810: 0x0810 = 0x%02x\n", v);
+ }
+ /*
+ * HR1=1 - Host Register 1 (0x0000), the one register in the driver's
+ * 0x44 sequence this tool never writes. The driver does a
+ * read-modify-write pair around the audio setup (capture #51-57):
+ * read 0x0000 -> 0x04
+ * write 0x0000 = 0x24 (bit5 AUTO_INC_DIS | bit2 REF_CLK_SEL)
+ * ... 0xd0 / FX2 image / 0xd1 ...
+ * write 0x0000 = 0x04 (AUTO_INC_DIS cleared again)
+ * The datasheet's default IS 0x04 (bit2 REF_CLK_SEL = 1, differential
+ * crystal input), so the pair only ever toggles bit5. Added because it
+ * is the last un-reproduced write; bit4/bit3 in the same register power
+ * down the AUX and video PLLs, so the register is worth watching.
+ * HR1A / HR1B override the two values.
+ */
+ if (getenv("HR1")) {
+ uint8_t a = 0x24, b = 0x04;
+ const char *e;
+
+ if ((e = getenv("HR1A")) != NULL)
+ a = (uint8_t)strtoul(e, NULL, 0);
+ if ((e = getenv("HR1B")) != NULL)
+ b = (uint8_t)strtoul(e, NULL, 0);
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0000, &a, 1);
+ fprintf(stderr, "HR1: 0x0000 = 0x%02x (then 0x%02x after the "
+ "0xd0/d1 image)\n", a, b);
+ }
+ /*
+ * A0800=1 sends the registers the Windows driver writes during its
+ * decoder init that this tool has never sent at all (capture #49-58):
+ * 0x0808=0xf6 0x0803=0x0b 0x0800=0x00
+ * 0x0801=0x00 0x0803=0x13
+ * The whole 0x0800-0x09ff block was written off early in this project as
+ * "not present, reads return 0x00" -- which is the same mistake that was
+ * made with the WM8739 (a write-only part whose read NACK says nothing
+ * about its presence). This driver writes 0x0800/0x0801/0x0803 on every
+ * single setup, so at minimum they are not "absent" to the vendor.
+ */
+ if (getenv("A0800")) {
+ static const uint16_t r[] = {
+ 0x0808, 0x0803, 0x0800, 0x0801, 0x0803
+ };
+ static const uint8_t v[] = {
+ 0xf6, 0x0b, 0x00, 0x00, 0x13
+ };
+ size_t k;
+ for (k = 0; k < sizeof(r) / sizeof(r[0]); k++)
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, r[k], &v[k], 1);
+ fprintf(stderr, "A0800: 0x0808=f6 0x0803=0b 0x0800=00 "
+ "0x0801=00 0x0803=13\n");
+ }
+ /*
+ * AUDIOBLK=1 replays the audio register programming the way the
+ * official Windows driver actually sends it: as ONE
+ * FX2CMD_I2C_WRITE_BLOCK (0x0c) per group, instead of a run of
+ * single-register 0x08 writes.
+ *
+ * The values below are copied verbatim from a USB capture of the
+ * driver while it was producing audio (VirtualBox usb sniffer, see
+ * docs/NOTES.md). Note that the 48 kHz group matches this repo's
+ * tbl_48000 byte for byte, INCLUDING 0x0900=0xaa / 0x0901=0x4f /
+ * 0x0902=0x01 / 0x0903=0x08 -- the words this project had marked as
+ * "poison" and deliberately never wrote. The values were never the
+ * problem; delivering them one register at a time was.
+ */
+ if (getenv("AUDIOBLK")) {
+ /* group 1: ADC / audio path */
+ static const uint16_t g1r[] = {
+ 0x0122, 0x0127, 0x0914, 0x0915, 0x0916, 0x0917,
+ 0x0918, 0x0919, 0x091a, 0x091b, 0x0808, 0x0809,
+ 0x080a, 0x080b
+ };
+ static const uint8_t g1v[] = {
+ 0x01, 0x50, 0xa0, 0x00, 0x00, 0x00,
+ 0xa0, 0x01, 0x00, 0x00, 0xf6, 0x00,
+ 0x00, 0x14
+ };
+ /* group 2: 0x08d0-0x08d3 */
+ static const uint16_t g2r[] = { 0x08d0, 0x08d1, 0x08d2, 0x08d3 };
+ static const uint8_t g2v[] = { 0x70, 0x38, 0x06, 0x01 };
+ /* group 3: the 48 kHz aux PLL + 0x0900 block */
+ static const uint16_t g3r[] = {
+ 0x0108, 0x0109, 0x010a, 0x010b, 0x0110, 0x0111,
+ 0x0112, 0x0113, 0x0127, 0x0900, 0x0901, 0x0902,
+ 0x0903, 0x0128, 0x0129, 0x012a, 0x012c, 0x012d,
+ 0x012e
+ };
+ static const uint8_t g3v[] = {
+ 0x0f, 0x04, 0x0a, 0x10, 0xe5, 0xd6,
+ 0x98, 0x00, 0x50, 0xaa, 0x4f, 0x01,
+ 0x08, 0xf8, 0x93, 0x11, 0xff, 0x5f,
+ 0x20
+ };
+ uint8_t b = 0xa1;
+ int rc = 0;
+ rc |= pvr2_i2c_write_block(p, CX2584X_I2C_ADDR, g1r, g1v,
+ (int)(sizeof(g1r) / sizeof(g1r[0])));
+ rc |= pvr2_i2c_write_block(p, CX2584X_I2C_ADDR, g2r, g2v,
+ (int)(sizeof(g2r) / sizeof(g2r[0])));
+ rc |= pvr2_i2c_write_block(p, CX2584X_I2C_ADDR, g3r, g3v,
+ (int)(sizeof(g3r) / sizeof(g3r[0])));
+ /* the DSP start trigger stays a single-register write */
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x012b, &b, 1);
+ fprintf(stderr, "AUDIOBLK: 3 block writes (0x0c) + 0x012b=0xa1"
+ "%s\n", rc ? " (some failed)" : "");
+ }
+ /*
+ * I2CW=<reg16>:<val>[,<reg16>:<val>...] - write arbitrary CX25837
+ * registers last, immediately before the encoder is started. Added to
+ * test the audio clock gating without a rebuild:
+ *
+ * 0x131 bit5 SCLK_GATE_MSK 0 = DIG_PWR_ON disables sample clock
+ * (SCLK) and I2S master clock (I2S_MCLK)
+ * 1 = gating of SCLK and I2S_MCLK inhibited
+ * 0x131 bit4 CLK5x_GATE_MSK 0 = DIG_PWR_ON disables CLK5x
+ * 0x131 bit3 VCLK_GATE_MSK 0 = DIG_PWR_ON disables VCLK
+ *
+ * Both this tool and the Windows driver write 0x131 = 0x00, but
+ * DIG_PWR_ON may be asserted at different moments in the two flows --
+ * if it is asserted in ours, bit5=0 means the CX25837's SCLK and
+ * I2S_MCLK are switched off, and the encoder's audio block would have
+ * no clock at all. That would explain why even MUTEAUDIO=1 (a silent
+ * mp2 stream) produces nothing. Try V131-style values here, e.g.
+ * I2CW=0x131:0x20
+ */
+ {
+ const char *e = getenv("I2CW");
+ while (e && *e) {
+ unsigned int reg = 0, val = 0;
+ char *end;
+ reg = (unsigned int)strtoul(e, &end, 0);
+ if (*end != ':')
+ break;
+ e = end + 1;
+ val = (unsigned int)strtoul(e, &end, 0);
+ e = (*end == ',') ? end + 1 : NULL;
+ {
+ uint8_t v = (uint8_t)val;
+ int rc = pvr2_i2c_write(p, CX2584X_I2C_ADDR,
+ (uint16_t)reg, &v, 1);
+ fprintf(stderr, "I2CW: 0x%04x = 0x%02x -> %s\n",
+ reg, v, rc < 0 ? "NACK" : "ok");
+ }
+ }
+ }
+ if (getenv("WINMASK"))
+ win_mask(p);
+ if (!replay_done) {
+ if (use_driver_seq) {
+ if (pvr2_encoder_config_driver(p, sample_rate) < 0)
+ fprintf(stderr, "warning: driver-sequence config reported errors\n");
+ } else if (pvr2_encoder_config(p, sample_rate) < 0) {
+ fprintf(stderr, "warning: encoder config reported errors\n");
+ }
+ }
+
+ /* Official driver clears bit 30 of the encoder status word (MBOX
+ * 0x48) right after SET_AUDIO_PROPERTIES. That bit gates the
+ * encoder's audio path, so leaving it set means no audio PES is ever
+ * produced no matter what the decoder side looks like. It was only
+ * cleared with -T before, because -T also drags in the full table
+ * write that destroys the picture. The clear on its own is a single
+ * read-modify-write, so it is done by default in MPEG mode and stays
+ * off for raw (which carries no audio anyway). */
+ /*
+ * ADCDUMP=1 reads back the CX2584x audio-ADC registers. Everything
+ * tried so far has been on the encoder or the clock side; if the ADC
+ * itself never sees a level, no encoder setting can produce audio,
+ * and this is where that shows up. 0x0900-0x090f is the audio
+ * input/AGC block, 0x0910-0x0921 the ADC control/status.
+ */
+ if (getenv("ADCDUMP")) {
+ uint8_t b;
+ static const uint16_t regs[] = {
+ 0x0100, 0x0101, 0x0102, 0x0103, 0x0104, 0x0105,
+ 0x0106, 0x0107, 0x0109, 0x010a, 0x010b, 0x010c,
+ 0x0808, 0x080b, 0x0914, 0x0918, 0x0919,
+ };
+ size_t k;
+ fprintf(stderr, "CX2584x register dump:\n");
+ for (k = 0; k < sizeof(regs)/sizeof(regs[0]); k++) {
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, regs[k], &b,
+ 1) == 0)
+ fprintf(stderr, " 0x%04x = 0x%02x (%3u)\n",
+ regs[k], b, b);
+ }
+ }
+
+ if (getenv("MBOXDUMP") && !raw_mode) {
+ /* Dump the encoder MBOX range: 0x40-0x5f. The audio path
+ * has to be visible somewhere in here - the stream is being
+ * produced, the gate bit is clear, and still no audio PES
+ * appears, so the state has to be read back rather than
+ * guessed at. */
+ uint32_t a;
+ fprintf(stderr, "MBOX dump 0x40-0x5f:\n");
+ for (a = 0x44; a <= 0x5f; a++) {
+ uint32_t v = 0;
+ if (pvr2_mbox_read(p, a, &v, 1) == 0)
+ fprintf(stderr, " 0x%02x = 0x%08x\n", a, v);
+ }
+ }
+ if (!raw_mode) {
+ uint32_t st48 = 0;
+ if (pvr2_mbox_read(p, 0x48, &st48, 1) == 0)
+ fprintf(stderr, "MBOX 0x48 before clear = 0x%08x "
+ "(bit30 %s)\n", st48,
+ (st48 & 0x40000000u) ? "SET" : "clear");
+ if (pvr2_enc_clear_flag(p, 0x40000000) < 0)
+ fprintf(stderr, "warning: encoder audio-flag clear "
+ "failed\n");
+ if (pvr2_mbox_read(p, 0x48, &st48, 1) == 0)
+ fprintf(stderr, "MBOX 0x48 after clear = 0x%08x "
+ "(bit30 %s)\n", st48,
+ (st48 & 0x40000000u) ? "SET" : "clear");
+ }
+ /*
+ * AUDSTART=1 reproduces ivtv's ordering around begin_capture.
+ *
+ * ivtv does this immediately before CX2341X_ENC_START_CAPTURE
+ * (ivtv-streams.c, ivtv_start_v4l2_encode_stream):
+ *
+ * "Avoid tinny audio problem - ensure audio clocks are going"
+ * v4l2_subdev_call(itv->sd_audio, audio, s_stream, 1);
+ * ... disable video clocks, msleep(300) ...
+ * ivtv_vapi(itv, CX2341X_ENC_INITIALIZE_INPUT, 0);
+ * ... re-enable video clocks ...
+ * ivtv_vapi(itv, CX2341X_ENC_START_CAPTURE, 2, captype, subtype);
+ *
+ * i.e. the codec is brought up FIRST, then INITIALIZE_INPUT, then
+ * START_CAPTURE. This tool has always called INITIALIZE_INPUT
+ * inside pvr2_encoder_config(), which runs *before* the WM8739 is
+ * initialised at all -- so the encoder sampled its audio input while
+ * the codec was still in its power-on (muted, inactive) state.
+ *
+ * AUDSTART re-does the codec bring-up, waits 300 ms, re-issues
+ * INITIALIZE_INPUT and then lets the normal start path run.
+ */
+ /*
+ * ★ DEFAULT ON since 2026-10-24: this ordering is what makes the audio
+ * state deterministic.
+ *
+ * Measured on the same source, 6 runs each (the state is fixed for a
+ * whole run - a 60 s capture stayed in one state from start to end):
+ *
+ * default (INITIALIZE_INPUT before the codec is up) 6 BRIGHT / 6 dull
+ * AUDSTART=1 (ivtv order) 0 BRIGHT / 6 dull
+ *
+ * and 1426 readable registers are IDENTICAL in both states at both
+ * start and end, so the difference is not a register value - it is the
+ * order in which the encoder latched its audio input. ivtv documents
+ * exactly this: "Avoid tinny audio problem - ensure audio clocks are
+ * going" before CX2341X_ENC_INITIALIZE_INPUT, which is the BRIGHT
+ * state (programme-correlated top end, 16-23 kHz at -10 dB relative).
+ *
+ * AUDSTART=0 restores the old ordering for an A/B.
+ */
+ {
+ const char *as = getenv("AUDSTART");
+ if (!(as && *as == '0') && !no_codec && codec_addr >= 0 &&
+ codec_addr < 0x50) {
+ struct timespec ts = { 0, 300000000L }; /* 300 ms */
+ {
+ /* AUDWAIT=<ms>: ivtv uses 300 ms; measure whether more
+ * is needed for the audio clock to settle. */
+ const char *w = getenv("AUDWAIT");
+ if (w && *w) {
+ long ms = atol(w);
+ if (ms < 0) ms = 0;
+ ts.tv_sec = ms / 1000;
+ ts.tv_nsec = (ms % 1000) * 1000000L;
+ }
+ }
+ uint32_t p0[1];
+ fprintf(stderr, "AUDSTART: codec up -> 300 ms -> "
+ "INITIALIZE_INPUT -> START_CAPTURE (ivtv order)\n");
+ wm8739_bringup(p, codec_addr);
+ nanosleep(&ts, NULL);
+ p0[0] = 0;
+ if (pvr2_enc_cmd(p, CX2341X_ENC_INITIALIZE_INPUT, p0, 0) < 0)
+ fprintf(stderr, "AUDSTART: INITIALIZE_INPUT failed\n");
+ }
+ }
+
+ if (getenv("AUDSTARTSEQ") && !raw_mode) {
+ /*
+ * The sequence the driver runs immediately BEFORE
+ * START_CAPTURE (capture #1097-1110):
+ * 0x0c: 0x0108=0f 0x0109=04 0x010a=0a 0x010b=10
+ * 0x0c: 0x0108=0f 0x0109=04 0x010a=0a 0x010b=18
+ * 0x0c: 0x012c=ff 0x012d=5f 0x012e=20 0x010b=18
+ * read 0x012b; write 0x012b = 0xa1
+ * read 0x0810; write 0x0810 = 0x01
+ * write 0x0808 = 0x00
+ * Note 0x010b = 0x18 here (bit 3 set) where the earlier block
+ * used 0x10, and 0x0810 is never written by this tool.
+ */
+ static const uint16_t br1[] = { 0x0108, 0x0109, 0x010a, 0x010b };
+ static const uint8_t bv1[] = { 0x0f, 0x04, 0x0a, 0x10 };
+ static const uint16_t br2[] = { 0x0108, 0x0109, 0x010a, 0x010b };
+ static const uint8_t bv2[] = { 0x0f, 0x04, 0x0a, 0x18 };
+ static const uint16_t br3[] = { 0x012c, 0x012d, 0x012e, 0x010b };
+ static const uint8_t bv3[] = { 0xff, 0x5f, 0x20, 0x18 };
+ uint8_t v = 0xa1, w = 0x01, z = 0x00;
+ int rc = 0;
+ rc |= pvr2_i2c_write_block(p, CX2584X_I2C_ADDR, br1, bv1, 4);
+ rc |= pvr2_i2c_write_block(p, CX2584X_I2C_ADDR, br2, bv2, 4);
+ rc |= pvr2_i2c_write_block(p, CX2584X_I2C_ADDR, br3, bv3, 4);
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x012b, &v, 1);
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0810, &w, 1);
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0808, &z, 1);
+ fprintf(stderr, "AUDSTARTSEQ: pre-capture audio blocks + "
+ "0x012b=0xa1 0x0810=0x01 0x0808=0x00%s\n",
+ rc ? " (errors)" : "");
+ }
+
+ if (getenv("AUDSEQ2") && !raw_mode) {
+ /*
+ * Byte-exact replay of the driver's pre-START_CAPTURE sequence
+ * (capture #1097-1110). AUDSTARTSEQ used a reduced version;
+ * this one includes everything the capture shows, notably
+ * 0x08f8-0x08fb, 0x0900=0x55 0x0901=0x55 (NOT the aa/4f of the
+ * setup table), and 0x010b=0x18 (bit 3, the audio clock enable).
+ */
+ static const uint16_t a_r[] = { 0x0108, 0x0109, 0x010a, 0x010b,
+ 0x0110, 0x0111, 0x0112, 0x0113, 0x0127 };
+ static const uint8_t a_v[] = { 0x0f, 0x04, 0x0a, 0x10,
+ 0xe5, 0xd6, 0x98, 0x00, 0x50 };
+ static const uint16_t b_r[] = { 0x0108, 0x0109, 0x010a, 0x010b,
+ 0x0110, 0x0111, 0x0112, 0x0113, 0x0127,
+ 0x08f8, 0x08f9, 0x08fa, 0x08fb,
+ 0x0900, 0x0901, 0x0902, 0x0903,
+ 0x0128, 0x0129, 0x012a };
+ static const uint8_t b_v[] = { 0x0f, 0x04, 0x0a, 0x18,
+ 0xe5, 0xd6, 0x98, 0x00, 0x50,
+ 0x00, 0x80, 0x01, 0x08,
+ 0x55, 0x55, 0x01, 0x08,
+ 0xf8, 0x93, 0x11 };
+ static const uint16_t c_r[] = { 0x012c, 0x012d, 0x012e };
+ static const uint8_t c_v[] = { 0xff, 0x5f, 0x20 };
+ uint8_t one = 0x01, zero = 0x00, a1 = 0xa1;
+ int rc = 0;
+ rc |= pvr2_i2c_write_block(p, CX2584X_I2C_ADDR, a_r, a_v, 9);
+ rc |= pvr2_i2c_write_block(p, CX2584X_I2C_ADDR, b_r, b_v, 20);
+ rc |= pvr2_i2c_write_block(p, CX2584X_I2C_ADDR, c_r, c_v, 3);
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x012b, &a1, 1);
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0810, &one, 1);
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0808, &zero, 1);
+ rc |= pvr2_i2c_write_block(p, CX2584X_I2C_ADDR, b_r, b_v, 20);
+ rc |= pvr2_i2c_write_block(p, CX2584X_I2C_ADDR, c_r, c_v, 3);
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x012b, &a1, 1);
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0810, &zero, 1);
+ fprintf(stderr, "AUDSEQ2: exact driver pre-capture sequence%s\n",
+ rc ? " (errors)" : "");
+ }
+
+ if (!replay_done) {
+ if (raw_mode) {
+ /*
+ * ★ Vendor subtype bitmask (yacxm cxm.h, the
+ * GV-MVP/RX family driver):
+ * 0x01 = YUV (video) 0x02 = PCM_AUDIO
+ * 0x04 = VBI
+ * with capture types 0 = MPEG, 1 = RAW, 2 = RAW
+ * PASSTHROUGH, 3 = VBI.
+ * yacxm starts MPEG as type 0 subtype 0x03 (video +
+ * audio) and raw as type 1 subtype 0x01 (video only);
+ * for its FM-radio source it drops the video bit, i.e.
+ * AUDIO ONLY = subtype 0x02.
+ *
+ * The Windows driver on THIS board sends type 0
+ * subtype 0x13 for MPEG -- bit 0x10 on top of
+ * video|audio. Our raw default (0x11 = 0x10|video)
+ * works, so 0x10 is a raw/passthrough-ish bit.
+ * RAWAUDIO=1 -> 0x03 (video|PCM, no 0x10)
+ * RAWAUDIO=<hex> -> that subtype verbatim
+ * AUDONLY=1 -> 0x02 (audio only, no video)
+ */
+ uint32_t sub = 0x11;
+ uint32_t ctype = 1; /* 1 = RAW; 2 = RAW PASSTHROUGH */
+ const char *ct = getenv("RAWCAPTYPE");
+ const char *ra = getenv("RAWAUDIO");
+ if (ct)
+ ctype = (uint32_t)strtoul(ct, NULL, 0);
+ if (ra)
+ sub = (ra[0] && strcmp(ra, "1"))
+ ? (uint32_t)strtoul(ra, NULL, 0)
+ : 0x03u;
+ if (getenv("AUDONLY"))
+ sub = 0x02u;
+ /*
+ * ★ Mixing audio into the raw video stream makes the
+ * video framing drift. Measured: the stream becomes
+ * [video 73,920 B][PCM record 4,620 B] ... interleaved
+ * so a fixed 518,400-byte frame size accumulates the
+ * record bytes as error -> the picture rolls (~2.8 s per
+ * revolution, matching "correct at first, drifting after
+ * a few seconds"). With subtype 0x11 (video only) the
+ * stream is exactly 518,400 bytes per frame and stays in
+ * phase (measured: 12 s, 359 frames, zero drift).
+ * ivtv keeps raw YUV and PCM on SEPARATE devices
+ * (video32 / video24) and its documentation states the
+ * YUV and PCM streams are not synchronised; the vendor
+ * driver carries YUVFixedSize / YUVRemoveResidual /
+ * YUVCompensateJittering knobs for the same reason.
+ */
+ if ((sub & 0x03u) == 0x03u)
+ fprintf(stderr,
+ "warning: subtype 0x%02x mixes audio into the "
+ "raw video stream;\n"
+ " the video framing will drift (measured "
+ "~4620 B per record, ~2.8 s per revolution).\n"
+ " Use the default RAWAUDIO=0x11 (video only) "
+ "for raw%s.\n",
+ sub,
+ getenv("SPLITAV")
+ ? " (SPLITAV removes the records but its "
+ "parser can mis-detect them)"
+ : ", or SPLITAV=1 to strip the records");
+ (void)pvr2_encoder_start_ex(p, ctype, sub);
+ enc_captype = ctype; enc_subtype = sub; enc_started = 1;
+ if (getenv("REGDUMP"))
+ reg_dump(p, "start");
+ }
+ else {
+ uint32_t sub = 0x13;
+ if (getenv("AUDONLY"))
+ sub = 0x02; /* audio only, no video */
+ if (pvr2_encoder_start_ex(p, 0, sub) < 0) {
+ ret = 1;
+ goto outexit;
+ }
+ enc_captype = 0; enc_subtype = sub; enc_started = 1;
+ }
+ /* The driver's one I2C write between START_CAPTURE and the
+ * stream. */
+ if (getenv("POSTCAP"))
+ postcap(p);
+
+ /* Video input select + Aux PLL (reference). */
+ if (raw_input >= 0) {
+ uint8_t d = (uint8_t)raw_input, v;
+ fprintf(stderr, "video input: raw 0x103=0x%02x\n", d);
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0103, &d, 1);
+ /* leave 0x401 mode as composite (0) - 0xf0 gives colour
+ * that way on this unit. */
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, 0x0401, &v, 1) == 0) {
+ v = v & ~0x06;
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0401, &v, 1);
+ }
+ } else if (pvr2_video_input_sel(p, composite ? 1 : 0,
+ composite ? 4 : svideo_idx) < 0)
+ fprintf(stderr, "warning: video input selection failed\n");
+ }
+ /* Audio Aux-PLL init. NOTE: this writes 0x0118 and the Aux PLL
+ * (0x0108/0x0110/0x0127) which the reference does NOT, and it was
+ * verified on hardware to BREAK capture (0 bytes). The reference
+ * only writes 0x115/0x116 for audio. Keep it off by default; enable
+ * with -T for audio experiments. */
+ if (use_driver_tables && !replay_done) {
+ if (pvr2_audio_init(p, sample_rate) < 0)
+ fprintf(stderr, "warning: audio init failed\n");
+ }
+ if (!replay_done) {
+ /*
+ * Audio serial-path enable bits. The reference writes
+ * 0x0115=0x0c, 0x0116=1<<2; the official driver table uses
+ * 0x0115=0x8f, 0x0116=0x07 and its comment says the pair
+ * enables the audio serial path. Which bit carries
+ * PLL_CLK_OUT_EN is not documented for this part, so both
+ * values are overridable to test which one lets audio
+ * through: V115=0x8f V116=0x07.
+ */
+ uint8_t v15 = 0x0c, v16 = 1 << 2;
+ const char *e;
+
+ /*
+ * BITSWEEP=<n> sets only bit n of 0x0115 (0x0116 left alone).
+ * The official driver value 0x8f differs from the reference
+ * 0x0c in bits 0,1 and 7, and 0x0116 differs in bits 0,1.
+ * PLL_CLK_OUT_EN is undocumented for this part, so each bit is
+ * worth trying on its own: if one of them is the clock output
+ * enable and the audio DSP simply has no clock, audio PES
+ * cannot appear no matter what else is programmed.
+ */
+ if ((e = getenv("BITSWEEP")) != NULL) {
+ int n = atoi(e);
+ v15 = (n >= 0 && n < 8) ? (uint8_t)(1 << n) : 0;
+ v16 = 0;
+ fprintf(stderr, "BITSWEEP: testing 0x0115 bit%d only"
+ " (0x%02x)\n", n, v15);
+ }
+ if ((e = getenv("V115")) != NULL)
+ v15 = (uint8_t)strtoul(e, NULL, 0);
+ if ((e = getenv("V116")) != NULL)
+ v16 = (uint8_t)strtoul(e, NULL, 0);
+ fprintf(stderr, "audio serial enables: 0x0115=0x%02x 0x0116=0x%02x\n",
+ v15, v16);
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0115, &v15, 1);
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0116, &v16, 1);
+ }
+
+ /*
+ * AUDTAB=1 : the gvmvprz2.dll audio-mode table (FUN_10015e50,
+ * 0x0418=0x2e 0x0419=0xba 0x041a=0x10), applied LATE so nothing
+ * re-zeroes it afterwards (the 308-entry table writes 0 as the
+ * u32-expansion of its neighbours). The Windows stack never
+ * addresses the WM8739 over I2C anywhere, so this decoder-side
+ * audio serial engine is the only audio configuration it makes.
+ */
+ if (getenv("AUDTAB")) {
+ if (pvr2_cx2584x_write_audio_mode(p, 1) < 0)
+ fprintf(stderr, "warning: AUDTAB failed\n");
+ else {
+ uint8_t v = 0;
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, 0x0418, &v, 1) == 0)
+ fprintf(stderr, "AUDTAB: 0x0418 readback 0x%02x\n", v);
+ }
+ }
+
+ /*
+ * DSPSTART=1 : the p2usbRZ2.sys set_sample_rate trigger
+ * (FUN_0002597b): read 0x012b, set bit0, write back -- the
+ * "start the audio DSP" step. Never tried on its own: the old
+ * -T path mixed it with the poisonous 0x0900-0x0903 writes.
+ */
+ if (getenv("DSPSTART")) {
+ uint8_t v = 0;
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, 0x012b, &v, 1) == 0) {
+ v |= 0x01;
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x012b, &v, 1);
+ fprintf(stderr, "DSPSTART: 0x012b -> 0x%02x\n", v);
+ }
+ }
+
+ /* NOTE: the official-driver decoder tables (pvr2_cx2584x_write_tables,
+ * 0x800-0x94b DSP block) and the stream-on extras (0x810|=1,
+ * 0x8d0/0x8d1/0x8d2) are NOT applied here. They were verified on
+ * hardware to BREAK capture (the encoder produces no data / the
+ * picture tears). The reference sequence above captures clean video.
+ * Enable them only for experiments via -T. */
+ if (use_driver_tables) {
+ if (pvr2_cx2584x_write_tables(p, japan_audio) < 0)
+ fprintf(stderr, "warning: decoder table init reported errors\n");
+ }
+ /*
+ * READBACK=1 re-reads the input-selection and ADC registers now that
+ * everything has been written. Every audio register coming back as
+ * zero would mean the I2C writes are not landing, which would point
+ * somewhere entirely different from a wrong value.
+ */
+ if (getenv("RD1")) {
+ uint8_t b;
+ static const uint16_t rl[] = { 0x0103, 0x0115, 0x0116,
+ 0x0808, 0x0914, 0x0918 };
+ size_t k;
+ fprintf(stderr, "RD1 (right after AUDDSP/ADCTAB):\n");
+ for (k = 0; k < sizeof(rl) / sizeof(rl[0]); k++)
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, rl[k], &b, 1) == 0)
+ fprintf(stderr, " 0x%04x = 0x%02x\n", rl[k], b);
+ }
+ /*
+ * W4TEST=1 writes the 0x0800+ registers as 4-byte words, the way
+ * the Linux cx25840 driver does (cx25840_write4), and reads them
+ * back as 4 bytes. Single-byte access to this block has been
+ * returning 0x00 on this part, so this checks whether the block
+ * needs the wider transaction.
+ */
+ if (getenv("W4TEST")) {
+ static const struct { uint16_t r; uint32_t v; } w4[] = {
+ { 0x0808, 0x00000011 }, /* carrier select */
+ { 0x0914, 0x000000a0 }, /* ADC enable */
+ { 0x0918, 0x000000a0 }, /* ADC enable */
+ };
+ uint8_t buf[4];
+ size_t k;
+ fprintf(stderr, "4-byte write test:\n");
+ for (k = 0; k < sizeof(w4)/sizeof(w4[0]); k++) {
+ buf[0] = w4[k].v & 0xff;
+ buf[1] = (w4[k].v >> 8) & 0xff;
+ buf[2] = (w4[k].v >> 16) & 0xff;
+ buf[3] = (w4[k].v >> 24) & 0xff;
+ if (pvr2_i2c_write(p, CX2584X_I2C_ADDR, w4[k].r,
+ buf, 4) < 0)
+ fprintf(stderr, " 0x%04x write failed\n",
+ w4[k].r);
+ }
+ for (k = 0; k < sizeof(w4)/sizeof(w4[0]); k++) {
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, w4[k].r,
+ buf, 4) == 0)
+ fprintf(stderr, " 0x%04x read4 = %02x %02x "
+ "%02x %02x\n", w4[k].r, buf[0], buf[1],
+ buf[2], buf[3]);
+ else
+ fprintf(stderr, " 0x%04x read4 failed\n",
+ w4[k].r);
+ }
+ }
+
+ /*
+ * I2CPROBE=1 sweeps the CX25843 register space and reports which
+ * addresses actually read back as something other than zero. On
+ * this part 0x00xx responds but 0x08xx/0x09xx always returns 0,
+ * so this maps exactly how much of the chip is reachable at all
+ * before spending any more effort on individual registers.
+ */
+ if (getenv("I2CPROBE")) {
+ uint32_t base;
+ fprintf(stderr, "CX25843 I2C probe (non-zero reads only):\n");
+ for (base = 0; base < 0x1000; base += 0x100) {
+ int found = 0;
+ uint32_t off;
+ for (off = 0; off < 0x100; off += 1) {
+ uint8_t b = 0;
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR,
+ (uint16_t)(base + off),
+ &b, 1) != 0)
+ continue;
+ if (b) {
+ if (!found) {
+ fprintf(stderr,
+ " 0x%04x:", base);
+ found = 1;
+ }
+ fprintf(stderr, " [%02x]=%02x", off, b);
+ }
+ }
+ if (found)
+ fprintf(stderr, "\n");
+ }
+ }
+
+ /*
+ * MBOXSCAN=1 sweeps the CX23416 mailbox memory and reports the
+ * regions that read back as something. The encoder's control
+ * registers live here; if the CX25843 audio block is reachable
+ * through the encoder rather than over I2C, it should show up as
+ * a region that responds.
+ */
+ /*
+ * CHIPID=1 reads the CX2584x identification registers. The user
+ * reports CX25837 on this board, not the CX25843 the code assumes.
+ * CX25837 is the predecessor of CX25843 and, unlike CX25843, its
+ * 0x08xx audio block is reachable - which would explain both why
+ * MagicTV gets audio off the same chip family and why nothing here
+ * does. Reading the ID settles which part is actually fitted
+ * instead of assuming.
+ */
+ /*
+ * SERSEQ=1 applies the register sequence recovered from
+ * IODataAud.ax (MagicTV's audio module, CX25837). Its table is an
+ * alternating array of {reg, value} u16 pairs, so it can be handed
+ * straight to the I2C writer one register at a time:
+ * 0x0115=0x0008 0x0116=0x0008 0x0117=0x0008 0x0118=0x0008 ...
+ * Every value is 8, which differs from both the official 0x8f/0x07
+ * and the reference 0x0c/0x04, so it is worth trying verbatim.
+ */
+ if (getenv("SERSEQ")) {
+ static const uint16_t regs[] = {
+ 0x0115, 0x0116, 0x0117, 0x0118, 0x0119, 0x011a,
+ 0x011b, 0x011c, 0x011d, 0x011e, 0x011f, 0x0120,
+ 0x0121, 0x0122, 0x0123,
+ };
+ size_t k;
+ uint8_t v = 0x08;
+ fprintf(stderr, "SERSEQ: IODataAud.ax register sequence\n");
+ for (k = 0; k < sizeof(regs) / sizeof(regs[0]); k++)
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, regs[k], &v, 1);
+ }
+
+ /*
+ * WM8739=<addr> initialises the audio codec the board carries.
+ *
+ * The board population includes a WM8739, and the CX25837 on this
+ * part has no reachable audio ADC of its own (0x08xx reads back as
+ * zero), so the codec is the likely source of the audio. Nothing in
+ * kare has ever touched it: only the decoder at 0x44 is
+ * programmed, so the codec has been sitting in reset the whole time.
+ *
+ * Sequence per the codec's normal-mode bring-up:
+ * R6 = 0x00 power up
+ * R7 = 0x049 "normal mode, 256fs, 48 kHz"
+ * R9 = 0x000 master mode
+ * A rate change later drops R9 to 0 first, then writes R8.
+ */
+ {
+ const char *w = getenv("WM8739");
+ int wa = -1;
+ if (w)
+ wa = (int)strtol(w, NULL, 0);
+ else if (!no_codec)
+ /* Default: bring the codec up on every capture. The
+ * confirmed method (docs/AUDIO_CAPTURE_METHOD.md) is
+ * 0x1a + the packed word format + R9=0x01; the codec
+ * has never been initialised in a normal run, it used
+ * to be an env-only experiment. */
+ wa = codec_addr;
+ if (wa >= 0) {
+ /* 0x51 is the 24C64WP EEPROM: writing it once bricked
+ * this unit (recovered with a CH341A). The WM873x
+ * control interface lives at 0x1a/0x1b, never at or
+ * above 0x50 -- refuse anything in the EEPROM range. */
+ if (wa >= 0x50 && wa < 0x60) {
+ fprintf(stderr, "WM8739: refusing 0x%02x -- "
+ "0x50-0x5f is the 24C64WP EEPROM "
+ "(prior brick). Use 0x1a/0x1b.\n", wa);
+ wa = -1;
+ }
+ }
+ if (wa >= 0) {
+ /*
+ * ★ Sequence taken from yacxm 0.1f (dev/cxm/cxm_audio.c,
+ * ADC_XWM8739_init) -- the proven reference for this exact
+ * codec on I-O DATA's own CX23416 hardware (GV-MVP/RX,
+ * RX2, RX2W). It is byte-for-byte compatible with our
+ * packed-register write: yacxm sends [0x34][reg<<1][data]
+ * and pvr2_wm873x_write(reg,data) emits the same two bytes.
+ *
+ * The two entries this tool was missing are the important
+ * ones:
+ *
+ * R0 / R1 = line input volume, bit7 = LINMUTE/RINMUTE.
+ * The WM8739 powers up with both line inputs MUTED
+ * (R0/R1 default 0x97 = mute + 0 dB), and the previous
+ * default sequence never wrote them at all -- so the ADC
+ * was converting silence. WM8739FULL was no better: it
+ * wrote R0=0x00 (-34.5 dB, nearly silent) and R1=0x80
+ * (RINMUTE=1, i.e. still muted). 0x17 = unmuted, 0 dB,
+ * which is what yacxm uses.
+ *
+ * R15 = 0x00: reset register, 0x00 = normal operation.
+ *
+ * R7 = 0x49 keeps the codec in MASTER mode (bit0), which is
+ * how yacxm documents it: the ADC then generates BCLK/LRCK
+ * itself and only needs MCLK on XTI.
+ */
+ struct { uint8_t r, v; } seq[] = {
+ { 15, 0x00 }, /* reset: normal operation */
+ { 0, 0x17 }, /* left line in: unmuted, 0 dB */
+ { 1, 0x17 }, /* right line in: unmuted, 0 dB */
+ { 5, 0x00 }, /* digital audio path control */
+ { 6, 0x5a }, /* power down control
+ * 0x5a = LINEINPD/ADCPD/OSCPD/
+ * POWEROFF all CLEAR (every block
+ * powered up) with the datasheet's
+ * "unused bits 1,3,4,6 = 1".
+ * 0x00 cleared those four bits as
+ * well, and both the Windows driver
+ * (capture: dev 0x1a reg 6 = 0x5a)
+ * and yacxm send 0x5a. */
+ { 7, 0x49 }, /* format: MASTER (bit6), 24-bit,
+ * left-justified (FORMAT=01) */
+ /*
+ * ★ R8 = 0x02 (384 fs) is the default (2026-10-15).
+ * SA_MCLK from the CX25837 is 18.43 MHz = 384 fs @
+ * 48 kHz (measured: pin46/XTI = 1.6 V mid-rail, and
+ * 0x127 = 0x50 = VCO/16). With R8 = 0x00 (256 fs)
+ * the codec generates LRCK = MCLK/256 = 72 kHz, so
+ * the encoder's PTS clock runs ~1.45x fast and the
+ * audio sounds sped up ("clock fast"). With 0x02
+ * (BOSR=1, 384 fs) LRCK = 48 kHz and the PTS span
+ * tracks wall time (~0.93x in an 8 s window).
+ * WM8739R8=<hex> still overrides for experiments.
+ */
+ { 8, 0x02 }, /* sampling: normal, 384fs, 48 kHz */
+ { 9, 0x01 }, /* activate */
+ };
+ /*
+ * WM8739R7=<hex> / WM8739R8=<hex> override those two
+ * entries of the table above. R8 encodes the MCLK/fs
+ * factor (BOSR: 0 = 256 fs, 1 = 384 fs in normal mode),
+ * and there is an open contradiction on this board:
+ * CX25837 0x127 = 0x50 (SA_MCLK = AUX_PLL VCO / 16 =
+ * 294.87/16 = 18.43 MHz = 384 fs) while this table
+ * writes R8 = 0x00 (256 fs, i.e. 12.288 MHz assumed).
+ * If SA_MCLK is really what clocks the codec, R8 should
+ * carry BOSR=1 (0x40). One run decides it.
+ */
+ {
+ static const struct { const char *e; uint8_t r; } ov[] = {
+ { "WM8739R7", 7 }, { "WM8739R8", 8 },
+ { "WM8739R0", 0 }, { "WM8739R1", 1 },
+ };
+ size_t oi;
+ for (oi = 0; oi < sizeof(ov) / sizeof(ov[0]); oi++) {
+ const char *o = getenv(ov[oi].e);
+ size_t si;
+ if (!o)
+ continue;
+ for (si = 0;
+ si < sizeof(seq) / sizeof(seq[0]); si++)
+ if (seq[si].r == ov[oi].r)
+ seq[si].v = (uint8_t)
+ strtoul(o, NULL, 0);
+ fprintf(stderr, "WM8739: R%u overridden to "
+ "0x%02x\n",
+ ov[oi].r,
+ (uint8_t)strtoul(o, NULL, 0));
+ }
+ /* WM8739VOL=<0..31>: line-input gain for BOTH
+ * channels in one shot. The 5-bit LINVOL/
+ * RINVOL field: 0x17 (23) = 0 dB, 0x1B (27) =
+ * +6 dB, 0x1F (31) = +12 dB (max). bit7
+ * LINMUTE/RINMUTE stays 0. Measured 2026-10-15:
+ * the audio stream exists but the content read
+ * -65 dB mean with the source quiet; this knob
+ * is the "dB sensitivity" the user asked for. */
+ {
+ const char *o = getenv("WM8739VOL");
+ if (o) {
+ unsigned vol =
+ (unsigned)strtoul(o, NULL, 0);
+ if (vol > 31)
+ vol = 31;
+ for (size_t si = 0;
+ si < sizeof(seq) /
+ sizeof(seq[0]);
+ si++)
+ if (seq[si].r == 0 ||
+ seq[si].r == 1)
+ seq[si].v =
+ (uint8_t)vol;
+ fprintf(stderr, "WM8739: R0/R1 "
+ "volume -> 0x%02x "
+ "(%s%d dB)\n",
+ (unsigned)vol,
+ vol >= 23 ? "+" : "",
+ (int)vol * 15 / 10
+ - 345 / 10);
+ }
+ }
+ }
+ size_t k;
+ int full = (getenv("WM8739FULL") != NULL);
+ /*
+ * WM8739SEQ="r:v[,r:v...]" replaces the default
+ * sequence with a fully custom one; WM8739REPEAT=n
+ * sends it n times with WM8739GAP ms between passes
+ * (default 1). Purpose: the board reads BCLK/LRCK
+ * static-high (tristated) while VMID=AVDD/2 shows R6
+ * landed - i.e. early registers stick and later ones
+ * don't. A repeated / reordered sequence tells us
+ * whether a mid-sequence break is real: if the user
+ * ever sees BCLK leave 3.3V (driven low or toggling),
+ * the writes got through.
+ */
+ const char *cs = getenv("WM8739SEQ");
+ struct { uint8_t r, v; } cust[24];
+ size_t cn = 0;
+ int repeat = 1, gap_ms = 50;
+ if (cs) {
+ const char *q = cs;
+ while (*q && cn < 24) {
+ unsigned r = 0, v = 0;
+ char *end;
+ r = (unsigned)strtoul(q, &end, 0);
+ if (*end != ':')
+ break;
+ v = (unsigned)strtoul(end + 1, &end, 0);
+ cust[cn].r = (uint8_t)r;
+ cust[cn].v = (uint8_t)v;
+ cn++;
+ q = (*end == ',') ? end + 1 : end;
+ }
+ fprintf(stderr, "WM8739SEQ: %zu custom regs\n",
+ cn);
+ }
+ {
+ const char *e = getenv("WM8739REPEAT");
+ if (e)
+ repeat = atoi(e);
+ if ((e = getenv("WM8739GAP")) != NULL)
+ gap_ms = atoi(e);
+ }
+ for (int pass = 0; pass < repeat; pass++) {
+ if (pass) {
+ struct timespec gs = {
+ gap_ms / 1000,
+ (long)(gap_ms % 1000) *
+ 1000000L
+ };
+ nanosleep(&gs, NULL);
+ }
+ if (cn) {
+ for (k = 0; k < cn; k++) {
+ int wrc = pvr2_wm873x_write(p,
+ (uint8_t)wa,
+ cust[k].r, cust[k].v);
+ fprintf(stderr,
+ " SEQ[%d] R%u = 0x%02x"
+ " -> %s\n", pass,
+ cust[k].r, cust[k].v,
+ (wrc < 0) ? "NACK" :
+ "ACK");
+ }
+ continue;
+ }
+ fprintf(stderr, "WM8739: init codec at "
+ "0x%02x%s (pass %d)\n",
+ wa, full ? " (full)" : "", pass);
+ /*
+ * The three-register bring-up the user quoted
+ * (R6=0, R7=0x049, R9=enable) takes the codec out
+ * of reset and picks normal mode / 256fs / 48 kHz.
+ * It still defaults to no input, no output and mute,
+ * so nothing reaches the encoder. WM8739FULL adds the
+ * rest of a working path: line input selected, line
+ * out on, digital input and the master-mode bit set so
+ * the codec actually supplies a clock, unmute, and the
+ * capture/enable bits.
+ */
+ struct { uint8_t r, v; } full_seq[] = {
+ { 0, 0x00 }, /* R0 - power up, DAC/ADC on */
+ { 1, 0x80 }, /* R1 - 18-bit word, no soft mute */
+ { 2, 0x00 }, /* R2 - no volume adjust */
+ { 5, 0x00 }, /* R5 - no mic boost */
+ { 6, 0x00 }, /* R6 - power DOWN control: 0x00
+ * powers every block up. 0x09
+ * (LINEINPD|DACPD) would power
+ * down the line input, i.e. the
+ * very signal the ADC must
+ * convert -- no audio ever. */
+ { 7, 0x49 }, /* R7 - normal mode, 256fs, 48 kHz */
+ { 8, 0x00 }, /* R8 - normal rate, no slow sample */
+ { 9, 0x01 }, /* R9 - active (was 0x00 = standby/disabled) */
+ { 10, 0x00 }, /* R10 - no IRQ */
+ { 15, 0x06 }, /* R15 - ADC, line input (left) */
+ /* NOTE: R16/R21 were EEPROM offsets from the 0x51 mislabel,
+ * NOT WM873x registers (WM873x has R0-R15 only). Removed. */
+ };
+ for (k = 0; k < sizeof(seq) / sizeof(seq[0]); k++) {
+ uint16_t rb = 0;
+ int wrc = pvr2_wm873x_write(p, (uint8_t)wa,
+ seq[k].r, seq[k].v);
+ /*
+ * ★ READS DISABLED BY DEFAULT. MEASURED
+ * (2026-10-14 night): the read-after-write is what
+ * KILLS the codec - with reads, video runs and audio
+ * PES is 0 with BCLK/LRCK tri-stated; the identical
+ * writes without reads produce real audio (75 PES/4s,
+ * ffprobe Stream #0:1 mp2 48k stereo 224k). The
+ * WM8739 is write-only; the read transaction (same
+ * address, R/W=1) drives the codec's interface into
+ * a state that discards the previously written
+ * registers. WM8739READ=1 restores the old readback
+ * for diagnostics only.
+ */
+ int rrc = getenv("WM8739READ") ?
+ pvr2_wm873x_read(p, (uint8_t)wa,
+ seq[k].r, &rb) : -2;
+ /* The WM8739 is write-only (datasheet: "will only
+ * respond to the R/W bit indicating a write"), so a
+ * read NACK is NOT evidence that the codec is absent.
+ * Report the write ACK separately -- that is the one
+ * that says whether the part answered its address. */
+ fprintf(stderr, " R%u = 0x%02x -> write %s, read %s\n",
+ seq[k].r, seq[k].v,
+ (wrc < 0) ? "NACK" : "ACK",
+ (rrc < 0) ? "NACK (write-only part)" :
+ (rb == seq[k].v) ? "ok" : "mismatch");
+ }
+ if (full) {
+ size_t j;
+ for (j = 0; j < sizeof(full_seq) / sizeof(full_seq[0]); j++) {
+ uint16_t rb = 0;
+ int wrc = pvr2_wm873x_write(p, (uint8_t)wa,
+ full_seq[j].r,
+ full_seq[j].v);
+ int rrc = pvr2_wm873x_read(p, (uint8_t)wa,
+ full_seq[j].r,
+ &rb);
+ fprintf(stderr, " R%u = 0x%02x -> write %s, "
+ "read %s\n", full_seq[j].r,
+ full_seq[j].v,
+ (wrc < 0) ? "NACK" : "ACK",
+ (rrc < 0) ? "NACK (write-only part)" :
+ (rb == full_seq[j].v) ? "ok" : "mismatch");
+ }
+ }
+ } /* pass loop */
+ }
+ }
+
+ if (getenv("WINI2C"))
+ win_i2c(p);
+ if (getenv("WINGPIO"))
+ win_gpio(p);
+
+ /*
+ * ★ NEC Y/C separator init by DEFAULT (2026-10-15): the vendor
+ * programs the uPD64084GC (0x5c) + uPD64031A (0x12) + audio
+ * control (0x5b) at init (#518-525). Our default flow never did,
+ * so the external 3-D Y/C separator stayed in reset and the
+ * capture had luma but no chroma ("colour missing"). NOWINI2C=1
+ * skips (diagnostics only).
+ */
+ if (!getenv("NOWINI2C")) {
+ /* pcap order: short block -> full 24-register tables ->
+ * short block again (the vendor's final state is the full
+ * table with the short block's overrides on top). */
+ win_i2c(p);
+ /*
+ * ★ The FULL NEC register tables are now OPT-IN (2026-10-24).
+ * They were the default (the condition read !getenv, so the
+ * name was inverted - flagged in the option inventory years
+ * ago), and they imprint a horizontal line every 16 lines:
+ *
+ * full tables band-boundary row diff 37.5 / 37.7 against
+ * interior 6.7 / 9.6 (ratio 5.6 / 3.9),
+ * lag-16 autocorrelation +0.58 / +0.61
+ * short block boundary 8.4 / 8.6 against interior 6.8 /
+ * 7.1 (ratio 1.2), autocorrelation +0.195
+ *
+ * and the full-table defect is bimodal: one of three runs came
+ * out clean (ratio 1.17) with the same code, which is why the
+ * line looked state-dependent. NECFULL=1 restores the full
+ * tables for A/B.
+ */
+ if (getenv("NECFULL") && *getenv("NECFULL") != '0') {
+ win_i2c_full(p);
+ win_i2c(p);
+ }
+ }
+
+ /* VP27s MPX audio-mode control (see vp27s_mode above). */
+ {
+ const char *vm = getenv("VPMODE");
+ if (vm)
+ vp27s_mode(p, vm);
+ }
+
+ /*
+ * ★ AUDIO MUX (2026-10-15, root cause of the "silent audio" bug):
+ * the NJM2750's CNT1/CNT2 are CX23416 GPIO[8]/GPIO[9] (confirmed by
+ * pcap: every audio-producing vendor session leaves bits 8+9 driven
+ * HIGH, and on-die bit-level A/B: DIR bit9 as an output is the exact
+ * switch between -60 dB and -16 dB). yacxm encodes LINE IN as
+ * OUT=0x300 for the same vendor family. Our default flow never made
+ * bits 8/9 outputs, so the NJM2750's internal 100k pull-downs held
+ * IN1 selected and the RCA (IN4b) never reached the WM8739.
+ * Do it by DEFAULT now; NOGPIOMUX=1 skips (diagnostics only).
+ */
+ if (!getenv("NOGPIOMUX")) {
+ pvr2_gpio_dir(p, 0x00000300, 0x00000300);
+ /*
+ * ★ MUXCYCLE=1 - give the NJM2750 CNT1/CNT2 pins an EDGE
+ * (2026-10-24).
+ *
+ * The audio state comes up bimodal, ~50/50 per run, and is
+ * fixed for the whole run (measured: 60 s constant, 6 runs
+ * before a USB reset 2 BRIGHT / 4 dull, 6 after 4 / 2 - so the
+ * reset is NOT the determinant). The state tracks the
+ * 15.7 kHz crosstalk level: BRIGHT -52 dB, dull -23.5 dB.
+ *
+ * Writing the same value the pins already hold produces no
+ * edge, and a selector built from static-pull-up inputs is
+ * exactly the kind of thing that can power up in either state
+ * until it sees a transition. Cycling CNT1/CNT2 through all
+ * four codes and back to IN4 (RCA) tests that.
+ */
+ if (getenv("MUXCYCLE")) {
+ static const uint32_t seq[4] = { 0x000, 0x100, 0x200,
+ 0x300 };
+ int q;
+ for (q = 0; q < 4; q++) {
+ pvr2_gpio_out(p, 0x00000300, seq[q]);
+ usleep(20000);
+ }
+ fprintf(stderr, "audio mux: cycled IN1..IN4, now IN4\n");
+ } else {
+ pvr2_gpio_out(p, 0x00000300, 0x00000300);
+ }
+ fprintf(stderr, "audio mux: GPIO8/9 -> outputs, high "
+ "(NJM2750 IN4 = RCA)\n");
+ }
+
+ /*
+ * I2CSCAN=1 walks the whole 7-bit I2C space looking for a second
+ * device. The board carries a WM8739 audio codec in addition to the
+ * CX25837 at 0x44 - if that is where the audio comes from, the codec
+ * has never been initialised and no encoder setting can conjure
+ * audio out of an unpowered ADC. The WM8739 answers on one of the
+ * usual codec addresses, so finding it is the first step.
+ */
+ /*
+ * I2CWATCH=<n> reads register <n> from every responder found by
+ * I2CSCAN, so a codec can be identified by its reset value even
+ * when the address is not the usual one. A WM8738/8739 sitting in
+ * reset reads 0x00 at every register except R0, which reads 0x40;
+ * once released, R7 bit 7 goes high and R9 takes the master-mode
+ * value. Seeing that transition on one of the unknown addresses
+ * would pin down which one it is.
+ */
+ {
+ const char *iw = getenv("I2CWATCH");
+ if (iw) {
+ int reg = (int)strtol(iw, NULL, 0);
+ uint8_t b = 0;
+ int addr;
+ fprintf(stderr, "I2C watch: reading R%d everywhere\n", reg);
+ for (addr = 0x03; addr <= 0x77; addr++) {
+ if (pvr2_i2c_read(p, (uint8_t)addr,
+ (uint16_t)reg, &b, 1) == 0)
+ fprintf(stderr, " 0x%02x: R%d = 0x%02x\n",
+ addr, reg, b);
+ }
+ }
+ }
+
+ /*
+ * UPD64031=<addr> programs the NEC uPD64031A that the board carries
+ * (silkscreen D64031AGJ).
+ *
+ * It is an NTSC ghost-reduction filter: without it the composite
+ * signal is not bandwidth-limited and shows exactly the ghosting and
+ * the comb pattern that shows up on this capture. kare has never
+ * touched it - only the decoder at 0x44 is programmed - so it has
+ * been running with whatever state power-on left it in. Values are
+ * the driver's upd64031a_init, which pairs with the uPD64083 3D
+ * Y/C separator.
+ */
+ {
+ const char *up = getenv("UPD64031");
+ if (up) {
+ int ua = (int)strtol(up, NULL, 0);
+ /* upd64031a_init, straight from the Linux driver */
+ static const uint8_t init[] = {
+ 0x00, 0xb8, 0x48, 0xd2, 0xe6,
+ 0x03, 0x10, 0x0b, 0xaf, 0x7f,
+ 0x00, 0x00, 0x1d, 0x5e, 0x00,
+ 0xd0,
+ };
+ size_t k;
+ int good = 0;
+ fprintf(stderr, "UPD64031A: ghost filter at 0x%02x\n", ua);
+ for (k = 0; k < sizeof(init); k++) {
+ uint8_t v = init[k], rb = 0;
+ pvr2_i2c_write(p, (uint8_t)ua, (uint16_t)k, &v, 1);
+ pvr2_i2c_read(p, (uint8_t)ua, (uint16_t)k, &rb, 1);
+ if (rb == v)
+ good++;
+ }
+ fprintf(stderr, " %d/%d registers read back "
+ "as written%s\n", good, (int)sizeof(init),
+ (good == (int)sizeof(init)) ? " (chip present)"
+ : " (not present)");
+ }
+ }
+
+ if (getenv("I2CSCAN")) {
+ uint8_t b = 0;
+ int addr;
+ (void)0;
+ fprintf(stderr, "I2C scan (7-bit 0x03-0x77):\n");
+ for (addr = 0x03; addr <= 0x77; addr++) {
+ if (pvr2_i2c_read(p, (uint8_t)addr, 0x0000, &b, 1) == 0) {
+ /* WM8738/8739 reset: reg7 bit7 is 0 until the
+ * reset line is released, and reg0 is a
+ * left-justified ID (0x80 for part 1, 0x40
+ * for the WM8738/39). Read a few more so the
+ * codec can be told apart from whatever else
+ * answers on the bus. */
+ uint8_t r1 = 0, r7 = 0, r9 = 0;
+ pvr2_i2c_read(p, (uint8_t)addr, 0x0001, &r1, 1);
+ pvr2_i2c_read(p, (uint8_t)addr, 0x0007, &r7, 1);
+ pvr2_i2c_read(p, (uint8_t)addr, 0x0009, &r9, 1);
+ fprintf(stderr, " 0x%02x: R0=%02x R1=%02x R7=%02x R9=%02x\n",
+ addr, b, r1, r7, r9);
+ }
+ }
+ fprintf(stderr, "I2C scan done\n");
+ }
+
+ /*
+ * I2CPROBE=<addr>[,<addr>...] : probe specific 7-bit addresses with
+ * BOTH a read and a write and report which one the FX2 ACKs.
+ *
+ * Why this exists: the WM8739 is a WRITE-ONLY 2-wire slave. Datasheet
+ * (Wolfson WM8739 AI Rev 2.2, "2-WIRE SERIAL CONTROL MODE"): "The
+ * WM8739 is a write only device and will only respond to the R/W bit
+ * indicating a write." I2CSCAN above only lists addresses that ACK a
+ * READ, so a WM8739 sitting in 2-wire mode is *invisible* to it, and a
+ * read NACK says nothing about whether the part is on the board. The
+ * write ACK is the discriminator.
+ *
+ * 0x01 and 0x7f are I2C-reserved addresses (0x00-0x07, 0x78-0x7f)
+ * that no device may acknowledge: they are the control. If those two
+ * also report ACK, the FX2 status byte is not a real ACK and no
+ * conclusion may be drawn from any of this.
+ */
+ {
+ const char *ip = getenv("I2CPROBE");
+ if (ip) {
+ char buf[256];
+ const char *s;
+ snprintf(buf, sizeof(buf), "%s",
+ (!strcmp(ip, "1")) ? "0x01,0x7f,0x1a,0x1b" : ip);
+ fprintf(stderr, "I2C probe (read ACK / write ACK):\n");
+ s = strtok(buf, ",");
+ while (s) {
+ uint8_t b = 0;
+ int addr = (int)strtol(s, NULL, 0);
+ int rr = pvr2_i2c_read(p, (uint8_t)addr, 0x0000,
+ &b, 1);
+ int wr = pvr2_i2c_write(p, (uint8_t)addr, 0x0000,
+ NULL, 0);
+ fprintf(stderr, " 0x%02x: read %s write %s\n",
+ addr, rr == 0 ? "ACK" : "NACK",
+ wr == 0 ? "ACK" : "NACK");
+ s = strtok(NULL, ",");
+ }
+ }
+ }
+
+ /*
+ * MBOXI2C=<n> writes MBOX word <n> on the CX23416, then reads it
+ * back. The chip's own mailbox is where its firmware lives, and
+ * MagicTV reaches the decoder's 0x08xx block through the encoder -
+ * the 24-byte IOCTL buffer it builds is handed to p2usbRZ2.sys, not to
+ * the FX2. So there has to be a mailbox-side I2C request. Sweeping
+ * the writable words and watching for one that changes, or that makes
+ * a decoder register answer, is how to find it.
+ */
+ {
+ const char *mi = getenv("MBOXI2C");
+ if (mi) {
+ uint32_t v = (uint32_t)strtoul(mi, NULL, 0);
+ uint32_t rb = 0;
+ if (pvr2_mbox_write(p, CX_MBOX_BASE, &v, 1) < 0)
+ fprintf(stderr, "MBOXI2C: write failed\n");
+ else if (pvr2_mbox_read(p, CX_MBOX_BASE, &rb, 1) == 0)
+ fprintf(stderr,
+ "MBOXI2C: wrote 0x%08x, reads back "
+ "0x%08x%s\n", v, rb,
+ (rb == v) ? " (held)" : " (changed)");
+ }
+ }
+
+ /*
+ * I2CPROXY=1 does what the Linux driver's prep_config has commented
+ * out: write 0x80000640 to MBOX words 0x01fe and 0x023e. The comment
+ * says Mike Isely saw no behavioural difference, but those two words
+ * are the only place anywhere in the reference drivers that touches
+ * the encoder's own I2C control rather than the decoder over
+ * FX2CMD_I2C_WRITE. If the 0x08xx block is reachable from the
+ * encoder side at all, it is through here.
+ */
+ if (getenv("I2CPROXY")) {
+ uint32_t v = 0x80000640;
+ pvr2_mbox_write(p, 0x01fe, &v, 1);
+ pvr2_mbox_write(p, 0x023e, &v, 1);
+ fprintf(stderr, "I2CPROXY: 0x01fe/0x023e = 0x%08x\n", v);
+ {
+ uint8_t b = 0;
+ int rc = pvr2_i2c_read(p, CX2584X_I2C_ADDR, 0x0810,
+ &b, 1);
+ fprintf(stderr, " 0x0810 now = 0x%02x (%s)\n", b,
+ (rc == 0) ? "read ok" : "read failed");
+ }
+ }
+
+ if (getenv("CHIPID")) {
+ uint8_t id0 = 0, id1 = 0;
+ int rc = pvr2_i2c_read(p, CX2584X_I2C_ADDR, 0x0100, &id0, 1);
+ if (rc == 0)
+ rc = pvr2_i2c_read(p, CX2584X_I2C_ADDR, 0x0101, &id1, 1);
+ if (rc == 0) {
+ unsigned int v = ((unsigned)id1 << 8) | id0;
+ print_chip_id(v);
+ } else
+ fprintf(stderr, "CHIPID: 0x0100 read failed\n");
+ }
+
+ if (getenv("MBOXSCAN")) {
+ uint32_t base;
+ fprintf(stderr, "CX23416 MBOX scan (non-zero dwords only):\n");
+ for (base = 0; base < 0x2000; base += 0x100) {
+ int found = 0;
+ uint32_t off;
+ for (off = 0; off < 0x100; off += 4) {
+ uint32_t v = 0;
+ if (pvr2_mbox_read(p, base + off, &v, 1) != 0)
+ continue;
+ if (v) {
+ if (!found) {
+ fprintf(stderr, " 0x%04x:",
+ base);
+ found = 1;
+ }
+ fprintf(stderr, " [%03x]=%08x", off, v);
+ }
+ }
+ if (found)
+ fprintf(stderr, "\n");
+ }
+ }
+
+ /*
+ * W810=1 does what the official driver's FUN_00026b58 does: read
+ * 0x0810, set bit 0, write it back. If the read returns 0x00 and
+ * the write does not stick, the audio gate cannot be reached on
+ * this part, which is what Linux implies with its
+ * "Don't write into audio registers on cx2583x chips" early return.
+ */
+ /*
+ * I2CVIA=1 retries the 0x08xx write/read a few different ways.
+ * Plain I2C reports success but the value never reads back, so this
+ * rules out the remaining variables one at a time: a 4-byte write
+ * (the driver's own {u32 reg,u32 val} table format), a write of two
+ * bytes instead of one, and a read back immediately after the write
+ * with no intervening command. If none of them stick, the block is
+ * genuinely not reachable over this bus on CX25843.
+ */
+ if (getenv("I2CVIA")) {
+ uint8_t one[1] = { 0x01 };
+ uint8_t four[4] = { 0x01, 0x00, 0x00, 0x00 };
+ uint8_t two[2] = { 0x00, 0x01 };
+ uint8_t rb[4];
+ struct { const char *name; const uint8_t *d; int n; } w[] = {
+ { "1 byte 0x01", one, 1 },
+ { "2 bytes 0x0001", two, 2 },
+ { "4 bytes LE 1", four, 4 },
+ };
+ size_t k;
+ for (k = 0; k < 3; k++) {
+ uint8_t v = 0;
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0810, w[k].d, w[k].n);
+ memset(rb, 0, sizeof rb);
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, 0x0810, rb,
+ w[k].n) == 0)
+ fprintf(stderr, " 0x0810 via %-16s -> %02x %s\n",
+ w[k].name, rb[0],
+ (rb[0] != 0) ? "STUCK" : "lost");
+ else
+ fprintf(stderr, " 0x0810 via %-16s -> read failed\n",
+ w[k].name);
+ v = 0; (void)v;
+ }
+ /* and the driver's own table format: {u32 reg, u32 val} */
+ {
+ uint8_t tbl[8];
+ tbl[0] = 0x10; tbl[1] = 0x08; tbl[2] = 0; tbl[3] = 0;
+ tbl[4] = 0x01; tbl[5] = 0; tbl[6] = 0; tbl[7] = 0;
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0000, tbl, 0);
+ /* bulk form the driver actually uses: several
+ * {reg,val} pairs in one transfer, reg addresses
+ * are NOT included in the length field */
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0810, tbl + 4, 4);
+ memset(rb, 0, sizeof rb);
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, 0x0810, rb, 1) == 0)
+ fprintf(stderr, " 0x0810 via driver table fmt -> %02x %s\n",
+ rb[0], (rb[0] != 0) ? "STUCK" : "lost");
+ }
+ }
+
+ if (getenv("W810")) {
+ uint8_t b = 0;
+ fprintf(stderr, "W810: official audio-enable sequence\n");
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, 0x0810, &b, 1) == 0)
+ fprintf(stderr, " read 0x0810 = 0x%02x\n", b);
+ b |= 1;
+ if (pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0810, &b, 1) == 0)
+ fprintf(stderr, " write 0x0810 = 0x%02x (ok)\n", b);
+ else
+ fprintf(stderr, " write 0x0810 FAILED\n");
+ {
+ uint8_t v = 0;
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, 0x0810, &v, 1) == 0)
+ fprintf(stderr, " readback 0x0810 = 0x%02x%s\n",
+ v, (v == b) ? " STUCK" : " LOST");
+ }
+ }
+
+ if (getenv("R810")) {
+ uint8_t b;
+ uint16_t rs[] = { 0x0800, 0x0808, 0x0810, 0x0811, 0x0812,
+ 0x0820, 0x0830, 0x0900, 0x0914, 0x0918 };
+ size_t k;
+ fprintf(stderr, "0x08xx/0x09xx reachability test:\n");
+ for (k = 0; k < sizeof(rs) / sizeof(rs[0]); k++) {
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, rs[k], &b, 1) == 0)
+ fprintf(stderr, " 0x%04x = 0x%02x\n", rs[k], b);
+ else
+ fprintf(stderr, " 0x%04x = READ FAILED\n", rs[k]);
+ }
+ }
+
+ if (getenv("READBACK")) {
+ uint8_t b;
+ static const uint16_t rl[] = { 0x0100, 0x0101, 0x0102, 0x0103, 0x0401, 0x0105,
+ 0x0115, 0x0116, 0x0808, 0x080b,
+ 0x0914, 0x0918, 0x0919 };
+ size_t k;
+ fprintf(stderr, "readback after init:\n");
+ for (k = 0; k < sizeof(rl) / sizeof(rl[0]); k++)
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, rl[k], &b, 1) == 0)
+ fprintf(stderr, " 0x%04x = 0x%02x (%3u)\n",
+ rl[k], b, b);
+ }
+ fprintf(stderr, "video decoder started\n");
+
+ /*
+ * GPIOOUT=<hex> / GPIODIR=<hex> drive the CX23416's card GPIO block
+ * (0x900c output value, 0x9020 direction) -- the same registers ivtv
+ * uses to select a card's audio input. On ivtv cards the audio
+ * source mux hangs off these bits, e.g. Yuan MPG600/MPG160
+ * (ivtv-gpio.c):
+ *
+ * bit 15 14 = IN1 IN0 1 0 = Line, 0 0 = Tuner
+ * bit 3..0 = AM3..AM0 audio mode (mute/stereo/mono)
+ * MPG600 ships DIR=0x3080 / OUT=0x000C
+ *
+ * This unit measures DIR=0x0000c400, i.e. bits 15, 14 and 10 are
+ * already configured as outputs, so the NJM2750M audio selector
+ * (CNT1/CNT2, 4 inputs, IN4 = the RCA jack per the board trace) is a
+ * plausible consumer of exactly those bits. That makes the audio
+ * *source* selectable in software after all -- it was never a
+ * CX25837 register, it is a GPIO-driven analog mux.
+ *
+ * Safety: GPIODIR is OR'd into 0x9020 (never a plain assignment, so
+ * the other outputs survive), and the sweep only ever toggles bits
+ * that the firmware *already* drives as outputs (14, 15, 10). Do
+ * not make a new bit an output until a board reading says it is safe.
+ */
+ {
+ const char *go = getenv("GPIOOUT");
+ const char *gd = getenv("GPIODIR");
+ if (go || gd) {
+ if (gd) {
+ uint32_t cur = 0, dir;
+ if (pvr2_read_reg(p, CX_REG_GPIO_DIR, &cur) == 0)
+ dir = cur | (uint32_t)strtoul(gd, NULL, 0);
+ else
+ dir = (uint32_t)strtoul(gd, NULL, 0);
+ pvr2_write_reg(p, CX_REG_GPIO_DIR, dir);
+ }
+ if (go)
+ pvr2_write_reg(p, CX_REG_GPIO_OUT,
+ (uint32_t)strtoul(go, NULL, 0));
+ {
+ uint32_t ro = 0, rd = 0, ri = 0;
+ pvr2_read_reg(p, CX_REG_GPIO_OUT, &ro);
+ pvr2_read_reg(p, CX_REG_GPIO_DIR, &rd);
+ pvr2_read_reg(p, 0x9008, &ri);
+ fprintf(stderr, "GPIO: out=0x%08x dir=0x%08x "
+ "in=0x%08x\n", ro, rd, ri);
+ }
+ }
+ }
+
+ /*
+ * DECGPIO=<0x160>:<0x164> writes the CX25837's *own* GPIO block:
+ * 0x160 is the output-enable, 0x164 the output data.
+ *
+ * The Linux cx25840 driver writes 0x160=0x1d / 0x164=0x00 for every
+ * board it supports, with this comment:
+ *
+ * "Drive GPIO2 direction and values for HVR1700 where an onboard
+ * mux selects the output of demodulator vs the 417. Failure to
+ * set this results in no DTV. It's safe to set this across all
+ * Hauppauge boards currently, regardless of the board type."
+ *
+ * So 0x160/0x164 is the decoder's board-level GPIO and is *known* to
+ * drive an onboard multiplexer. This board's audio source selector
+ * is the NJM2750M (CNT1/CNT2, 4 inputs, IN4 = the RCA jack per the
+ * board trace), and the 308-entry vendor table never touches 0x016x
+ * at all -- so the mux is left at whatever the pull resistors give.
+ * That makes this the most plausible place for the audio-source
+ * select to live.
+ */
+ {
+ const char *dg = getenv("DECGPIO");
+ if (dg) {
+ unsigned int oe = 0, dat = 0;
+ uint8_t v;
+ if (sscanf(dg, "%x:%x", &oe, &dat) == 2) {
+ v = (uint8_t)oe;
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0160, &v, 1);
+ v = (uint8_t)dat;
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0164, &v, 1);
+ }
+ {
+ uint8_t a = 0, b = 0;
+ pvr2_i2c_read(p, CX2584X_I2C_ADDR, 0x0160, &a, 1);
+ pvr2_i2c_read(p, CX2584X_I2C_ADDR, 0x0164, &b, 1);
+ fprintf(stderr, "DECGPIO: 0x160(OE)=0x%02x "
+ "0x164(data)=0x%02x\n", a, b);
+ }
+ }
+ }
+
+ /*
+ * ENCDIAG=1 dumps the CX23416's own register space around the audio
+ * path, read back *after* the encoder is configured and started.
+ *
+ * Why: every software-visible audio control (SET_AUDIO_PROPERTIES,
+ * SET_AUDIO_ID, MUTE_AUDIO, the CX25837 serial-audio registers) has
+ * been swept without producing a single audio PES, and MUTE_AUDIO=1
+ * (documented to emit a *silent* audio stream) produces none either --
+ * so the encoder itself is not generating audio. The chip's own
+ * status is the next thing to look at rather than another guess at a
+ * register table:
+ *
+ * 0x9008 GPIO get input state (audio-path strap / ADC presence?)
+ * 0x900c GPIO set output state
+ * 0x9020 GPIO direction
+ * 0x9050 SPU control (bit0 must be set for SPU running)
+ * 0x9054 Reset HW blocks
+ * 0x9058 VPU control
+ * 0x2D00 AO (audio output) control
+ * 0xa064 APU command
+ *
+ * A zeroed 0x9050/0x2d00 block while video runs is evidence the audio
+ * half of the chip was never brought up; a non-zero block that still
+ * yields no PES points upstream at the ADC/I2S wiring.
+ */
+ if (getenv("ENCDIAG")) {
+ static const struct { uint16_t reg; const char *name; } er[] = {
+ { 0x0040, "interrupt status" },
+ { 0x0048, "interrupt mask" },
+ { 0x2800, "video display module control" },
+ { 0x2d00, "AO (audio output) control" },
+ { 0x2d24, "bytes flushed" },
+ { 0x9008, "GPIO get input state" },
+ { 0x900c, "GPIO set output state" },
+ { 0x9020, "GPIO direction" },
+ { 0x9050, "SPU control" },
+ { 0x9054, "reset HW blocks" },
+ { 0x9058, "VPU control" },
+ { 0xa018, "interrupt pending" },
+ { 0xa064, "APU command" },
+ };
+ size_t k;
+ fprintf(stderr, "ENCDIAG: CX23416 register space (after start)\n");
+ for (k = 0; k < sizeof(er) / sizeof(er[0]); k++) {
+ uint32_t v = 0;
+ if (pvr2_read_reg(p, er[k].reg, &v) == 0)
+ fprintf(stderr, " 0x%04x = 0x%08x %s\n",
+ er[k].reg, v, er[k].name);
+ else
+ fprintf(stderr, " 0x%04x = READ FAILED %s\n",
+ er[k].reg, er[k].name);
+ }
+ /*
+ * AODUMP=1 - walk the CX23416's audio output (AO) block,
+ * 0x2d00-0x2d3f, to find a counter that moves. 0x2d24 is the
+ * one this project has been watching ("bytes flushed", always
+ * 0), but if that is the wrong register the whole conclusion
+ * "the encoder emits no audio" rests on a bad measurement.
+ * Comparing this dump between MUTEAUDIO=0 and MUTEAUDIO=1
+ * shows whether ANY part of the audio path moves.
+ */
+ if (getenv("AODUMP")) {
+ uint16_t r;
+ fprintf(stderr, "AODUMP 0x2d00-0x2d3f:\n");
+ for (r = 0x2d00; r <= 0x2d3f; r++) {
+ uint32_t v = 0;
+ if (pvr2_read_reg(p, r, &v) == 0 && v != 0)
+ fprintf(stderr, " 0x%04x = 0x%08x\n", r, v);
+ }
+ fprintf(stderr, "AODUMP 0xa000-0xa07f:\n");
+ for (r = 0xa000; r <= 0xa07f; r++) {
+ uint32_t v = 0;
+ if (pvr2_read_reg(p, r, &v) == 0 && v != 0)
+ fprintf(stderr, " 0x%04x = 0x%08x\n", r, v);
+ }
+ }
+ }
+
+ /*
+ * EPSCAN=1 : the board exposes FOUR bulk IN endpoints (0x81, 0x84,
+ * 0x86, 0x88). kare only ever reads 0x84 (MPEG PS). Before
+ * dismissing a separate-audio-pipe design, sniff the other three
+ * while the encoder is running: any endpoint that returns
+ * continuous data here is a second stream (audio/VBI/raw).
+ */
+ if (getenv("EPSCAN")) {
+ static const uint8_t eps[] = { 0x81, 0x86, 0x88 };
+ size_t ei;
+ for (ei = 0; ei < sizeof(eps) / sizeof(eps[0]); ei++) {
+ uint8_t buf[4096];
+ int n, got, k, total = 0, r;
+ fprintf(stderr, "EPSCAN: probing 0x%02x\n", eps[ei]);
+ for (n = 0; n < 3; n++) {
+ got = 0;
+ r = libusb_bulk_transfer(p->dev, eps[ei],
+ buf, sizeof(buf),
+ &got, 500);
+ if (r != 0) {
+ fprintf(stderr, " read err %s\n",
+ libusb_error_name(r));
+ break;
+ }
+ total += got;
+ if (n == 0 && got > 0) {
+ fprintf(stderr, " first %d:", got);
+ for (k = 0; k < 16 && k < got; k++)
+ fprintf(stderr, " %02x",
+ buf[k]);
+ fprintf(stderr, "\n");
+ }
+ }
+ fprintf(stderr, " total %d bytes in 3 reads\n",
+ total);
+ }
+ }
+
+ /*
+ * -P [user]: run a player as another (non-root) user and feed it the
+ * stream directly through a pipe. kare keeps root (it needs the USB
+ * node), the player drops to `user` (VLC refuses to run as root), and
+ * because this is a real pipe between two processes neither the
+ * /dev/fd namespace problem with su(1) nor the S_IFIFO stat problem
+ * with a named pipe applies.
+ */
+ if (0) {
+ /* unused */
+ } else if (!strcmp(out_path, "-")) {
+ out_fp = stdout;
+#if defined(_WIN32)
+ _setmode(_fileno(stdout), _O_BINARY);
+#endif
+ /* Pipelining to a live player: make sure data reaches the
+ * reader promptly instead of sitting in a stdio buffer. */
+ setvbuf(out_fp, NULL, _IONBF, 0);
+ fprintf(stderr, "piping to stdout (Ctrl-C to stop)\n");
+ } else {
+ out_fp = fopen(out_path, "wb");
+ }
+ if (!out_fp) {
+ fprintf(stderr, "cannot open output %s\n", out_path);
+ ret = 1;
+ goto outexit;
+ }
+
+ signal(SIGINT, on_sigint);
+#if !defined(_WIN32)
+ signal(SIGTERM, on_sigint);
+ /* When the player closes the pipe we must still run our own shutdown
+ * (which sends CX2341X_ENC_STOP_CAPTURE); SIGPIPE would kill us
+ * mid-cleanup and leave the encoder running. */
+ signal(SIGPIPE, SIG_IGN);
+#endif
+
+ fprintf(stderr, "capturing to %s ... (Ctrl-C to stop)\n", out_path);
+ clock_gettime(CLOCK_MONOTONIC, &t0);
+
+ /* Prepare the player child process. We fork here, drop privileges in
+ * the child, and exec VLC with our pipe already on its stdin. This
+ * avoids su(1) entirely: su starts a fresh devfs namespace where
+ * /dev/fd is empty, so VLC's "fd://0" cannot be opened. Here the
+ * child inherits the real pipe, so "-"/fd://0 resolves to it. */
+ if (auto_player && player_user) {
+ /*
+ * -W: start VLC once, right now, and feed it a real pipe.
+ * kare stays root (USB node), the child drops to
+ * player_user (VLC refuses root) and inherits the pipe on fd 0.
+ * No su(1) (its devfs namespace hides /dev/fd), no FIFO
+ * (S_IFIFO, stat size 0 makes players buffer), no files, and
+ * crucially no restart loop: VLC reads this one stream for as
+ * long as we write, so there is no re-probe and no lag.
+ */
+ int pfd[2];
+ if (pipe(pfd) < 0) {
+ fprintf(stderr, "pipe failed\n");
+ ret = 1;
+ goto outexit;
+ }
+ fflush(NULL);
+ {
+ pid_t pid = fork();
+ if (pid == 0) {
+ const char *disp = getenv("DISPLAY");
+ close(pfd[1]);
+ dup2(pfd[0], STDIN_FILENO);
+ if (pfd[0] != STDIN_FILENO)
+ close(pfd[0]);
+ if (setuid_name(player_user) < 0)
+ _exit(127);
+ setenv("DISPLAY", disp ? disp : ":0", 1);
+ setenv("HOME", "/home/beatrice", 1);
+ {
+ char xa[512];
+ struct passwd *pw =
+ getpwnam(player_user);
+ snprintf(xa, sizeof(xa), "%s/.Xauthority",
+ pw ? pw->pw_dir
+ : "/home/beatrice");
+ setenv("XAUTHORITY", xa, 1);
+ }
+ setenv("XDG_RUNTIME_DIR", "/tmp/xdg", 1);
+ if (raw_mode) {
+ /* y4m/raw: let VLC detect the format.
+ * Forcing --demux=ps makes it refuse. */
+ if (hm12_interlace)
+ execlp("cvlc", "cvlc",
+ "--vout=xcb_xv",
+ "--file-caching=0",
+ "--deinterlace=1",
+ hm12_interlace == 1 ?
+ "--deinterlace-mode=blend" :
+ "--deinterlace-mode=blend",
+ "--drop-late-frames",
+ "--skip-frames",
+ "--no-video-title-show", "-",
+ (char *)NULL);
+ execlp("cvlc", "cvlc",
+ "--vout=xcb_xv",
+ "--file-caching=0",
+ "--drop-late-frames", "--skip-frames",
+ "--no-video-title-show", "-",
+ (char *)NULL);
+ } else {
+ execlp("cvlc", "cvlc",
+ "--vout=xcb_xv", "--demux=ps",
+ "--file-caching=0",
+ "--avcodec-hurry-up",
+ "--clock-jitter=0",
+ "--clock-synchro=0",
+ "--drop-late-frames",
+ "--skip-frames",
+ "--no-video-title-show", "-",
+ (char *)NULL);
+ }
+ _exit(127);
+ }
+ if (pid < 0) {
+ fprintf(stderr, "fork failed\n");
+ ret = 1;
+ goto outexit;
+ }
+ close(pfd[0]);
+ out_fp = fdopen(pfd[1], "wb");
+ if (!out_fp) {
+ fprintf(stderr, "fdopen failed\n");
+ ret = 1;
+ goto outexit;
+ }
+ setvbuf(out_fp, NULL, _IONBF, 0);
+ fprintf(stderr, "started cvlc as %s (pid %d)\n",
+ player_user, (int)pid);
+ }
+ } else if (player_user) {
+ fprintf(stderr, "streaming to stdout for user %s "
+ "(no player started)\n", player_user);
+ }
+
+ /* Live mode: one continuously-written regular file. */
+ if (live_mode) {
+ if (!*live_path) {
+ fprintf(stderr, "--live needs a path\n");
+ ret = 1;
+ goto outexit;
+ }
+ live_fp = fopen(live_path, "wb");
+ if (!live_fp) {
+ fprintf(stderr, "cannot open %s\n", live_path);
+ ret = 1;
+ goto outexit;
+ }
+ fprintf(stderr, "live mode: writing %s\n", live_path);
+ }
+
+ /* -B/--planes: open the per-plane PGM dumps (files are created on
+ * the first frame, once the frame size is known). */
+ if (planes_prefix)
+ hm12_planes_open(planes_prefix);
+ if (luma_path && hm12_luma_open(luma_path) != 0)
+ fprintf(stderr, "luma output disabled\n");
+ if (raw_hm12_path) {
+ raw_hm12_fp = fopen(raw_hm12_path, "wb");
+ if (!raw_hm12_fp)
+ fprintf(stderr, "cannot open %s\n", raw_hm12_path);
+ }
+
+ g_cap = pvr2_capture_new(p, data_cb, NULL);
+ if (!g_cap) {
+ fprintf(stderr, "cannot create capture context\n");
+ ret = 1;
+ goto outexit;
+ }
+ /* Make the capture context end the encoder capture (0x82) before it
+ * turns USB streaming off, with the values the capture started with. */
+ if (enc_started)
+ pvr2_capture_set_enc_stop(g_cap, enc_captype, enc_subtype);
+
+ /* If a time limit is set, run the capture in a worker thread so the
+ * main thread can time it out. Without a limit we run in-thread. */
+ if (limit_sec > 0) {
+ run_capture_timed(g_cap, limit_sec);
+ } else {
+ if (pvr2_capture_run(g_cap) < 0 && !g_stop)
+ ret = 1;
+ }
+
+ {
+ struct timespec t1;
+ double secs;
+ pvr2_capture_stats_t st;
+ clock_gettime(CLOCK_MONOTONIC, &t1);
+ secs = (double)(t1.tv_sec - t0.tv_sec) +
+ (double)(t1.tv_nsec - t0.tv_nsec) / 1e9;
+ /*
+ * ENCDIAG also dumps the audio-path registers a second time,
+ * after the capture, so the two dumps can be compared. The
+ * one that matters is 0x2d24 "bytes flushed": if the audio
+ * output block were passing samples, it would have moved.
+ */
+ if (getenv("ENCDIAG") && p) {
+ uint32_t ao = 0, bf = 0, apu = 0;
+ pvr2_read_reg(p, 0x2d00, &ao);
+ pvr2_read_reg(p, 0x2d24, &bf);
+ pvr2_read_reg(p, 0xa064, &apu);
+ fprintf(stderr, "ENCDIAG after capture: "
+ "0x2d00=0x%08x 0x2d24(bytes flushed)=0x%08x "
+ "0xa064(APU)=0x%08x\n", ao, bf, apu);
+
+ /*
+ * Read the decoder's clock/PLL/serial registers back.
+ *
+ * Everything known about these so far comes from the
+ * values that were WRITTEN (vendor table, XP driver
+ * capture). Reading them after a run is the only way
+ * to tell "programmed and latched" from "the write
+ * never landed". Points of interest:
+ * 0x0127 SA_MCLK_SEL/DIV -- 0x50 was written, and
+ * pvr2_cx25837_pll_test read 0x00 here once
+ * 0x0118/0x011c PLL words (Linux uses
+ * 0x00000414 / 0x01d1744c)
+ * 0x0115/0x0116 serial-audio enable bits
+ * 0x0160/0x0164 the GPIO block Linux documents as
+ * driving an on-board mux
+ * A register that answers ERR, or answers something
+ * other than what was written, is one where the write
+ * is not taking effect.
+ */
+ {
+ static const uint16_t dr[] = {
+ 0x0108, 0x0109, 0x010a, 0x010b,
+ 0x0110, 0x0111, 0x0112, 0x0113,
+ 0x0115, 0x0116, 0x0118, 0x0119,
+ 0x011a, 0x011b, 0x011c, 0x011d,
+ 0x011e, 0x011f, 0x0127, 0x0128,
+ 0x0129, 0x012a, 0x012b, 0x012c,
+ 0x012d, 0x012e, 0x0160, 0x0164,
+ 0x0140, 0x0141,
+ };
+ size_t k;
+ for (k = 0; k < sizeof(dr) / sizeof(dr[0]); k++) {
+ uint8_t v = 0xee;
+ int rc = pvr2_i2c_read(p, CX2584X_I2C_ADDR,
+ dr[k], &v, 1);
+ fprintf(stderr, " DEC 0x%04x = %s%02x\n",
+ dr[k], rc < 0 ? "ERR " : "", v);
+ }
+ }
+ }
+ fprintf(stderr, "\ncaptured %llu bytes in %.1f s (%.2f Mbit/s)\n",
+ total_bytes, secs,
+ secs > 0 ? (total_bytes * 8.0 / 1e6) / secs : 0.0);
+ fprintf(stderr, "pes: %lu video (0xE0), %lu audio (0xC0-0xDF), "
+ "%lu other start codes\n",
+ video_pes_count, audio_pes_count, other_pes_count);
+ /*
+ * ★ In raw mode there are no PES start codes to count by
+ * design, so the "pes: 0/0/0" line the user kept seeing is
+ * not a fault. Report the HM12 frame counter instead.
+ */
+ if (raw_mode)
+ fprintf(stderr, "raw: %lu HM12 frames, %llu bytes\n",
+ raw_frame_count, total_bytes);
+ if (g_cap) {
+ pvr2_capture_stats(g_cap, &st);
+ fprintf(stderr,
+ "usb: %ld packets, %ld short, %ld zero, "
+ "%ld stall, %ld overflow, %ld errors\n",
+ st.packets, st.short_xfer, st.zero_xfer,
+ st.stall, st.overflow, st.errors);
+ }
+ }
+
+outexit:
+ if (getenv("REGDUMP"))
+ reg_dump(p, "end");
+ if (split_av)
+ split_flush();
+ pcm_close();
+ if (raw_hm12_fp)
+ fclose(raw_hm12_fp);
+ hm12_luma_close();
+ hm12_planes_close();
+ if (live_fp) {
+ fflush(live_fp);
+ fclose(live_fp);
+ live_fp = NULL;
+ }
+ if (out_fp) {
+ fclose(out_fp);
+ out_fp = NULL;
+ }
+ pvr2_capture_free(g_cap);
+ g_cap = NULL;
+ pvr2_exit(p);
+out_free:
+ free(cx_fw);
+ free(fx2_fw);
+ free(p);
+ return ret;
+}