summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/capture.c210
-rw-r--r--src/cx2584x_audio.c121
-rw-r--r--src/cx2584x_pll_test.c85
-rw-r--r--src/cx2584x_ser_init.c317
-rw-r--r--src/cx2584x_ser_test.c63
-rw-r--r--src/cx2584x_tables.c376
-rw-r--r--src/device.c583
-rw-r--r--src/driver_seq.c67
-rw-r--r--src/encoder.c1085
-rw-r--r--src/firmware.c401
-rw-r--r--src/hm12.c510
-rw-r--r--src/kare.c5340
-rw-r--r--src/spoon.c1969
-rw-r--r--src/test_cx.c174
-rw-r--r--src/test_mbox.c113
15 files changed, 11414 insertions, 0 deletions
diff --git a/src/capture.c b/src/capture.c
new file mode 100644
index 0000000..6063991
--- /dev/null
+++ b/src/capture.c
@@ -0,0 +1,210 @@
+/*
+ * capture.c - USB bulk stream capture from EP 0x84
+ *
+ * Part of mpegcap.
+ *
+ * The MPEG-2 program stream arrives on bulk endpoint 0x84. We use
+ * libusb's async API with a small pool of transfers so that there is
+ * always a pending read (required for reliable high-bandwidth capture).
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "pvrusb2.h"
+#include "capture.h"
+
+#define NUM_TRANSFERS 4
+#define TRANSFER_SIZE 0x20000
+
+struct pvr2_capture {
+ pvr2_dev *p;
+ pvr2_data_cb cb;
+ void *user;
+ libusb_transfer *xfer[NUM_TRANSFERS];
+ uint8_t *buf[NUM_TRANSFERS];
+ volatile int stop;
+ volatile int errors;
+ /* diagnostics: USB stream health. Short/zero-length completions mean
+ * the encoder is not keeping up and frames are being lost, which shows
+ * up as a large latency in the player because the PTS still advances at
+ * the nominal frame rate. */
+ volatile long pkts; /* completed non-empty transfers */
+ volatile long short_xfer; /* completed, but < TRANSFER_SIZE */
+ volatile long zero_xfer; /* completed with 0 bytes */
+ volatile long stall; /* LIBUSB_TRANSFER_STALL */
+ volatile long overflow; /* LIBUSB_TRANSFER_OVERFLOW */
+ /* encoder (type, subtype) this capture was started with, so the stop
+ * command can be sent with the same values before streaming off */
+ int enc_stop_valid;
+ uint32_t enc_type, enc_subtype;
+};
+
+static void LIBUSB_CALL capture_cb(struct libusb_transfer *tr)
+{
+ struct pvr2_capture *c = tr->user_data;
+
+ if (tr->status == LIBUSB_TRANSFER_COMPLETED && tr->actual_length > 0) {
+ c->pkts++;
+ if (tr->actual_length < TRANSFER_SIZE)
+ c->short_xfer++;
+ if (c->cb)
+ c->cb(tr->buffer, tr->actual_length, c->user);
+ } else if (tr->status == LIBUSB_TRANSFER_COMPLETED) {
+ c->zero_xfer++; /* empty completion: no data, not an error */
+ } else if (tr->status == LIBUSB_TRANSFER_STALL) {
+ c->stall++;
+ c->errors++;
+ if (c->errors > 100)
+ c->stop = 1;
+ return;
+ } else if (tr->status == LIBUSB_TRANSFER_OVERFLOW) {
+ c->overflow++;
+ c->errors++;
+ if (c->errors > 100)
+ c->stop = 1;
+ return;
+ } else if (tr->status == LIBUSB_TRANSFER_NO_DEVICE ||
+ tr->status == LIBUSB_TRANSFER_ERROR) {
+ c->errors++;
+ if (c->errors > 100)
+ c->stop = 1;
+ return;
+ }
+
+ if (!c->stop) {
+ if (libusb_submit_transfer(tr) != 0) {
+ c->errors++;
+ if (c->errors > 100)
+ c->stop = 1;
+ }
+ }
+}
+
+pvr2_capture_t *pvr2_capture_new(pvr2_dev *p, pvr2_data_cb cb, void *user)
+{
+ struct pvr2_capture *c = calloc(1, sizeof(*c));
+ int i;
+
+ if (!c)
+ return NULL;
+ c->p = p;
+ c->cb = cb;
+ c->user = user;
+
+ for (i = 0; i < NUM_TRANSFERS; i++) {
+ c->buf[i] = malloc(TRANSFER_SIZE);
+ c->xfer[i] = libusb_alloc_transfer(0);
+ if (!c->buf[i] || !c->xfer[i]) {
+ pvr2_capture_free(c);
+ return NULL;
+ }
+ libusb_fill_bulk_transfer(c->xfer[i], p->dev, EP_VIDEO_IN,
+ c->buf[i], TRANSFER_SIZE,
+ capture_cb, c, 0);
+ }
+ return c;
+}
+
+void pvr2_capture_stop(pvr2_capture_t *c)
+{
+ if (c)
+ c->stop = 1;
+}
+
+void pvr2_capture_set_enc_stop(pvr2_capture_t *c, uint32_t captype,
+ uint32_t subtype)
+{
+ if (!c)
+ return;
+ c->enc_type = captype;
+ c->enc_subtype = subtype;
+ c->enc_stop_valid = 1;
+}
+
+int pvr2_capture_run(pvr2_capture_t *c)
+{
+ int i, r;
+
+ for (i = 0; i < NUM_TRANSFERS; i++) {
+ r = libusb_submit_transfer(c->xfer[i]);
+ if (r != 0) {
+ fprintf(stderr, "submit transfer failed: %s\n",
+ libusb_error_name(r));
+ return -1;
+ }
+ }
+
+ if (pvr2_streaming_on(c->p) < 0) {
+ fprintf(stderr, "streaming on (0x36) failed\n");
+ return -1;
+ }
+
+ while (!c->stop) {
+ struct timeval tv = { 0, 250000 };
+ r = libusb_handle_events_timeout_completed(c->p->ctx, &tv, NULL);
+ if (r != 0 && r != LIBUSB_ERROR_TIMEOUT) {
+ if (r == LIBUSB_ERROR_INTERRUPTED)
+ continue;
+ fprintf(stderr, "handle_events: %s\n", libusb_error_name(r));
+ break;
+ }
+ }
+
+ /*
+ * ★ Tell the encoder to end the capture BEFORE switching USB
+ * streaming off (vendor order: 0x82 then 0x37; yacxm does the same
+ * and then waits for the EOS interrupt). Without this the encoder
+ * keeps its mode and frame buffer, so the next run -- especially one
+ * that changes capture type (MPEG -> raw) -- came up stuck showing
+ * the previous buffer. NOENCSTOP=1 skips it, which is how that
+ * symptom is reproduced on purpose (A/B).
+ */
+ if (c->enc_stop_valid && !getenv("NOENCSTOP")) {
+ uint32_t when = (c->enc_type == 0) ? 0 : 1; /* MPEG: end of GOP */
+ pvr2_encoder_stop(c->p, c->enc_type, c->enc_subtype, when);
+ /* let the firmware deliver the tail / EOS */
+ {
+ struct timeval tv = { 0, 300000 };
+ libusb_handle_events_timeout_completed(c->p->ctx, &tv,
+ NULL);
+ }
+ }
+
+ pvr2_streaming_off(c->p);
+ for (i = 0; i < NUM_TRANSFERS; i++)
+ libusb_cancel_transfer(c->xfer[i]);
+ {
+ struct timeval tv = { 0, 200000 };
+ libusb_handle_events_timeout_completed(c->p->ctx, &tv, NULL);
+ }
+ return c->errors ? -1 : 0;
+}
+
+void pvr2_capture_stats(pvr2_capture_t *c, pvr2_capture_stats_t *st)
+{
+ if (!st)
+ return;
+ memset(st, 0, sizeof(*st));
+ if (!c)
+ return;
+ st->packets = c->pkts;
+ st->short_xfer = c->short_xfer;
+ st->zero_xfer = c->zero_xfer;
+ st->stall = c->stall;
+ st->overflow = c->overflow;
+ st->errors = c->errors;
+}
+
+void pvr2_capture_free(pvr2_capture_t *c)
+{
+ int i;
+ if (!c)
+ return;
+ for (i = 0; i < NUM_TRANSFERS; i++) {
+ if (c->xfer[i])
+ libusb_free_transfer(c->xfer[i]);
+ free(c->buf[i]);
+ }
+ free(c);
+}
diff --git a/src/cx2584x_audio.c b/src/cx2584x_audio.c
new file mode 100644
index 0000000..b801652
--- /dev/null
+++ b/src/cx2584x_audio.c
@@ -0,0 +1,121 @@
+/*
+ * cx2584x_audio.c - CX2584x audio clock/serial-port configuration
+ *
+ * Part of mpegcap.
+ *
+ * This table was recovered by reverse-engineering the official Windows
+ * driver (p2usbRZ2.sys) with Ghidra. In the driver the decoder object's
+ * set_sample_rate method (FUN_0002597b) selects one of several register
+ * tables based on the requested rate and the "MakoUseFW" flag, writes the
+ * table over I2C to device 0x44, then read-modify-writes register 0x012b
+ * with bit0 set to start the audio DSP.
+ *
+ * The entries below are the MakoUseFW=1 (driver default) tables, verbatim:
+ * FUN_0002597b: table base local_57c+0x90 = 48000 Hz
+ * table base local_57c+0xe0 = 44100 Hz
+ * table base local_57c+0xb8 = 32000 Hz
+ *
+ * Without the 0x0900-0x0903 and 0x0128-0x012e writes (which mpegcapt.c
+ * and the Linux driver never issue for this device) the CS5340 ADC is
+ * clocked but the encoder's audio serial path produces no audio PES.
+ */
+#include <stdio.h>
+
+#include "pvrusb2.h"
+
+typedef struct {
+ uint16_t reg;
+ uint8_t val;
+} cx_reg_t;
+
+/* 48000 Hz (driver table @ +0x90) */
+static const cx_reg_t tbl_48000[] = {
+ { 0x0108, 0x0f }, { 0x0109, 0x04 }, { 0x010a, 0x0a }, { 0x010b, 0x10 },
+ { 0x0110, 0xe5 }, { 0x0111, 0xd6 }, { 0x0112, 0x98 }, { 0x0113, 0x00 },
+ { 0x0127, 0x50 },
+ { 0x0900, 0xaa }, { 0x0901, 0x4f }, { 0x0902, 0x01 }, { 0x0903, 0x08 },
+ { 0x0128, 0xf8 }, { 0x0129, 0x93 }, { 0x012a, 0x11 },
+ { 0x012c, 0xff }, { 0x012d, 0x5f }, { 0x012e, 0x20 },
+};
+
+/* 44100 Hz (driver table @ +0xe0) */
+static const cx_reg_t tbl_44100[] = {
+ { 0x0108, 0x0f }, { 0x0109, 0x04 }, { 0x010a, 0x09 }, { 0x010b, 0x10 },
+ { 0x0110, 0xd6 }, { 0x0111, 0x6b }, { 0x0112, 0xec }, { 0x0113, 0x00 },
+ { 0x0127, 0x50 },
+ { 0x0900, 0x59 }, { 0x0901, 0x6d }, { 0x0902, 0x01 }, { 0x0903, 0x08 },
+ { 0x0128, 0x38 }, { 0x0129, 0x7e }, { 0x012a, 0x05 },
+ { 0x012c, 0x8f }, { 0x012d, 0x1b }, { 0x012e, 0x20 },
+};
+
+/* 32000 Hz (driver table @ +0xb8) */
+static const cx_reg_t tbl_32000[] = {
+ { 0x0108, 0x0f }, { 0x0109, 0x04 }, { 0x010a, 0x06 }, { 0x010b, 0x10 },
+ { 0x0110, 0xee }, { 0x0111, 0x39 }, { 0x0112, 0xbb }, { 0x0113, 0x01 },
+ { 0x0127, 0x50 },
+ { 0x0900, 0x7f }, { 0x0901, 0xf7 }, { 0x0902, 0x01 }, { 0x0903, 0x08 },
+ { 0x0128, 0xf8 }, { 0x0129, 0x2e }, { 0x012a, 0x0d },
+ { 0x012c, 0xff }, { 0x012d, 0x2f }, { 0x012e, 0x20 },
+};
+
+int pvr2_cx2584x_audio_config(pvr2_dev *p, int sample_rate)
+{
+ return pvr2_cx2584x_audio_config_opt(p, sample_rate, 0);
+}
+
+/*
+ * skipmask bisects the slice (one run of the capture test per bit):
+ * bit0 (0x1): skip 0x0900-0x0903 (audio PLL block)
+ * bit1 (0x2): skip 0x0108-0x0113 + 0x0127 (aux/rate PLL words) --
+ * reprogramming the aux PLL on a live decoder has killed
+ * the stream here twice (the old -T path, and RATETAB)
+ * bit2 (0x4): skip 0x0128-0x012e (fractional tuning words)
+ * Windows programs this slice on a cold decoder where the PLL words
+ * simply lock before anything consumes them; a warm decoder wedges.
+ */
+int pvr2_cx2584x_audio_config_opt(pvr2_dev *p, int sample_rate, int skipmask)
+{
+ const cx_reg_t *tbl;
+ int n, i, errs = 0;
+ uint8_t v;
+
+ switch (sample_rate) {
+ case 32000: tbl = tbl_32000; n = (int)(sizeof(tbl_32000)/sizeof(tbl_32000[0])); break;
+ case 44100: tbl = tbl_44100; n = (int)(sizeof(tbl_44100)/sizeof(tbl_44100[0])); break;
+ case 48000:
+ default: tbl = tbl_48000; n = (int)(sizeof(tbl_48000)/sizeof(tbl_48000[0])); break;
+ }
+
+ for (i = 0; i < n; i++) {
+ if ((skipmask & 1) &&
+ tbl[i].reg >= 0x0900 && tbl[i].reg <= 0x0903)
+ continue;
+ if ((skipmask & 2) &&
+ ((tbl[i].reg >= 0x0108 && tbl[i].reg <= 0x0113) ||
+ tbl[i].reg == 0x0127))
+ continue;
+ if ((skipmask & 4) &&
+ tbl[i].reg >= 0x0128 && tbl[i].reg <= 0x012e)
+ continue;
+ if (pvr2_i2c_write(p, CX2584X_I2C_ADDR, tbl[i].reg,
+ &tbl[i].val, 1) < 0) {
+ if (p->verbose)
+ fprintf(stderr, "audio cfg: write %04x=%02x failed\n",
+ tbl[i].reg, tbl[i].val);
+ errs++;
+ }
+ }
+
+ /* Trigger: read 0x012b, set bit0, write back (driver FUN_0002597b). */
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, 0x012b, &v, 1) == 0) {
+ v |= 0x01;
+ if (pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x012b, &v, 1) < 0)
+ errs++;
+ } else {
+ errs++;
+ }
+
+ if (errs && p->verbose)
+ fprintf(stderr, "audio cfg: %d error(s)\n", errs);
+ return errs ? -1 : 0;
+}
diff --git a/src/cx2584x_pll_test.c b/src/cx2584x_pll_test.c
new file mode 100644
index 0000000..aad658b
--- /dev/null
+++ b/src/cx2584x_pll_test.c
@@ -0,0 +1,85 @@
+/* cx2584x_pll_test.c - CX25837 PLL / clock block 0x0130-0x0150.
+ *
+ * Extracted from p2usbRZ2.sys .data+0039a0, first-write-wins, low byte.
+ * Format is {u32 reg, u32 val} in the driver, but CX25837's I2C is
+ * 1-byte wide WITH auto-increment, so each register is one byte.
+ *
+ * WHY THIS BLOCK: measured 0x0127 (SA_MCLK_SEL/DIV) = 0x00, i.e. the
+ * serializer MCLK output is OFF. Writing Linux's 0x50 to 0x127 did
+ * NOT make the WM8739 answer on I2C 0x1A. The PLL itself was also
+ * unprogrammed: 0x118 and 0x11c both read 0x00000000 where Linux
+ * writes 0x00000414 and 0x01d1744c for the 28.636 MHz crystal.
+ * This block is the driver's own PLL/clock setup and must go in
+ * BEFORE 0x127 is useful.
+ *
+ * apply=0 : read-only compare against the live decoder, no writes
+ */
+#include "pvrusb2.h"
+#include <stdio.h>
+
+typedef struct { uint16_t reg; uint8_t val; } cx_p8_t;
+
+static const cx_p8_t tbl_pll_0x130[] = {
+ { 0x0130, 0x02 },
+ { 0x0131, 0x00 },
+ { 0x0132, 0x00 },
+ { 0x0133, 0x00 },
+ { 0x0134, 0x02 },
+ { 0x0135, 0x25 },
+ { 0x0136, 0x97 },
+ { 0x0137, 0x0a },
+ { 0x0138, 0x00 },
+ { 0x0139, 0x21 },
+ { 0x013a, 0xe7 },
+ { 0x013b, 0x00 },
+ { 0x013c, 0x00 },
+ { 0x013d, 0x00 },
+ { 0x013e, 0x36 },
+ { 0x013f, 0x00 },
+ { 0x0140, 0x04 },
+ { 0x0141, 0xb0 },
+ { 0x0142, 0x00 },
+ { 0x0143, 0x00 },
+ { 0x0144, 0x10 },
+ { 0x0145, 0x32 },
+ { 0x0146, 0x54 },
+ { 0x0147, 0x76 },
+ { 0x0148, 0x90 },
+ { 0x0149, 0x00 },
+ { 0x014a, 0x00 },
+ { 0x014b, 0x00 },
+ { 0x014c, 0x00 },
+ { 0x014d, 0x00 },
+ { 0x014e, 0x00 },
+ { 0x014f, 0x00 },
+};
+
+int pvr2_cx25837_pll_test(pvr2_dev *p, int apply)
+{
+ int i, n = (int)(sizeof(tbl_pll_0x130)/sizeof(tbl_pll_0x130[0]));
+ int errs = 0, diffs = 0;
+ uint8_t rb;
+
+ fprintf(stderr, "pll-test: 0x0130-0x0150, %d regs, %s\n", n,
+ apply ? "WRITING" : "read-only compare");
+
+ for (i = 0; i < n; i++) {
+ if (apply) {
+ if (pvr2_i2c_write(p, CX2584X_I2C_ADDR,
+ tbl_pll_0x130[i].reg, &tbl_pll_0x130[i].val, 1) < 0)
+ errs++;
+ } else {
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR,
+ tbl_pll_0x130[i].reg, &rb, 1) < 0) {
+ errs++;
+ } else if (rb != tbl_pll_0x130[i].val) {
+ diffs++;
+ fprintf(stderr, "pll-test: 0x%04x table=%02x live=%02x DIFF\n",
+ tbl_pll_0x130[i].reg, tbl_pll_0x130[i].val, rb);
+ }
+ }
+ }
+ fprintf(stderr, "pll-test: %d regs, %d i2c errors, %d differ\n",
+ n, errs, diffs);
+ return errs;
+}
diff --git a/src/cx2584x_ser_init.c b/src/cx2584x_ser_init.c
new file mode 100644
index 0000000..f3ba214
--- /dev/null
+++ b/src/cx2584x_ser_init.c
@@ -0,0 +1,317 @@
+/* cx2584x_ser_init.c - CX25837 register init table extracted from the
+ * official Windows driver p2usbRZ2.sys on 2026-10-04.
+ *
+ * Source: .data+0039a0, 308 entries, format {u32 reg, u32 val} little-endian,
+ * applied by FUN_00025574 via the CX2584x I2C slave (addr 2 = 0x44).
+ *
+ * BYTE GRANULARITY (2026-10-04): the CX25837 I2C slave is ONE byte wide
+ * with auto-increment. Each u32 table entry therefore expands to four
+ * consecutive single-byte register writes (reg, reg+1, reg+2, reg+3) --
+ * exactly the side effects the Windows driver produced on the wire.
+ * A u32 "read back and compare" at reg N instead returns regs N..N+3
+ * and produced 217/308 bogus DIFFs; all comparisons here are 1 byte.
+ *
+ * NOTE: the 0x08xx/0x09xx audio-DSP registers are NOT in this table
+ * (asserted in scripts/expand_ser_table.py); Linux cx25840-audio.c skips
+ * 0x900/0x904/0x90c when is_cx2583x(), and a 0x0900 write was measured
+ * to kill video on this unit. Do not add them.
+ */
+#include "pvrusb2.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+typedef struct { uint16_t reg; uint8_t val; } cx_ser_b_t;
+
+static const cx_ser_b_t tbl_ser_bytes[] = {
+ { 0x0130, 0x02 }, { 0x0131, 0x00 }, { 0x0132, 0x00 }, { 0x0133, 0x00 }, { 0x0130, 0x00 }, { 0x0131, 0x00 },
+ { 0x0132, 0x00 }, { 0x0133, 0x00 }, { 0x0138, 0x00 }, { 0x0139, 0x00 }, { 0x013a, 0x00 }, { 0x013b, 0x00 },
+ { 0x0139, 0x21 }, { 0x013a, 0x00 }, { 0x013b, 0x00 }, { 0x013c, 0x00 }, { 0x013a, 0xe7 }, { 0x013b, 0x00 },
+ { 0x013c, 0x00 }, { 0x013d, 0x00 }, { 0x013b, 0x00 }, { 0x013c, 0x00 }, { 0x013d, 0x00 }, { 0x013e, 0x00 },
+ { 0x0134, 0x02 }, { 0x0135, 0x00 }, { 0x0136, 0x00 }, { 0x0137, 0x00 }, { 0x0135, 0x25 }, { 0x0136, 0x00 },
+ { 0x0137, 0x00 }, { 0x0138, 0x00 }, { 0x0136, 0x97 }, { 0x0137, 0x00 }, { 0x0138, 0x00 }, { 0x0139, 0x00 },
+ { 0x0137, 0x0a }, { 0x0138, 0x00 }, { 0x0139, 0x00 }, { 0x013a, 0x00 }, { 0x0135, 0x25 }, { 0x0136, 0x00 },
+ { 0x0137, 0x00 }, { 0x0138, 0x00 }, { 0x0135, 0x24 }, { 0x0136, 0x00 }, { 0x0137, 0x00 }, { 0x0138, 0x00 },
+ { 0x0135, 0x25 }, { 0x0136, 0x00 }, { 0x0137, 0x00 }, { 0x0138, 0x00 }, { 0x04a0, 0x01 }, { 0x04a1, 0x00 },
+ { 0x04a2, 0x00 }, { 0x04a3, 0x00 }, { 0x04a0, 0x00 }, { 0x04a1, 0x00 }, { 0x04a2, 0x00 }, { 0x04a3, 0x00 },
+ { 0x048b, 0xe0 }, { 0x048c, 0x00 }, { 0x048d, 0x00 }, { 0x048e, 0x00 }, { 0x0400, 0x01 }, { 0x0401, 0x00 },
+ { 0x0402, 0x00 }, { 0x0403, 0x00 }, { 0x0401, 0xf0 }, { 0x0402, 0x00 }, { 0x0403, 0x00 }, { 0x0404, 0x00 },
+ { 0x0402, 0x08 }, { 0x0403, 0x00 }, { 0x0404, 0x00 }, { 0x0405, 0x00 }, { 0x0403, 0x00 }, { 0x0404, 0x00 },
+ { 0x0405, 0x00 }, { 0x0406, 0x00 }, { 0x0404, 0x32 }, { 0x0405, 0x00 }, { 0x0406, 0x00 }, { 0x0407, 0x00 },
+ { 0x0405, 0x25 }, { 0x0406, 0x00 }, { 0x0407, 0x00 }, { 0x0408, 0x00 }, { 0x0406, 0x10 }, { 0x0407, 0x00 },
+ { 0x0408, 0x00 }, { 0x0409, 0x00 }, { 0x0407, 0x00 }, { 0x0408, 0x00 }, { 0x0409, 0x00 }, { 0x040a, 0x00 },
+ { 0x0408, 0x00 }, { 0x0409, 0x00 }, { 0x040a, 0x00 }, { 0x040b, 0x00 }, { 0x0409, 0x80 }, { 0x040a, 0x00 },
+ { 0x040b, 0x00 }, { 0x040c, 0x00 }, { 0x040a, 0x00 }, { 0x040b, 0x00 }, { 0x040c, 0x00 }, { 0x040d, 0x00 },
+ { 0x040b, 0x00 }, { 0x040c, 0x00 }, { 0x040d, 0x00 }, { 0x040e, 0x00 }, { 0x040c, 0x00 }, { 0x040d, 0x00 },
+ { 0x040e, 0x00 }, { 0x040f, 0x00 }, { 0x040d, 0x91 }, { 0x040e, 0x00 }, { 0x040f, 0x00 }, { 0x0410, 0x00 },
+ { 0x040e, 0x7f }, { 0x040f, 0x00 }, { 0x0410, 0x00 }, { 0x0411, 0x00 }, { 0x040f, 0x00 }, { 0x0410, 0x00 },
+ { 0x0411, 0x00 }, { 0x0412, 0x00 }, { 0x0410, 0xbe }, { 0x0411, 0x00 }, { 0x0412, 0x00 }, { 0x0413, 0x00 },
+ { 0x0411, 0x07 }, { 0x0412, 0x00 }, { 0x0413, 0x00 }, { 0x0414, 0x00 }, { 0x0412, 0xff }, { 0x0413, 0x00 },
+ { 0x0414, 0x00 }, { 0x0415, 0x00 }, { 0x0413, 0x7f }, { 0x0414, 0x00 }, { 0x0415, 0x00 }, { 0x0416, 0x00 },
+ { 0x0414, 0x08 }, { 0x0415, 0x00 }, { 0x0416, 0x00 }, { 0x0417, 0x00 }, { 0x0415, 0x80 }, { 0x0416, 0x00 },
+ { 0x0417, 0x00 }, { 0x0418, 0x00 }, { 0x0416, 0x00 }, { 0x0417, 0x00 }, { 0x0418, 0x00 }, { 0x0419, 0x00 },
+ { 0x0417, 0x00 }, { 0x0418, 0x00 }, { 0x0419, 0x00 }, { 0x041a, 0x00 }, { 0x0418, 0x00 }, { 0x0419, 0x00 },
+ { 0x041a, 0x00 }, { 0x041b, 0x00 }, { 0x0419, 0x00 }, { 0x041a, 0x00 }, { 0x041b, 0x00 }, { 0x041c, 0x00 },
+ { 0x041a, 0x00 }, { 0x041b, 0x00 }, { 0x041c, 0x00 }, { 0x041d, 0x00 }, { 0x041b, 0x04 }, { 0x041c, 0x00 },
+ { 0x041d, 0x00 }, { 0x041e, 0x00 }, { 0x041c, 0x00 }, { 0x041d, 0x00 }, { 0x041e, 0x00 }, { 0x041f, 0x00 },
+ { 0x041d, 0x00 }, { 0x041e, 0x00 }, { 0x041f, 0x00 }, { 0x0420, 0x00 }, { 0x041e, 0x08 }, { 0x041f, 0x00 },
+ { 0x0420, 0x00 }, { 0x0421, 0x00 }, { 0x041f, 0x00 }, { 0x0420, 0x00 }, { 0x0421, 0x00 }, { 0x0422, 0x00 },
+ { 0x0420, 0x80 }, { 0x0421, 0x00 }, { 0x0422, 0x00 }, { 0x0423, 0x00 }, { 0x0421, 0x80 }, { 0x0422, 0x00 },
+ { 0x0423, 0x00 }, { 0x0424, 0x00 }, { 0x0422, 0x00 }, { 0x0423, 0x00 }, { 0x0424, 0x00 }, { 0x0425, 0x00 },
+ { 0x0423, 0x00 }, { 0x0424, 0x00 }, { 0x0425, 0x00 }, { 0x0426, 0x00 }, { 0x0424, 0x00 }, { 0x0425, 0x00 },
+ { 0x0426, 0x00 }, { 0x0427, 0x00 }, { 0x0425, 0x00 }, { 0x0426, 0x00 }, { 0x0427, 0x00 }, { 0x0428, 0x00 },
+ { 0x0426, 0x00 }, { 0x0427, 0x00 }, { 0x0428, 0x00 }, { 0x0429, 0x00 }, { 0x0427, 0x00 }, { 0x0428, 0x00 },
+ { 0x0429, 0x00 }, { 0x042a, 0x00 }, { 0x0428, 0x00 }, { 0x0429, 0x00 }, { 0x042a, 0x00 }, { 0x042b, 0x00 },
+ { 0x0429, 0x00 }, { 0x042a, 0x00 }, { 0x042b, 0x00 }, { 0x042c, 0x00 }, { 0x042a, 0x00 }, { 0x042b, 0x00 },
+ { 0x042c, 0x00 }, { 0x042d, 0x00 }, { 0x042b, 0x00 }, { 0x042c, 0x00 }, { 0x042d, 0x00 }, { 0x042e, 0x00 },
+ { 0x042c, 0x00 }, { 0x042d, 0x00 }, { 0x042e, 0x00 }, { 0x042f, 0x00 }, { 0x042d, 0x00 }, { 0x042e, 0x00 },
+ { 0x042f, 0x00 }, { 0x0430, 0x00 }, { 0x042e, 0x00 }, { 0x042f, 0x00 }, { 0x0430, 0x00 }, { 0x0431, 0x00 },
+ { 0x042f, 0x00 }, { 0x0430, 0x00 }, { 0x0431, 0x00 }, { 0x0432, 0x00 }, { 0x0430, 0x00 }, { 0x0431, 0x00 },
+ { 0x0432, 0x00 }, { 0x0433, 0x00 }, { 0x0431, 0x00 }, { 0x0432, 0x00 }, { 0x0433, 0x00 }, { 0x0434, 0x00 },
+ { 0x0432, 0x00 }, { 0x0433, 0x00 }, { 0x0434, 0x00 }, { 0x0435, 0x00 }, { 0x0433, 0x00 }, { 0x0434, 0x00 },
+ { 0x0435, 0x00 }, { 0x0436, 0x00 }, { 0x0434, 0x00 }, { 0x0435, 0x00 }, { 0x0436, 0x00 }, { 0x0437, 0x00 },
+ { 0x0435, 0x00 }, { 0x0436, 0x00 }, { 0x0437, 0x00 }, { 0x0438, 0x00 }, { 0x0436, 0x00 }, { 0x0437, 0x00 },
+ { 0x0438, 0x00 }, { 0x0439, 0x00 }, { 0x0437, 0x00 }, { 0x0438, 0x00 }, { 0x0439, 0x00 }, { 0x043a, 0x00 },
+ { 0x0438, 0x3c }, { 0x0439, 0x00 }, { 0x043a, 0x00 }, { 0x043b, 0x00 }, { 0x0439, 0x1e }, { 0x043a, 0x00 },
+ { 0x043b, 0x00 }, { 0x043c, 0x00 }, { 0x043a, 0x00 }, { 0x043b, 0x00 }, { 0x043c, 0x00 }, { 0x043d, 0x00 },
+ { 0x043b, 0x00 }, { 0x043c, 0x00 }, { 0x043d, 0x00 }, { 0x043e, 0x00 }, { 0x043c, 0x00 }, { 0x043d, 0x00 },
+ { 0x043e, 0x00 }, { 0x043f, 0x00 }, { 0x043d, 0x00 }, { 0x043e, 0x00 }, { 0x043f, 0x00 }, { 0x0440, 0x00 },
+ { 0x043e, 0xf0 }, { 0x043f, 0x00 }, { 0x0440, 0x00 }, { 0x0441, 0x00 }, { 0x043f, 0xff }, { 0x0440, 0x00 },
+ { 0x0441, 0x00 }, { 0x0442, 0x00 }, { 0x0440, 0xa9 }, { 0x0441, 0x00 }, { 0x0442, 0x00 }, { 0x0443, 0x00 },
+ { 0x0441, 0x0b }, { 0x0442, 0x00 }, { 0x0443, 0x00 }, { 0x0444, 0x00 }, { 0x0442, 0x00 }, { 0x0443, 0x00 },
+ { 0x0444, 0x00 }, { 0x0445, 0x00 }, { 0x0443, 0x00 }, { 0x0444, 0x00 }, { 0x0445, 0x00 }, { 0x0446, 0x00 },
+ { 0x0444, 0x00 }, { 0x0445, 0x00 }, { 0x0446, 0x00 }, { 0x0447, 0x00 }, { 0x0445, 0x00 }, { 0x0446, 0x00 },
+ { 0x0447, 0x00 }, { 0x0448, 0x00 }, { 0x0446, 0x00 }, { 0x0447, 0x00 }, { 0x0448, 0x00 }, { 0x0449, 0x00 },
+ { 0x0447, 0x00 }, { 0x0448, 0x00 }, { 0x0449, 0x00 }, { 0x044a, 0x00 }, { 0x0448, 0x00 }, { 0x0449, 0x00 },
+ { 0x044a, 0x00 }, { 0x044b, 0x00 }, { 0x0449, 0x00 }, { 0x044a, 0x00 }, { 0x044b, 0x00 }, { 0x044c, 0x00 },
+ { 0x044a, 0x00 }, { 0x044b, 0x00 }, { 0x044c, 0x00 }, { 0x044d, 0x00 }, { 0x044b, 0x00 }, { 0x044c, 0x00 },
+ { 0x044d, 0x00 }, { 0x044e, 0x00 }, { 0x044c, 0x7e }, { 0x044d, 0x00 }, { 0x044e, 0x00 }, { 0x044f, 0x00 },
+ { 0x044d, 0x7e }, { 0x044e, 0x00 }, { 0x044f, 0x00 }, { 0x0450, 0x00 }, { 0x044e, 0x94 }, { 0x044f, 0x00 },
+ { 0x0450, 0x00 }, { 0x0451, 0x00 }, { 0x044f, 0x09 }, { 0x0450, 0x00 }, { 0x0451, 0x00 }, { 0x0452, 0x00 },
+ { 0x0450, 0x2c }, { 0x0451, 0x00 }, { 0x0452, 0x00 }, { 0x0453, 0x00 }, { 0x0451, 0x1b }, { 0x0452, 0x00 },
+ { 0x0453, 0x00 }, { 0x0454, 0x00 }, { 0x0452, 0x11 }, { 0x0453, 0x00 }, { 0x0454, 0x00 }, { 0x0455, 0x00 },
+ { 0x0453, 0x8f }, { 0x0454, 0x00 }, { 0x0455, 0x00 }, { 0x0456, 0x00 }, { 0x0454, 0x14 }, { 0x0455, 0x00 },
+ { 0x0456, 0x00 }, { 0x0457, 0x00 }, { 0x0455, 0x20 }, { 0x0456, 0x00 }, { 0x0457, 0x00 }, { 0x0458, 0x00 },
+ { 0x0456, 0x01 }, { 0x0457, 0x00 }, { 0x0458, 0x00 }, { 0x0459, 0x00 }, { 0x0457, 0x08 }, { 0x0458, 0x00 },
+ { 0x0459, 0x00 }, { 0x045a, 0x00 }, { 0x0458, 0x28 }, { 0x0459, 0x00 }, { 0x045a, 0x00 }, { 0x045b, 0x00 },
+ { 0x0459, 0x7e }, { 0x045a, 0x00 }, { 0x045b, 0x00 }, { 0x045c, 0x00 }, { 0x045a, 0xd4 }, { 0x045b, 0x00 },
+ { 0x045c, 0x00 }, { 0x045d, 0x00 }, { 0x045b, 0x5e }, { 0x045c, 0x00 }, { 0x045d, 0x00 }, { 0x045e, 0x00 },
+ { 0x045c, 0x1d }, { 0x045d, 0x00 }, { 0x045e, 0x00 }, { 0x045f, 0x00 }, { 0x045d, 0x3b }, { 0x045e, 0x00 },
+ { 0x045f, 0x00 }, { 0x0460, 0x00 }, { 0x045e, 0x13 }, { 0x045f, 0x00 }, { 0x0460, 0x00 }, { 0x0461, 0x00 },
+ { 0x045f, 0x11 }, { 0x0460, 0x00 }, { 0x0461, 0x00 }, { 0x0462, 0x00 }, { 0x0460, 0xbb }, { 0x0461, 0x00 },
+ { 0x0462, 0x00 }, { 0x0463, 0x00 }, { 0x0461, 0x10 }, { 0x0462, 0x00 }, { 0x0463, 0x00 }, { 0x0464, 0x00 },
+ { 0x0462, 0x1f }, { 0x0463, 0x00 }, { 0x0464, 0x00 }, { 0x0465, 0x00 }, { 0x0463, 0x4c }, { 0x0464, 0x00 },
+ { 0x0465, 0x00 }, { 0x0466, 0x00 }, { 0x0464, 0x28 }, { 0x0465, 0x00 }, { 0x0466, 0x00 }, { 0x0467, 0x00 },
+ { 0x0465, 0x90 }, { 0x0466, 0x00 }, { 0x0467, 0x00 }, { 0x0468, 0x00 }, { 0x0466, 0xa1 }, { 0x0467, 0x00 },
+ { 0x0468, 0x00 }, { 0x0469, 0x00 }, { 0x0467, 0x6c }, { 0x0468, 0x00 }, { 0x0469, 0x00 }, { 0x046a, 0x00 },
+ { 0x0468, 0x06 }, { 0x0469, 0x00 }, { 0x046a, 0x00 }, { 0x046b, 0x00 }, { 0x0469, 0x09 }, { 0x046a, 0x00 },
+ { 0x046b, 0x00 }, { 0x046c, 0x00 }, { 0x046a, 0x19 }, { 0x046b, 0x00 }, { 0x046c, 0x00 }, { 0x046d, 0x00 },
+ { 0x046b, 0x57 }, { 0x046c, 0x00 }, { 0x046d, 0x00 }, { 0x046e, 0x00 }, { 0x046c, 0x3e }, { 0x046d, 0x00 },
+ { 0x046e, 0x00 }, { 0x046f, 0x00 }, { 0x046d, 0x22 }, { 0x046e, 0x00 }, { 0x046f, 0x00 }, { 0x0470, 0x00 },
+ { 0x046e, 0xe7 }, { 0x046f, 0x00 }, { 0x0470, 0x00 }, { 0x0471, 0x00 }, { 0x046f, 0x21 }, { 0x0470, 0x00 },
+ { 0x0471, 0x00 }, { 0x0472, 0x00 }, { 0x0470, 0x7a }, { 0x0471, 0x00 }, { 0x0472, 0x00 }, { 0x0473, 0x00 },
+ { 0x0471, 0x00 }, { 0x0472, 0x00 }, { 0x0473, 0x00 }, { 0x0474, 0x00 }, { 0x0472, 0x2d }, { 0x0473, 0x00 },
+ { 0x0474, 0x00 }, { 0x0475, 0x00 }, { 0x0473, 0x5a }, { 0x0474, 0x00 }, { 0x0475, 0x00 }, { 0x0476, 0x00 },
+ { 0x0474, 0x18 }, { 0x0475, 0x00 }, { 0x0476, 0x00 }, { 0x0477, 0x00 }, { 0x0475, 0xb0 }, { 0x0476, 0x00 },
+ { 0x0477, 0x00 }, { 0x0478, 0x00 }, { 0x0476, 0x1e }, { 0x0477, 0x00 }, { 0x0478, 0x00 }, { 0x0479, 0x00 },
+ { 0x0477, 0x1c }, { 0x0478, 0x00 }, { 0x0479, 0x00 }, { 0x047a, 0x00 }, { 0x0478, 0x1f }, { 0x0479, 0x00 },
+ { 0x047a, 0x00 }, { 0x047b, 0x00 }, { 0x0479, 0x01 }, { 0x047a, 0x00 }, { 0x047b, 0x00 }, { 0x047c, 0x00 },
+ { 0x047a, 0x15 }, { 0x047b, 0x00 }, { 0x047c, 0x00 }, { 0x047d, 0x00 }, { 0x047b, 0x00 }, { 0x047c, 0x00 },
+ { 0x047d, 0x00 }, { 0x047e, 0x00 }, { 0x047c, 0x00 }, { 0x047d, 0x00 }, { 0x047e, 0x00 }, { 0x047f, 0x00 },
+ { 0x047d, 0x00 }, { 0x047e, 0x00 }, { 0x047f, 0x00 }, { 0x0480, 0x00 }, { 0x047e, 0x08 }, { 0x047f, 0x00 },
+ { 0x0480, 0x00 }, { 0x0481, 0x00 }, { 0x047f, 0x00 }, { 0x0480, 0x00 }, { 0x0481, 0x00 }, { 0x0482, 0x00 },
+ { 0x0480, 0x94 }, { 0x0481, 0x00 }, { 0x0482, 0x00 }, { 0x0483, 0x00 }, { 0x0481, 0x00 }, { 0x0482, 0x00 },
+ { 0x0483, 0x00 }, { 0x0484, 0x00 }, { 0x0482, 0x00 }, { 0x0483, 0x00 }, { 0x0484, 0x00 }, { 0x0485, 0x00 },
+ { 0x0483, 0x00 }, { 0x0484, 0x00 }, { 0x0485, 0x00 }, { 0x0486, 0x00 }, { 0x0484, 0x00 }, { 0x0485, 0x00 },
+ { 0x0486, 0x00 }, { 0x0487, 0x00 }, { 0x0485, 0x00 }, { 0x0486, 0x00 }, { 0x0487, 0x00 }, { 0x0488, 0x00 },
+ { 0x0486, 0x60 }, { 0x0487, 0x00 }, { 0x0488, 0x00 }, { 0x0489, 0x00 }, { 0x0487, 0x42 }, { 0x0488, 0x00 },
+ { 0x0489, 0x00 }, { 0x048a, 0x00 }, { 0x0488, 0x26 }, { 0x0489, 0x00 }, { 0x048a, 0x00 }, { 0x048b, 0x00 },
+ { 0x0489, 0xe9 }, { 0x048a, 0x00 }, { 0x048b, 0x00 }, { 0x048c, 0x00 }, { 0x048a, 0x03 }, { 0x048b, 0x00 },
+ { 0x048c, 0x00 }, { 0x048d, 0x00 }, { 0x048b, 0xf0 }, { 0x048c, 0x00 }, { 0x048d, 0x00 }, { 0x048e, 0x00 },
+ { 0x048c, 0xdc }, { 0x048d, 0x00 }, { 0x048e, 0x00 }, { 0x048f, 0x00 }, { 0x048d, 0x40 }, { 0x048e, 0x00 },
+ { 0x048f, 0x00 }, { 0x0490, 0x00 }, { 0x048e, 0x10 }, { 0x048f, 0x00 }, { 0x0490, 0x00 }, { 0x0491, 0x00 },
+ { 0x048f, 0x00 }, { 0x0490, 0x00 }, { 0x0491, 0x00 }, { 0x0492, 0x00 }, { 0x0490, 0x0a }, { 0x0491, 0x00 },
+ { 0x0492, 0x00 }, { 0x0493, 0x00 }, { 0x0491, 0x00 }, { 0x0492, 0x00 }, { 0x0493, 0x00 }, { 0x0494, 0x00 },
+ { 0x0492, 0x3f }, { 0x0493, 0x00 }, { 0x0494, 0x00 }, { 0x0495, 0x00 }, { 0x0493, 0xcd }, { 0x0494, 0x00 },
+ { 0x0495, 0x00 }, { 0x0496, 0x00 }, { 0x0494, 0x00 }, { 0x0495, 0x00 }, { 0x0496, 0x00 }, { 0x0497, 0x00 },
+ { 0x0495, 0x03 }, { 0x0496, 0x00 }, { 0x0497, 0x00 }, { 0x0498, 0x00 }, { 0x0496, 0x1f }, { 0x0497, 0x00 },
+ { 0x0498, 0x00 }, { 0x0499, 0x00 }, { 0x0497, 0x16 }, { 0x0498, 0x00 }, { 0x0499, 0x00 }, { 0x049a, 0x00 },
+ { 0x0498, 0x22 }, { 0x0499, 0x00 }, { 0x049a, 0x00 }, { 0x049b, 0x00 }, { 0x0499, 0x0e }, { 0x049a, 0x00 },
+ { 0x049b, 0x00 }, { 0x049c, 0x00 }, { 0x049a, 0x00 }, { 0x049b, 0x00 }, { 0x049c, 0x00 }, { 0x049d, 0x00 },
+ { 0x049b, 0x20 }, { 0x049c, 0x00 }, { 0x049d, 0x00 }, { 0x049e, 0x00 }, { 0x049c, 0x0f }, { 0x049d, 0x00 },
+ { 0x049e, 0x00 }, { 0x049f, 0x00 }, { 0x049d, 0x02 }, { 0x049e, 0x00 }, { 0x049f, 0x00 }, { 0x04a0, 0x00 },
+ { 0x049e, 0x4c }, { 0x049f, 0x00 }, { 0x04a0, 0x00 }, { 0x04a1, 0x00 }, { 0x049f, 0x00 }, { 0x04a0, 0x00 },
+ { 0x04a1, 0x00 }, { 0x04a2, 0x00 }, { 0x04a0, 0x00 }, { 0x04a1, 0x00 }, { 0x04a2, 0x00 }, { 0x04a3, 0x00 },
+ { 0x04a1, 0x00 }, { 0x04a2, 0x00 }, { 0x04a3, 0x00 }, { 0x04a4, 0x00 }, { 0x04a2, 0x00 }, { 0x04a3, 0x00 },
+ { 0x04a4, 0x00 }, { 0x04a5, 0x00 }, { 0x04a3, 0x00 }, { 0x04a4, 0x00 }, { 0x04a5, 0x00 }, { 0x04a6, 0x00 },
+ { 0x04a4, 0x00 }, { 0x04a5, 0x00 }, { 0x04a6, 0x00 }, { 0x04a7, 0x00 }, { 0x04a5, 0x00 }, { 0x04a6, 0x00 },
+ { 0x04a7, 0x00 }, { 0x04a8, 0x00 }, { 0x04a6, 0x00 }, { 0x04a7, 0x00 }, { 0x04a8, 0x00 }, { 0x04a9, 0x00 },
+ { 0x04a7, 0x00 }, { 0x04a8, 0x00 }, { 0x04a9, 0x00 }, { 0x04aa, 0x00 }, { 0x04a8, 0x00 }, { 0x04a9, 0x00 },
+ { 0x04aa, 0x00 }, { 0x04ab, 0x00 }, { 0x04a9, 0x00 }, { 0x04aa, 0x00 }, { 0x04ab, 0x00 }, { 0x04ac, 0x00 },
+ { 0x04aa, 0x00 }, { 0x04ab, 0x00 }, { 0x04ac, 0x00 }, { 0x04ad, 0x00 }, { 0x04ab, 0x00 }, { 0x04ac, 0x00 },
+ { 0x04ad, 0x00 }, { 0x04ae, 0x00 }, { 0x04ac, 0x00 }, { 0x04ad, 0x00 }, { 0x04ae, 0x00 }, { 0x04af, 0x00 },
+ { 0x04ab, 0x00 }, { 0x04ac, 0x00 }, { 0x04ad, 0x00 }, { 0x04ae, 0x00 }, { 0x04ae, 0x00 }, { 0x04af, 0x00 },
+ { 0x04b0, 0x00 }, { 0x04b1, 0x00 }, { 0x04af, 0x00 }, { 0x04b0, 0x00 }, { 0x04b1, 0x00 }, { 0x04b2, 0x00 },
+ { 0x04b0, 0x02 }, { 0x04b1, 0x00 }, { 0x04b2, 0x00 }, { 0x04b3, 0x00 }, { 0x04b1, 0x00 }, { 0x04b2, 0x00 },
+ { 0x04b3, 0x00 }, { 0x04b4, 0x00 }, { 0x04b2, 0x00 }, { 0x04b3, 0x00 }, { 0x04b4, 0x00 }, { 0x04b5, 0x00 },
+ { 0x04b3, 0x00 }, { 0x04b4, 0x00 }, { 0x04b5, 0x00 }, { 0x04b6, 0x00 }, { 0x0200, 0x00 }, { 0x0201, 0x00 },
+ { 0x0202, 0x00 }, { 0x0203, 0x00 }, { 0x0201, 0x00 }, { 0x0202, 0x00 }, { 0x0203, 0x00 }, { 0x0204, 0x00 },
+ { 0x0202, 0x00 }, { 0x0203, 0x00 }, { 0x0204, 0x00 }, { 0x0205, 0x00 }, { 0x0203, 0x00 }, { 0x0204, 0x00 },
+ { 0x0205, 0x00 }, { 0x0206, 0x00 }, { 0x0204, 0xff }, { 0x0205, 0x00 }, { 0x0206, 0x00 }, { 0x0207, 0x00 },
+ { 0x0205, 0xff }, { 0x0206, 0x00 }, { 0x0207, 0x00 }, { 0x0208, 0x00 }, { 0x0206, 0x00 }, { 0x0207, 0x00 },
+ { 0x0208, 0x00 }, { 0x0209, 0x00 }, { 0x0207, 0x00 }, { 0x0208, 0x00 }, { 0x0209, 0x00 }, { 0x020a, 0x00 },
+ { 0x0208, 0xff }, { 0x0209, 0x00 }, { 0x020a, 0x00 }, { 0x020b, 0x00 }, { 0x0209, 0xff }, { 0x020a, 0x00 },
+ { 0x020b, 0x00 }, { 0x020c, 0x00 }, { 0x020a, 0x00 }, { 0x020b, 0x00 }, { 0x020c, 0x00 }, { 0x020d, 0x00 },
+ { 0x020b, 0x00 }, { 0x020c, 0x00 }, { 0x020d, 0x00 }, { 0x020e, 0x00 }, { 0x020c, 0x00 }, { 0x020d, 0x00 },
+ { 0x020e, 0x00 }, { 0x020f, 0x00 }, { 0x020d, 0x00 }, { 0x020e, 0x00 }, { 0x020f, 0x00 }, { 0x0210, 0x00 },
+ { 0x020e, 0x00 }, { 0x020f, 0x00 }, { 0x0210, 0x00 }, { 0x0211, 0x00 }, { 0x020f, 0x00 }, { 0x0210, 0x00 },
+ { 0x0211, 0x00 }, { 0x0212, 0x00 }, { 0x0210, 0x20 }, { 0x0211, 0x00 }, { 0x0212, 0x00 }, { 0x0213, 0x00 },
+ { 0x0211, 0x00 }, { 0x0212, 0x00 }, { 0x0213, 0x00 }, { 0x0214, 0x00 }, { 0x0212, 0x00 }, { 0x0213, 0x00 },
+ { 0x0214, 0x00 }, { 0x0215, 0x00 }, { 0x0213, 0x00 }, { 0x0214, 0x00 }, { 0x0215, 0x00 }, { 0x0216, 0x00 },
+ { 0x0214, 0x33 }, { 0x0215, 0x00 }, { 0x0216, 0x00 }, { 0x0217, 0x00 }, { 0x0215, 0x00 }, { 0x0216, 0x00 },
+ { 0x0217, 0x00 }, { 0x0218, 0x00 }, { 0x0216, 0x00 }, { 0x0217, 0x00 }, { 0x0218, 0x00 }, { 0x0219, 0x00 },
+ { 0x0217, 0x00 }, { 0x0218, 0x00 }, { 0x0219, 0x00 }, { 0x021a, 0x00 }, { 0x0218, 0x00 }, { 0x0219, 0x00 },
+ { 0x021a, 0x00 }, { 0x021b, 0x00 }, { 0x0219, 0x00 }, { 0x021a, 0x00 }, { 0x021b, 0x00 }, { 0x021c, 0x00 },
+ { 0x021a, 0x00 }, { 0x021b, 0x00 }, { 0x021c, 0x00 }, { 0x021d, 0x00 }, { 0x021b, 0x00 }, { 0x021c, 0x00 },
+ { 0x021d, 0x00 }, { 0x021e, 0x00 }, { 0x021c, 0x00 }, { 0x021d, 0x00 }, { 0x021e, 0x00 }, { 0x021f, 0x00 },
+ { 0x021d, 0x00 }, { 0x021e, 0x00 }, { 0x021f, 0x00 }, { 0x0220, 0x00 }, { 0x021e, 0x00 }, { 0x021f, 0x00 },
+ { 0x0220, 0x00 }, { 0x0221, 0x00 }, { 0x021f, 0x00 }, { 0x0220, 0x00 }, { 0x0221, 0x00 }, { 0x0222, 0x00 },
+ { 0x0100, 0x71 }, { 0x0101, 0x00 }, { 0x0102, 0x00 }, { 0x0103, 0x00 }, { 0x0101, 0x83 }, { 0x0102, 0x00 },
+ { 0x0103, 0x00 }, { 0x0104, 0x00 }, { 0x0102, 0x00 }, { 0x0103, 0x00 }, { 0x0104, 0x00 }, { 0x0105, 0x00 },
+ { 0x0103, 0x00 }, { 0x0104, 0x00 }, { 0x0105, 0x00 }, { 0x0106, 0x00 }, { 0x0104, 0x80 }, { 0x0105, 0x00 },
+ { 0x0106, 0x00 }, { 0x0107, 0x00 }, { 0x0105, 0xcc }, { 0x0106, 0x00 }, { 0x0107, 0x00 }, { 0x0108, 0x00 },
+ { 0x0106, 0x16 }, { 0x0107, 0x00 }, { 0x0108, 0x00 }, { 0x0109, 0x00 }, { 0x0107, 0x07 }, { 0x0108, 0x00 },
+ { 0x0109, 0x00 }, { 0x010a, 0x00 }, { 0x0108, 0x0f }, { 0x0109, 0x00 }, { 0x010a, 0x00 }, { 0x010b, 0x00 },
+ { 0x0109, 0x04 }, { 0x010a, 0x00 }, { 0x010b, 0x00 }, { 0x010c, 0x00 }, { 0x010a, 0x0a }, { 0x010b, 0x00 },
+ { 0x010c, 0x00 }, { 0x010d, 0x00 }, { 0x010b, 0x10 }, { 0x010c, 0x00 }, { 0x010d, 0x00 }, { 0x010e, 0x00 },
+ { 0x010c, 0xfe }, { 0x010d, 0x00 }, { 0x010e, 0x00 }, { 0x010f, 0x00 }, { 0x010d, 0xe2 }, { 0x010e, 0x00 },
+ { 0x010f, 0x00 }, { 0x0110, 0x00 }, { 0x010e, 0x2b }, { 0x010f, 0x00 }, { 0x0110, 0x00 }, { 0x0111, 0x00 },
+ { 0x010f, 0x00 }, { 0x0110, 0x00 }, { 0x0111, 0x00 }, { 0x0112, 0x00 }, { 0x0110, 0x09 }, { 0x0111, 0x00 },
+ { 0x0112, 0x00 }, { 0x0113, 0x00 }, { 0x0111, 0xd7 }, { 0x0112, 0x00 }, { 0x0113, 0x00 }, { 0x0114, 0x00 },
+ { 0x0112, 0x98 }, { 0x0113, 0x00 }, { 0x0114, 0x00 }, { 0x0115, 0x00 }, { 0x0113, 0x00 }, { 0x0114, 0x00 },
+ { 0x0115, 0x00 }, { 0x0116, 0x00 }, { 0x0114, 0x00 }, { 0x0115, 0x00 }, { 0x0116, 0x00 }, { 0x0117, 0x00 },
+ { 0x0115, 0x8f }, { 0x0116, 0x00 }, { 0x0117, 0x00 }, { 0x0118, 0x00 }, { 0x0116, 0x07 }, { 0x0117, 0x00 },
+ { 0x0118, 0x00 }, { 0x0119, 0x00 }, { 0x0117, 0x00 }, { 0x0118, 0x00 }, { 0x0119, 0x00 }, { 0x011a, 0x00 },
+ { 0x0118, 0x00 }, { 0x0119, 0x00 }, { 0x011a, 0x00 }, { 0x011b, 0x00 }, { 0x0119, 0x00 }, { 0x011a, 0x00 },
+ { 0x011b, 0x00 }, { 0x011c, 0x00 }, { 0x011a, 0x00 }, { 0x011b, 0x00 }, { 0x011c, 0x00 }, { 0x011d, 0x00 },
+ { 0x011b, 0x00 }, { 0x011c, 0x00 }, { 0x011d, 0x00 }, { 0x011e, 0x00 }, { 0x011c, 0x00 }, { 0x011d, 0x00 },
+ { 0x011e, 0x00 }, { 0x011f, 0x00 }, { 0x011d, 0x00 }, { 0x011e, 0x00 }, { 0x011f, 0x00 }, { 0x0120, 0x00 },
+ { 0x011e, 0x00 }, { 0x011f, 0x00 }, { 0x0120, 0x00 }, { 0x0121, 0x00 }, { 0x011f, 0x00 }, { 0x0120, 0x00 },
+ { 0x0121, 0x00 }, { 0x0122, 0x00 }, { 0x0120, 0x00 }, { 0x0121, 0x00 }, { 0x0122, 0x00 }, { 0x0123, 0x00 },
+ { 0x0121, 0x00 }, { 0x0122, 0x00 }, { 0x0123, 0x00 }, { 0x0124, 0x00 }, { 0x0122, 0x01 }, { 0x0123, 0x00 },
+ { 0x0124, 0x00 }, { 0x0125, 0x00 }, { 0x0123, 0x10 }, { 0x0124, 0x00 }, { 0x0125, 0x00 }, { 0x0126, 0x00 },
+ { 0x0124, 0x87 }, { 0x0125, 0x00 }, { 0x0126, 0x00 }, { 0x0127, 0x00 }, { 0x0125, 0xb6 }, { 0x0126, 0x00 },
+ { 0x0127, 0x00 }, { 0x0128, 0x00 }, { 0x0126, 0x00 }, { 0x0127, 0x00 }, { 0x0128, 0x00 }, { 0x0129, 0x00 },
+ { 0x0127, 0x50 }, { 0x0128, 0x00 }, { 0x0129, 0x00 }, { 0x012a, 0x00 }, { 0x0128, 0x00 }, { 0x0129, 0x00 },
+ { 0x012a, 0x00 }, { 0x012b, 0x00 }, { 0x0129, 0x94 }, { 0x012a, 0x00 }, { 0x012b, 0x00 }, { 0x012c, 0x00 },
+ { 0x012a, 0x11 }, { 0x012b, 0x00 }, { 0x012c, 0x00 }, { 0x012d, 0x00 }, { 0x012b, 0xa0 }, { 0x012c, 0x00 },
+ { 0x012d, 0x00 }, { 0x012e, 0x00 }, { 0x012c, 0x00 }, { 0x012d, 0x00 }, { 0x012e, 0x00 }, { 0x012f, 0x00 },
+ { 0x012d, 0x60 }, { 0x012e, 0x00 }, { 0x012f, 0x00 }, { 0x0130, 0x00 }, { 0x012e, 0x20 }, { 0x012f, 0x00 },
+ { 0x0130, 0x00 }, { 0x0131, 0x00 }, { 0x012f, 0x11 }, { 0x0130, 0x00 }, { 0x0131, 0x00 }, { 0x0132, 0x00 },
+ { 0x0130, 0x00 }, { 0x0131, 0x00 }, { 0x0132, 0x00 }, { 0x0133, 0x00 }, { 0x0131, 0x00 }, { 0x0132, 0x00 },
+ { 0x0133, 0x00 }, { 0x0134, 0x00 }, { 0x0132, 0x00 }, { 0x0133, 0x00 }, { 0x0134, 0x00 }, { 0x0135, 0x00 },
+ { 0x0133, 0x00 }, { 0x0134, 0x00 }, { 0x0135, 0x00 }, { 0x0136, 0x00 }, { 0x0134, 0x02 }, { 0x0135, 0x00 },
+ { 0x0136, 0x00 }, { 0x0137, 0x00 }, { 0x0135, 0x25 }, { 0x0136, 0x00 }, { 0x0137, 0x00 }, { 0x0138, 0x00 },
+ { 0x0136, 0x97 }, { 0x0137, 0x00 }, { 0x0138, 0x00 }, { 0x0139, 0x00 }, { 0x0137, 0x0a }, { 0x0138, 0x00 },
+ { 0x0139, 0x00 }, { 0x013a, 0x00 }, { 0x0138, 0x00 }, { 0x0139, 0x00 }, { 0x013a, 0x00 }, { 0x013b, 0x00 },
+ { 0x0139, 0x21 }, { 0x013a, 0x00 }, { 0x013b, 0x00 }, { 0x013c, 0x00 }, { 0x013a, 0xe7 }, { 0x013b, 0x00 },
+ { 0x013c, 0x00 }, { 0x013d, 0x00 }, { 0x013b, 0x00 }, { 0x013c, 0x00 }, { 0x013d, 0x00 }, { 0x013e, 0x00 },
+ { 0x0140, 0x04 }, { 0x0141, 0x00 }, { 0x0142, 0x00 }, { 0x0143, 0x00 }, { 0x0141, 0xb0 }, { 0x0142, 0x00 },
+ { 0x0143, 0x00 }, { 0x0144, 0x00 }, { 0x0142, 0x00 }, { 0x0143, 0x00 }, { 0x0144, 0x00 }, { 0x0145, 0x00 },
+ { 0x0143, 0x00 }, { 0x0144, 0x00 }, { 0x0145, 0x00 }, { 0x0146, 0x00 }, { 0x0144, 0x10 }, { 0x0145, 0x00 },
+ { 0x0146, 0x00 }, { 0x0147, 0x00 }, { 0x0145, 0x32 }, { 0x0146, 0x00 }, { 0x0147, 0x00 }, { 0x0148, 0x00 },
+ { 0x0146, 0x54 }, { 0x0147, 0x00 }, { 0x0148, 0x00 }, { 0x0149, 0x00 }, { 0x0147, 0x76 }, { 0x0148, 0x00 },
+ { 0x0149, 0x00 }, { 0x014a, 0x00 }, { 0x0148, 0x90 }, { 0x0149, 0x00 }, { 0x014a, 0x00 }, { 0x014b, 0x00 },
+ { 0x0149, 0x00 }, { 0x014a, 0x00 }, { 0x014b, 0x00 }, { 0x014c, 0x00 }, { 0x014a, 0x00 }, { 0x014b, 0x00 },
+ { 0x014c, 0x00 }, { 0x014d, 0x00 }, { 0x014b, 0x00 }, { 0x014c, 0x00 }, { 0x014d, 0x00 }, { 0x014e, 0x00 },
+ { 0x014c, 0x00 }, { 0x014d, 0x00 }, { 0x014e, 0x00 }, { 0x014f, 0x00 }, { 0x014d, 0x00 }, { 0x014e, 0x00 },
+ { 0x014f, 0x00 }, { 0x0150, 0x00 }, { 0x014e, 0x00 }, { 0x014f, 0x00 }, { 0x0150, 0x00 }, { 0x0151, 0x00 },
+ { 0x014f, 0x00 }, { 0x0150, 0x00 }, { 0x0151, 0x00 }, { 0x0152, 0x00 }, { 0x013c, 0x00 }, { 0x013d, 0x00 },
+ { 0x013e, 0x00 }, { 0x013f, 0x00 }, { 0x013d, 0x00 }, { 0x013e, 0x00 }, { 0x013f, 0x00 }, { 0x0140, 0x00 },
+ { 0x013e, 0x36 }, { 0x013f, 0x00 }, { 0x0140, 0x00 }, { 0x0141, 0x00 }, { 0x013f, 0x00 }, { 0x0140, 0x00 },
+ { 0x0141, 0x00 }, { 0x0142, 0x00 },
+};
+
+/*
+ * apply=0 : read-only compare, 1 byte per register, prints every mismatch.
+ * apply=1 : write the table over I2C 0x44, 1 byte per register.
+ *
+ * Range restriction / bisection (both modes):
+ * SERFROM=0xNNNN / SERTO=0xNNNN : only registers in [from,to].
+ * SERSKIP="lo:hi,lo:hi" (hex) : skip those ranges (apply mode).
+ * SERSKIP exists to bisect which section of the table wedges a warm
+ * decoder -- the full table applied at once kills the stream.
+ */
+int pvr2_cx25837_ser_init(pvr2_dev *p, int apply)
+{
+ int i, n = (int)(sizeof(tbl_ser_bytes)/sizeof(tbl_ser_bytes[0]));
+ int errs = 0, diffs = 0, skipped = 0;
+ uint8_t rb;
+ uint16_t from = 0, to = 0xffff;
+ uint16_t sk_lo[8], sk_hi[8];
+ int nskip = 0;
+ const char *e;
+
+ if ((e = getenv("SERFROM")) != NULL)
+ from = (uint16_t)strtoul(e, NULL, 0);
+ if ((e = getenv("SERTO")) != NULL)
+ to = (uint16_t)strtoul(e, NULL, 0);
+ if (from != 0 || to != 0xffff)
+ fprintf(stderr, "ser: range limited to 0x%04x-0x%04x\n",
+ from, to);
+
+ if (apply) {
+ e = getenv("SERSKIP");
+ while (e && nskip < 8) {
+ char *end;
+ unsigned long lo = strtoul(e, &end, 16);
+ unsigned long hi = lo;
+ if (*end == ':') {
+ e = end + 1;
+ hi = strtoul(e, &end, 16);
+ }
+ e = (*end == ',') ? end + 1 : NULL;
+ sk_lo[nskip] = (uint16_t)lo;
+ sk_hi[nskip] = (uint16_t)hi;
+ nskip++;
+ }
+ if (nskip)
+ fprintf(stderr, "ser: SERSKIP %d range(s)\n", nskip);
+ }
+
+ for (i = 0; i < n; i++) {
+ int k, skip = 0;
+ if (tbl_ser_bytes[i].reg < from || tbl_ser_bytes[i].reg > to)
+ continue;
+ for (k = 0; k < nskip; k++)
+ if (tbl_ser_bytes[i].reg >= sk_lo[k] &&
+ tbl_ser_bytes[i].reg <= sk_hi[k]) {
+ skip = 1;
+ break;
+ }
+ if (skip) {
+ skipped++;
+ continue;
+ }
+ if (apply) {
+ if (pvr2_i2c_write(p, CX2584X_I2C_ADDR,
+ tbl_ser_bytes[i].reg,
+ &tbl_ser_bytes[i].val, 1) < 0)
+ errs++;
+ } else {
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR,
+ tbl_ser_bytes[i].reg, &rb, 1) < 0) {
+ errs++;
+ } else if (rb != tbl_ser_bytes[i].val) {
+ diffs++;
+ fprintf(stderr,
+ "ser: 0x%04x table=%02x live=%02x DIFF\n",
+ tbl_ser_bytes[i].reg,
+ tbl_ser_bytes[i].val, rb);
+ }
+ }
+ }
+ fprintf(stderr,
+ "ser: %d byte writes, %d skipped, %d reads failed, %d differ\n",
+ apply ? n - skipped : n, apply ? skipped : 0, errs, diffs);
+ return errs;
+}
diff --git a/src/cx2584x_ser_test.c b/src/cx2584x_ser_test.c
new file mode 100644
index 0000000..fc8c8bd
--- /dev/null
+++ b/src/cx2584x_ser_test.c
@@ -0,0 +1,63 @@
+/* cx2584x_ser_test.c - NARROW SERIALIZER TEST (0x0400-0x040f only, 1 byte/reg).
+ *
+ * Extracted from p2usbRZ2.sys .data+0039a0, entries [16]..[31].
+ * CX25837 I2C is 1-byte wide WITH auto-increment, so each register is
+ * written as a single byte, not u32.
+ *
+ * SCOPE: this is a DELIBERATELY SMALL slice (16 registers) so that if the
+ * write damages video it is immediately obvious and reversible by
+ * power-cycling / re-running mpegcap. The full 308-entry table lives in
+ * cx2584x_ser_init.c and has NOT been applied.
+ */
+#include "pvrusb2.h"
+#include <stdio.h>
+
+typedef struct { uint16_t reg; uint8_t val; } cx_t8_t;
+
+static const cx_t8_t tbl_ser_0x400[] = {
+ { 0x0400, 0x01 },
+ { 0x0401, 0xf0 },
+ { 0x0402, 0x08 },
+ { 0x0403, 0x00 },
+ { 0x0404, 0x32 },
+ { 0x0405, 0x25 },
+ { 0x0406, 0x10 },
+ { 0x0407, 0x00 },
+ { 0x0408, 0x00 },
+ { 0x0409, 0x80 },
+ { 0x040a, 0x00 },
+ { 0x040b, 0x00 },
+ { 0x040c, 0x00 },
+ { 0x040d, 0x91 },
+ { 0x040e, 0x7f },
+ { 0x040f, 0x00 },
+};
+
+int pvr2_cx25837_ser_test(pvr2_dev *p, int apply)
+{
+ int i, n = (int)(sizeof(tbl_ser_0x400)/sizeof(tbl_ser_0x400[0]));
+ int errs = 0, diffs = 0;
+ uint8_t rb;
+
+ fprintf(stderr, "ser-test: 0x0400-0x040f, %d regs, %s\n", n,
+ apply ? "WRITING" : "read-only compare");
+
+ for (i = 0; i < n; i++) {
+ if (apply) {
+ if (pvr2_i2c_write(p, CX2584X_I2C_ADDR,
+ tbl_ser_0x400[i].reg, &tbl_ser_0x400[i].val, 1) < 0)
+ errs++;
+ } else {
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR,
+ tbl_ser_0x400[i].reg, &rb, 1) < 0) {
+ errs++;
+ } else if (rb != tbl_ser_0x400[i].val) {
+ diffs++;
+ fprintf(stderr, "ser-test: 0x%04x table=%02x live=%02x DIFF\n",
+ tbl_ser_0x400[i].reg, tbl_ser_0x400[i].val, rb);
+ }
+ }
+ }
+ fprintf(stderr, "ser-test: %d regs, %d i2c errors, %d differ\n", n, errs, diffs);
+ return errs;
+}
diff --git a/src/cx2584x_tables.c b/src/cx2584x_tables.c
new file mode 100644
index 0000000..8c154f2
--- /dev/null
+++ b/src/cx2584x_tables.c
@@ -0,0 +1,376 @@
+/*
+ * cx2584x_tables.c - CX2584x decoder register initialisation tables
+ * recovered from the official Windows driver.
+ *
+ * Part of mpegcap.
+ *
+ * The official I-O DATA driver (p2usbRZ2.sys) writes two big register
+ * tables to the CX25843 (I2C 0x44) during decoder setup. They were
+ * recovered with Ghidra from the decoder-class method FUN_00026ac7,
+ * which calls FUN_00025574(obj, 2, i2c_addr, table):
+ * - table @ file 0x3f1d8 (306 entries): the full video/audio DSP init
+ * for 525/60 (NTSC). This is the block that the Python reference and
+ * mpegcapt.c never write, and which enables colour reproduction and
+ * the audio serial path (0x115 = 0x8f, 0x116 = 0x07, 0x808 = 0x11,
+ * the 0x800-0x94b DSP block).
+ * - table @ file 0x3fb70 (14 entries): the audio-ADC block
+ * (0x914/0x918 = 0xa0, 0x808 = 0xf6 = BTSC).
+ *
+ * FUN_00026ac7 selects table1 when the "PAL" flag is 0, table2 otherwise;
+ * we use the NTSC table (table1) plus the audio table.
+ */
+#include <stdio.h>
+
+#include "pvrusb2.h"
+#include <stdlib.h>
+
+typedef struct { uint16_t reg; uint8_t val; } cx_reg_t;
+
+static const cx_reg_t decoder_init_ntsc[] = {
+ { 0x0810, 0x01 }, { 0x0115, 0x8f }, { 0x0116, 0x07 }, { 0x0122, 0x01 },
+ { 0x0127, 0x50 }, { 0x0800, 0x54 }, { 0x0801, 0x07 }, { 0x0802, 0xe0 },
+ { 0x0803, 0x13 }, { 0x0804, 0x00 }, { 0x0805, 0x00 }, { 0x0806, 0x00 },
+ { 0x0807, 0x00 }, { 0x0808, 0x11 }, { 0x0809, 0x00 }, { 0x080a, 0x00 },
+ { 0x080b, 0x00 }, { 0x080c, 0x00 }, { 0x080d, 0x00 }, { 0x080e, 0x00 },
+ { 0x080f, 0x00 }, { 0x0810, 0x00 }, { 0x0811, 0x01 }, { 0x0812, 0xff },
+ { 0x0813, 0x00 }, { 0x0814, 0x0a }, { 0x0815, 0x00 }, { 0x0816, 0x2e },
+ { 0x0817, 0x01 }, { 0x0818, 0xc0 }, { 0x0819, 0x31 }, { 0x081a, 0x00 },
+ { 0x081b, 0x00 }, { 0x081c, 0x00 }, { 0x081d, 0x00 }, { 0x081e, 0x80 },
+ { 0x081f, 0x47 }, { 0x0820, 0x00 }, { 0x0821, 0x28 }, { 0x0822, 0xd8 },
+ { 0x0823, 0x7f }, { 0x0824, 0xae }, { 0x0825, 0x8a }, { 0x0826, 0xae },
+ { 0x0827, 0x8a }, { 0x0828, 0x20 }, { 0x0829, 0xa2 }, { 0x082a, 0x08 },
+ { 0x082b, 0x00 }, { 0x082c, 0xf9 }, { 0x082d, 0x07 }, { 0x082e, 0xe1 },
+ { 0x082f, 0x11 }, { 0x0830, 0x11 }, { 0x0831, 0x00 }, { 0x0832, 0x00 },
+ { 0x0833, 0x00 }, { 0x0834, 0x33 }, { 0x0835, 0x0b }, { 0x0836, 0x00 },
+ { 0x0837, 0x00 }, { 0x0838, 0x00 }, { 0x0839, 0x00 }, { 0x083a, 0x00 },
+ { 0x083b, 0x00 }, { 0x083c, 0x00 }, { 0x083d, 0x00 }, { 0x083e, 0x05 },
+ { 0x083f, 0x05 }, { 0x0840, 0x00 }, { 0x0841, 0x00 }, { 0x0842, 0x00 },
+ { 0x0843, 0x00 }, { 0x0844, 0x00 }, { 0x0845, 0x1c }, { 0x0846, 0xfc },
+ { 0x0847, 0x00 }, { 0x0848, 0x11 }, { 0x0849, 0x00 }, { 0x084a, 0x00 },
+ { 0x084b, 0x00 }, { 0x084c, 0x83 }, { 0x084d, 0x02 }, { 0x084e, 0x00 },
+ { 0x084f, 0x00 }, { 0x0850, 0x80 }, { 0x0851, 0x47 }, { 0x0852, 0xa2 },
+ { 0x0853, 0x00 }, { 0x0854, 0x00 }, { 0x0855, 0x00 }, { 0x0856, 0x00 },
+ { 0x0857, 0x00 }, { 0x0858, 0x96 }, { 0x0859, 0x06 }, { 0x085a, 0x00 },
+ { 0x085b, 0x80 }, { 0x085c, 0x07 }, { 0x085d, 0x01 }, { 0x085e, 0x00 },
+ { 0x085f, 0x02 }, { 0x0860, 0x8b }, { 0x0861, 0x0d }, { 0x0862, 0x0a },
+ { 0x0863, 0x00 }, { 0x0864, 0x00 }, { 0x0865, 0x04 }, { 0x0866, 0x01 },
+ { 0x0867, 0x05 }, { 0x0868, 0x01 }, { 0x0869, 0x00 }, { 0x086a, 0x33 },
+ { 0x086b, 0x46 }, { 0x086c, 0x69 }, { 0x086d, 0x87 }, { 0x086e, 0x05 },
+ { 0x086f, 0x00 }, { 0x0870, 0x33 }, { 0x0871, 0x48 }, { 0x0872, 0x04 },
+ { 0x0873, 0x00 }, { 0x0874, 0x1a }, { 0x0875, 0x22 }, { 0x0876, 0x00 },
+ { 0x0877, 0x00 }, { 0x0878, 0xbf }, { 0x0879, 0x02 }, { 0x087a, 0xbf },
+ { 0x087b, 0x02 }, { 0x087c, 0xec }, { 0x087d, 0x45 }, { 0x087e, 0x73 },
+ { 0x087f, 0x78 }, { 0x0880, 0x71 }, { 0x0881, 0x0a }, { 0x0882, 0x80 },
+ { 0x0883, 0x0c }, { 0x0884, 0x1f }, { 0x0885, 0x00 }, { 0x0886, 0x83 },
+ { 0x0887, 0x37 }, { 0x0888, 0x4a }, { 0x0889, 0x80 }, { 0x088a, 0x4a },
+ { 0x088b, 0x80 }, { 0x088c, 0x25 }, { 0x088d, 0x40 }, { 0x088e, 0xc1 },
+ { 0x088f, 0x1f }, { 0x0890, 0x00 }, { 0x0891, 0x08 }, { 0x0892, 0x83 },
+ { 0x0893, 0x3f }, { 0x0894, 0x4a }, { 0x0895, 0x80 }, { 0x0896, 0x4a },
+ { 0x0897, 0x80 }, { 0x0898, 0x25 }, { 0x0899, 0x40 }, { 0x089a, 0xc1 },
+ { 0x089b, 0x1f }, { 0x089c, 0x00 }, { 0x089d, 0x09 }, { 0x089e, 0x00 },
+ { 0x089f, 0x00 }, { 0x08a0, 0x78 }, { 0x08a1, 0x06 }, { 0x08a2, 0xd6 },
+ { 0x08a3, 0x12 }, { 0x08a4, 0x00 }, { 0x08a5, 0x90 }, { 0x08a6, 0x00 },
+ { 0x08a7, 0x00 }, { 0x08a8, 0xde }, { 0x08a9, 0x53 }, { 0x08aa, 0x03 },
+ { 0x08ab, 0x00 }, { 0x08ac, 0xb1 }, { 0x08ad, 0x01 }, { 0x08ae, 0x00 },
+ { 0x08af, 0x00 }, { 0x08b0, 0xd0 }, { 0x08b1, 0xf3 }, { 0x08b2, 0x00 },
+ { 0x08b3, 0x00 }, { 0x08b4, 0x00 }, { 0x08b5, 0x00 }, { 0x08b6, 0x00 },
+ { 0x08b7, 0x00 }, { 0x08b8, 0xe8 }, { 0x08b9, 0x03 }, { 0x08ba, 0xff },
+ { 0x08bb, 0x0f }, { 0x08bc, 0xff }, { 0x08bd, 0x0f }, { 0x08be, 0xff },
+ { 0x08bf, 0x0f }, { 0x08c0, 0x00 }, { 0x08c1, 0x00 }, { 0x08c2, 0x00 },
+ { 0x08c3, 0x00 }, { 0x08c4, 0x00 }, { 0x08c5, 0x00 }, { 0x08c6, 0x00 },
+ { 0x08c7, 0x00 }, { 0x08c8, 0x00 }, { 0x08c9, 0x00 }, { 0x08ca, 0x01 },
+ { 0x08cb, 0x00 }, { 0x08cc, 0x20 }, { 0x08cd, 0x00 }, { 0x08ce, 0x08 },
+ { 0x08cf, 0x00 }, { 0x08d0, 0x70 }, { 0x08d1, 0x38 }, { 0x08d2, 0x06 },
+ { 0x08d3, 0x01 }, { 0x08d4, 0x24 }, { 0x08d5, 0x00 }, { 0x08d6, 0xff },
+ { 0x08d7, 0x7f }, { 0x08d8, 0x00 }, { 0x08d9, 0x18 }, { 0x08da, 0x18 },
+ { 0x08db, 0x18 }, { 0x08dc, 0xa3 }, { 0x08dd, 0x33 }, { 0x08de, 0xff },
+ { 0x08df, 0x7f }, { 0x08e0, 0x01 }, { 0x08e1, 0x00 }, { 0x08e2, 0x06 },
+ { 0x08e3, 0x01 }, { 0x08e4, 0x24 }, { 0x08e5, 0x00 }, { 0x08e6, 0xff },
+ { 0x08e7, 0x7f }, { 0x08e8, 0x00 }, { 0x08e9, 0x18 }, { 0x08ea, 0x18 },
+ { 0x08eb, 0x18 }, { 0x08ec, 0xa3 }, { 0x08ed, 0x33 }, { 0x08ee, 0xff },
+ { 0x08ef, 0x7f }, { 0x08f0, 0xfc }, { 0x08f1, 0xff }, { 0x08f2, 0xff },
+ { 0x08f3, 0x0f }, { 0x08f4, 0x00 }, { 0x08f5, 0x00 }, { 0x08f6, 0x00 },
+ { 0x08f7, 0x00 }, { 0x08f8, 0x00 }, { 0x08f9, 0x80 }, { 0x08fa, 0x01 },
+ { 0x08fb, 0x04 }, { 0x08fc, 0x00 }, { 0x08fd, 0x80 }, { 0x08fe, 0x01 },
+ { 0x08ff, 0x04 }, { 0x0900, 0xaa }, { 0x0901, 0x4f }, { 0x0902, 0x01 },
+ { 0x0903, 0x04 }, { 0x0904, 0x82 }, { 0x0905, 0x4f }, { 0x0906, 0x01 },
+ { 0x0907, 0x04 }, { 0x0908, 0xaa }, { 0x0909, 0x4f }, { 0x090a, 0x01 },
+ { 0x090b, 0x04 }, { 0x090c, 0xaa }, { 0x090d, 0x4f }, { 0x090e, 0x01 },
+ { 0x090f, 0x04 }, { 0x0910, 0xc9 }, { 0x0911, 0x00 }, { 0x0912, 0x80 },
+ { 0x0913, 0x4c }, { 0x0914, 0xa0 }, { 0x0915, 0x00 }, { 0x0916, 0x00 },
+ { 0x0917, 0x00 }, { 0x0918, 0xa0 }, { 0x0919, 0x01 }, { 0x091a, 0x00 },
+ { 0x091b, 0x00 }, { 0x091c, 0x00 }, { 0x091d, 0x00 }, { 0x091e, 0x00 },
+ { 0x091f, 0x00 }, { 0x0920, 0x00 }, { 0x0921, 0x48 }, { 0x0922, 0x3d },
+ { 0x0923, 0xf5 }, { 0x0924, 0x05 }, { 0x0925, 0x05 }, { 0x0926, 0x00 },
+ { 0x0927, 0x00 }, { 0x0948, 0x00 }, { 0x0949, 0x2e }, { 0x094a, 0x3f },
+ { 0x094b, 0x4a }, { 0x0810, 0x00 },
+};
+
+static const cx_reg_t decoder_audio[] = {
+ { 0x0122, 0x01 }, { 0x0127, 0x50 }, { 0x0914, 0xa0 }, { 0x0915, 0x00 },
+ { 0x0916, 0x00 }, { 0x0917, 0x00 }, { 0x0918, 0xa0 }, { 0x0919, 0x01 },
+ { 0x091a, 0x00 }, { 0x091b, 0x00 }, { 0x0808, 0xf6 }, { 0x0809, 0x00 },
+ { 0x080a, 0x00 }, { 0x080b, 0x14 },
+};
+
+/*
+ * The audio-ADC block as it appears on the CD that shipped with the board.
+ *
+ * /mnt/cdr/Driver/p2usbRZ2.sys (dated 2004-11-24) is a different build
+ * from the copy in /tmp/vbshare - md5 bcf534dd against a33cd0ab - and its
+ * second table starts four registers earlier than the one already in use:
+ * 0x0948..0x094b come before 0x0810 and the 0x0914 run. Those four do not
+ * appear in the other build at all. ADCTAB2 selects this variant.
+ */
+/*
+ * The audio table MagicTV builds, from FUN_10015e50.
+ *
+ * param_1 picks the variant: 1 -> 0x418=0x2e 0x419=0xba 0x41a=0x10,
+ * 0 -> 0x418=0 0x419=0 0x41a=0, anything else -> 0x418=0 0x419=0 0x41a=0
+ * with the mode word 0x03. All of it sits in the 0x04xx decoder block,
+ * not 0x08xx - so on this part the audio configuration is reachable, it
+ * was just never written. GVDECTAB applies this alongside the video
+ * table when AUDTAB is set.
+ */
+static const cx_reg_t decoder_audio_mode[] = {
+ { 0x0418, 0x2e }, { 0x0419, 0xba }, { 0x041a, 0x10 },
+};
+
+static const cx_reg_t decoder_audio_off[] = {
+ { 0x0418, 0x00 }, { 0x0419, 0x00 }, { 0x041a, 0x00 },
+};
+
+int pvr2_cx2584x_write_audio_mode(pvr2_dev *p, int on)
+{
+ const cx_reg_t *tab = on ? decoder_audio_mode : decoder_audio_off;
+ int i, errs = 0;
+
+ for (i = 0; i < 3; i++) {
+ uint8_t v = tab[i].val;
+ if (pvr2_i2c_write(p, CX2584X_I2C_ADDR, tab[i].reg, &v, 1) < 0)
+ errs++;
+ }
+ return errs ? -1 : 0;
+}
+
+static const cx_reg_t decoder_audio_adc_cd[] = {
+ { 0x0948, 0x00 }, { 0x0949, 0x2e },
+ { 0x094a, 0x3f }, { 0x094b, 0x4a },
+ { 0x0810, 0x00 },
+ { 0x0122, 0x01 }, { 0x0127, 0x50 },
+ { 0x0914, 0xa0 }, { 0x0915, 0x00 },
+ { 0x0916, 0x00 }, { 0x0917, 0x00 },
+ { 0x0918, 0xa0 }, { 0x0919, 0x00 },
+ { 0x091a, 0x00 }, { 0x091b, 0x00 },
+ { 0x0808, 0xf7 }, { 0x0809, 0x00 },
+ { 0x080a, 0x00 }, { 0x080b, 0x14 },
+};
+
+
+/*
+ * The audio half of the video/audio DSP block, 0x0808-0x081f.
+ *
+ * The full 306-register NTSC table is what breaks the picture, and 302 of
+ * its entries live in 0x0800-0x094b. These are the audio-side registers
+ * from the same block, extracted so the audio path can be brought up
+ * without touching the video DSP that was destroying the image.
+ */
+static const cx_reg_t decoder_audio_dsp[] = {
+ { 0x0808, 0x11 }, { 0x0809, 0x00 }, { 0x080a, 0x00 }, { 0x080b, 0x00 },
+ { 0x080c, 0x00 }, { 0x080d, 0x00 }, { 0x080e, 0x00 }, { 0x080f, 0x00 },
+ { 0x0810, 0x00 }, { 0x0811, 0x01 }, { 0x0812, 0xff }, { 0x0813, 0x00 },
+ { 0x0814, 0x0a }, { 0x0815, 0x00 }, { 0x0816, 0x2e }, { 0x0817, 0x01 },
+ { 0x0818, 0xc0 }, { 0x0819, 0x31 }, { 0x081a, 0x00 }, { 0x081b, 0x00 },
+ { 0x081c, 0x00 }, { 0x081d, 0x00 }, { 0x081e, 0x80 }, { 0x081f, 0x47 },
+};
+
+int pvr2_cx2584x_write_audio_dsp(pvr2_dev *p, int japan_audio)
+{
+ int i, errs = 0;
+
+ for (i = 0; i < (int)(sizeof(decoder_audio_dsp) /
+ sizeof(decoder_audio_dsp[0])); i++) {
+ uint16_t reg = decoder_audio_dsp[i].reg;
+ uint8_t val = decoder_audio_dsp[i].val;
+ if (reg == 0x0808 && japan_audio)
+ val = 0xf7;
+ if (pvr2_i2c_write(p, CX2584X_I2C_ADDR, reg, &val, 1) < 0)
+ errs++;
+ }
+ if (errs && p->verbose)
+ fprintf(stderr, "cx2584x audio dsp: %d write error(s)\n", errs);
+ return errs ? -1 : 0;
+}
+
+/*
+ * Audio-ADC block on its own.
+ *
+ * The full table write was found to destroy the picture, so it cannot be
+ * used to chase the missing audio. This applies just the audio-ADC part
+ * (0x0914/0x0918 = 0xa0 bring the ADC up, 0x0808 selects the carrier
+ * standard) so the audio path can be tested without touching the video
+ * DSP. This is the table the official driver writes from
+ * pvr2_cx2584x_write_tables()'s second loop.
+ */
+int pvr2_cx2584x_write_audio_table(pvr2_dev *p, int japan_audio)
+{
+ int i, errs = 0;
+ const cx_reg_t *tab = decoder_audio;
+ int n = (int)(sizeof(decoder_audio)/sizeof(decoder_audio[0]));
+
+ /* ADCTAB2 picks the variant that shipped on the CD with the board;
+ * it carries 0x0948-0x094b, which the other build has not got. */
+ if (getenv("ADCTAB2")) {
+ tab = decoder_audio_adc_cd;
+ n = (int)(sizeof(decoder_audio_adc_cd) /
+ sizeof(decoder_audio_adc_cd[0]));
+ }
+
+ for (i = 0; i < n; i++) {
+ uint16_t reg = tab[i].reg;
+ uint8_t val = tab[i].val;
+ if (reg == 0xffffffff)
+ break;
+ /* 0x808: 0xf6 = BTSC (US), 0xf7 = EIAJ (Japan) */
+ if (reg == 0x0808 && japan_audio)
+ val = 0xf7;
+ if (pvr2_i2c_write(p, CX2584X_I2C_ADDR, reg, &val, 1) < 0)
+ errs++;
+ }
+ if (errs && p->verbose)
+ fprintf(stderr, "cx2584x audio table: %d write error(s)\n", errs);
+ return errs ? -1 : 0;
+}
+
+int pvr2_cx2584x_write_tables(pvr2_dev *p, int japan_audio)
+{
+ int i, errs = 0;
+
+ for (i = 0; i < (int)(sizeof(decoder_init_ntsc)/sizeof(decoder_init_ntsc[0])); i++) {
+ if (pvr2_i2c_write(p, CX2584X_I2C_ADDR, decoder_init_ntsc[i].reg,
+ &decoder_init_ntsc[i].val, 1) < 0)
+ errs++;
+ }
+ for (i = 0; i < (int)(sizeof(decoder_audio)/sizeof(decoder_audio[0])); i++) {
+ uint16_t reg = decoder_audio[i].reg;
+ uint8_t val = decoder_audio[i].val;
+ /* 0x808: 0xf6 = BTSC (US), 0xf7 = EIAJ (Japan) */
+ if (reg == 0x0808 && japan_audio)
+ val = 0xf7;
+ if (pvr2_i2c_write(p, CX2584X_I2C_ADDR, reg, &val, 1) < 0)
+ errs++;
+ }
+
+ if (errs && p->verbose)
+ fprintf(stderr, "cx2584x tables: %d write error(s)\n", errs);
+ return errs ? -1 : 0;
+}
+
+/*
+ * Decoder register table recovered from MagicTV's own RZ2 driver.
+ *
+ * The board is a CX25837 (device id 0x8373), not the CX25843 this code was
+ * originally written for. gvmvprz2.dll - the GV-MVP/RZ2 driver package,
+ * its Setup.ini says AppName=GV-MVP/RZ2 - builds a decoder table in
+ * FUN_10014f20 and an audio PLL block in FUN_10015fd0. This is the first
+ * of those, read off the decompiled assignment order.
+ *
+ * Note what is not here: the 0x08xx audio block. That one is unreachable
+ * on this part over I2C, which is why the audio PES question is still open.
+ * What this does give us is the 0x0400-0x04a5 video path the real driver
+ * programs - 0x048b, 0x043e-0x0441, 0x044c-0x044f, 0x0454-0x0459,
+ * 0x0463-0x046e among them - adaptive comb and noise reduction settings
+ * mpegcap has never touched. Those are the most likely home of the
+ * residual comb pattern in the raw capture.
+ */
+struct gv_dec_reg {
+ uint16_t reg;
+ uint8_t val[4];
+ int n;
+};
+
+static const struct gv_dec_reg gv_dec_table[] = {
+ { 0x048b, { 160 }, 1 },
+ { 0x0400, { 32 }, 1 },
+ { 0x0401, { 240 }, 1 },
+ { 0x0404, { 54 }, 1 },
+ { 0x0405, { 37 }, 1 },
+ { 0x0406, { 16 }, 1 },
+ { 0x0409, { 128 }, 1 },
+ { 0x040d, { 129 }, 1 },
+ { 0x0412, { 255 }, 1 },
+ { 0x0413, { 127 }, 1 },
+ { 0x0415, { 128 }, 1 },
+ { 0x0420, { 128 }, 1 },
+ { 0x0421, { 128 }, 1 },
+ { 0x043e, { 240 }, 1 },
+ { 0x043f, { 255 }, 1 },
+ { 0x0440, { 169 }, 1 },
+ { 0x0441, { 11 }, 1 },
+ { 0x044c, { 112 }, 1 },
+ { 0x044d, { 153 }, 1 },
+ { 0x044e, { 16 }, 1 },
+ { 0x044f, { 44 }, 1 },
+ { 0x0454, { 13 }, 1 },
+ { 0x0455, { 196 }, 1 },
+ { 0x0457, { 38 }, 1 },
+ { 0x0458, { 119 }, 1 },
+ { 0x0459, { 136 }, 1 },
+ { 0x045b, { 84 }, 1 },
+ { 0x0461, { 20 }, 1 },
+ { 0x0463, { 52 }, 1 },
+ { 0x0464, { 110 }, 1 },
+ { 0x0465, { 202 }, 1 },
+ { 0x0466, { 54 }, 1 },
+ { 0x0468, { 231 }, 1 },
+ { 0x046c, { 32 }, 1 },
+ { 0x046d, { 246 }, 1 },
+ { 0x046e, { 132 }, 1 },
+ { 0x0470, { 122 }, 1 },
+ { 0x0472, { 45 }, 1 },
+ { 0x0473, { 91 }, 1 },
+ { 0x0474, { 26 }, 1 },
+ { 0x0475, { 144 }, 1 },
+ { 0x0476, { 30 }, 1 },
+ { 0x0477, { 22 }, 1 },
+ { 0x0478, { 31 }, 1 },
+ { 0x047a, { 80 }, 1 },
+ { 0x047b, { 70 }, 1 },
+ { 0x047c, { 31 }, 1 },
+ { 0x047d, { 124 }, 1 },
+ { 0x0480, { 222 }, 1 },
+ { 0x0487, { 66 }, 1 },
+ { 0x0488, { 25 }, 1 },
+ { 0x0489, { 214 }, 1 },
+ { 0x048b, { 168 }, 1 },
+ { 0x048c, { 220 }, 1 },
+ { 0x048d, { 64 }, 1 },
+ { 0x048e, { 16 }, 1 },
+ { 0x0490, { 138 }, 1 },
+ { 0x0492, { 63 }, 1 },
+ { 0x0493, { 205 }, 1 },
+ { 0x0496, { 31 }, 1 },
+ { 0x0497, { 22 }, 1 },
+ { 0x0498, { 35 }, 1 },
+ { 0x049c, { 20 }, 1 },
+ { 0x049e, { 80 }, 1 },
+ { 0x049f, { 32 }, 1 },
+ { 0x04a0, { 15 }, 1 },
+ { 0x04a2, { 12 }, 1 },
+};
+
+int pvr2_cx2584x_write_dec_table(pvr2_dev *p)
+{
+ size_t i;
+ int k, errs = 0;
+
+ for (i = 0; i < sizeof(gv_dec_table) / sizeof(gv_dec_table[0]); i++) {
+ for (k = 0; k < gv_dec_table[i].n; k++) {
+ uint8_t v = gv_dec_table[i].val[k];
+ if (pvr2_i2c_write(p, CX2584X_I2C_ADDR,
+ gv_dec_table[i].reg, &v, 1) < 0)
+ errs++;
+ }
+ }
+ return errs;
+}
diff --git a/src/device.c b/src/device.c
new file mode 100644
index 0000000..88c42cd
--- /dev/null
+++ b/src/device.c
@@ -0,0 +1,583 @@
+/*
+ * device.c - libusb device management, FX2 commands, I2C, MBOX
+ *
+ * Part of mpegcap: cross-platform CX23416/FX2 USB MPEG capture.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#if !defined(_WIN32)
+#include <unistd.h> /* geteuid() */
+#endif
+
+#include "pvrusb2.h"
+
+/* ================================================================== */
+/* Device management */
+/* ================================================================== */
+
+int pvr2_init(pvr2_dev *p)
+{
+ memset(p, 0, sizeof(*p));
+ if (libusb_init(&p->ctx) < 0) {
+ fprintf(stderr, "libusb_init failed\n");
+ return -1;
+ }
+ return 0;
+}
+
+void pvr2_exit(pvr2_dev *p)
+{
+ if (p->dev) {
+ libusb_release_interface(p->dev, 0);
+ libusb_close(p->dev);
+ p->dev = NULL;
+ }
+ if (p->ctx) {
+ libusb_exit(p->ctx);
+ p->ctx = NULL;
+ }
+}
+
+int pvr2_find_device(pvr2_dev *p, uint16_t vid, uint16_t pid)
+{
+ libusb_device **list = NULL;
+ ssize_t cnt;
+ int found = 0;
+ ssize_t i;
+
+ p->vid = vid;
+ p->pid = pid;
+
+ cnt = libusb_get_device_list(p->ctx, &list);
+ if (cnt < 0)
+ return -1;
+
+ for (i = 0; i < cnt; i++) {
+ struct libusb_device_descriptor desc;
+ if (libusb_get_device_descriptor(list[i], &desc) < 0)
+ continue;
+ if (desc.idVendor == vid && desc.idProduct == pid &&
+ desc.bcdDevice != 0x0100) {
+ char manuf[128] = "", prod[128] = "";
+ libusb_device_handle *h = NULL;
+ /* Try to describe the device (best-effort) */
+ if (libusb_open(list[i], &h) == 0) {
+ libusb_get_string_descriptor_ascii(h, desc.iManufacturer,
+ (unsigned char *)manuf, sizeof(manuf));
+ libusb_get_string_descriptor_ascii(h, desc.iProduct,
+ (unsigned char *)prod, sizeof(prod));
+ libusb_close(h);
+ }
+ fprintf(stderr, "device found: %04x:%04x %s %s\n",
+ desc.idVendor, desc.idProduct, manuf, prod);
+ found = 1;
+ break;
+ }
+ }
+ libusb_free_device_list(list, 1);
+
+ if (!found)
+ return -1;
+
+ p->dev = libusb_open_device_with_vid_pid(p->ctx, vid, pid);
+ if (!p->dev) {
+ fprintf(stderr, "cannot open device %04x:%04x "
+ "(permissions? kernel driver attached?)\n", vid, pid);
+ return -1;
+ }
+
+ /*
+ * A cold unit enumerates as the Cypress default 04b4:8613 until the
+ * FX2 firmware is uploaded - the INF calls that image Eagle.bix, and
+ * it is what turns the device into 04bb:0514. Without this fallback
+ * there is nothing to open on a unit that has just been plugged in
+ * after a power cycle, and the only symptom is "device not found".
+ */
+ if (p->verbose)
+ fprintf(stderr, "opened %04x:%04x\n", vid, pid);
+
+#if defined(LIBUSB_API_VERSION) && LIBUSB_API_VERSION >= 0x01000102
+ /* Detach a kernel driver automatically if one is attached.
+ * Linux: usbfs. On FreeBSD there is no kernel driver for this
+ * device.
+ *
+ * IMPORTANT: on FreeBSD this call issues USBDEVFS_CLAIMINTERFACE /
+ * DETACHKERNELDRIVER internally, which needs root. As a normal user
+ * it returns EPERM (-99) and, worse, leaves the interface in a state
+ * where the following claim also fails with -99. So only enable it
+ * when we are root. */
+ if (geteuid() == 0)
+ libusb_set_auto_detach_kernel_driver(p->dev, 1);
+#endif
+
+ /* Claim interface 0. If it is busy (a previous run left the device
+ * in a bad state, or another process holds it), reset and retry.
+ * NOTE: libusb_reset_device() needs root on FreeBSD, so for a normal
+ * user we only retry the claim. */
+ /*
+ * USBRESET=1 - force a USB port reset before touching the device.
+ *
+ * This is the software equivalent of the "10 s replug" the notes
+ * call for when the CX23416 is left wedged (e.g. after an experiment
+ * that writes its registers in the wrong order -- writing
+ * 0x9054/0x9058 before the firmware image did exactly that on
+ * 2026-10-14). A port reset makes the FX2 re-load its firmware
+ * from EEPROM and resets everything downstream, without needing
+ * physical access to the cable.
+ */
+ if (getenv("USBRESET")) {
+ int rr = libusb_reset_device(p->dev);
+ struct timespec ts = { 3, 0 };
+
+ fprintf(stderr, "USBRESET: libusb_reset_device r=%d (%s)\n",
+ rr, libusb_error_name(rr));
+ nanosleep(&ts, NULL);
+ /*
+ * After a port reset the device re-enumerates and the old
+ * handle can go stale, so drop it and open a fresh one.
+ */
+ libusb_close(p->dev);
+ p->dev = libusb_open_device_with_vid_pid(p->ctx, vid, pid);
+ fprintf(stderr, "USBRESET: reopen -> %s\n",
+ p->dev ? "ok" : "FAILED");
+ if (!p->dev)
+ return -1;
+ }
+
+ {
+ int tries;
+ for (tries = 0; tries < 3; tries++) {
+ int cr = libusb_claim_interface(p->dev, 0);
+ if (cr == 0)
+ break;
+ if (tries == 0)
+ fprintf(stderr, "claim attempt 1 failed: %s\n",
+ libusb_error_name(cr));
+ if (tries == 0) {
+ /* Detach explicitly (in case auto-detach did not). */
+ libusb_detach_kernel_driver(p->dev, 0);
+ } else if (tries == 1 && geteuid() == 0) {
+ fprintf(stderr,
+ "interface 0 busy, resetting device...\n");
+ libusb_reset_device(p->dev);
+ }
+ {
+ struct timespec ts = { 0, 300000000L };
+ nanosleep(&ts, NULL);
+ }
+ }
+ if (tries == 3) {
+ fprintf(stderr,
+ "cannot claim interface 0 (is another process using the device?)\n");
+ libusb_close(p->dev);
+ p->dev = NULL;
+ return -1;
+ }
+ }
+ return 0;
+}
+
+int pvr2_scan(pvr2_dev *p)
+{
+ libusb_device **list = NULL;
+ ssize_t cnt, i;
+
+ cnt = libusb_get_device_list(p->ctx, &list);
+ if (cnt < 0)
+ return -1;
+ fprintf(stderr, "USB devices:\n");
+ for (i = 0; i < cnt; i++) {
+ struct libusb_device_descriptor desc;
+ uint8_t bus, addr;
+ if (libusb_get_device_descriptor(list[i], &desc) < 0)
+ continue;
+ bus = libusb_get_bus_number(list[i]);
+ addr = libusb_get_device_address(list[i]);
+ fprintf(stderr, " %04x:%04x bus %u addr %u\n",
+ desc.idVendor, desc.idProduct, bus, addr);
+ }
+ libusb_free_device_list(list, 1);
+ return 0;
+}
+
+/* ================================================================== */
+/* Bulk helpers */
+/* ================================================================== */
+
+static int bulk_out(pvr2_dev *p, uint8_t ep, const uint8_t *buf, int len)
+{
+ int transferred = 0;
+ int r = libusb_bulk_transfer(p->dev, ep, (unsigned char *)buf, len,
+ &transferred, 5000);
+ if (r != 0 || transferred != len) {
+ if (p->verbose)
+ fprintf(stderr, "bulk_out ep 0x%02x len %d -> r=%d tr=%d (%s)\n",
+ ep, len, r, transferred, libusb_error_name(r));
+ return -1;
+ }
+ return 0;
+}
+
+static int bulk_in(pvr2_dev *p, uint8_t ep, uint8_t *buf, int len)
+{
+ int transferred = 0;
+ int r = libusb_bulk_transfer(p->dev, ep, buf, len, &transferred, 1000);
+ if (r != 0) {
+ if (p->verbose)
+ fprintf(stderr, "bulk_in ep 0x%02x len %d -> r=%d (%s)\n",
+ ep, len, r, libusb_error_name(r));
+ return -1;
+ }
+ return transferred;
+}
+
+/* Public wrappers for the command endpoints (used by the encoder layer) */
+int pvr2_raw_in(pvr2_dev *p, uint8_t ep, uint8_t *buf, int len)
+{
+ return bulk_in(p, ep, buf, len);
+}
+
+int bulk_cmd_out(pvr2_dev *p, const uint8_t *buf, int len)
+{
+ return bulk_out(p, EP_CMD_OUT, buf, len);
+}
+
+int bulk_cmd_in(pvr2_dev *p, uint8_t *buf, int len)
+{
+ return bulk_in(p, EP_CMD_IN, buf, len);
+}
+
+int pvr2_get_usb_speed(pvr2_dev *p)
+{
+ uint8_t cmd = FX2CMD_GET_USB_SPEED;
+ uint8_t buf[64];
+ int n;
+
+ if (bulk_out(p, EP_CMD_OUT, &cmd, 1) < 0)
+ return -1;
+ n = bulk_in(p, EP_CMD_IN, buf, sizeof(buf));
+ if (n < 1)
+ return -1;
+ return buf[0];
+}
+
+/* ================================================================== */
+/* FX2 simple command / register access */
+/* ================================================================== */
+
+int pvr2_simple_cmd(pvr2_dev *p, uint8_t cmd, const uint8_t *arg, int arglen)
+{
+ uint8_t buf[8];
+ buf[0] = cmd;
+ if (arglen > 0 && arg)
+ memcpy(buf + 1, arg, arglen);
+ else
+ arglen = 0;
+ return bulk_out(p, EP_CMD_OUT, buf, 1 + arglen);
+}
+
+int pvr2_write_reg(pvr2_dev *p, uint16_t reg, uint32_t val)
+{
+ uint8_t buf[8];
+ buf[0] = FX2CMD_REG_WRITE;
+ buf[1] = val & 0xff;
+ buf[2] = (val >> 8) & 0xff;
+ buf[3] = (val >> 16) & 0xff;
+ buf[4] = (val >> 24) & 0xff;
+ buf[5] = 0x00;
+ buf[6] = (reg >> 8) & 0xff;
+ buf[7] = reg & 0xff;
+ return bulk_out(p, EP_CMD_OUT, buf, 8);
+}
+
+int pvr2_read_reg(pvr2_dev *p, uint16_t reg, uint32_t *val)
+{
+ uint8_t buf[8];
+ uint8_t in[8];
+ int n;
+
+ memset(buf, 0, sizeof(buf));
+ buf[0] = FX2CMD_REG_READ;
+ buf[6] = (reg >> 8) & 0xff;
+ buf[7] = reg & 0xff;
+ if (bulk_out(p, EP_CMD_OUT, buf, 8) < 0)
+ return -1;
+ n = bulk_in(p, EP_CMD_IN, in, sizeof(in));
+ if (n < 4)
+ return -1;
+ *val = (uint32_t)in[0] | ((uint32_t)in[1] << 8) |
+ ((uint32_t)in[2] << 16) | ((uint32_t)in[3] << 24);
+ return 0;
+}
+
+int pvr2_gpio_dir(pvr2_dev *p, uint32_t mask, uint32_t val)
+{
+ uint32_t reg = val;
+
+ if (~mask) {
+ if (pvr2_read_reg(p, CX_REG_GPIO_DIR, &reg) < 0)
+ return -1;
+ reg = (reg & ~mask) | (val & mask);
+ }
+ return pvr2_write_reg(p, CX_REG_GPIO_DIR, reg);
+}
+
+int pvr2_gpio_out(pvr2_dev *p, uint32_t mask, uint32_t val)
+{
+ uint32_t reg = val;
+
+ if (~mask) {
+ if (pvr2_read_reg(p, CX_REG_GPIO_OUT, &reg) < 0)
+ return -1;
+ reg = (reg & ~mask) | (val & mask);
+ }
+ return pvr2_write_reg(p, CX_REG_GPIO_OUT, reg);
+}
+
+/* ================================================================== */
+/* I2C via FX2 */
+/* ================================================================== */
+
+int pvr2_i2c_write(pvr2_dev *p, uint8_t dev_addr, uint16_t reg,
+ const uint8_t *data, int len)
+{
+ uint8_t buf[256];
+ uint8_t in[16];
+ int n;
+
+ /* [0x08][i2c_addr][len+2][reg_hi][reg_lo][data...] */
+ buf[0] = FX2CMD_I2C_WRITE;
+ buf[1] = dev_addr;
+ buf[2] = len + 2;
+ buf[3] = (reg >> 8) & 0xff;
+ buf[4] = reg & 0xff;
+ memcpy(buf + 5, data, len);
+ if (bulk_out(p, EP_CMD_OUT, buf, len + 5) < 0)
+ return -1;
+ /* status byte (0x08 = OK) */
+ n = bulk_in(p, EP_CMD_IN, in, sizeof(in));
+ if (n < 1 || in[0] != 8) {
+ if (p->verbose)
+ fprintf(stderr, "i2c write status %d (expect 8)\n",
+ n > 0 ? in[0] : -1);
+ return -1;
+ }
+ return 0;
+}
+
+/*
+ * pvr2_i2c_write_block - write N registers to one device in a single FX2
+ * command (FX2CMD_I2C_WRITE_BLOCK).
+ *
+ * Recovered from a USB capture of the official Windows driver: every
+ * multi-register block -- the whole audio DSP block 0x0800-0x091b, the
+ * auxiliary PLL words, the 0x08d0-0x08d3 stream-on words -- is written this
+ * way, never as a run of single-register 0x08 writes. Single registers
+ * (e.g. the 0x012b DSP-start trigger) do use 0x08, so both paths exist.
+ *
+ * The captured packets are 64 bytes long on the wire (the used part is
+ * 4 + 3*count and the rest is whatever was in the driver's buffer), but the
+ * FX2 only reads count entries, so only the used part is sent here.
+ */
+int pvr2_i2c_write_block(pvr2_dev *p, uint8_t dev_addr,
+ const uint16_t *regs, const uint8_t *vals, int n)
+{
+ uint8_t buf[256];
+ uint8_t in[16];
+ int i, len = 0, r;
+
+ if (n < 1 || n > 84 || 4 + 3 * n > (int)sizeof(buf))
+ return -1;
+ buf[len++] = FX2CMD_I2C_WRITE_BLOCK;
+ buf[len++] = dev_addr;
+ buf[len++] = (uint8_t)n;
+ buf[len++] = 0x03; /* bytes per entry */
+ for (i = 0; i < n; i++) {
+ buf[len++] = (regs[i] >> 8) & 0xff;
+ buf[len++] = regs[i] & 0xff;
+ buf[len++] = vals[i];
+ }
+ if (bulk_out(p, EP_CMD_OUT, buf, len) < 0)
+ return -1;
+ r = bulk_in(p, EP_CMD_IN, in, sizeof(in));
+ if (r < 1 || in[0] != 8) {
+ if (p->verbose)
+ fprintf(stderr, "i2c block write status %d "
+ "(expect 8)\n", r > 0 ? in[0] : -1);
+ return -1;
+ }
+ return 0;
+}
+
+/*
+ * pvr2_audio_block_write - replay the audio register programming exactly as
+ * the official Windows driver sends it (captured over USB, see
+ * docs/NOTES.md and docs/xp-init-sequence.txt).
+ *
+ * The driver writes these registers as THREE FX2 block-I2C commands (0x0c),
+ * not as runs of single-register 0x08 writes, and it does so BEFORE the
+ * CX23416 firmware image is transferred. The values are identical to this
+ * repo's tbl_48000, including 0x0900=0xaa / 0x0901=0x4f, which this project
+ * had previously marked "poison" and never wrote -- the driver writes it
+ * normally, so the value was never the problem.
+ *
+ * The 0x012b DSP-start trigger stays a single-register write, as captured.
+ */
+int pvr2_audio_block_write(pvr2_dev *p)
+{
+ /* 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 (stream on) */
+ static const uint16_t g2r[] = { 0x08d0, 0x08d1, 0x08d2, 0x08d3 };
+ static const uint8_t g2v[] = { 0x70, 0x38, 0x06, 0x01 };
+ /* group 3: 48 kHz aux PLL + the 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])));
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x012b, &b, 1);
+ return rc;
+}
+
+int pvr2_i2c_read(pvr2_dev *p, uint8_t dev_addr, uint16_t reg,
+ uint8_t *data, int len)
+{
+ uint8_t buf[8];
+ uint8_t in[256];
+ int n;
+
+ /* [0x09][arglen=2][rlen][i2c_addr][reg_hi][reg_lo] */
+ buf[0] = FX2CMD_I2C_READ;
+ buf[1] = 2;
+ buf[2] = len;
+ buf[3] = dev_addr;
+ buf[4] = (reg >> 8) & 0xff;
+ buf[5] = reg & 0xff;
+ if (bulk_out(p, EP_CMD_OUT, buf, 6) < 0)
+ return -1;
+ /* response: status byte + len data bytes */
+ n = bulk_in(p, EP_CMD_IN, in, sizeof(in));
+ if (n < len + 1)
+ return -1;
+ if (in[0] != 8) {
+ if (p->verbose)
+ fprintf(stderr, "i2c read status %d (expect 8)\n", in[0]);
+ return -1;
+ }
+ memcpy(data, in + 1, len);
+ return 0;
+}
+
+/* ------------------------------------------------------------------ */
+/* WM873x (Wolfson codec / ADC) packed-register I2C access */
+/* ------------------------------------------------------------------ */
+/*
+ * The WM873x (WM8731/8737/8738 family) packs a 7-bit register number and
+ * a 9-bit data value into TWO bytes after the device address:
+ * [dev_addr][(reg<<1)|(data>>8)][data&0xff]
+ * The generic pvr2_i2c_write() treats 'reg' as a 16-bit sub-address and
+ * sends [dev][reg>>8][reg&0xff][data...] — which the WM873x misreads as
+ * "register 0 = low 9 bits", so every write before this helper landed on
+ * the wrong register and read back "rejected". Encode the packed form
+ * into the 16-bit 'reg' field and send zero data bytes to match.
+ */
+int pvr2_wm873x_write(pvr2_dev *p, uint8_t dev_addr, uint8_t reg, uint16_t data)
+{
+ uint16_t packed = (uint16_t)(((uint16_t)reg << 9) | (data & 0x1ff));
+ return pvr2_i2c_write(p, dev_addr, packed, NULL, 0);
+}
+
+int pvr2_wm873x_read(pvr2_dev *p, uint8_t dev_addr, uint8_t reg, uint16_t *out)
+{
+ uint8_t b[2];
+ /* read: send [dev][(reg<<1)|0][0x00], then read 2 bytes
+ * (B15-B9=reg, B8=data MSB, B7-B0=data LSB) */
+ if (pvr2_i2c_read(p, dev_addr, (uint16_t)((uint16_t)reg << 9), b, 2) < 0)
+ return -1;
+ *out = (uint16_t)((b[0] & 0x01) << 8) | b[1];
+ return 0;
+}
+
+/* ================================================================== */
+/* Utility */
+/* ================================================================== */
+
+uint32_t pvr2_swab32(uint32_t v)
+{
+ return ((v & 0x000000ffu) << 24) | ((v & 0x0000ff00u) << 8) |
+ ((v & 0x00ff0000u) >> 8) | ((v & 0xff000000u) >> 24);
+}
+
+void pvr2_swap32_buf(uint8_t *buf, size_t nblocks)
+{
+ size_t i;
+ for (i = 0; i < nblocks; i++) {
+ uint8_t a = buf[i * 4 + 0];
+ uint8_t b = buf[i * 4 + 1];
+ buf[i * 4 + 0] = buf[i * 4 + 3];
+ buf[i * 4 + 1] = buf[i * 4 + 2];
+ buf[i * 4 + 2] = b;
+ buf[i * 4 + 3] = a;
+ }
+}
+
+int pvr2_load_file(const char *path, uint8_t **out, size_t *len)
+{
+ FILE *f = fopen(path, "rb");
+ long sz;
+ uint8_t *buf;
+
+ if (!f) {
+ fprintf(stderr, "cannot open %s\n", path);
+ return -1;
+ }
+ fseek(f, 0, SEEK_END);
+ sz = ftell(f);
+ fseek(f, 0, SEEK_SET);
+ if (sz <= 0) {
+ fclose(f);
+ return -1;
+ }
+ buf = malloc((size_t)sz);
+ if (!buf) {
+ fclose(f);
+ return -1;
+ }
+ if (fread(buf, 1, (size_t)sz, f) != (size_t)sz) {
+ free(buf);
+ fclose(f);
+ return -1;
+ }
+ fclose(f);
+ *out = buf;
+ *len = (size_t)sz;
+ return 0;
+}
diff --git a/src/driver_seq.c b/src/driver_seq.c
new file mode 100644
index 0000000..307f49f
--- /dev/null
+++ b/src/driver_seq.c
@@ -0,0 +1,67 @@
+/*
+ * driver_seq.c - the GV-MVP/RZ2 official driver's extra capture-start
+ * commands (recovered with Ghidra from p2usbRZ2.sys FUN_000217a2).
+ *
+ * IMPORTANT FINDING (verified on hardware):
+ * The driver's *complete* command list is NOT a drop-in replacement for
+ * the mpegcapt.c config: it omits several commands (0xbb/0xc7/0xd6/
+ * 0x99/0xb7/0x89/0x95/0xa1) and sending only the driver list stalls the
+ * MPEG stream after one transfer. Conversely, the mpegcapt.c config
+ * plus the driver's 0xdc (MISC) group produces a full-rate, stable
+ * stream.
+ *
+ * So this function keeps the known-good mpegcapt.c config and appends
+ * the driver-only extras: the seven 0xdc (MISC) commands and the
+ * encoder status-flag clear. Video is stable; audio still does not
+ * appear, so the remaining audio enabler is elsewhere (see NOTES.md).
+ *
+ * Part of mpegcap.
+ */
+#include <stdio.h>
+
+#include "pvrusb2.h"
+
+int pvr2_encoder_config_driver(pvr2_dev *p, int sample_rate)
+{
+ uint32_t a[8];
+
+ /* Known-good base config (mpegcapt.c / Linux pvrusb2). */
+ if (pvr2_encoder_config(p, sample_rate) < 0) {
+ if (p->verbose)
+ fprintf(stderr, "driver-seq: base config errors\n");
+ return -1;
+ }
+
+ /*
+ * Driver-only MISC (0xdc) group.
+ *
+ * ★ The values below were WRONG until 2026-10-14: they had been
+ * guessed from driver_capture_seq.txt, whose argument list is written
+ * in PUSH order (last argument first), so param0 and param1 came out
+ * swapped and two entries were invented. These are the values the
+ * driver actually sends, read out of the USB capture
+ * (/ROM/rz2-usb.pcap, EP 0x01, cmd 0xdc): six calls per session, in
+ * this order, with every other argument zero:
+ * MISC(5,0) MISC(3,1) MISC(8,0)
+ * MISC(4,1) MISC(0,3) MISC(15,0)
+ * (driver_capture_seq.txt's #5 "3,0" and #7 "[obj+0x1d8],EAX,0x0f"
+ * reverse to (0,3) and (0x0f,...) = 15, which do agree; #6 does not
+ * appear in the capture at all.)
+ * The same values are available as ENCMISC=1 in encoder.c.
+ */
+ a[0] = 5; a[1] = 0;
+ (void)pvr2_enc_cmd(p, CX2341X_ENC_MISC, a, 2);
+ a[0] = 3; a[1] = 1;
+ (void)pvr2_enc_cmd(p, CX2341X_ENC_MISC, a, 2);
+ a[0] = 8; a[1] = 0;
+ (void)pvr2_enc_cmd(p, CX2341X_ENC_MISC, a, 2);
+ a[0] = 4; a[1] = 1;
+ (void)pvr2_enc_cmd(p, CX2341X_ENC_MISC, a, 2);
+ a[0] = 0; a[1] = 3;
+ (void)pvr2_enc_cmd(p, CX2341X_ENC_MISC, a, 2);
+ a[0] = 15; a[1] = 0;
+ (void)pvr2_enc_cmd(p, CX2341X_ENC_MISC, a, 2);
+
+ return 0;
+}
+
diff --git a/src/encoder.c b/src/encoder.c
new file mode 100644
index 0000000..64c28fe
--- /dev/null
+++ b/src/encoder.c
@@ -0,0 +1,1085 @@
+#include <stdlib.h>
+/*
+ * encoder.c - CX23416 encoder MBOX command layer and setup sequences
+ *
+ * Part of mpegcap.
+ *
+ * The CX23416 exposes a 32-bit "MBOX" register window at memory address
+ * 0x44. Commands are issued by writing a 16-word block there, setting
+ * the DRIVER_DONE|DRIVER_BUSY bits in word 0, then polling word 0 until
+ * FIRMWARE_DONE is set.
+ */
+#include <stdio.h>
+#include <string.h>
+#include <time.h>
+
+#if defined(_WIN32)
+#include <windows.h>
+#endif
+
+#include "pvrusb2.h"
+
+#define MBOX_WORDS 16
+#define MBOX_CMD_WORDS 12 /* words actually written before the "go" */
+
+static void usleep100(void)
+{
+#if defined(_WIN32)
+ Sleep(1);
+#else
+ struct timespec ts = { 0, 100000L };
+ nanosleep(&ts, NULL);
+#endif
+}
+
+/* ================================================================== */
+/* Raw MBOX access */
+/* ================================================================== */
+
+int pvr2_mbox_write(pvr2_dev *p, uint32_t addr, const uint32_t *data, int count)
+{
+ uint8_t buf[1 + 7 * 8];
+ int pos = 0; /* index into data[] */
+ int addr_cur = (int)addr;
+
+ while (count > 0) {
+ int next = count > 8 ? 8 : count;
+ int i;
+
+ buf[0] = FX2CMD_MEM_WRITE_DWORD;
+ for (i = 0; i < next; i++) {
+ uint32_t d = data[pos];
+ buf[1 + 7 * i + 0] = d & 0xff;
+ buf[1 + 7 * i + 1] = (d >> 8) & 0xff;
+ buf[1 + 7 * i + 2] = (d >> 16) & 0xff;
+ buf[1 + 7 * i + 3] = (d >> 24) & 0xff;
+ buf[1 + 7 * i + 4] = (addr_cur >> 16) & 0xff;
+ buf[1 + 7 * i + 5] = (addr_cur >> 8) & 0xff;
+ buf[1 + 7 * i + 6] = addr_cur & 0xff;
+ pos++;
+ addr_cur++;
+ count--;
+ }
+ if (bulk_cmd_out(p, buf, 7 * next + 1) < 0)
+ return -1;
+ }
+ return 0;
+}
+
+int pvr2_mbox_read(pvr2_dev *p, uint32_t addr, uint32_t *data, int count)
+{
+ int done = 0;
+ int addr_cur = (int)addr;
+
+ while (done < count) {
+ int next = (count - done) >= 16 ? 16 : 1;
+ uint8_t buf[8];
+ uint8_t in[64];
+ int n, j;
+
+ memset(buf, 0, sizeof(buf));
+ buf[0] = next == 16 ? FX2CMD_MEM_READ_64BYTES : FX2CMD_MEM_READ_DWORD;
+ buf[5] = (addr_cur >> 16) & 0xff;
+ buf[6] = (addr_cur >> 8) & 0xff;
+ buf[7] = addr_cur & 0xff;
+ if (bulk_cmd_out(p, buf, 8) < 0)
+ return -1;
+ n = bulk_cmd_in(p, in, next * 4 + 8);
+ if (n < next * 4)
+ return -1;
+ for (j = 0; j < next; j++)
+ data[done + j] = (uint32_t)in[j * 4 + 0] |
+ ((uint32_t)in[j * 4 + 1] << 8) |
+ ((uint32_t)in[j * 4 + 2] << 16) |
+ ((uint32_t)in[j * 4 + 3] << 24);
+ done += next;
+ addr_cur += next;
+ }
+ return 0;
+}
+
+/* ================================================================== */
+/* Encoder commands */
+/* ================================================================== */
+
+static void mkcmd(uint32_t *data, uint32_t cmd, const uint32_t *para, int size)
+{
+ int i = 0;
+ data[i++] = 0;
+ data[i++] = cmd;
+ data[i++] = 0;
+ data[i++] = 0x00060000; /* timeout */
+ for (; i < MBOX_WORDS; i++) {
+ if (size > 0) {
+ data[i] = *para++;
+ size--;
+ } else {
+ data[i] = 0;
+ }
+ }
+}
+
+int pvr2_enc_cmd(pvr2_dev *p, uint32_t cmd, const uint32_t *args, int nargs)
+{
+ uint32_t data[MBOX_WORDS];
+ uint32_t stat = 0;
+ int i;
+
+ mkcmd(data, cmd, args, nargs);
+
+ if (pvr2_mbox_write(p, CX_MBOX_BASE, data, MBOX_CMD_WORDS) < 0)
+ return -1;
+
+ /* "go": DRIVER_DONE | DRIVER_BUSY */
+ {
+ uint32_t go = CX_MBOX_DRIVER_DONE | CX_MBOX_DRIVER_BUSY;
+ if (pvr2_mbox_write(p, CX_MBOX_BASE, &go, 1) < 0)
+ return -1;
+ }
+
+ /* poll FIRMWARE_DONE */
+ for (i = 0; i < 1000; i++) {
+ if (pvr2_mbox_read(p, CX_MBOX_BASE, &stat, 1) < 0)
+ return -1;
+ if (stat & CX_MBOX_FIRMWARE_DONE)
+ break;
+ usleep100();
+ }
+ if (!(stat & CX_MBOX_FIRMWARE_DONE)) {
+ fprintf(stderr, "encoder command 0x%02x timed out\n", cmd);
+ return -1;
+ }
+
+ /* return to idle */
+ {
+ uint32_t zero = 0;
+ pvr2_mbox_write(p, CX_MBOX_BASE, &zero, 1);
+ }
+ return 0;
+}
+
+int pvr2_enc_get_version(pvr2_dev *p, uint32_t *ver)
+{
+ if (pvr2_enc_cmd(p, CX2341X_ENC_GET_VERSION, NULL, 0) < 0)
+ return -1;
+ if (pvr2_mbox_read(p, CX_MBOX_BASE + 4, ver, 1) < 0)
+ return -1;
+ return 0;
+}
+
+int pvr2_enc_ping(pvr2_dev *p)
+{
+ return pvr2_enc_cmd(p, CX2341X_ENC_PING_FW, NULL, 0);
+}
+
+/*
+ * pvr2_enc_clear_flag - read-modify-write the encoder status word at
+ * MBOX 0x48, clearing the given bits.
+ *
+ * The official driver does this in FUN_0001dd93 (called with 0x40000000
+ * right after SET_AUDIO_PROPERTIES): it reads MBOX word 0x48 and clears
+ * bit 30. That bit gates the encoder's audio path.
+ */
+int pvr2_enc_clear_flag(pvr2_dev *p, uint32_t bits)
+{
+ uint32_t v;
+
+ if (pvr2_mbox_read(p, 0x48, &v, 1) < 0)
+ return -1;
+ v &= ~bits;
+ if (pvr2_mbox_write(p, 0x48, &v, 1) < 0)
+ return -1;
+ return 0;
+}
+
+/* ================================================================== */
+/* Encoder setup sequences */
+/* ================================================================== */
+
+int pvr2_encoder_preconfig(pvr2_dev *p)
+{
+ uint32_t para[8];
+#define CMD(c, n) do { if (pvr2_enc_cmd(p, (c), para, (n)) < 0) \
+ fprintf(stderr, "preconfig cmd 0x%02x failed\n", (c)); } while (0)
+
+ para[0] = 3; para[1] = 1; para[2] = 0; para[3] = 0;
+ CMD(CX2341X_ENC_MISC, 4);
+ para[0] = 8; para[1] = 0; para[2] = 0; para[3] = 0;
+ CMD(CX2341X_ENC_MISC, 4);
+ para[0] = 0; para[1] = 3; para[2] = 0; para[3] = 0;
+ CMD(CX2341X_ENC_MISC, 4);
+ para[0] = 15; para[1] = 0; para[2] = 0; para[3] = 0;
+ CMD(CX2341X_ENC_MISC, 4);
+ para[0] = 4; para[1] = 1;
+ CMD(CX2341X_ENC_MISC, 2);
+#undef CMD
+ return 0;
+}
+
+int vsync_lines = 0x140; /* SET_NUM_VSYNC_LINES: buffer depth */
+
+int pvr2_encoder_config(pvr2_dev *p, int sample_rate)
+{
+ uint32_t para[8];
+ int errs = 0;
+#define CMD(c, n) do { if (pvr2_enc_cmd(p, (c), para, (n)) < 0) { \
+ fprintf(stderr, "config cmd 0x%02x failed\n", (c)); errs++; } } while (0)
+
+ /*
+ * SET_OUTPUT_PORT takes TWO ports: param[0] = video, param[1] = audio.
+ * The INF pins OutType=10 for this device (param[0] = 1), and this tool
+ * has always sent param[1] = 0. The Windows driver sends **[1, 2]**
+ * (docs/xp-init-sequence.txt: cmd 0xbb, args 1,2,0,0,0,0, the very first
+ * encoder command of its session), i.e. it enables an audio output port
+ * that this tool leaves at 0. That is the only audio-specific argument
+ * that differs between the two stacks.
+ * OUTTYPE=<n> video port only (historical, default 1)
+ * OUTPORT=<v>,<a> both ports; e.g. OUTPORT=1,2 = the driver's value
+ */
+ {
+ const char *e = getenv("OUTPORT");
+ const char *o = getenv("OUTTYPE");
+ unsigned int vid = o ? (unsigned int)strtoul(o, NULL, 0) : 1;
+ unsigned int aud = 0;
+ if (e)
+ sscanf(e, "%u,%u", &vid, &aud);
+ para[0] = vid; para[1] = aud;
+ }
+ CMD(CX2341X_ENC_SET_OUTPUT_PORT, 2);
+
+ /*
+ * ENCDNR=1 sends the four DNR/coring commands the Windows driver puts
+ * in its early set, right after SET_OUTPUT_PORT (capture #18-21):
+ * 0x9b = [2,0,0,0] 0x9f = [1,255,0,255]
+ * 0x9d = [0,0,0,0] 0x9f = [255,0,255,0]
+ * This tool never sends 0x9b or 0x9d at all and sends 0x9f only under
+ * AUDCMD, so the pair has never been exercised here. (AUDCMD already
+ * carries the driver's *late* set, which sits after SET_AUDIO_PROP.)
+ */
+ if (getenv("ENCDNR")) {
+ para[0] = 2; para[1] = 0; para[2] = 0; para[3] = 0;
+ CMD(0x9b, 4);
+ para[0] = 1; para[1] = 255; para[2] = 0; para[3] = 255;
+ CMD(0x9f, 4);
+ para[0] = 0; para[1] = 0; para[2] = 0; para[3] = 0;
+ CMD(0x9d, 4);
+ para[0] = 255; para[1] = 0; para[2] = 255; para[3] = 0;
+ CMD(0x9f, 4);
+ }
+
+ /*
+ * ENCMISC=1 sends the six CX2341X_ENC_MISC calls the Windows driver
+ * issues just before SET_NUM_VSYNC_LINES (capture #30-35):
+ * MISC(5,0) MISC(3,1) MISC(8,0) MISC(4,1) MISC(0,3) MISC(15,0)
+ * This tool only ever sent MISC(12) (the documented audio-interface
+ * reset), so these subcommands have never been tried here.
+ */
+ if (getenv("ENCMISC")) {
+ static const uint32_t m[][2] = {
+ { 5, 0 }, { 3, 1 }, { 8, 0 },
+ { 4, 1 }, { 0, 3 }, { 15, 0 },
+ };
+ size_t k;
+ for (k = 0; k < sizeof(m) / sizeof(m[0]); k++) {
+ para[0] = m[k][0]; para[1] = m[k][1];
+ para[2] = 0; para[3] = 0;
+ CMD(CX2341X_ENC_MISC, 4);
+ }
+ }
+
+ para[0] = 7; para[1] = 0x0190;
+ CMD(CX2341X_ENC_SET_PGM_INDEX_INFO, 2);
+
+ /* Frame-buffer depth. The stock 0x140 (320 lines) makes the encoder
+ * hold ~1.5 s of video before it starts emitting, which shows up as
+ * playback lag. Smaller values shorten that window. */
+ para[0] = vsync_lines; para[1] = vsync_lines;
+ CMD(CX2341X_ENC_SET_NUM_VSYNC_LINES, 2);
+
+ para[0] = 0; para[1] = 0; para[2] = 0x10000000; para[3] = 0xffffffff;
+ CMD(CX2341X_ENC_SET_EVENT_NOTIFY, 4);
+
+ para[0] = 0; /* NTSC 29.97 */
+ CMD(CX2341X_ENC_SET_FRAME_RATE, 1);
+
+ para[0] = 480; para[1] = 720; /* NTSC 720x480 */
+ CMD(CX2341X_ENC_SET_FRAME_SIZE, 2);
+
+ para[0] = 2; /* 4:3 */
+ CMD(CX2341X_ENC_SET_ASPECT_RATIO, 1);
+
+ /*
+ * The Windows driver does not send a single "disable" word here; it
+ * walks the VBI line table, two commands per line (#132-177):
+ * SET_VBI_LINE[0x80000000|n, 0,0,0,0] then SET_VBI_LINE[n, 0,0,0,0]
+ * for n = 1..23 (the 0x80000000 form is the "line number valid" bit).
+ * VBISWEEP=1 replays that; without it the historical single call below
+ * is kept.
+ */
+ if (getenv("VBISWEEP")) {
+ unsigned int n;
+ for (n = 1; n <= 23; n++) {
+ para[0] = 0x80000000u | n;
+ para[1] = 0; para[2] = 0; para[3] = 0; para[4] = 0;
+ CMD(CX2341X_ENC_SET_VBI_LINE, 5);
+ para[0] = n;
+ para[1] = 0; para[2] = 0; para[3] = 0; para[4] = 0;
+ CMD(CX2341X_ENC_SET_VBI_LINE, 5);
+ }
+ } else {
+ para[0] = 0xffffffff; para[1] = 0; para[2] = 0;
+ para[3] = 0; para[4] = 0;
+ CMD(CX2341X_ENC_SET_VBI_LINE, 5);
+ }
+
+ para[0] = 0; /* program stream (MPEG-PS) */
+ {
+ /* STREAMTYPE=10 = DVD stream, which is what the Windows
+ * driver actually sets (USB capture, docs/NOTES.md). */
+ const char *e = getenv("STREAMTYPE");
+ if (e)
+ para[0] = (uint32_t)strtoul(e, NULL, 0);
+ }
+ CMD(CX2341X_ENC_SET_STREAM_TYPE, 1);
+
+ /*
+ * SET_AUDIO_ID (0x89) assigns the *transport stream ID* of the
+ * encoded audio stream (cx2341x-devel: "Assigns the transport stream
+ * ID of the encoded audio stream"). It is NOT an audio input
+ * selector -- the comment here used to claim it selected the audio
+ * input, which is wrong, and no sweep of its value can change the
+ * input. It only matters for transport-stream output; it stays 0
+ * because that is what the reference uses.
+ */
+ para[0] = 0;
+ CMD(CX2341X_ENC_SET_AUDIO_ID, 1);
+
+ /*
+ * CX2341X_ENC_SET_BIT_RATE, per the API documentation:
+ * Param[0] 0=variable bitrate, 1=constant bitrate
+ * Param[1] average bitrate in bits per second
+ * Param[2] peak bitrate in bits per second, DIVIDED BY 400
+ * Param[3] mux bitrate / 400 (0)
+ * Param[4] rate control VBR padding (0)
+ * Param[5] VBV buffer (unused)
+ *
+ * ★ These two fields used to be the wrong way round: the peak was
+ * sent in Param[1] and the average/400 in Param[2], i.e. the encoder
+ * was told "average 6 Mbit/s, peak 4 Mbit/s" -- a peak below the
+ * average, which is contradictory. The rate controller then pinned
+ * the quantiser at its coarsest value (measured: quantiser_scale_code
+ * reaching 31 on I, P and B slices at the stock 4 Mbit/s) and the
+ * picture showed blocking / mosaic. Linux's cx2341x.c sends
+ * [mode, video_bitrate, video_bitrate_peak / 400, 0, 0]; this now
+ * matches that order. Verify with scripts/mpgqual.py.
+ *
+ * The official driver's INF pins Bitrate=4000000, BitratePeak=6000000.
+ */
+ {
+ const char *e;
+ uint32_t br = 4000000, bp = 6000000;
+ uint32_t mux = 0; /* 0 = auto (old behaviour) */
+ if ((e = getenv("BR")) != NULL)
+ br = (uint32_t)strtoul(e, NULL, 0);
+ if ((e = getenv("BRPEAK")) != NULL)
+ bp = (uint32_t)strtoul(e, NULL, 0);
+ /*
+ * ★ MUX=<bits/s> sets Param[3] (mux bitrate / 400).
+ *
+ * MEASURED 2026-10-15: with Param[3]=0 the encoder emits
+ * pack headers whose mux_rate field reads 15.75 Mbit/s
+ * while the stream actually runs ~6.2 Mbit/s. The SCR
+ * clock then advances per-pack as if the data rate were
+ * 15.75 Mbit/s, i.e. SCR runs at ~0.36x wall time while
+ * PTS runs at true 29.97 fps. A player that slaves its
+ * clock to SCR sees its buffer fill ~2.5x faster than
+ * SCR-time and keeps buffering -- that was the growing
+ * multi-second LIVE LAG (and the old "Incorrect SCR
+ * timing in advance" VLC warnings). Setting the mux rate
+ * to the real total (video avg + audio + overhead) makes
+ * SCR track wall time and the live edge stays ~0.3 s.
+ */
+ /*
+ * ★ MUX=<bits/s> sets the program mux rate so the SCR clock
+ * runs at wall time (see the measurement note below).
+ * Units measured on hardware: the pack header's mux_rate
+ * field comes out at param3 * 800 bit/s (asking for
+ * 7,000,000 with /400 gave a 14,000,400 field), so the
+ * divisor here is 800, not 400.
+ */
+ if ((e = getenv("MUX")) != NULL)
+ mux = (uint32_t)strtoul(e, NULL, 0);
+ para[0] = 0; /* variable bitrate */
+ para[1] = br; /* average bitrate, bits/s */
+ para[2] = bp / 400; /* peak bitrate / 400 */
+ para[3] = mux / 800; /* mux rate: param3*800 = field */
+ para[4] = 0; para[5] = 0;
+ }
+ CMD(CX2341X_ENC_SET_BIT_RATE, 6);
+
+ para[0] = 0x0f; para[1] = 0x03;
+ CMD(CX2341X_ENC_SET_GOP_PROPERTIES, 2);
+
+ para[0] = 0x00;
+ CMD(CX2341X_ENC_SET_3_2_PULLDOWN, 1);
+
+ para[0] = 0x00;
+ CMD(CX2341X_ENC_SET_GOP_CLOSURE, 1);
+
+ /* Audio properties. The working reference (pvrusb2_capture.py)
+ * uses the mpegcapt-style value 0x40b8|N. The official driver uses
+ * 0xe9, but on this device 0xe9 alone did not produce audio and the
+ * 0x40b8 form is the known-good one, so use it. */
+ /*
+ * Two forms are in circulation. pvrusb2_capture.py, and so the
+ * mpegcapt lineage this code started from, uses 0x40b8 | N with N
+ * selecting the sample rate. The official I-O DATA Windows driver
+ * uses a plain 0xe9 instead. AUDIOPROP picks between them, because
+ * neither has produced audio here so far and the codec is only just
+ * being initialised - the encoder's idea of what the audio format is
+ * may be the missing piece.
+ */
+ {
+ const char *ap = getenv("AUDIOPROP");
+ /*
+ * The INF's SamplingRate is 2, which selects 44.1 kHz on this
+ * part, and AudioOutputMode/AudioCRC are both 0.
+ */
+ if ((ap = getenv("AUDIOPROP")) != NULL)
+ para[0] = (uint32_t)strtoul(ap, NULL, 0);
+ else switch (sample_rate) {
+ case 32000: para[0] = 0x40b8 | 2; break;
+ case 44100: para[0] = 0x40b8 | 0; break;
+ case 48000:
+ default: para[0] = 0x40b8 | 1; break;
+ }
+ }
+ CMD(CX2341X_ENC_SET_AUDIO_PROP, 1);
+
+ /*
+ * Three commands the Windows driver sends immediately after
+ * SET_AUDIO_PROPERTIES, which are NOT in the cx2341x API list
+ * (they sit between SET_ASPECT_RATIO 0x99 and SET_SPATIAL_FILTER
+ * 0xa1). Captured values:
+ * 0x9b = [2, 0, 0, 0]
+ * 0x9f = [0, 0, 255, 0]
+ * 0x9d = [0, 0, 0, 0]
+ * 0x9f = [0, 0, 255, 0] (repeated)
+ * They arrive right after the audio properties, so they are the
+ * prime suspects for "the encoder needs to be told there is audio".
+ * AUDCMD=1 sends them.
+ */
+ if (getenv("AUDCMD")) {
+ para[0] = 2; para[1] = 0; para[2] = 0; para[3] = 0;
+ CMD(0x9b, 4);
+ para[0] = 0; para[1] = 0; para[2] = 255; para[3] = 0;
+ CMD(0x9f, 4);
+ para[0] = 0; para[1] = 0; para[2] = 0; para[3] = 0;
+ CMD(0x9d, 4);
+ para[0] = 0; para[1] = 0; para[2] = 255; para[3] = 0;
+ CMD(0x9f, 4);
+ }
+
+ para[0] = 1; para[1] = 1;
+ {
+ /* SPATIAL=<a>,<b>: the driver sends 3,1 (capture). */
+ const char *e = getenv("SPATIAL");
+ if (e) {
+ unsigned int a = 1, b = 1;
+ sscanf(e, "%u,%u", &a, &b);
+ para[0] = a; para[1] = b;
+ }
+ }
+ CMD(CX2341X_ENC_SET_SPATIAL_FILTER, 2);
+
+ CMD(CX2341X_ENC_INITIALIZE_INPUT, 0);
+
+ /*
+ * CX2341X_ENC_MISC command 12 = "reset audio interface after channel
+ * change or input switch (has no argument). Needed for the cx2584x,
+ * not needed for the mspx4xx, but it doesn't seem to do any harm
+ * calling it regardless." (cx2341x-devel, CX2341X_ENC_MISC)
+ *
+ * This unit's decoder is a CX25837 -- cx2583x family, the same
+ * serial-audio-interface design the note calls out -- and neither
+ * this tool nor pvrusb2 (whose ENC_MISC list this file mirrors) ever
+ * sends it. It is the only documented encoder-side command that
+ * touches the audio *interface* rather than the audio format, so it
+ * is the first thing to try for "the encoder never sees the ADC".
+ *
+ * AUDIORESET selects the shape:
+ * 0 = do not send it
+ * 1 = MISC(12,0,0,0) (default; MISC is a 4-word command)
+ * 2 = MISC(12) ("has no argument")
+ * 3 = MISC(12,0) (command + value)
+ * Commands 13 (set audio volume delay) and 14 (set audio delay) are
+ * also exposed via AUDIODELAY=<13|14>:<value> for completeness.
+ */
+ {
+ const char *ar = getenv("AUDIORESET");
+ int mode = ar ? atoi(ar) : 1;
+ if (mode == 1) {
+ para[0] = 12; para[1] = 0; para[2] = 0; para[3] = 0;
+ CMD(CX2341X_ENC_MISC, 4);
+ } else if (mode == 2) {
+ para[0] = 12;
+ CMD(CX2341X_ENC_MISC, 1);
+ } else if (mode == 3) {
+ para[0] = 12; para[1] = 0;
+ CMD(CX2341X_ENC_MISC, 2);
+ }
+ }
+ {
+ const char *ad = getenv("AUDIODELAY");
+ if (ad) {
+ int which = atoi(ad);
+ const char *colon = strchr(ad, ':');
+ uint32_t v = colon ? (uint32_t)strtoul(colon + 1, NULL, 0) : 0;
+ if (which == 13 || which == 14) {
+ para[0] = (uint32_t)which; para[1] = v;
+ para[2] = 0; para[3] = 0;
+ CMD(CX2341X_ENC_MISC, 4);
+ }
+ }
+ }
+#undef CMD
+ return errs ? -1 : 0;
+}
+
+int pvr2_encoder_start(pvr2_dev *p)
+{
+ return pvr2_encoder_start_ex(p, 0, 0x13); /* MPEG */
+}
+
+/*
+ * pvr2_encoder_start_ex - start capture with an explicit (type, subtype).
+ * MPEG : type=0, subtype=0x13
+ * raw YUV (HM12): type=1, subtype=0x11 (see cx2341x-uapi docs)
+ */
+int pvr2_encoder_start_ex(pvr2_dev *p, uint32_t captype, uint32_t subtype)
+{
+ uint32_t para[8];
+ int r;
+ int skip_mute = (getenv("NOSTARTMUTE") != NULL);
+
+ /*
+ * ★ The Windows driver sends NEITHER 0xd9 (MUTE_VIDEO) nor 0xda
+ * (MUTE_AUDIO): the pcap's full command census over four start/stop
+ * cycles is 0x81/0x82/0x8f/0x91/0x95/0x97/0x99/0x9b/0x9d/0x9f/0xa1/
+ * 0xb1/0xb7/0xb9/0xbb/0xbd/0xc5/0xc7/0xcd/0xd5/0xd6/0xdc and nothing
+ * else -- both are absent. This tool has always sent them just before
+ * START_CAPTURE, so NOSTARTMUTE=1 skips the pair to match.
+ */
+ if (!skip_mute) {
+ para[0] = 0;
+ r = pvr2_enc_cmd(p, CX2341X_ENC_MUTE_VIDEO, para, 1);
+ if (r < 0)
+ fprintf(stderr, "mute video failed\n");
+ }
+
+ /*
+ * Audio mute. MUTE_AUDIO=1 asks the encoder to produce a *silent*
+ * mpeg audio stream (cx2341x-devel: "1=audio muted (produces silent
+ * mpeg audio stream)"). That is a control measurement, not a
+ * feature: if audio PES start appearing with mute on and the count
+ * is 0 with mute off, the encoder's audio path works and the problem
+ * is upstream (the ADC / I2S input); if the count is 0 either way,
+ * the encoder is not emitting audio PES at all.
+ */
+ {
+ const char *mu = getenv("MUTEAUDIO");
+ if (!skip_mute) {
+ para[0] = mu ? (uint32_t)strtoul(mu, NULL, 0) : 0;
+ r = pvr2_enc_cmd(p, CX2341X_ENC_MUTE_AUDIO, para, 1);
+ if (r < 0)
+ fprintf(stderr, "unmute audio failed\n");
+ }
+ }
+
+ para[0] = captype; para[1] = subtype;
+ r = pvr2_enc_cmd(p, CX2341X_ENC_START_CAPTURE, para, 2);
+ if (r < 0) {
+ fprintf(stderr, "encoder start failed\n");
+ return -1;
+ }
+ fprintf(stderr, "CX23416 encoder started (captype=%u subtype=0x%x)\n",
+ captype, subtype);
+ return 0;
+}
+
+/*
+ * pvr2_encoder_stop - CX2341X_ENC_STOP_CAPTURE (0x82).
+ *
+ * ★ This call was MISSING entirely (the header defined the command but no
+ * code ever sent it): every run just stopped reading USB and closed, so the
+ * encoder was never told to end the capture. Both references do send it:
+ *
+ * vendor pcap (4 start/stop cycles): 0x81 [0,19,..] ... 0x82 [1,0,19,..]
+ * i.e. when=1 (stop now), type=0 (MPEG), subtype=0x13
+ * yacxm cxm_stop_encoder(): CXM_FW_CMD_END_CAPTURE (0x82) with
+ * parameters[0] = mpeg ? 0 : 1 ("when": 0 = end of GOP, 1 = now),
+ * parameters[1] = type, parameters[2] = subtype -- and then waits up to
+ * 1 s for the EOS interrupt.
+ *
+ * Symptom this fixes: after an MPEG run, switching to raw/YUV left the
+ * encoder holding its previous state/buffer, so the new run appeared to
+ * "stop on the previous buffer". Sending the stop with the SAME
+ * (type, subtype) the capture was started with returns the encoder to idle
+ * before the next mode change.
+ *
+ * when: 0 = stop at end of GOP (MPEG, graceful), 1 = stop immediately.
+ * STOPENV=<0|1> overrides "when" for experiments.
+ */
+int pvr2_encoder_stop(pvr2_dev *p, uint32_t captype, uint32_t subtype,
+ uint32_t when)
+{
+ uint32_t para[3];
+ const char *e = getenv("STOPENV");
+ int r, tries;
+
+ if (e)
+ when = (uint32_t)strtoul(e, NULL, 0);
+ para[0] = when; para[1] = captype; para[2] = subtype;
+ /*
+ * Retry: in raw mode the firmware holds ~1.5 s of HM12 frames, so the
+ * mailbox handshake can time out (pvr2_enc_cmd polls ~100 ms) while
+ * the encoder is busy flushing. A FAILED stop leaves the encoder
+ * running, which is exactly the state that makes the next mode change
+ * come up stuck, so it is worth three tries.
+ */
+ for (r = -1, tries = 0; tries < 3; tries++) {
+ r = pvr2_enc_cmd(p, CX2341X_ENC_STOP_CAPTURE, para, 3);
+ if (r == 0)
+ break;
+ {
+ struct timespec ts = { 0, 200000000L };
+ nanosleep(&ts, NULL);
+ }
+ }
+ fprintf(stderr, "CX23416 encoder stop (0x82) when=%u captype=%u "
+ "subtype=0x%x -> %s\n", when, captype, subtype,
+ r < 0 ? "FAILED" : "ok");
+ return r;
+}
+
+/* ================================================================== */
+/* CX25843 (cx2583x family) decoder initialisation */
+/* ================================================================== */
+
+/* Read-modify-write a single decoder register (and_or helper).
+ * mask/val are taken as unsigned int so that constructs like ~0xc0 are
+ * not truncated to a byte (which would turn ~0xc0 into 0x3f). */
+static int cx2584x_and_or(pvr2_dev *p, uint16_t reg, unsigned int mask,
+ unsigned int val)
+{
+ uint8_t v;
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, reg, &v, 1) < 0)
+ return -1;
+ v = (uint8_t)((v & ~(uint8_t)mask) | ((uint8_t)val & (uint8_t)mask));
+ return pvr2_i2c_write(p, CX2584X_I2C_ADDR, reg, &v, 1);
+}
+
+/*
+ * cx25836_initialize - datasheet startup, page 3-77 of the CX25836/43
+ * datasheet. Ported from the Linux cx25840 driver's cx25836_initialize().
+ *
+ * The cx2583x family does NOT need the microcontroller firmware image
+ * (v4l-cx25840.fw); only the cx25840/41/44/45 do. The cx2583x bring-up
+ * is this short register sequence, which starts the internal DLL used for
+ * the video/audio clock tree.
+ */
+int pvr2_cx2584x_init(pvr2_dev *p)
+{
+ /* 2. reset toggle */
+ if (cx2584x_and_or(p, 0x000, ~0x01, 0x01) < 0) return -1;
+ if (cx2584x_and_or(p, 0x000, ~0x01, 0x00) < 0) return -1;
+ /* 3a. */
+ if (cx2584x_and_or(p, 0x15a, ~0x70, 0x00) < 0) return -1;
+ /* 3b. */
+ if (cx2584x_and_or(p, 0x15b, ~0x1e, 0x06) < 0) return -1;
+ /* 3c. */
+ if (cx2584x_and_or(p, 0x159, ~0x02, 0x02) < 0) return -1;
+ /* 3d. short delay */
+ {
+ struct timespec ts = { 0, 10000000L }; /* 10 ms */
+ nanosleep(&ts, NULL);
+ }
+ /* 3e. */
+ if (cx2584x_and_or(p, 0x159, ~0x02, 0x00) < 0) return -1;
+ /* 3f. */
+ if (cx2584x_and_or(p, 0x159, ~0xc0, 0xc0) < 0) return -1;
+ /* 3g. */
+ if (cx2584x_and_or(p, 0x159, ~0x01, 0x00) < 0) return -1;
+ if (cx2584x_and_or(p, 0x159, ~0x01, 0x01) < 0) return -1;
+ /* 3h. */
+ if (cx2584x_and_or(p, 0x15b, ~0x1e, 0x10) < 0) return -1;
+
+ return 0;
+}
+
+/*
+ * cx2584x_input_change - follow steps 8c/8d of section 3.16 of the
+ * CX25840 datasheet, plus the audio-standard setup.
+ *
+ * Ported from the Linux cx25840 driver's input_change(). For NTSC the
+ * video mode must be set (0x402, 0x49f, 0x401) and the audio carrier
+ * standard chosen. This device is a Japanese model (BTSC vs EIAJ
+ * matters), so 0x808 is programmed with the EIAJ value (0xf7) which is
+ * what the Linux driver uses for V4L2_STD_NTSC_M_JP.
+ */
+int pvr2_cx2584x_input_change(pvr2_dev *p, int japan_audio)
+{
+ uint8_t d;
+
+ /* 8c: video mode */
+ d = 0x04; pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0402, &d, 1);
+ d = 0x14; pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x049f, &d, 1);
+ cx2584x_and_or(p, 0x0401, ~0x60, 0x00);
+ cx2584x_and_or(p, 0x0401, ~0x60, 0x60);
+
+ /*
+ * Audio standard. On the cx2583x family the driver deliberately
+ * does NOT touch 0x810/0x808-style audio DSP registers (it causes
+ * audio drop-out on cx25840/41), but the audio carrier must still be
+ * selected. The decoder mutes audio until 0x810 bit0 is set; for
+ * NTSC the carrier byte goes into 0x808 and the subcarrier into
+ * 0x80b.
+ * 0xf7 = EIAJ (Japan) 0xf6 = BTSC (US)
+ */
+ cx2584x_and_or(p, 0x0810, ~0x01, 0x01);
+ d = japan_audio ? 0xf7 : 0xf6;
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0808, &d, 1);
+ d = 0x00;
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x080b, &d, 1);
+
+ return 0;
+}
+
+/* ================================================================== */
+/* Video decoder (CX25843) input selection + audio PLL */
+/* ================================================================== */
+
+/*
+ * pvr2_video_input - select the video input, matching the Linux cx25840
+ * driver's cx25840_video_input() encoding of register 0x0103 and 0x0401.
+ *
+ * 0x0103 layout (base 0xf0):
+ * bits 0-3: luma input (0..7 -> In1..In8)
+ * bits 4-5: chroma input (from In4..In7 / In7..In8) [S-Video]
+ * bits 6-7: audio input (In4..In8)
+ * Register 0x0401 bits 1-2 select the input MODE: 0=composite, 2=S-Video,
+ * 6=component.
+ *
+ * ★ RZ2 CORRECTION (2026-10-15, measured from the vendor pcap): the yellow
+ * RCA (composite) is NOT on In4. The vendor's capture sequence writes
+ * 0x103 = 0xe1 with 0x401 = 0xf2, i.e. CH1 = In2, CH2 = In6, MODE = Y/C.
+ * The board routes the composite jack to In2 (CH1) + In6 (CH2) and the
+ * decoder runs in Y/C mode. Our old default (0x103 = 0xf3 = CH1 = In4,
+ * CH2 = None, composite mode) put luma on the wrong pin and no chroma at
+ * all, which is exactly "colour missing + crawling dots". The old comment
+ * claiming "0xf3 gives full colour" was wrong (it was verified on a
+ * different symptom, never against the vendor's 0xe1).
+ *
+ * mode 0 = S-Video, index selects the chroma input (0..4 above);
+ * mode 1 = composite, index is In1..In8 (0xf0 + index - 1).
+ */
+/*
+ * ★ Input switching, from the CX25836/7 datasheet (Table 3-13 / 3-14):
+ * 0x401 INPUT_MODE (bits 2:1) = 00 Composite Video/Audio (ADC1=CVBS,
+ * ADC2=Audio) | 01 Y/C, S-Video (ADC1=Luma, ADC2=Chroma) | 11 Y/Pb/Pr.
+ * Writing INPUT_MODE triggers the AFE auto-config (Table 3-14): the
+ * 0x105/0x106 AFE fields (CLAMP_EN_CHx etc.) are then set BY THE CHIP.
+ * The vendor writes 0x105 = 0xdd in every session of the pcap, composite
+ * and Y/C alike -- the Y/C auto-config value -- which is consistent with
+ * the RCA being routed through the NEC pair (uPD64031A ADC+clamp ->
+ * uPD64084GC 3-D Y/C separation) and arriving at the decoder as a Y/C
+ * pair on In2 (luma) / In6 (chroma).
+ *
+ * ★ The vendor's input-switch sequence, measured (pcap, repeated at every
+ * session start):
+ * 0x103 = 0x11 (luma In2) with 0x401 still 0xf0 (composite)
+ * 0x103 = 0xd0 (luma In1, chroma In5) <- intermediate step
+ * 0x401 = 0xf2 (INPUT_MODE = 01, Y/C -> AFE auto-config)
+ * 0x103 = 0xe1 (luma In2, chroma In6) <- final state
+ * 0x103 = 0xe1 (repeated)
+ * INPUTSEQ=0 skips the two intermediate steps (diagnostics / A-B).
+ */
+static void input_switch_seq(pvr2_dev *p)
+{
+ uint8_t v, mode;
+ struct timespec ts = { 0, 20000000L }; /* 20 ms settle */
+
+ fprintf(stderr, "input switch (vendor sequence): 0x103=0x11 (composite) "
+ "-> 0x103=0xd0 -> 0x401=0xf2 (Y/C) -> 0x103=0xe1\n");
+ /* 1. composite mode first (INPUT_MODE = 00) */
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, 0x0401, &mode, 1) == 0) {
+ mode &= (uint8_t)~0x06;
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0401, &mode, 1);
+ }
+ v = 0x11;
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0103, &v, 1);
+ nanosleep(&ts, NULL);
+ /* 2. intermediate luma/chroma step */
+ v = 0xd0;
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0103, &v, 1);
+ nanosleep(&ts, NULL);
+ /* 3. switch to Y/C (INPUT_MODE = 01); the chip auto-configures the
+ * AFE on this write */
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, 0x0401, &mode, 1) == 0) {
+ mode = (uint8_t)((mode & (uint8_t)~0x06) | 0x02);
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0401, &mode, 1);
+ }
+ nanosleep(&ts, NULL);
+ /* 4. final pin pair (the caller re-writes 0x103 with the rest) */
+ v = 0xe1;
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0103, &v, 1);
+ nanosleep(&ts, NULL);
+}
+
+int pvr2_video_input_sel(pvr2_dev *p, int mode, int index)
+{
+ uint8_t val, d, reg103;
+
+ if (mode == 0) { /* S-Video */
+ /*
+ * ★ MEASURED 2026-10-25 with a recorder in the S jack: the S
+ * jack is luma In1 + chroma In5, i.e. 0x103 = 0xd0.
+ *
+ * Evidence, not inference:
+ * - 0x103=0xd0 gives a real picture (a film played on the
+ * recorder); 0xc3, the value this table used to send,
+ * gives a dead-flat black frame.
+ * - General Status 2 (0x040e) reads 0x7d for luma In1 and
+ * only 0x00-0x09 for In2..In8: 0x7d is VPRES|AGC_LOCK|
+ * CSC_LOCK|VLOCK|HLOCK, so In1 is the only pin carrying a
+ * video signal with sync. A null reading on the others is
+ * "no signal", not "pin absent".
+ * - The chroma plane confirms the C pin: with chroma on In5
+ * the raw U/V planes carry signal (U sd 9.85, |dU| 1.29);
+ * with In6/In7/In8 they are exactly 128.00, sd 0.00 - dead.
+ * - It is also the datasheet's canonical Y1/C1 pair
+ * (CX25836/7 Table 3-5: Y1 -> CH{1}_SRC 000, C1 ->
+ * CH{2}_SRC 01).
+ *
+ * The old table {0xc3,0xd3,0xe3,0x33,0x73} had luma pinned to
+ * In4 and was never measured with anything in the jack; 0xc3
+ * in particular puts CH{2} on the SAME pin as CH{1}
+ * (CH{2}_SRC 00 = CVBS4/Y4), which cannot be an S-Video pair.
+ *
+ * Only chroma In5 is measured; the other three are the
+ * datasheet's remaining C inputs, kept for experiments.
+ */
+ static const uint8_t svid[4] = { 0xd0, 0xe0, 0x30, 0x70 };
+ static const int cpin[4] = { 5, 6, 7, 8 };
+ if (index < 0) index = 0;
+ if (index > 3) index = 3;
+ reg103 = svid[index];
+ fprintf(stderr, "video input: S-Video luma In1 + chroma In%d "
+ "(0x103=0x%02x, Y/C mode)%s\n", cpin[index], reg103,
+ index == 0 ? "" : " - chroma pin not measured");
+ } else { /* composite */
+ /*
+ * ★ RZ2: the composite jack is CH1=In2 + CH2=In6 in Y/C
+ * mode (0x103 = 0xe1, 0x401 bits1-2 = 01). -I still
+ * overrides everything for experiments.
+ */
+ const char *ri = getenv("VIDIN");
+ if (ri) {
+ reg103 = (uint8_t)strtoul(ri, NULL, 0);
+ } else {
+ reg103 = 0xe1;
+ /* reproduce the driver's composite -> Y/C switch
+ * (INPUTSEQ=0 skips it) */
+ if (!getenv("INPUTSEQ"))
+ input_switch_seq(p);
+ }
+ fprintf(stderr, "video input: composite via the NEC pair "
+ "(In2+In6, 0x103=0x%02x, Y/C mode)\n", reg103);
+ }
+ /*
+ * Bits 6-7 of 0x0103 select the audio input (In4..In8). They are
+ * left at whatever the base 0xf0..0xf7 value carries, which is 0 -
+ * and with no audio input selected the ADC never sees a signal, so
+ * no audio PES can appear no matter what the clock registers say.
+ * AIN=<n> overrides it: 0..4 -> In4..In8.
+ */
+ {
+ const char *ain = getenv("AIN");
+ if (ain) {
+ int n = atoi(ain);
+ if (n < 0) n = 0;
+ if (n > 4) n = 4;
+ reg103 = (uint8_t)((reg103 & 0x3f) | (n << 6));
+ fprintf(stderr, "audio input: In%d (0x103 bits6-7 = "
+ "%d, 0x103=0x%02x)\n", 4 + n, n, reg103);
+ }
+ }
+ if (pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0103, &reg103, 1) < 0)
+ return -1;
+
+ /* Video Mode Control 2 (reg 0x0401): bits 1-2 = input mode.
+ * ★ RZ2 composite also runs in Y/C mode (vendor writes 0xf2). */
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, 0x0401, &val, 1) < 0)
+ return -1;
+ d = (val & ~0x06) | 0x02;
+ if (pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0401, &d, 1) < 0)
+ return -1;
+
+ /*
+ * AFE Control 2 (0x0105). ★ The vendor writes 0xdd here in EVERY
+ * session of the pcap -- the composite (RCA) one included -- and 0xdd
+ * is the Y/C auto-config value (bits 3:1 = 110, CLAMP_EN_CH2 set).
+ * That is the AFE setting that matches a signal arriving as Y/C from
+ * the NEC pair, which is what the RCA jack actually is on this board.
+ * The old code cleared bits 3:1 for composite (0xd1), i.e. configured
+ * the AFE for a raw CVBS input that never reaches the decoder.
+ * AFE105=<hex> overrides.
+ */
+ {
+ const char *e = getenv("AFE105");
+ d = e ? (uint8_t)strtoul(e, NULL, 0) : 0xdd;
+ }
+ if (pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0105, &d, 1) < 0)
+ return -1;
+
+ /*
+ * ★ Vertical blanking delay (0x0474) AND the 656 blanking (0x0477),
+ * measured 2026-10-25. These two must move together.
+ *
+ * The top of the captured picture carried the source's VBI waveform:
+ * a fixed row of white dashes (the user's "上によくわからない線"),
+ * with rows 0/1 byte-identical frame to frame, row 2 nearly so and
+ * row 3 carrying the changing data.
+ *
+ * 0x0474 is the delay from vertical reset to the start of active
+ * video, and one count = one output row: 20 -> rows 0-3 are VBI,
+ * 21 -> row 0 blank ... 24 -> all four blanked.
+ *
+ * ★ But raising 0x0474 ALONE makes the top WORSE, not better: the
+ * datasheet (5-77) says V656BLANK_CNT "must = vblank_cnt + 0x04 to
+ * have vblank and v656blank line up", and 0x0477 is what sets the
+ * V-bit the ENCODER reads off the 656 bus. Move only 0x0474 and the
+ * encoder still considers those rows active video, so it keeps
+ * whatever the ADC reports: Y=1 and chroma 141/116, which renders as
+ * the user's "ピンクと緑の線" (Y=1,U=V=141 -> dark magenta;
+ * Y=16,U=V=116 -> green).
+ *
+ * Measured pairs (0x0474, 0x0477), raw y4m, top rows of luma plane:
+ * 20,24 Y 54,54,39,47 chroma neutral <- VBI dashes, old
+ * 24,24 Y 1, 1, 1, 1 sat 254 <- pink/green (broken pair)
+ * 24,26 Y 1, 1,16,16 sat 180 <- half fixed
+ * 24,28 Y 16,16,16,16 sat 4 <- clean, picture in place
+ * 24,30 Y 16,16,16,16 sat 10 <- clean but window slid
+ * So 24/28 it is: the film's letterbox edge moves from row 14 to row 10
+ * only because the window now really starts at NTSC line 21 instead of
+ * line 17, and the source's bottom letterbox becomes visible too.
+ *
+ * Do not use the vendor table's 26: it blanks two rows of real picture,
+ * invisible on a letterboxed film and wrong on a full-frame source.
+ * VBLANK=<n> overrides both (0 = leave the decoder alone, for A/B).
+ */
+ {
+ const char *e = getenv("VBLANK");
+ uint8_t v = e ? (uint8_t)strtoul(e, NULL, 0) : 0x18;
+ if (v) {
+ uint8_t b656 = (uint8_t)(v + 4);
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0474, &v, 1);
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0477, &b656, 1);
+ }
+ }
+ (void)val;
+
+ return 0;
+}
+
+int pvr2_video_input(pvr2_dev *p, int composite)
+{
+ return pvr2_video_input_sel(p, composite ? 1 : 0, composite ? 5 : 0);
+}
+
+int pvr2_audio_init(pvr2_dev *p, int sample_rate)
+{
+ uint8_t buf[8];
+ uint32_t pll_frac;
+ uint8_t pll_int, pll_post;
+ uint8_t pin12;
+
+ fprintf(stderr, "audio sampling rate: %d Hz\n", sample_rate);
+ switch (sample_rate) {
+ case 32000:
+ /*
+ * Two sets of values exist for 32 kHz and they disagree:
+ * pvr2_audio_init post=0x1e frac=0x012a0869
+ * official driver post=0x10 frac=0x01bb39ee
+ * 44.1 and 48 kHz agree between the two, 32 kHz is the odd
+ * one out, which is why 32 kHz is the rate to test against
+ * the driver table. PLLDIV32 selects between them.
+ */
+ if (getenv("PLLDIV32")) {
+ pll_int = 0x06; pll_post = 0x10;
+ pll_frac = 0x01bb39ee;
+ fprintf(stderr, " 32 kHz PLL: using the official "
+ "driver values (post=0x10 frac=0x01bb39ee)\n");
+ } else {
+ pll_int = 0x08; pll_post = 0x1e;
+ pll_frac = 0x012a0869;
+ fprintf(stderr, " 32 kHz PLL: using pvr2_audio_init "
+ "values (post=0x1e frac=0x012a0869)\n");
+ }
+ break;
+ case 44100:
+ pll_int = 0x09; pll_post = 0x18; pll_frac = 0x00ec6bd6;
+ break;
+ case 48000:
+ default:
+ pll_int = 0x0a; pll_post = 0x18; pll_frac = 0x0098d6e5;
+ break;
+ }
+
+ /* Aux PLL (reg 0x0108, 4 bytes) */
+ buf[0] = 0x0f;
+ buf[1] = 0x04;
+ buf[2] = pll_int;
+ buf[3] = pll_post;
+ if (pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0108, buf, 4) < 0)
+ return -1;
+
+ /* Aux PLL fractional (reg 0x0110, 4 bytes) */
+ buf[0] = pll_frac & 0xff;
+ buf[1] = (pll_frac >> 8) & 0xff;
+ buf[2] = (pll_frac >> 16) & 0xff;
+ buf[3] = (pll_frac >> 24) & 0xff;
+ if (pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0110, buf, 4) < 0)
+ return -1;
+
+ /* Pin Configuration 12 (reg 0x0127) */
+ pin12 = (1 << 6) | (uint8_t)(256.0 / 384.0 * pll_post);
+ if (pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0127, &pin12, 1) < 0)
+ return -1;
+
+ /* Pin control: 0x0118 selects the audio serial-output mode. The
+ * 0x0115/0x0116 enable bits are ORed in by the caller after this
+ * function so they are not clobbered here. */
+ {
+ uint8_t d;
+ d = 0x02; pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0118, &d, 1);
+ }
+
+ return 0;
+}
+
+/* ================================================================== */
+/* Streaming */
+/* ================================================================== */
+
+int pvr2_streaming_on(pvr2_dev *p)
+{
+ uint8_t cmd = FX2CMD_STREAMING_ON;
+ return pvr2_simple_cmd(p, cmd, NULL, 0);
+}
+
+int pvr2_streaming_off(pvr2_dev *p)
+{
+ uint8_t cmd = FX2CMD_STREAMING_OFF;
+ return pvr2_simple_cmd(p, cmd, NULL, 0);
+}
diff --git a/src/firmware.c b/src/firmware.c
new file mode 100644
index 0000000..fb7a7cc
--- /dev/null
+++ b/src/firmware.c
@@ -0,0 +1,401 @@
+/*
+ * firmware.c - FX2 and CX23416 firmware download
+ *
+ * Part of mpegcap.
+ *
+ * FX2 firmware uses the EZ-USB standard 0xA0 control transfer (cold state
+ * only). CX23416 firmware is pushed through the FX2 command channel and
+ * then bulk-transferred to EP 0x02, 32-bit word swapped.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#if defined(_WIN32)
+#include <windows.h>
+#endif
+
+#include "pvrusb2.h"
+
+/* ================================================================== */
+/* FX2 firmware (EZ-USB renumeration) */
+/* ================================================================== */
+
+int pvr2_upload_fx2(pvr2_dev *p, const uint8_t *fw, size_t len)
+{
+ size_t off;
+ uint8_t one = 1, zero = 0;
+
+ if (len != 0x2000 && len != 0x4000) {
+ fprintf(stderr, "unexpected FX2 firmware size %zu "
+ "(expected 8192 or 16384)\n", len);
+ return -1;
+ }
+
+ /* CPU reset assert: bRequest 0xA0, wValue 0xE600 (CPUCS), data = 1 */
+ if (libusb_control_transfer(p->dev, 0x40, 0xA0, 0xE600, 0,
+ &one, 1, 1000) < 0) {
+ fprintf(stderr, "FX2 reset assert failed\n");
+ return -1;
+ }
+
+ /* Write firmware in 0x800 byte chunks, wValue = target address */
+ for (off = 0; off < len; off += 0x800) {
+ size_t chunk = (len - off) < 0x800 ? (len - off) : 0x800;
+ if (libusb_control_transfer(p->dev, 0x40, 0xA0, (uint16_t)off, 0,
+ (unsigned char *)(fw + off),
+ (uint16_t)chunk, 1000) < 0) {
+ fprintf(stderr, "FX2 download failed at 0x%zx\n", off);
+ return -1;
+ }
+ }
+
+ /* CPU reset release -> device re-enumerates */
+ if (libusb_control_transfer(p->dev, 0x40, 0xA0, 0xE600, 0,
+ &zero, 1, 1000) < 0) {
+ fprintf(stderr, "FX2 reset release failed\n");
+ return -1;
+ }
+
+ fprintf(stderr, "FX2 firmware %zu bytes downloaded, re-enumerating...\n", len);
+ return 0;
+}
+
+/* ================================================================== */
+/* CX23416 encoder firmware */
+/* ================================================================== */
+
+int pvr2_upload_firmware2(pvr2_dev *p, const uint8_t *fw, size_t len)
+{
+ uint8_t cmd;
+ size_t off;
+ int total = 0;
+ /* Linux pvrusb2 uses 0x2000 byte chunks (FIRMWARE_CHUNK_SIZE);
+ * mpegcapt.c used 0x8000. Both are accepted by the FX2, but the
+ * smaller size matches the mainline driver and is more forgiving
+ * of host scheduling jitter. */
+ const size_t CHUNK = 0x2000;
+ uint8_t *buf;
+ size_t len4;
+
+ if (len % 4) {
+ fprintf(stderr, "CX23416 firmware size must be a multiple of 4\n");
+ return -1;
+ }
+
+ /* 1) Encoder resume / power on */
+ /*
+ * ENCPWRRST=1 - cut power to the encoder first, then resume. This
+ * is the strongest software reset available when a botched register
+ * order has left the CX23416 unable to boot its firmware (a plain
+ * re-run, FX2RESET and even a USB port reset all failed to recover
+ * it on 2026-10-14).
+ */
+ if (getenv("ENCPWRRST")) {
+ struct timespec ts = { 1, 0 };
+
+ fprintf(stderr, "ENCPWRRST: cutting encoder power before resume\n");
+ (void)pvr2_simple_cmd(p, FX2CMD_POWER_OFF, NULL, 0);
+ nanosleep(&ts, NULL);
+ }
+
+ cmd = FX2CMD_POWER_ON; /* 0xde */
+ if (pvr2_simple_cmd(p, cmd, NULL, 0) < 0)
+ fprintf(stderr, "POWER_ON command failed\n");
+
+ /* FX2 keeps an IN report pending after some commands. The reference
+ * sequence (mpegcapt.c) issues GET_USB_SPEED (0x0b) and
+ * GET_EEPROM_ADDR (0xeb) and drains the response on EP 0x81 before
+ * touching the encoder. Skipping this leaves stale data queued on
+ * the control-IN endpoint and the encoder never starts. */
+ {
+ uint8_t tmp[64];
+ cmd = FX2CMD_GET_USB_SPEED; /* 0x0b */
+ pvr2_simple_cmd(p, cmd, NULL, 0);
+ bulk_cmd_in(p, tmp, sizeof(tmp));
+ cmd = FX2CMD_GET_EEPROM_ADDR; /* 0xeb */
+ pvr2_simple_cmd(p, cmd, NULL, 0);
+ bulk_cmd_in(p, tmp, sizeof(tmp));
+ }
+
+ /* The reference sequence probes the video decoder over I2C (device
+ * 0x44 = CX25843) before initialising the encoder registers. These
+ * reads are not cosmetic: the CX23416 I2C master clock has to be
+ * exercised before the encoder PLL/registers come alive. Skipping
+ * them leaves the encoder CPU halted (MBOX "go" word never clears). */
+ {
+ uint8_t idb[4];
+ (void)pvr2_i2c_read(p, CX2584X_I2C_ADDR, 0x0100, idb, 2);
+ (void)pvr2_i2c_read(p, CX2584X_I2C_ADDR, 0x040d, idb, 1);
+ (void)pvr2_i2c_read(p, CX2584X_I2C_ADDR, 0x040e, idb, 1);
+ }
+
+ /*
+ * AUDIOEARLY=1 reproduces the Windows driver's position for the whole
+ * audio/decoder setup: the USB capture shows it happens here, after
+ * the 0x0b/0xde handshake and the I2C probe but BEFORE the CX23416
+ * firmware image is transferred.
+ *
+ * Captured order (docs/xp-init-sequence.txt):
+ * 0x0159=0x23,0x21 0x015d=0x23,0x21 0x015b=0x00,0x10
+ * 0x015f=0x00,0x06 0x0134=0x01 0x0135=0x18 0x0136=0x0a
+ * 0x0137=0x00 0x013c=0x01,0x00
+ * 0x0115=0x8c 0x0116=0x07 0x0118=0x02
+ * -> 0x0c block writes (video, PLL, audio)
+ * -> firmware image
+ *
+ * This tool has always written 0x0115/0x0116 after START_CAPTURE, and
+ * 0x0115=0x8c there wedges the stream to 0 bytes -- which is why the
+ * value was recorded as "poison". Written here it is fine (measured),
+ * so the position, not the value, was the problem.
+ */
+ if (getenv("AUDIOEARLY")) {
+ static const struct { uint16_t r; uint8_t v; } seq[] = {
+ { 0x0159, 0x23 }, { 0x0159, 0x21 },
+ { 0x015d, 0x23 }, { 0x015d, 0x21 },
+ { 0x015b, 0x00 }, { 0x015b, 0x10 },
+ { 0x015f, 0x00 }, { 0x015f, 0x06 },
+ { 0x0134, 0x01 }, { 0x0135, 0x18 }, { 0x0136, 0x0a },
+ { 0x0137, 0x00 },
+ { 0x013c, 0x01 }, { 0x013c, 0x00 },
+ { 0x0115, 0x8c }, { 0x0116, 0x07 }, { 0x0118, 0x02 },
+ };
+ size_t k;
+ int rc;
+ fprintf(stderr, "AUDIOEARLY: decoder/audio setup before the "
+ "firmware image (driver order)\n");
+ for (k = 0; k < sizeof(seq) / sizeof(seq[0]); k++)
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, seq[k].r,
+ &seq[k].v, 1);
+
+ /*
+ * DEV6043=1 - two I2C writes the driver makes right here, after
+ * its 0x0108-0x0113 block and before 0x0808 (capture #47-48):
+ * dev 0x60, reg 0x0650, 3 data bytes ce 01 a0
+ * dev 0x43, reg 0x0016, 2 data bytes 10 44
+ * This tool has never addressed either device. The second one
+ * is interesting: the capture shows its completion status as
+ * **0x07, not 0x08**, i.e. the driver's own write is not
+ * acknowledged -- so whatever 0x43 is, it either is not present
+ * or does not accept that transfer. Replicated literally
+ * (reg 0x0650 with 3 data bytes reproduces the wire bytes
+ * exactly, whatever the device's real register width is).
+ */
+ if (getenv("DEV6043")) {
+ static const uint8_t d60[3] = { 0xce, 0x01, 0xa0 };
+ static const uint8_t d43[2] = { 0x10, 0x44 };
+ int a = pvr2_i2c_write(p, 0x60, 0x0650, d60, 3);
+ int b = pvr2_i2c_write(p, 0x43, 0x0016, d43, 2);
+ fprintf(stderr, "DEV6043: 0x60/0650 -> %s, 0x43/0016 -> %s\n",
+ a < 0 ? "NACK" : "ACK", b < 0 ? "NACK" : "ACK");
+ }
+ /*
+ * D0UPLOAD=1 - the driver sends a 12982-byte image on EP 0x02
+ * *between* 0xd0 and 0xd1. This tool's AUDIOFX2 path sends
+ * those two commands back to back with nothing in between, so
+ * the image has never been uploaded. Captured at
+ * /ROM/rz2-usb.pcap events 298-308 (0xd0, three EP 0x02
+ * transfers of 5120+4096+3766 bytes, 0xd1), saved as
+ * ref/d0_upload_12982.bin.
+ *
+ * The image is 8051 machine code -- it begins `02 2a 77`
+ * (LJMP 2A77h, the classic 8051 reset vector) and contains the
+ * strings "FM signal detected" / "AM signal detected". It is
+ * NOT byte-swapped, unlike the CX23416 image, so it is sent
+ * verbatim.
+ */
+ if (getenv("D0UPLOAD")) {
+ const char *ip = getenv("D0IMG");
+ FILE *fp;
+
+ if (!ip)
+ ip = "ref/d0_upload_12982.bin";
+ fp = fopen(ip, "rb");
+ if (!fp) {
+ fprintf(stderr, "D0UPLOAD: cannot open %s\n", ip);
+ } else {
+ long sz, off2;
+ uint8_t *img;
+ int bad = 0;
+
+ fseek(fp, 0, SEEK_END);
+ sz = ftell(fp);
+ fseek(fp, 0, SEEK_SET);
+ img = malloc((size_t)sz);
+ if (!img || fread(img, 1, (size_t)sz, fp)
+ != (size_t)sz) {
+ fprintf(stderr, "D0UPLOAD: read failed\n");
+ bad = 1;
+ }
+ fclose(fp);
+ if (!bad) {
+ static const uint8_t d0p[5] =
+ { 0x44, 0x02, 0x08, 0x02, 0x00 };
+ uint8_t tmp[64];
+
+ (void)pvr2_simple_cmd(p, 0xd0, d0p, 5);
+ memset(tmp, 0, sizeof(tmp));
+ (void)bulk_cmd_in(p, tmp, sizeof(tmp));
+ for (off2 = 0; off2 < sz; off2 += 4096) {
+ int chunk = (int)((sz - off2) < 4096
+ ? (sz - off2) : 4096);
+ int tr = 0;
+ int r = libusb_bulk_transfer(
+ p->dev, EP_FW_OUT,
+ img + off2, chunk,
+ &tr, 5000);
+ if (r != 0 || tr != chunk) {
+ fprintf(stderr, "D0UPLOAD: "
+ "chunk at %ld failed "
+ "(r=%d tr=%d)\n",
+ off2, r, tr);
+ bad = 1;
+ break;
+ }
+ }
+ memset(tmp, 0, sizeof(tmp));
+ (void)pvr2_simple_cmd(p, 0xd1, NULL, 0);
+ (void)bulk_cmd_in(p, tmp, sizeof(tmp));
+ fprintf(stderr, "D0UPLOAD: 0xd0 -> %ld bytes"
+ " -> 0xd1 %s\n", sz,
+ bad ? "(errors)" : "ok");
+ }
+ free(img);
+ }
+ }
+ rc = pvr2_audio_block_write(p);
+ fprintf(stderr, "AUDIOEARLY: 0x0c blocks %s\n",
+ rc ? "reported errors" : "ok");
+
+ /* The HR1 pair closes here: the driver clears AUTO_INC_DIS
+ * again once the 0xd0/d1 image has been uploaded. */
+ if (getenv("HR1")) {
+ const char *e = getenv("HR1B");
+ uint8_t b = e ? (uint8_t)strtoul(e, NULL, 0) : 0x04;
+
+ pvr2_i2c_write(p, CX2584X_I2C_ADDR, 0x0000, &b, 1);
+ fprintf(stderr, "HR1: 0x0000 = 0x%02x (AUTO_INC_DIS "
+ "cleared after the image)\n", b);
+ }
+
+ /*
+ * The driver also issues two FX2 commands this tool does not
+ * implement at all, right between the 0x0800/0x0801 writes and
+ * the audio block writes:
+ * 0xd0 payload 44 02 08 02 00
+ * 0xd1 no payload
+ * Both are followed by a response read on EP 0x81. Send them
+ * here, padded to 64 bytes exactly as captured, and drain the
+ * response.
+ */
+ if (getenv("AUDIOFX2")) {
+ uint8_t buf[64];
+ uint8_t tmp[64];
+ memset(buf, 0, sizeof(buf));
+ buf[0] = 0xd0;
+ buf[1] = 0x44; buf[2] = 0x02; buf[3] = 0x08;
+ buf[4] = 0x02; buf[5] = 0x00;
+ (void)pvr2_simple_cmd(p, 0xd0, buf + 1, 5);
+ memset(tmp, 0, sizeof(tmp));
+ (void)bulk_cmd_in(p, tmp, sizeof(tmp));
+ memset(buf, 0, sizeof(buf));
+ buf[0] = 0xd1;
+ (void)pvr2_simple_cmd(p, 0xd1, NULL, 0);
+ memset(tmp, 0, sizeof(tmp));
+ (void)bulk_cmd_in(p, tmp, sizeof(tmp));
+ fprintf(stderr, "AUDIOFX2: 0xd0 / 0xd1 sent\n");
+ }
+ }
+
+ /* 2) interrupt mask + GPIO + deep reset + register init */
+ pvr2_write_reg(p, CX_REG_INTR_MASK, 0xffffffff);
+ pvr2_gpio_dir(p, 0xffffffff, 0x00000088);
+ pvr2_gpio_out(p, 0xffffffff, 0x00000008);
+
+ cmd = FX2CMD_DEEP_RESET; /* 0xdd */
+ pvr2_simple_cmd(p, cmd, NULL, 0);
+
+ pvr2_write_reg(p, CX_REG_APU_CMD, 0x00000000);
+ pvr2_gpio_dir(p, 0xffffffff, 0x00000408);
+ pvr2_gpio_out(p, 0xffffffff, 0x00000008);
+ pvr2_write_reg(p, CX_REG_VPU_CTRL, 0xffffffed);
+ pvr2_write_reg(p, CX_REG_VPU_RESET, 0xfffffffd);
+ /*
+ * SDRAM refresh. The official driver writes 0x80000640 here (capture
+ * #92); this tool has always written 0x80000800. SDRAMREF=<hex>
+ * overrides so the driver's value can be tried.
+ */
+ {
+ const char *e = getenv("SDRAMREF");
+ pvr2_write_reg(p, CX_REG_SDRAM_REFRESH,
+ e ? (uint32_t)strtoul(e, NULL, 0) : 0x80000800);
+ }
+ pvr2_write_reg(p, CX_REG_SDRAM_PRECHARGE, 0x0000001a);
+ pvr2_write_reg(p, CX_REG_I2C_CLOCK, 0x00000000);
+ pvr2_write_reg(p, 0xaa00, 0x00000000);
+ pvr2_write_reg(p, 0xaa04, 0x00057810);
+ pvr2_write_reg(p, 0xaa10, 0x00148500);
+ pvr2_write_reg(p, 0xaa18, 0x00840000);
+
+ /* 3) FWPOST1 + MEMSEL */
+ cmd = FX2CMD_FWPOST1; /* 0x52 */
+ pvr2_simple_cmd(p, cmd, NULL, 0);
+
+ /*
+ * ★ Do NOT move the 0x9054/0x9058 writes up here. A 2026-10-14
+ * attempt (env FWORDER, now removed) put them between FWPOST1 and
+ * the firmware image, believing that was the driver's order; it
+ * broke the boot outright ("encoder command 0x80 timed out",
+ * "firmware not running"). The driver's real order, read from the
+ * capture WITH the EP 0x02 transfers included, is:
+ * FWPOST1 -> transfer -> 0x9054=ffffffff -> 0x9058=ffffffe8 -> MEMSEL
+ * which is exactly what step 5 below does. The earlier mis-reading
+ * came from a parser that only tracked EP 0x01, so the firmware
+ * image was invisible and the VPU writes looked like they preceded
+ * it. scripts/xpcap.py now prints the EP 0x02 transfers.
+ */
+
+ {
+ uint8_t arg = 0x00;
+ cmd = FX2CMD_MEMSEL; /* 0x06 */
+ pvr2_simple_cmd(p, cmd, &arg, 1);
+ }
+
+ /* 4) bulk-transfer firmware to EP 0x02, 0x8000 at a time, swab32 */
+ 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 transferred = 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,
+ &transferred, 5000);
+ if (r != 0 || transferred != (int)chunk) {
+ fprintf(stderr, "CX23416 firmware download failed at "
+ "0x%zx (r=%d tr=%d)\n", off, r, transferred);
+ free(buf);
+ return -1;
+ }
+ total += (int)chunk;
+ }
+ free(buf);
+ fprintf(stderr, "CX23416 firmware %d bytes downloaded\n", total);
+
+ /* 5) post-processing */
+ pvr2_write_reg(p, CX_REG_VPU_RESET, 0xffffffff);
+ pvr2_write_reg(p, CX_REG_VPU_CTRL, 0xffffffe8);
+
+ {
+ uint8_t arg = 0x00;
+ pvr2_simple_cmd(p, FX2CMD_MEMSEL, &arg, 1);
+ }
+ return 0;
+}
diff --git a/src/hm12.c b/src/hm12.c
new file mode 100644
index 0000000..0cf6e0c
--- /dev/null
+++ b/src/hm12.c
@@ -0,0 +1,510 @@
+/*
+ * hm12.c - HM12 ("Hauppauge Macroblock") raw YUV 4:2:0 handling
+ *
+ * Part of mpegcap.
+ *
+ * The CX23416 can emit raw YUV in a chip-specific macroblock-tiled
+ * layout called HM12. The authoritative description is the kernel
+ * documentation (userspace-api/media/drivers/cx2341x-uapi.html, section
+ * "The cx2341x driver"):
+ *
+ * Layout (720-wide fixed, height must be a multiple of 32):
+ * - The frame is a Y plane followed by a UV plane.
+ * - Y plane: divided into 16x16 pixel blocks, transmitted left-to-right,
+ * top-to-bottom; each block is sent line by line (16 bytes per line).
+ * - UV plane: divided into 16x8 UV-value blocks; each line is 8 UV pairs
+ * (16 bytes), interleaved as U,V,U,V,...
+ *
+ * This file implements the inverse mapping described by the kernel's
+ * de_macro_y() / de_macro_uv() example, producing planar Y, U and V
+ * planes, and can write a YUV4MPEG2 (.y4m) stream that VLC / ffmpeg play
+ * directly.
+ */
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include "hm12.h"
+
+/* 1 = apply the light spatial filter to the raw planes (see below). */
+int hm12_filter = 0; /* off: the 32-bit word swap fixes the real defect */
+int hm12_hfilter = 0;
+int hm12_interlace = 0; /* 0=Ip 1=It 2=Ib */
+int hm12_vstep = 1; /* 1 = neighbouring lines, 2 = same field */ /* horizontal pass is off: it costs detail, not stripes */
+
+/*
+ * HM12 -> planar YUV420, per the official kernel reference
+ * (Documentation/driver-api/media/drivers/cx2341x-devel.rst, section
+ * "Non-compressed file format", the raw-format C example).
+ *
+ * "The Y plane is divided into blocks of 16x16 pixels from left to
+ * right and from top to bottom. Each block is transmitted in turn,
+ * line-by-line."
+ * "The UV plane is divided into blocks of 16x16 UV values going from
+ * left to right, top to bottom. Each block is transmitted in turn,
+ * line-by-line." (8 interleaved U,V pairs per 16-byte line)
+ *
+ * The frame width is always 720 and the height must be a multiple of 32,
+ * otherwise macroblocks are missing and the picture is unusable.
+ */
+/*
+ * HM12 words arrive byte-reversed within each 32-bit word.
+ *
+ * The encoder hands over each 16-byte macroblock line as four little-endian
+ * 32-bit words, but with the bytes inside each word in the opposite order:
+ * p3 p2 p1 p0 p7 p6 p5 p4 ... Without the swap, every group of four
+ * adjacent samples is mirrored, so smooth horizontal gradients come out as
+ * sawtooths - which reads as the "2-pixel pairing" and the jagged vertical
+ * edges.
+ *
+ * This is a permutation, so nothing is lost: the picture that comes out with
+ * the swap is the correct one. Confirmed visually on real frames - the menu
+ * text ("はじめから / つづきから / コンフィグ") is crisp and the dot/lace
+ * pattern disappears entirely.
+ */
+#define SW32(p, i) ((p)[((i) & ~3) + 3 - ((i) & 3)])
+
+void hm12_de_macro_y(unsigned char *dst, unsigned char *src,
+ int dstride, int w, int h)
+{
+ unsigned int y, x, i, j;
+
+ for (y = 0; y < (unsigned)h; y += 16) {
+ for (x = 0; x < (unsigned)w; x += 16) {
+ for (i = 0; i < 16; i++) {
+ unsigned char *d = dst + x + (y + i) * dstride;
+ for (j = 0; j < 16; j++)
+ d[j] = SW32(src, j);
+ src += 16;
+ }
+ }
+ }
+ {
+ /*
+ * ★ Block line 0 concealment (HM12FIX0, default 1).
+ *
+ * ★ The FIRST line of every 16-line block does not belong to
+ * the picture. Measured on this unit (later line, same HM12
+ * layout): it correlates only 0.49 with the rows above and
+ * below while interior rows measure 0.99, and no
+ * reconstruction recovers it - rolling it one block (16 px)
+ * raises the correlation to 0.53 only, and the block-level
+ * match is 0.15. So the row is genuinely not in the stream
+ * and has to be CONCEALED, and the concealment choice is what
+ * the eye sees:
+ * - averaging the two neighbours leaves a blended,
+ * half-detail row every 16 lines -> reads as thin
+ * horizontal lines on a detailed picture;
+ * - copying one fresh neighbour is invisible (a duplicated
+ * row cannot be told from its neighbour) and costs one
+ * line of vertical detail per 16.
+ * So: copy the row below over the block's first row.
+ *
+ * HM12FIX0=0 turns it off (to see the raw defect).
+ */
+ /*
+ * ★ DEFAULT OFF (2026-10-24) - back to the 10-16 baseline.
+ *
+ * This whole block was added by me today and is the only decode-side
+ * change since the build the user called "very good". It forces
+ * row 0 of every 16-line band to be an exact copy of row 1, while the
+ * source's own 2-row pairing leaves those rows ~3.9 grey levels
+ * apart - so it flattens 30 rows out of 480 and leaves them visibly
+ * different from every other pair. The 10-16 build did not do this.
+ * HM12FIX0=1 re-enables it for experiments.
+ */
+ static int on = -1;
+ if (on < 0) {
+ const char *e = getenv("HM12FIX0");
+ on = (e && *e && strcmp(e, "0") != 0);
+ }
+ if (on) {
+ for (y = 0; y + 1 < (unsigned)h; y += 16)
+ memcpy(dst + (size_t)y * dstride,
+ dst + (size_t)(y + 1) * dstride,
+ (size_t)w);
+ }
+ }
+}
+
+/*
+ * Descramble the U/V plane (official reference implementation).
+ * The values are interleaved in 16-byte lines holding 8 pairs, arranged
+ * as 16x16-value blocks (16 rows of 8 values) scanned left to right, top
+ * to bottom.
+ *
+ * The 32-bit word swap above applies here too, and it also fixes the
+ * apparent U/V order: once each pair is read in the right byte order the
+ * first sample of a pair is U (Cb) and the second is V (Cr). Reading it
+ * the other way round renders skin cyan.
+ */
+void hm12_de_macro_uv(unsigned char *dstu, unsigned char *dstv,
+ unsigned char *src, int dstride, int w, int h)
+{
+ unsigned int y, x, i, k;
+
+ for (y = 0; y < (unsigned)h; y += 16) {
+ for (x = 0; x < (unsigned)w; x += 8) {
+ for (i = 0; i < 16; i++) {
+ int idx = (int)(x + (y + i) * dstride);
+ for (k = 0; k < 8; k++) {
+ dstu[idx + (int)k] = SW32(src, 2 * k);
+ dstv[idx + (int)k] = SW32(src, 2 * k + 1);
+ }
+ src += 16;
+ }
+ }
+ }
+}
+
+/* Size in bytes of one HM12 frame at 720 x h (h must be multiple of 32). */
+size_t hm12_frame_size(int w, int h)
+{
+ (void)w; /* width is always 720 for HM12 */
+ return (size_t)720 * (size_t)h * 3 / 2;
+}
+
+int hm12_write_y4m_header(FILE *f, int w, int h, unsigned int fps_num,
+ unsigned int fps_den)
+{
+ /*
+ * YUV4MPEG2 tag. Measured on real frames the encoder emits
+ * **limited range** chroma: U/V span 16..240 (and Y 16..254), not
+ * 0..255. Declaring C420 (full range) makes the player stretch the
+ * chroma, which turns the colours pink and washes out skin tones.
+ * C420mpeg2 is the limited-range tag.
+ */
+ return fprintf(f, "YUV4MPEG2 W%d H%d F%d:%d %s A1:1 C420mpeg2\n",
+ w, h, fps_num, fps_den,
+ hm12_interlace == 1 ? "It" :
+ hm12_interlace == 2 ? "Ib" : "Ip") < 0 ? -1 : 0;
+}
+
+/*
+ * Chroma layout, MEASURED on this hardware (GV-MVP/RZ2, CX23416 raw).
+ *
+ * The encoder emits chroma as 16-byte groups holding 8 interleaved U,V
+ * pairs, laid out in 8-row bands of 8x8 blocks. The correct handling is:
+ * 1. de-interleave the 8 U,V pairs of each 16-byte group
+ * 2. de-block them into 8x8 tiles
+ * Verified numerically: this gives a U/V correlation of 0.925 and a
+ * row-to-row difference of 2.77, versus 0.277 / 12.21 for treating the
+ * chroma as plain planes - i.e. the latter is noise, not colour.
+ */
+/*
+ * Light spatial filter, applied after the HM12 de-macroblock.
+ *
+ * The raw capture path has no filtering at all, so whatever noise the
+ * source carries (composite video over an RCA cable, the decoder's own
+ * filtering) shows up as per-pixel speckle. The MPEG path hides this with
+ * SET_SPATIAL_FILTER [1,1]. This does the same job on the raw planes so
+ * the picture looks comparable.
+ *
+ * Implemented as two separable 1-D passes (one vertical, one horizontal),
+ * which is O(n) per axis and cheap enough to stay in real time. A 1-2-1
+ * kernel is used: it removes single-pixel speckle without softening edges
+ * as much as a 3-tap box or gaussian would.
+ */
+/*
+ * Spatial filter, applied after the HM12 de-macroblock.
+ *
+ * HORIZONTAL ONLY. There was a vertical 1-2-1 pass here, added to remove
+ * what looked like comb striping. That was a misdiagnosis: the striping
+ * (adjacent-row difference 28.38) came from captures where the encoder had
+ * dropped to half rate and was interleaving two different instants into
+ * one 518400-byte block. Measured on a healthy full-rate capture the same
+ * figure is 3.23, level with the MPEG capture of the same source (3.90) -
+ * i.e. there was no comb to remove. The vertical pass was therefore only
+ * destroying detail: adjacent-pixel correlation 0.938 unfiltered against
+ * 0.991 filtered, and |x - x+1| 13.00 against 5.67.
+ *
+ * What is real is a fixed 2-pixel grouping in the luma. The mean
+ * adjacent-pixel difference either side of an even/odd column boundary
+ * gives a ratio of 0.43, against 0.83 for MPEG: pixels arrive in pairs,
+ * smooth inside a pair and stepped across the boundary, which is what
+ * reads as the lines not being formed. A vertical pass cannot touch it.
+ * Two horizontal passes fix it:
+ *
+ * horizontal only 0.43
+ * + 1 pass 0.69
+ * + 2 passes 0.91
+ * MPEG reference 0.83
+ *
+ * Only luma is filtered. Chroma is signed and the 1-2-1 kernel is not
+ * energy preserving for it, so filtering U and V shrinks them by different
+ * amounts, rotates the hue and turns the picture pink.
+ */
+static inline unsigned char filt3(int a, int b, int c)
+{
+ int v = (a + 2 * b + c + 2) >> 2;
+ if (v < 0) v = 0;
+ if (v > 255) v = 255;
+ return (unsigned char)v;
+}
+
+static void hm12_filter_plane(unsigned char *p, unsigned char *tmp,
+ int w, int h, int stride)
+{
+ int x, y, pass;
+ (void)tmp;
+
+ /* Two horizontal passes, in place with a rolling window: when p[x] is
+ * written the neighbour on the right is still untouched, and the
+ * original p[x-1] is carried in a variable.
+ *
+ * No copy from tmp: there is no vertical pass left to fill it, and
+ * copying it in would drag in whatever was there before.
+ *
+ * One pass, not two. Measured on the same frame:
+ * 0 passes lag1 11.24 2px ratio 0.428
+ * 1 pass lag1 6.37 2px ratio 0.715
+ * 2 passes lag1 4.72 2px ratio 0.920
+ * 3 passes lag1 3.80 2px ratio 0.997
+ * (lag1 = mean |x - x+1|, so higher means more fine detail survives.)
+ * A single pass already lands the ratio near the MPEG reference of
+ * 0.83 while keeping roughly twice the detail of the two-pass
+ * version. */
+ for (pass = 0; pass < 1; pass++) {
+ for (y = 0; y < h; y++) {
+ unsigned char *row = p + (size_t)y * stride;
+ int prev = row[0];
+ row[0] = filt3(row[0], row[0],
+ (w > 1) ? row[1] : row[0]);
+ for (x = 1; x < w - 1; x++) {
+ int cur = row[x];
+ row[x] = filt3(prev, cur, row[x + 1]);
+ prev = cur;
+ }
+ if (w > 1)
+ row[w - 1] = filt3(prev, row[w - 1], row[w - 1]);
+ }
+ }
+ (void)hm12_vstep; /* retained for experiments; no vertical pass */
+}
+
+/* Luma-only output (see hm12.h). Greyscale YUV4MPEG2: luma in the Y slot,
+ * both chroma planes held neutral so nothing tints the picture. */
+static FILE *lf_fp;
+static int lf_pending;
+static size_t lf_tail; /* neutral chroma bytes appended per frame */
+static unsigned char *lf_buf;
+
+int hm12_luma_open(const char *path)
+{
+ hm12_luma_close();
+ if (!path || !*path)
+ return -1;
+ lf_fp = fopen(path, "wb");
+ if (!lf_fp) {
+ fprintf(stderr, "cannot open luma output %s\n", path);
+ return -1;
+ }
+ lf_pending = 1; /* the header needs the frame size, known at frame 1 */
+ return 0;
+}
+
+int hm12_luma_write(const unsigned char *y, int w, int h)
+{
+ size_t planey = (size_t)w * h;
+
+ if (!lf_fp)
+ return -1;
+ if (lf_pending) {
+ fprintf(lf_fp,
+ "YUV4MPEG2 W%d H%d F30000:1001 %s A1:1 C420mpeg2\n",
+ w, h,
+ hm12_interlace == 1 ? "It" :
+ hm12_interlace == 2 ? "Ib" : "Ip");
+ lf_tail = (size_t)(w / 2) * (h / 2) * 2;
+ if (!lf_buf) {
+ lf_buf = malloc(planey + lf_tail);
+ if (!lf_buf) {
+ lf_pending = 0;
+ return -1;
+ }
+ }
+ memset(lf_buf + planey, 128, lf_tail);
+ lf_pending = 0;
+ fprintf(stderr, " luma: %dx%d greyscale y4m\n", w, h);
+ }
+ memcpy(lf_buf, y, planey);
+ fprintf(lf_fp, "FRAME\n");
+ fwrite(lf_buf, 1, planey + lf_tail, lf_fp);
+ /* flush every frame: MODE=luma points this at the live file, and a
+ * buffered luma stream would lag the HTTP live edge behind by the
+ * stdio buffer. The cost is one write per frame either way. */
+ fflush(lf_fp);
+ return 0;
+}
+
+void hm12_luma_close(void)
+{
+ if (lf_fp)
+ fclose(lf_fp);
+ lf_fp = NULL;
+ lf_pending = 0;
+ if (lf_buf) {
+ free(lf_buf);
+ lf_buf = NULL;
+ }
+}
+
+static FILE *pf_y, *pf_u, *pf_v, *pf_uv;
+static char pf_prefix[512];
+static int pf_pending; /* prefix stored, files not opened yet */
+static int pf_w, pf_h, pf_cw, pf_ch;
+static unsigned char *pf_buf; /* one frame's worth of plane data */
+
+static FILE *planes_open_one(const char *suffix, int w, int h)
+{
+ char path[640];
+ FILE *f;
+
+ snprintf(path, sizeof path, "%s.%s.y4m", pf_prefix, suffix);
+ f = fopen(path, "wb");
+ if (!f)
+ return NULL;
+ fprintf(f, "YUV4MPEG2 W%d H%d F30000:1001 %s A1:1 C420mpeg2\n",
+ w, h,
+ hm12_interlace == 1 ? "It" :
+ hm12_interlace == 2 ? "Ib" : "Ip");
+ fprintf(stderr, " plane: %s (%dx%d)\n", path, w, h);
+ return f;
+}
+
+int hm12_planes_open(const char *prefix)
+{
+ hm12_planes_close();
+ snprintf(pf_prefix, sizeof pf_prefix, "%s", prefix);
+ pf_pending = 1;
+ return 0;
+}
+
+int hm12_planes_write(const unsigned char *y, const unsigned char *u,
+ const unsigned char *v, int w, int h)
+{
+ size_t nc, i;
+
+ if (!pf_pending && !pf_y)
+ return -1;
+ if (pf_pending) {
+ pf_w = w; pf_h = h; pf_cw = w / 2; pf_ch = h / 2;
+ if (!pf_buf) {
+ pf_buf = malloc((size_t)pf_w * pf_h +
+ (size_t)pf_cw * pf_ch * 2);
+ if (!pf_buf) {
+ fprintf(stderr, "out of memory for plane dump\n");
+ pf_pending = 0;
+ return -1;
+ }
+ }
+ pf_y = planes_open_one("Y", w, h);
+ pf_u = planes_open_one("U", w, h);
+ pf_v = planes_open_one("V", w, h);
+ pf_uv = planes_open_one("uv", w, h);
+ pf_pending = 0;
+ if (!pf_y || !pf_u || !pf_v || !pf_uv || !pf_buf) {
+ fprintf(stderr, "cannot set up plane output under %s\n",
+ pf_prefix);
+ return -1;
+ }
+ }
+ nc = (size_t)pf_cw * pf_ch;
+
+ /* Y plane, neutral chroma -> displays as greyscale detail */
+ memcpy(pf_buf, y, (size_t)pf_w * pf_h);
+ memset(pf_buf + (size_t)pf_w * pf_h, 128, nc * 2);
+ fprintf(pf_y, "FRAME\n");
+ fwrite(pf_buf, 1, (size_t)pf_w * pf_h + nc * 2, pf_y);
+
+ /* Cb alone: mid grey luma, V neutral */
+ memset(pf_buf, 128, (size_t)pf_w * pf_h);
+ memcpy(pf_buf + (size_t)pf_w * pf_h, u, nc);
+ memset(pf_buf + (size_t)pf_w * pf_h + nc, 128, nc);
+ fprintf(pf_u, "FRAME\n");
+ fwrite(pf_buf, 1, (size_t)pf_w * pf_h + nc * 2, pf_u);
+
+ /* Cr alone: mid grey luma, U neutral */
+ memset(pf_buf, 128, (size_t)pf_w * pf_h);
+ memset(pf_buf + (size_t)pf_w * pf_h, 128, nc);
+ memcpy(pf_buf + (size_t)pf_w * pf_h + nc, v, nc);
+ fprintf(pf_v, "FRAME\n");
+ fwrite(pf_buf, 1, (size_t)pf_w * pf_h + nc * 2, pf_v);
+
+ /* chroma difference, gain x4 so a small cast is still visible:
+ * blue tint => U above V, which is what a swapped pair looks like */
+ {
+ unsigned char *p = pf_buf + (size_t)pf_w * pf_h;
+ unsigned char *q = p + nc;
+ for (i = 0; i < nc; i++) {
+ int a = ((int)u[i] - 128) * 4 + 128;
+ int b = ((int)v[i] - 128) * 4 + 128;
+ p[i] = (unsigned char)(a < 0 ? 0 : a > 255 ? 255 : a);
+ q[i] = (unsigned char)(b < 0 ? 0 : b > 255 ? 255 : b);
+ }
+ }
+ fprintf(pf_uv, "FRAME\n");
+ fwrite(pf_buf, 1, (size_t)pf_w * pf_h + nc * 2, pf_uv);
+ return 0;
+}
+
+void hm12_planes_close(void)
+{
+ if (pf_y) fclose(pf_y);
+ if (pf_u) fclose(pf_u);
+ if (pf_v) fclose(pf_v);
+ if (pf_uv) fclose(pf_uv);
+ pf_y = pf_u = pf_v = pf_uv = NULL;
+ pf_pending = 0;
+ if (pf_buf) {
+ free(pf_buf);
+ pf_buf = NULL;
+ }
+}
+
+int hm12_write_frame_y4m(FILE *f, const unsigned char *hm12, int w, int h,
+ unsigned char *scratch)
+{
+ size_t planey = (size_t)w * h;
+ size_t planeuv = planey / 4;
+ unsigned char *y = scratch;
+ unsigned char *u = scratch + planey;
+ unsigned char *v = scratch + planey + planeuv;
+ static unsigned char *ftmp;
+
+ if (fprintf(f, "FRAME\n") < 0)
+ return -1;
+
+ /* Y: macroblock-tiled, needs de-macroblocking. */
+ hm12_de_macro_y(y, (unsigned char *)hm12, w, w, h);
+ /* Chroma: de-interleave the V,U pairs, then de-block. */
+ hm12_de_macro_uv(u, v, (unsigned char *)(hm12 + planey), w / 2,
+ w / 2, h / 2);
+
+ if (hm12_filter) {
+ if (!ftmp) {
+ ftmp = malloc(planey);
+ if (!ftmp)
+ return -1;
+ }
+ /* Luma only. Filtering the chroma planes shifts the hue:
+ * the 1-2-1 kernel is not energy preserving for the
+ * signed chroma values, so U and V shrink differently and the
+ * picture picks up a pink cast. Speckle there is far less
+ * visible than in the luma, so leaving it alone is the better
+ * trade. */
+ hm12_filter_plane(y, ftmp, w, h, w);
+ }
+
+ if (fwrite(y, 1, planey, f) != planey)
+ return -1;
+ if (fwrite(u, 1, planeuv, f) != planeuv)
+ return -1;
+ if (fwrite(v, 1, planeuv, f) != planeuv)
+ return -1;
+ if (lf_fp)
+ hm12_luma_write(y, w, h);
+ if (pf_pending || pf_y)
+ hm12_planes_write(y, u, v, w, h);
+ return 0;
+}
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;
+}
diff --git a/src/spoon.c b/src/spoon.c
new file mode 100644
index 0000000..764d769
--- /dev/null
+++ b/src/spoon.c
@@ -0,0 +1,1969 @@
+/*
+ * spoon — single-binary live viewer for the GV-MVP/RZ2 (kare's sibling).
+ *
+ * The user's ask (2026-10-15):
+ * - NOT a shell+python pipeline: one C program.
+ * - ffplay embedded = libavformat/libavcodec/libswresample +
+ * SDL2 for video+audio out (this host: SDL2 OSS -> /dev/dsp, hw.snd
+ * default_unit 9 = HDMI).
+ * - MODE: mpeg (video+audio) | raw (y4m from kare's HM12 writer).
+ * Audio ON/OFF freely selectable (raw is video-only by chip design).
+ * - Minimal lag: we read the growing live FILE directly (no HTTP, no
+ * sockets), poll at 2 ms, decode the moment a packet exists, and never
+ * buffer ahead. Audio is the master clock (if enabled) so A/V stays
+ * synced while both run as close to the write edge as possible.
+ *
+ * Usage:
+ * spoon [-a] [-m | -r] [-f FILE] [-W] -- by default it LAUNCHES
+ * kare itself (like live-play.sh did) and follows its --live file;
+ * -f follows an existing file only; -a disables audio; -W keeps video
+ * window off (audio-only monitor); -m/-r pick MPEG vs raw(y4m) capture.
+ *
+ * Build (FreeBSD, ffmpeg + SDL2 from ports):
+ * cc -O2 -o spoon spoon.c \
+ * $(pkg-config --cflags --libs libavformat libavcodec \
+ * libswresample libavutil sdl2)
+ */
+
+#include <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <math.h>
+#include <signal.h>
+#include <stdarg.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <poll.h>
+#include <sys/ioctl.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <sys/socket.h>
+
+/*
+ * Windows support (2026-10-16). spoon was POSIX-only: fork/execv to
+ * start kare, pipe(), pread(), kill/waitpid, setenv, usleep. The layer
+ * below keeps the SAME code body with Windows primitives:
+ * pipe() -> _pipe (_O_BINARY)
+ * fork+execv -> _spawnvp(_P_NOWAIT) with the pipe write end dup'ed onto
+ * stdout for the child (the classic _dup2/_spawn/restore)
+ * kill() -> TerminateProcess (last resort; the graceful stop goes
+ * through the control channel's "Q" command)
+ * pread() -> win_pread() (_lseeki64 + _read)
+ * usleep() -> Sleep(), setenv() -> _putenv_s()
+ * NOT compile-verified here: there is no MinGW/MSVC toolchain on this FreeBSD
+ * host, so build this path on Windows (see the spoon note in Makefile.win).
+ */
+#if defined(_WIN32)
+#include <windows.h>
+#include <io.h>
+#include <fcntl.h>
+#include <process.h>
+#define usleep(us) Sleep((DWORD)((us) / 1000))
+static int win_setenv(const char *k, const char *v) { return _putenv_s(k, v); }
+#define setenv win_setenv
+static ssize_t win_pread(int fd, void *buf, size_t n, off_t off)
+{
+ _lseeki64(fd, (long long)off, SEEK_SET);
+ return (ssize_t)_read(fd, buf, (unsigned)n);
+}
+#define pread win_pread
+static int win_pipe(int fds[2]) { return _pipe(fds, 1 << 20, _O_BINARY); }
+#define pipe win_pipe
+static void win_kill(int pid)
+{
+ if (pid > 0)
+ TerminateProcess((HANDLE)(intptr_t)pid, 0);
+}
+#define kill(pid, sig) win_kill(pid)
+/* waitpid(pid, st, WNOHANG) / waitpid(pid, st, 0) -> WaitForSingleObject */
+#ifndef WNOHANG
+#define WNOHANG 1
+#endif
+static int win_waitpid(int pid, int *st, int opt)
+{
+ (void)st;
+ if (pid <= 0)
+ return -1;
+ return WaitForSingleObject((HANDLE)(intptr_t)pid,
+ opt ? 0 : INFINITE) == WAIT_OBJECT_0
+ ? pid : 0;
+}
+#define waitpid win_waitpid
+#endif
+
+#include <SDL.h>
+#ifdef SDL_AUDIO
+#include <SDL_audio.h>
+#endif
+
+#include <libavformat/avformat.h>
+#include <libavcodec/avcodec.h>
+#include <libswresample/swresample.h>
+#include <libavutil/imgutils.h>
+#include <libavutil/opt.h>
+#include <libavutil/time.h>
+
+/* ---------------- tunables ---------------- */
+static int opt_audio = 1; /* -a toggles */
+static int opt_raw = 0; /* -r raw y4m, -m mpeg (default) */
+static int opt_novideo = 0; /* -W */
+static const char *opt_file = NULL; /* -f */
+/* ★ No live file any more (2026-10-16): when spoon launches the capture
+ * it uses a pipe. The old /tmp/spoon-<uid>.bin existed for VLC and was
+ * never truncated, so a raw (15.5 MB/s) session filled the root FS. */
+static const char *kare_path = "./kare";
+static const char *fw_mpeg = "firmware/cx23416/cx_1_raw.bin";
+
+/* live file poll: the whole point is NOT to wait */
+#define POLL_US 2000 /* 2 ms */
+#define PROBE_SIZE (1 << 20)
+
+static float dc_x1 = 0.0f, dc_y1 = 0.0f; /* DC-blocker state */
+static volatile sig_atomic_t g_stop = 0;
+static void on_sig(int s) { (void)s; g_stop = 1; }
+
+/* ---------------- SDL audio out ---------------- */
+static SDL_AudioSpec g_aspec;
+static Uint8 *g_abuf = NULL; /* ring */
+static size_t g_abuf_sz, g_awrite, g_aread;
+/*
+ * ★ A/V latency: the ring used to be allowed to fill to its full 2 s and the
+ * whole capture loop is gated by "ring nearly full", so the PICTURE ran up to
+ * ~2 s ahead of the audio you hear (reported: "MPEG audio lags the picture by
+ * several seconds"). Keep only ~250 ms of unplayed audio queued;
+ * MPEGVIEW_ABUF=<ms> retunes it.
+ */
+static size_t g_abuf_target = 0;
+static SDL_mutex *g_amtx = NULL;
+
+static void audio_cb(void *u, Uint8 *stream, int len)
+{
+ (void)u;
+ size_t avail = (g_awrite >= g_aread) ? g_awrite - g_aread
+ : g_abuf_sz - g_aread + g_awrite;
+ size_t n = (size_t)len < avail ? (size_t)len : avail;
+ size_t first = g_abuf_sz - g_aread;
+ if (first > n) first = n;
+ memcpy(stream, g_abuf + g_aread, first);
+ if (n > first)
+ memcpy(stream + first, g_abuf, n - first);
+ memset(stream + n, 0, (size_t)len - n);
+ g_aread = (g_aread + n) % g_abuf_sz;
+}
+
+/* total buffered bytes pending in the ring */
+static size_t audio_pending(void)
+{
+ size_t a = (g_awrite >= g_aread) ? g_awrite - g_aread
+ : g_abuf_sz - g_aread + g_awrite;
+ return a;
+}
+
+/* ---------------- video out (SDL2 texture) ----------------
+ * Zero-copy note (measured 2026-10-15): this host is Intel IvyBridge HD4000
+ * with i915kms + GLAMOR Textured Video (Xv PutImage only, no VA-API path for
+ * live MPEG-2 here). SDL_UpdateYUVTexture uploads the decoded frame to the
+ * GPU texture once per frame and RenderPresent flips it via DRI3/Present —
+ * that IS the zero-copy display path on this stack: no /tmp file, no extra
+ * userland copy of the pixels (the only copy is the required GPU upload,
+ * which DMA-BUF import would also need for a software-decoded frame).
+ * True DMA-BUF import (drm_prime / VA-API decode-to-surface) only pays off
+ * with hardware decode; our frames come from libavcodec software decode, so
+ * texture upload is already the floor. If a future VA-API path lands, swap
+ * SDL_UpdateYUVTexture for AV_HWFramesContext + SDL texture-from-DMA-BUF. */
+static SDL_Window *g_win = NULL;
+static SDL_Renderer *g_ren = NULL;
+static SDL_Texture *g_tex = NULL;
+
+
+/*
+ * ★ A/V sync for the live MPEG view. The audio you hear is inevitably behind
+ * the picture by (SDL ring + the OSS kernel buffer, ~340 ms here and not
+ * tunable because the sysctl is read-only). The picture is decoded and drawn
+ * the moment it arrives, so the ONLY way to line the two up is to hold the
+ * video back by that same amount. Frames are queued with their arrival time
+ * and drawn once they are old enough.
+ * MPEGVIEW_VDELAY=<ms> extra delay (default 340 = the kernel play buffer)
+ * MPEGVIEW_VDELAY=0 disable the whole thing
+ */
+
+/*
+ * ★ Low-frequency noise removal (hum + rumble). Measured on a silent source:
+ * the MPEG audio carries a 60 Hz hum with a strong harmonic series
+ * (120/180/240/300 Hz) plus broadband hiss, so a plain DC blocker is not
+ * enough. Chain: 2nd-order high-pass (kills the 60 Hz fundamental and the
+ * rumble below it) followed by narrow notches at f0..5*f0 (kills the
+ * harmonics). Verified offline on a captured stream: -27.5 dB at 60 Hz,
+ * -21.6..-22.3 dB at the harmonics, and -0.0 dB from 500 Hz up, i.e. the
+ * program band is untouched.
+ * MPEGVIEW_HPF=<Hz> high-pass corner (default 80; 0 = off)
+ * MPEGVIEW_HUM=<f0> mains frequency (default 60; 0 = no notches)
+ * MPEGVIEW_NODC=1 disables the whole chain (as before)
+ */
+struct bq { float b0, b1, b2, a1, a2, x1, x2, y1, y2; };
+
+static void bq_hp(struct bq *q, double fs, double f0, double qq)
+{
+ double w0 = 2.0 * M_PI * f0 / fs, a = sin(w0) / (2.0 * qq),
+ c = cos(w0), a0 = 1.0 + a;
+ memset(q, 0, sizeof(*q));
+ q->b0 = (float)((1.0 + c) / 2.0 / a0);
+ q->b1 = (float)(-(1.0 + c) / a0);
+ q->b2 = (float)((1.0 + c) / 2.0 / a0);
+ q->a1 = (float)(-2.0 * c / a0);
+ q->a2 = (float)((1.0 - a) / a0);
+}
+
+static void bq_notch(struct bq *q, double fs, double f0, double qq)
+{
+ double w0 = 2.0 * M_PI * f0 / fs, a = sin(w0) / (2.0 * qq),
+ c = cos(w0), a0 = 1.0 + a;
+ memset(q, 0, sizeof(*q));
+ q->b0 = (float)(1.0 / a0);
+ q->b1 = (float)(-2.0 * c / a0);
+ q->b2 = (float)(1.0 / a0);
+ q->a1 = (float)(-2.0 * c / a0);
+ q->a2 = (float)((1.0 - a) / a0);
+}
+
+static inline float bq_run(struct bq *q, float x)
+{
+ float y = q->b0 * x + q->b1 * q->x1 + q->b2 * q->x2 -
+ q->a1 * q->y1 - q->a2 * q->y2;
+ q->x2 = q->x1; q->x1 = x;
+ q->y2 = q->y1; q->y1 = y;
+ return y;
+}
+
+#define NHUM 5
+static struct bq g_hpf;
+static int g_hpf_on;
+static struct bq g_hum[NHUM];
+static int g_nhum;
+
+static void audio_filters_init(double fs)
+{
+ const char *e;
+ double f0;
+ if (getenv("MPEGVIEW_NODC"))
+ return;
+ e = getenv("MPEGVIEW_HPF");
+ f0 = e ? atof(e) : 80.0;
+ if (f0 > 0.0 && f0 < fs / 2.0) {
+ bq_hp(&g_hpf, fs, f0, 0.707);
+ g_hpf_on = 1;
+ }
+ e = getenv("MPEGVIEW_HUM");
+ f0 = e ? atof(e) : 60.0;
+ if (f0 > 0.0) {
+ int k;
+ for (k = 0; k < NHUM; k++) {
+ double h = f0 * (k + 1);
+ if (h < fs / 2.0 - 100.0) {
+ bq_notch(&g_hum[g_nhum], fs, h, 15.0);
+ g_nhum++;
+ }
+ }
+ }
+ fprintf(stderr, "audio filters: high-pass %s, %d hum notches at "
+ "%.0f Hz series\n", g_hpf_on ? "on" : "off", g_nhum, f0);
+}
+
+static void audio_filters_apply(int16_t *p, size_t n)
+{
+ size_t i;
+ int k;
+ if (!g_hpf_on && !g_nhum)
+ return;
+ for (i = 0; i < n; i++) {
+ float x = (float)p[i];
+ for (k = 0; k < g_nhum; k++)
+ x = bq_run(&g_hum[k], x);
+ if (g_hpf_on)
+ x = bq_run(&g_hpf, x);
+ if (x > 32767.0f) x = 32767.0f;
+ if (x < -32768.0f) x = -32768.0f;
+ p[i] = (int16_t)x;
+ }
+}
+
+static void video_show(AVFrame *fr); /* defined below */
+static void ctl_send(const char *fmt, ...); /* defined below */
+static int g_again; /* volume, defined below */
+
+
+#define VDQ_N 48
+static AVFrame *g_vq[VDQ_N];
+static double g_vt[VDQ_N];
+static int g_vq_n;
+
+static double vdq_delay_ms(void)
+{
+ double d;
+ const char *e = getenv("MPEGVIEW_VDELAY");
+ /*
+ * Measured with tools/dsp_lat.c: the kernel hands out 1024-byte blocks
+ * (5.3 ms) and its whole queue is only 8192 B (43 ms), so the device
+ * side is NOT the problem -- the app's own ring is (it used to be
+ * allowed to hold 2 s). Default to a small device allowance.
+ */
+ d = e ? (double)atol(e) : 50.0;
+ if (g_abuf_target) {
+ size_t p = audio_pending();
+ double denom = (double)g_aspec.freq *
+ (double)(g_aspec.channels ? g_aspec.channels : 2) * 2.0;
+ if (denom > 0.0)
+ d += (double)p / denom * 1000.0;
+ }
+ return d < 0.0 ? 0.0 : d;
+}
+
+static void vdq_push(AVFrame *fr)
+{
+ if (g_vq_n >= VDQ_N) {
+ /* keep the queue bounded: drop the oldest */
+ av_frame_unref(g_vq[0]);
+ memmove(g_vq, g_vq + 1, sizeof(g_vq[0]) * (size_t)(g_vq_n - 1));
+ memmove(g_vt, g_vt + 1, sizeof(g_vt[0]) * (size_t)(g_vq_n - 1));
+ g_vq_n--;
+ }
+ g_vq[g_vq_n] = av_frame_alloc();
+ av_frame_ref(g_vq[g_vq_n], fr);
+ g_vt[g_vq_n] = SDL_GetTicks() / 1000.0;
+ g_vq_n++;
+}
+
+static void vdq_flush(void)
+{
+ double now = SDL_GetTicks() / 1000.0;
+ double d = vdq_delay_ms() / 1000.0;
+ while (g_vq_n > 0 && now - g_vt[0] >= d) {
+ video_show(g_vq[0]);
+ av_frame_unref(g_vq[0]);
+ memmove(g_vq, g_vq + 1, sizeof(g_vq[0]) * (size_t)(g_vq_n - 1));
+ memmove(g_vt, g_vt + 1, sizeof(g_vt[0]) * (size_t)(g_vq_n - 1));
+ g_vq_n--;
+ }
+}
+
+/* values the bar cycles (the keys change the same ones) */
+static int g_yc_bypass = 0; /* vendor coring (2/9/3/6) or bypass */
+static int g_gr_mode = 0; /* 0 on, 1 off, 2 through */
+static int g_svideo = 0;
+static int g_lc = 2, g_lg = 9, g_cc = 3, g_cg = 6;
+static int g_ycmode = 0; /* 0 = 3D Y/C, 1 = 2D Y/C + NR */
+static int g_pre = 1; /* 1 = PREGHSTS -2.6us, 0 = -1.0us */
+
+/* ==================================================================
+ * ★ Control bar (2026-10-24)
+ *
+ * A real, clickable strip across the top of the window. Every option that can
+ * change while the capture runs has a chip; clicking a chip cycles its value.
+ * Nothing here restarts the capture:
+ * DEINT / VOL act in this process
+ * LP / NT / PAD / IN / YC / GR / YCM / PRE go to kare over CTLFILE
+ * ARST / WM send the two recovery commands (see the notes)
+ *
+ * The chips are laid out by measuring them, so adding an entry to g_chips is
+ * all it takes to add an option; the bar wraps to as many rows as it needs and
+ * the window grows to match, which is why the height is computed before the
+ * window is created.
+ *
+ * No SDL_ttf on this host, so labels are drawn from a 5x7 bitmap font
+ * generated by tools/gen_font.py.
+ * ================================================================== */
+#define BAR_ROW_H 30
+
+/* generated by tools/gen_font.py - do not edit by hand */
+static const char g_font_chars[] = " %+-./0123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+static const unsigned char g_font[][7] = {
+ { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, /* */
+ { 0x18, 0x19, 0x02, 0x04, 0x08, 0x13, 0x03 }, /* % */
+ { 0x00, 0x04, 0x04, 0x1f, 0x04, 0x04, 0x00 }, /* + */
+ { 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00 }, /* - */
+ { 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x0c }, /* . */
+ { 0x01, 0x01, 0x02, 0x04, 0x08, 0x10, 0x10 }, /* / */
+ { 0x0e, 0x11, 0x13, 0x15, 0x19, 0x11, 0x0e }, /* 0 */
+ { 0x04, 0x0c, 0x04, 0x04, 0x04, 0x04, 0x0e }, /* 1 */
+ { 0x0e, 0x11, 0x01, 0x02, 0x04, 0x08, 0x1f }, /* 2 */
+ { 0x1e, 0x01, 0x01, 0x0e, 0x01, 0x01, 0x1e }, /* 3 */
+ { 0x02, 0x06, 0x0a, 0x12, 0x1f, 0x02, 0x02 }, /* 4 */
+ { 0x1f, 0x10, 0x1e, 0x01, 0x01, 0x11, 0x0e }, /* 5 */
+ { 0x0e, 0x10, 0x10, 0x1e, 0x11, 0x11, 0x0e }, /* 6 */
+ { 0x1f, 0x01, 0x02, 0x04, 0x08, 0x08, 0x08 }, /* 7 */
+ { 0x0e, 0x11, 0x11, 0x0e, 0x11, 0x11, 0x0e }, /* 8 */
+ { 0x0e, 0x11, 0x11, 0x0f, 0x01, 0x01, 0x0e }, /* 9 */
+ { 0x00, 0x0c, 0x0c, 0x00, 0x0c, 0x0c, 0x00 }, /* : */
+ { 0x0e, 0x11, 0x11, 0x1f, 0x11, 0x11, 0x11 }, /* A */
+ { 0x1e, 0x11, 0x11, 0x1e, 0x11, 0x11, 0x1e }, /* B */
+ { 0x0e, 0x11, 0x10, 0x10, 0x10, 0x11, 0x0e }, /* C */
+ { 0x1e, 0x11, 0x11, 0x11, 0x11, 0x11, 0x1e }, /* D */
+ { 0x1f, 0x10, 0x10, 0x1e, 0x10, 0x10, 0x1f }, /* E */
+ { 0x1f, 0x10, 0x10, 0x1e, 0x10, 0x10, 0x10 }, /* F */
+ { 0x0e, 0x11, 0x10, 0x17, 0x11, 0x11, 0x0f }, /* G */
+ { 0x11, 0x11, 0x11, 0x1f, 0x11, 0x11, 0x11 }, /* H */
+ { 0x1f, 0x04, 0x04, 0x04, 0x04, 0x04, 0x1f }, /* I */
+ { 0x07, 0x02, 0x02, 0x02, 0x02, 0x12, 0x0c }, /* J */
+ { 0x11, 0x12, 0x14, 0x18, 0x14, 0x12, 0x11 }, /* K */
+ { 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x1f }, /* L */
+ { 0x11, 0x1b, 0x15, 0x15, 0x11, 0x11, 0x11 }, /* M */
+ { 0x11, 0x19, 0x15, 0x13, 0x11, 0x11, 0x11 }, /* N */
+ { 0x0e, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0e }, /* O */
+ { 0x1e, 0x11, 0x11, 0x1e, 0x10, 0x10, 0x10 }, /* P */
+ { 0x0e, 0x11, 0x11, 0x11, 0x15, 0x12, 0x0d }, /* Q */
+ { 0x1e, 0x11, 0x11, 0x1e, 0x14, 0x12, 0x11 }, /* R */
+ { 0x0f, 0x10, 0x10, 0x0e, 0x01, 0x01, 0x1e }, /* S */
+ { 0x1f, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04 }, /* T */
+ { 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0e }, /* U */
+ { 0x11, 0x11, 0x11, 0x11, 0x11, 0x0a, 0x04 }, /* V */
+ { 0x11, 0x11, 0x11, 0x15, 0x15, 0x1b, 0x11 }, /* W */
+ { 0x11, 0x11, 0x0a, 0x04, 0x0a, 0x11, 0x11 }, /* X */
+ { 0x11, 0x11, 0x0a, 0x04, 0x04, 0x04, 0x04 }, /* Y */
+ { 0x1f, 0x01, 0x02, 0x04, 0x08, 0x10, 0x1f }, /* Z */
+};
+/* 43 glyphs */
+
+
+static void bar_glyph(SDL_Renderer *r, int x, int y, int s, char c)
+{
+ const char *p = strchr(g_font_chars, c);
+ int idx, row, col;
+
+ if (!p)
+ p = strchr(g_font_chars, ' ');
+ if (!p)
+ return;
+ idx = (int)(p - g_font_chars);
+ for (row = 0; row < 7; row++) {
+ unsigned v = g_font[idx][row];
+ for (col = 0; col < 5; col++) {
+ if (v & (1u << (4 - col))) {
+ SDL_Rect rc = { x + col * s, y + row * s, s, s };
+ SDL_RenderFillRect(r, &rc);
+ }
+ }
+ }
+}
+
+static void bar_text(SDL_Renderer *r, int x, int y, int s, const char *txt)
+{
+ int i;
+ for (i = 0; txt[i]; i++)
+ bar_glyph(r, x + i * 6 * s, y, s, txt[i]);
+}
+
+static int bar_text_w(const char *txt, int s)
+{
+ int n = (int)strlen(txt);
+ return n ? (n * 6 - 1) * s : 0;
+}
+
+/* ---- the options ------------------------------------------------- */
+
+struct bar_chip {
+ void (*text)(char *buf, size_t n); /* label + current value */
+ void (*click)(void); /* advance one step */
+ /*
+ * ★ The WIDEST label this chip can ever show.
+ *
+ * The chip is sized from this, not from the current label: measuring the
+ * live label and keeping the width made the text spill out of its box the
+ * moment a longer value was selected ("YCM 3D" -> "YCM 2D+NR",
+ * "LP OFF" -> "LP 15K"), and because the layout was only computed once,
+ * the spilled text could also run into the next chip.
+ */
+ const char *widest;
+};
+
+/* VOL (this process) */
+static const int g_vol_pct[4] = { 100, 75, 50, 25 };
+static int g_vol_i = 0;
+static void chip_vol_text(char *b, size_t n)
+{
+ snprintf(b, n, "VOL %d", g_vol_pct[g_vol_i]);
+}
+static void chip_vol_click(void)
+{
+ g_vol_i = (g_vol_i + 1) % 4;
+ g_again = g_vol_pct[g_vol_i];
+ fprintf(stderr, "bar: volume %d%%\n", g_again);
+}
+
+/* LP low-pass (kare) */
+static const int g_lp_hz[4] = { 0, 15000, 10000, 6000 };
+static const char *g_lp_names[4] = { "OFF", "15K", "10K", "6K" };
+static int g_lp_i;
+static void chip_lp_text(char *b, size_t n)
+{
+ snprintf(b, n, "LP %s", g_lp_names[g_lp_i]);
+}
+static void chip_lp_click(void)
+{
+ g_lp_i = (g_lp_i + 1) % 4;
+ ctl_send("LP %d", g_lp_hz[g_lp_i]);
+ fprintf(stderr, "bar: LP %s\n", g_lp_names[g_lp_i]);
+}
+
+/* NT notch (kare) */
+static const int g_nt_hz[4] = { 0, 15734, 15625, 60 };
+static const char *g_nt_names[4] = { "OFF", "15734", "15625", "HUM" };
+static int g_nt_i;
+static void chip_nt_text(char *b, size_t n)
+{
+ snprintf(b, n, "NT %s", g_nt_names[g_nt_i]);
+}
+static void chip_nt_click(void)
+{
+ g_nt_i = (g_nt_i + 1) % 4;
+ ctl_send("NTCH %d", g_nt_hz[g_nt_i]);
+ fprintf(stderr, "bar: notch %s\n", g_nt_names[g_nt_i]);
+}
+
+/* PAD attenuation (kare) */
+static const int g_pad_db[4] = { 0, -6, -12, -18 };
+static int g_pad_i;
+static void chip_pad_text(char *b, size_t n)
+{
+ snprintf(b, n, "PAD %d", g_pad_db[g_pad_i]);
+}
+static void chip_pad_click(void)
+{
+ g_pad_i = (g_pad_i + 1) % 4;
+ ctl_send("PAD %d", g_pad_db[g_pad_i]);
+ fprintf(stderr, "bar: pad %d dB\n", g_pad_db[g_pad_i]);
+}
+
+/* INPUT: composite vs S-Video. Composite reaches the decoder as Y/C through
+ * the NEC pair (luma In2, chroma In6, 0x103=0xe1). ★ The S jack is
+ * MEASURED (2026-10-25, a recorder plugged in): luma In1 + chroma In5,
+ * 0x103=0xd0 - it shows a real picture, while the old 0xc3 (luma In4) is a
+ * dead flat black frame. */
+static void chip_in_text(char *b, size_t n)
+{
+ snprintf(b, n, "IN %s", g_svideo ? "SVID" : "COMP");
+}
+static void chip_in_click(void)
+{
+ g_svideo = !g_svideo;
+ ctl_send("IN 0x%x", g_svideo ? 0xd0 : 0xe1);
+ ctl_send("MODE 0xf2");
+ fprintf(stderr, "bar: input %s\n", g_svideo ? "svideo" : "composite");
+}
+
+/* YC: the NEC coring/ghost pairs, or bypass */
+static void chip_yc_text(char *b, size_t n)
+{
+ snprintf(b, n, "YC %s", g_yc_bypass ? "BYPASS" : "VENDOR");
+}
+static void chip_yc_click(void)
+{
+ g_yc_bypass = !g_yc_bypass;
+ if (g_yc_bypass)
+ ctl_send("YC0");
+ else
+ ctl_send("YC %d %d %d %d", g_lc, g_lg, g_cc, g_cg);
+ fprintf(stderr, "bar: YC %s\n", g_yc_bypass ? "bypass" : "vendor");
+}
+
+/* GR: ghost reduction mode (0 on, 1 off, 2 through) */
+static const char *g_gr_names[3] = { "ON", "OFF", "THRU" };
+static void chip_gr_text(char *b, size_t n)
+{
+ snprintf(b, n, "GR %s", g_gr_names[g_gr_mode % 3]);
+}
+static void chip_gr_click(void)
+{
+ g_gr_mode = (g_gr_mode + 1) % 3;
+ ctl_send("GR %d", g_gr_mode);
+ fprintf(stderr, "bar: ghost %s\n", g_gr_names[g_gr_mode]);
+}
+
+/* YCM: 3-D Y/C or 2-D + noise reduction (the 3-D filter keeps a frame of
+ * memory, which is what drags colour behind a cut) */
+static void chip_ycm_text(char *b, size_t n)
+{
+ snprintf(b, n, "YCM %s", g_ycmode ? "2D+NR" : "3D");
+}
+static void chip_ycm_click(void)
+{
+ g_ycmode = !g_ycmode;
+ ctl_send("YCMODE %d", g_ycmode);
+ fprintf(stderr, "bar: Y/C mode %s\n", g_ycmode ? "2D+NR" : "3D");
+}
+
+/* PRE: ghost pre-filter position */
+static void chip_pre_text(char *b, size_t n)
+{
+ snprintf(b, n, "PRE %s", g_pre ? "-2.6" : "-1.0");
+}
+static void chip_pre_click(void)
+{
+ g_pre = !g_pre;
+ ctl_send("PRE %d", g_pre);
+ fprintf(stderr, "bar: pre-ghost %s\n", g_pre ? "-2.6us" : "-1.0us");
+}
+
+/* ARST: CX2341X_ENC_MISC 12, the audio-interface reset. Measured to flip a
+ * live capture out of the wrong audio state, so it is worth one click. */
+static void chip_arst_text(char *b, size_t n)
+{
+ snprintf(b, n, "ARESET");
+}
+static void chip_arst_click(void)
+{
+ ctl_send("ARESET");
+ fprintf(stderr, "bar: sent ARESET\n");
+}
+
+/* WM: re-send the WM8739 bring-up (measured NOT to fix the state, kept because
+ * it is the cheap test if a future firmware behaves differently) */
+static void chip_wm_text(char *b, size_t n)
+{
+ snprintf(b, n, "CODEC");
+}
+static void chip_wm_click(void)
+{
+ ctl_send("WM");
+ fprintf(stderr, "bar: re-sent WM8739 bring-up\n");
+}
+
+static const struct bar_chip g_chips[] = {
+ { chip_vol_text, chip_vol_click , "VOL 100" },
+ { chip_lp_text, chip_lp_click , "LP 15K" },
+ { chip_nt_text, chip_nt_click , "NT 15734" },
+ { chip_pad_text, chip_pad_click , "PAD -18" },
+ { chip_in_text, chip_in_click , "IN SVIDEO" },
+ { chip_yc_text, chip_yc_click , "YC VENDOR" },
+ { chip_gr_text, chip_gr_click , "GR THRU" },
+ { chip_ycm_text, chip_ycm_click , "YCM 2D+NR" },
+ { chip_pre_text, chip_pre_click , "PRE -2.6" },
+ { chip_arst_text, chip_arst_click , "ARESET" },
+ { chip_wm_text, chip_wm_click , "CODEC" },
+};
+#define NCHIP ((int)(sizeof(g_chips) / sizeof(g_chips[0])))
+
+#define CHIP_MAX 32
+static int g_chip_x[NCHIP], g_chip_y[NCHIP], g_chip_w[NCHIP];
+static int g_bar_rows = 1, g_bar_h = BAR_ROW_H, g_bar_lay_w;
+
+/*
+ * Lay the chips out for a window of width w: left to right, wrapping when the
+ * next chip would not fit. Called before the window is created (so the window
+ * can be tall enough) and again on resize.
+ */
+static void bar_layout(int w)
+{
+ char buf[CHIP_MAX];
+ int i, x = 6, y = 4, row = 0;
+
+ g_bar_lay_w = w;
+ for (i = 0; i < NCHIP; i++) {
+ int cw;
+ snprintf(buf, sizeof(buf), "%s",
+ g_chips[i].widest ? g_chips[i].widest : "");
+ cw = bar_text_w(buf, 2) + 14; /* 7 px each side */
+ if (x + cw > w - 6 && x > 6) {
+ x = 6;
+ y += BAR_ROW_H - 6;
+ row++;
+ }
+ g_chip_x[i] = x;
+ g_chip_y[i] = y;
+ g_chip_w[i] = cw;
+ x += cw + 4;
+ }
+ g_bar_rows = row + 1;
+ /*
+ * Height = the last chip's bottom edge plus a margin, so there is padding
+ * under the bar instead of the video starting flush against it. (The
+ * first version used a fixed 10 px, which left the second row of chips
+ * with no room at all once there were 12 of them.)
+ */
+ g_bar_h = (g_bar_rows - 1) * (BAR_ROW_H - 6) + 4 +
+ (BAR_ROW_H - 14) + 8;
+}
+
+static void bar_draw(SDL_Renderer *r, int w)
+{
+ SDL_Rect bg = { 0, 0, w, g_bar_h };
+ char buf[CHIP_MAX];
+ int i;
+
+ if (g_bar_lay_w != w)
+ bar_layout(w);
+
+ SDL_SetRenderDrawColor(r, 24, 24, 28, 255);
+ SDL_RenderFillRect(r, &bg);
+
+ for (i = 0; i < NCHIP; i++) {
+ SDL_Rect rc = { g_chip_x[i], g_chip_y[i],
+ g_chip_w[i], BAR_ROW_H - 14 };
+ SDL_SetRenderDrawColor(r, 58, 58, 66, 255);
+ SDL_RenderFillRect(r, &rc);
+ SDL_SetRenderDrawColor(r, 210, 210, 215, 255);
+ g_chips[i].text(buf, sizeof(buf));
+ bar_text(r, g_chip_x[i] + 6, g_chip_y[i] + 2, 2, buf);
+ }
+}
+
+static void bar_click(int x, int y)
+{
+ int i;
+ if (y >= g_bar_h)
+ return;
+ for (i = 0; i < NCHIP; i++) {
+ if (x >= g_chip_x[i] && x < g_chip_x[i] + g_chip_w[i] &&
+ y >= g_chip_y[i] && y < g_chip_y[i] + BAR_ROW_H - 14) {
+ g_chips[i].click();
+ return;
+ }
+ }
+}
+
+static void video_show(AVFrame *fr)
+{
+ if (!g_win) {
+ /*
+ * The bar's height depends on how many chips fit in one row, so it
+ * has to be laid out BEFORE the window exists - otherwise the window
+ * is created one row too short and the bottom of the picture (and the
+ * last row of chips) is cut off. Measured: 12 chips wrapped to two
+ * rows wanted 58 px but the window had been made with 30, and the
+ * bottom-right of the video was missing.
+ */
+ bar_layout(fr->width);
+ /*
+ * Linear filtering on the upscale: at 2x the nearest-neighbour
+ * look is all stair-steps, and the encoder's picture is already
+ * soft. Set before the renderer is created - the hint is read
+ * once, when the texture is made.
+ */
+ SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1");
+ if (SDL_CreateWindowAndRenderer(fr->width, fr->height + g_bar_h,
+ SDL_WINDOW_RESIZABLE, &g_win, &g_ren) < 0) {
+ fprintf(stderr, "SDL video: %s\n", SDL_GetError());
+ opt_novideo = 1;
+ return;
+ }
+ SDL_SetWindowTitle(g_win, "spoon");
+ /*
+ * Below ~400 px wide the chips wrap to so many rows that the
+ * bar alone fills the window (measured: at 240x150 the bar
+ * took all of it and the picture was not drawn at all), so
+ * keep the window from going that small.
+ */
+ SDL_SetWindowMinimumSize(g_win, 400, 300);
+ g_tex = SDL_CreateTexture(g_ren,
+ SDL_PIXELFORMAT_YV12,
+ SDL_TEXTUREACCESS_STREAMING,
+ fr->width, fr->height);
+ if (!g_tex) {
+ fprintf(stderr, "SDL texture: %s\n", SDL_GetError());
+ opt_novideo = 1;
+ return;
+ }
+ }
+ SDL_UpdateYUVTexture(g_tex, NULL,
+ fr->data[0], fr->linesize[0],
+ fr->data[1], fr->linesize[1],
+ fr->data[2], fr->linesize[2]);
+ {
+ /*
+ * ★ The window is resizable, so draw into the CURRENT window
+ * size, not the frame size. The first version used
+ * {0, bar, fr->width, fr->height} no matter what the window
+ * was, so dragging the window bigger only added black - the
+ * picture stayed 720x480 in the corner. Now the picture is
+ * scaled to fit the area below the bar, aspect kept, and
+ * centred (letterbox), so resizing up enlarges it and
+ * resizing down shrinks it instead of cropping.
+ *
+ * The bar itself stays at native pixel size on purpose: the
+ * chips are a fixed-size UI and bar_click() works in window
+ * pixels, so scaling it would need a coordinate transform
+ * for every click.
+ */
+ int ww = 0, wh = 0;
+ double s;
+ SDL_Rect dst;
+
+ SDL_GetRendererOutputSize(g_ren, &ww, &wh);
+ if (ww <= 0 || wh <= 0) {
+ ww = fr->width;
+ wh = fr->height + g_bar_h;
+ }
+ /* the bar may need another row at the new width */
+ if (g_bar_lay_w != ww)
+ bar_layout(ww);
+
+ if (wh - g_bar_h < 1) {
+ /* window squeezed below the bar: draw the bar only */
+ SDL_SetRenderDrawColor(g_ren, 0, 0, 0, 255);
+ SDL_RenderClear(g_ren);
+ bar_draw(g_ren, ww);
+ SDL_RenderPresent(g_ren);
+ return;
+ }
+
+ s = (double)(wh - g_bar_h) / (double)fr->height;
+ if ((double)ww / (double)fr->width < s)
+ s = (double)ww / (double)fr->width;
+ if (s <= 0.0)
+ s = 1.0;
+ dst.w = (int)((double)fr->width * s + 0.5);
+ dst.h = (int)((double)fr->height * s + 0.5);
+ if (dst.w < 1) dst.w = 1;
+ if (dst.h < 1) dst.h = 1;
+ dst.x = (ww - dst.w) / 2;
+ dst.y = g_bar_h + (wh - g_bar_h - dst.h) / 2;
+
+ /* SPOON_SCALEDBG=1: print what the resize maths decided */
+ {
+ const char *dbg = getenv("SPOON_SCALEDBG");
+ static int last_w = -1, last_h = -1;
+ if (dbg && (ww != last_w || wh != last_h)) {
+ last_w = ww;
+ last_h = wh;
+ fprintf(stderr, "scale: window %dx%d bar %d -> "
+ "picture %dx%d at %d,%d (x%.3f)\n",
+ ww, wh, g_bar_h, dst.w, dst.h,
+ dst.x, dst.y, s);
+ }
+ }
+
+ /*
+ * ★ SDL_RenderClear fills with the DRAW colour, not with black
+ * - and the previous frame's bar_draw leaves it at the glyph
+ * grey (210,210,215). Without this line the letterbox around
+ * an enlarged picture came out light grey instead of black
+ * (measured: 66 px strips down both sides at 1440x900).
+ */
+ SDL_SetRenderDrawColor(g_ren, 0, 0, 0, 255);
+ SDL_RenderClear(g_ren);
+ SDL_RenderCopy(g_ren, g_tex, NULL, &dst);
+ bar_draw(g_ren, ww);
+ }
+ SDL_RenderPresent(g_ren);
+}
+
+/* ---------------- growing-file AVIO for libavformat ----------------
+ * libavformat normally wants seekable input; a growing file is fine if we
+ * implement seek only within written data and report HUGE file size so the
+ * MPEG-PS demuxer never pre-scans to the end. */
+/*
+ * MPEGVIEW_AUDIO=1 (raw mode): show the raw YUV picture in SDL *and* play the
+ * encoder PCM at the same time. Reference: ivtv exposes raw YUV on
+ * /dev/video32 and PCM on /dev/video24 from the same subtype-0x03 session --
+ * one stream demultiplexed into two outputs. We do the same: kare takes the
+ * PCM out of the raw stream and hands it over on fd 3 (--pcmfd 3) while the
+ * now-clean video arrives on the y4m pipe.
+ */
+static int g_audio_on = 0;
+/*
+ * ★ MPEGVIEW_AUDIOVOL=<percent> (default 25): the raw PCM comes straight off
+ * the encoder front end at ~-5 dBFS (measured), i.e. about 40 dB hotter than
+ * the MPEG audio path, so it is painfully loud as-is. Scale before queueing.
+ */
+/*
+ * ★ Default 100%, not 25% (2026-10-23).
+ *
+ * 25% is -12 dB applied in software to int16 samples: the top two bits of
+ * every sample are thrown away before the device sees them, and the raw path
+ * then plays 12 dB quieter than the mixer expects. It was introduced when the
+ * raw PCM was believed to be overdriven - but those +-32768 peaks were the
+ * byte-swapped sample halves (fixed in 5efed36), not clipping. Measured with
+ * the swap in place and a real source playing: peak -11 dBFS, rms -27 dBFS,
+ * crest 15 dB, i.e. 11 dB of headroom, so no scaling is needed at all.
+ *
+ * MPEGVIEW_AUDIOVOL=<0..200> still overrides it, and the level meter printed
+ * every second ("audio level: peak ... rms ... crest ...") shows whether a
+ * given source actually needs attenuation.
+ */
+static int g_again = 100;
+static int g_audio_ok = 1; /* SDL audio subsystem came up */
+static int g_pcmin = -1;
+static int g_pfd2[2] = { -1, -1 };
+static SDL_AudioDeviceID g_adev = 0;
+static unsigned char g_pcmbuf[65536];
+
+static int g_fd = -1;
+/* ★ 2026-10-16: when spoon launches kare itself there is NO live
+ * file any more -- kare writes into a pipe (-o -) and we read it. The
+ * growing --live file existed for VLC, which needs a seekable file; spoon
+ * IS the player (SDL), so nothing needs to seek, and a pipe cannot fill the
+ * disk. (The live file took the root FS to ENOSPC on 2026-10-16: 15.5 MB/s
+ * of raw y4m, and neither kare nor spoon ever truncates it.) A pipe
+ * also puts the reader exactly at the live edge. */
+static int g_usepipe = 0;
+static off_t g_maxpos = 0; /* highest byte ever read = live edge */
+static off_t g_pos = 0; /* OUR logical position (what libav thinks).
+ * libav buffers ahead, so the fd position is
+ * NOT the logical position; SEEK_CUR must be
+ * relative to this, not to lseek(SEEK_CUR). */
+
+static int fio_read(void *opaque, uint8_t *buf, int buf_size)
+{
+ (void)opaque;
+ for (;;) {
+ ssize_t n;
+ if (g_usepipe) {
+ /* sequential: a pipe has no offsets, and the reader
+ * is always at the live edge */
+ n = read(g_fd, buf, (size_t)buf_size);
+ if (n > 0) {
+ g_pos += n;
+ g_maxpos = g_pos;
+ return (int)n;
+ }
+ if (n == 0) { /* writer gone */
+ if (g_stop) return AVERROR_EOF;
+ usleep(POLL_US);
+ continue;
+ }
+ if (errno == EINTR) continue;
+ return AVERROR(errno);
+ }
+ n = pread(g_fd, buf, (size_t)buf_size, g_pos);
+ if (n > 0) {
+ g_pos += n;
+ if (g_pos > g_maxpos)
+ g_maxpos = g_pos;
+ return (int)n;
+ }
+ if (n == 0) {
+ /* -f <complete file>: real EOF, report it. Growing
+ * live file: not written yet = the live edge; libav
+ * treats AVERROR(EAGAIN) as "retry". */
+ if (opt_file)
+ return AVERROR_EOF;
+ if (g_stop) return AVERROR_EOF;
+ usleep(POLL_US);
+ continue;
+ }
+ if (errno == EINTR) continue;
+ return AVERROR(errno);
+ }
+}
+static int64_t fio_seek(void *opaque, int64_t offset, int whence)
+{
+ (void)opaque;
+ int64_t pos;
+ /* A pipe cannot seek: say so, and let libavformat run in streaming
+ * mode (it does that for stdin/ffplay too). */
+ if (g_usepipe)
+ return AVERROR(ENOSYS);
+ switch (whence) {
+ case SEEK_CUR: pos = g_pos + offset; break;
+ case SEEK_END:
+ /* -f <complete file>: report the real size (the mpeg demuxer
+ * needs it for duration/stream detection). Growing file:
+ * keep the huge lie so it never pre-scans to "the end". */
+ if (opt_file) {
+ struct stat fst;
+ if (fstat(g_fd, &fst) == 0)
+ return (int64_t)fst.st_size + offset;
+ return AVERROR(EIO);
+ }
+ pos = (1LL << 40) + offset;
+ break;
+ case AVSEEK_SIZE:
+ if (opt_file) {
+ struct stat fst;
+ if (fstat(g_fd, &fst) == 0)
+ return (int64_t)fst.st_size;
+ return AVERROR(EIO);
+ }
+ return 1LL << 40; /* lie: huge */
+ default: pos = offset; break;
+ }
+ if (!opt_file && pos > g_maxpos) return AVERROR(EINVAL); /* beyond edge */
+ g_pos = pos;
+ return pos;
+}
+
+/* ---------------- live parameter control (CTLFILE) ----------------
+ * ★ 2026-10-16: spoon is the keyboard front-end for kare's CTLFILE
+ * command channel, so the NEC/decoder parameters can be changed while the
+ * picture runs -- no recompile, no replug. spoon only appends text
+ * lines; kare owns the device and executes them (and echoes the result
+ * to its own stderr).
+ *
+ * b uPD64084GC coring bypass <-> vendor coring (the "noise reduction")
+ * g uPD64031A ghost reduction: ON -> OFF -> THROUGH
+ * c input mux: composite (NEC pair, In2+In6) <-> S-Video (In4+chroma)
+ * s read back the uPD64031A status register RD00
+ * h/l luma core -/+ H/L luma gain -/+
+ * j/k chroma core -/+ J/K chroma gain -/+
+ * p print what the keys do
+ * Disabled entirely when -f <file> is used (no capture child of ours).
+ */
+static FILE *g_ctl = NULL;
+static char g_ctlpath[96];
+
+static void ctl_send(const char *fmt, ...)
+{
+ char line[128];
+ va_list ap;
+ if (!g_ctl)
+ return;
+ va_start(ap, fmt);
+ vsnprintf(line, sizeof(line), fmt, ap);
+ va_end(ap);
+ fprintf(g_ctl, "%s\n", line);
+ fflush(g_ctl);
+ fprintf(stderr, "spoon: %s\n", line);
+}
+
+static void key_help(void)
+{
+ fprintf(stderr,
+ "keys: b=coring bypass g=GR on/off/through c=input "
+ "s=status o=show all\n"
+ " m=Y/C mode (3D <-> 2D+NR) a=pre-ghost range "
+ "(-1.0 <-> -2.6us)\n"
+ " h/l luma core j/k chroma core Shift+those = gains "
+ "p=help q=quit\n");
+}
+
+static void key_action(SDL_Keycode k, int shift)
+{
+ switch (k) {
+ case SDLK_b:
+ g_yc_bypass = !g_yc_bypass;
+ if (g_yc_bypass)
+ ctl_send("YC0");
+ else
+ ctl_send("YC %d %d %d %d", g_lc, g_lg, g_cc, g_cg);
+ break;
+ case SDLK_g:
+ g_gr_mode = (g_gr_mode + 1) % 3;
+ ctl_send("GR %d", g_gr_mode);
+ break;
+ case SDLK_c:
+ g_svideo = !g_svideo;
+ /* composite reaches the decoder as Y/C via the NEC pair
+ * (luma In2 / chroma In6); the S jack map (In4) is an
+ * unverified assumption - see chip_in_text() */
+ if (g_svideo)
+ ctl_send("IN 0xc3");
+ else
+ ctl_send("IN 0xe1");
+ ctl_send("MODE 0xf2");
+ break;
+ case SDLK_s:
+ ctl_send("R 0x12 0");
+ break;
+ case SDLK_h: if (shift) { if (g_lg > 0) g_lg--; } else if (g_lc > 0) g_lc--; goto yc;
+ case SDLK_l: if (shift) { if (g_lg < 15) g_lg++; } else if (g_lc < 15) g_lc++; goto yc;
+ case SDLK_j: if (shift) { if (g_cg > 0) g_cg--; } else if (g_cc > 0) g_cc--; goto yc;
+ case SDLK_k: if (shift) { if (g_cg < 15) g_cg++; } else if (g_cc < 15) g_cc++; goto yc;
+yc:
+ g_yc_bypass = 0;
+ ctl_send("YC %d %d %d %d", g_lc, g_lg, g_cc, g_cg);
+ break;
+ case SDLK_m:
+ g_ycmode = !g_ycmode;
+ ctl_send("YCMODE %d", g_ycmode);
+ break;
+ case SDLK_a:
+ g_pre = !g_pre;
+ ctl_send("PRE %d", g_pre);
+ break;
+ case SDLK_o:
+ ctl_send("SHOW");
+ break;
+ case SDLK_p:
+ key_help();
+ break;
+ case SDLK_q:
+ case SDLK_ESCAPE:
+ g_stop = 1;
+ break;
+ }
+}
+
+/* ---------------- second input: the split PCM file ----------------
+ * ★ MPEGVIEW_PCM=<path> with -r: kare runs the one-pass split
+ * (SPLITAV=1, subtype 0x03) and writes the y4m video to our pipe plus the
+ * raw PCM to a growing RIFF/WAVE file. We open that file with a second
+ * AVIO (same growing-file policy as the main input) and play its audio, so
+ * the live view has BOTH raw video and raw audio.
+ */
+static int p_fd = -1;
+static off_t p_pos = 0, p_maxpos = 0;
+
+static int pio_read(void *opaque, uint8_t *buf, int buf_size)
+{
+ (void)opaque;
+ for (;;) {
+ ssize_t n = pread(p_fd, buf, (size_t)buf_size, p_pos);
+ if (n > 0) {
+ p_pos += n;
+ if (p_pos > p_maxpos) p_maxpos = p_pos;
+ return (int)n;
+ }
+ if (n == 0) {
+ if (g_stop) return AVERROR_EOF;
+ usleep(POLL_US); /* still being written */
+ continue;
+ }
+ if (errno == EINTR) continue;
+ return AVERROR(errno);
+ }
+}
+static int64_t pio_seek(void *opaque, int64_t offset, int whence)
+{
+ (void)opaque;
+ int64_t pos;
+ switch (whence) {
+ case SEEK_CUR: pos = p_pos + offset; break;
+ case SEEK_END: pos = (1LL << 40) + offset; break;
+ case AVSEEK_SIZE: return 1LL << 40; /* lie: never pre-scan */
+ default: pos = offset; break;
+ }
+ p_pos = pos;
+ return pos;
+}
+
+/* ---------------- main ---------------- */
+int main(int argc, char **argv)
+{
+ int i;
+ for (i = 1; i < argc && argv[i]; i++) {
+ const char *a = argv[i];
+ if (!strcmp(a, "-a")) opt_audio = 0;
+ else if (!strcmp(a, "-r")) opt_raw = 1;
+ else if (!strcmp(a, "-m")) opt_raw = 0;
+ else if (!strcmp(a, "-W")) opt_novideo = 1;
+ else if (!strcmp(a, "-f") && i + 1 < argc) opt_file = argv[++i];
+ else { fprintf(stderr, "usage: spoon [-a] [-m|-r] [-W] [-f FILE]\n run as the desktop user (needs DISPLAY + XAUTHORITY); root use -W or -f\n"); return 1; }
+ }
+
+ /*
+ * ★ Say which build this is (2026-10-24). A running window keeps the
+ * code it was started with, so "the fix changed nothing" has twice been
+ * an old process on this project; the stamp makes that visible instead
+ * of arguable.
+ */
+ fprintf(stderr, "spoon build %s %s\n", __DATE__, __TIME__);
+
+ signal(SIGINT, on_sig);
+ signal(SIGTERM, on_sig);
+ /* A closed pipe (the capture child exiting) must not kill the player
+ * mid-cleanup: EPIPE comes back as a write error instead. */
+ signal(SIGPIPE, SIG_IGN);
+ pid_t cap = -1;
+ const char *live = opt_file ? opt_file : "pipe:";
+ if (!opt_file) {
+ /* If no X display is reachable, fail fast with a clear message
+ * instead of capturing invisibly (root without XAUTHORITY hits
+ * this; run as the desktop user, e.g. beatrice). */
+ if (!opt_novideo && !getenv("DISPLAY")) {
+ fprintf(stderr, "spoon: no DISPLAY; run as the "
+ "desktop user (e.g. beatrice) or with -W "
+ "(audio only)\n");
+ return 1;
+ }
+ /*
+ * ★ No live file: kare writes into a pipe (-o -) and we
+ * read it. execv() directly (not via /bin/sh) so the pid we
+ * kill at the end IS kare -- the old sh -c wrapper left
+ * kare running when only the shell got the SIGTERM.
+ */
+ int pfd[2];
+ if (pipe(pfd) < 0) { perror("pipe"); return 1; }
+ /* live parameter channel: kare opens CTLFILE, we append */
+ snprintf(g_ctlpath, sizeof(g_ctlpath), "/tmp/spoon-%d.ctl",
+ (int)geteuid());
+ unlink(g_ctlpath);
+ {
+ FILE *f = fopen(g_ctlpath, "w");
+ if (f)
+ fclose(f);
+ }
+ setenv("CTLFILE", g_ctlpath, 1);
+ {
+ char *av[32];
+ int n = 0;
+ g_audio_on = getenv("MPEGVIEW_AUDIO") != NULL;
+ av[n++] = (char *)kare_path;
+ if (g_audio_on && opt_raw) {
+ /*
+ * ★ A socketpair, not a pipe (2026-10-23).
+ *
+ * FreeBSD's pipe buffer is fixed at 64 KB
+ * (BIG_PIPE_SIZE) and there is no
+ * F_SETPIPE_SZ, so the audio path only has
+ * 64 KB = 341 ms of slack. The viewer
+ * drains it from the same loop that decodes
+ * video, and one slow frame is enough for
+ * the writer to hit EAGAIN - kare then
+ * DROPS the record (it must not block, that
+ * stalls USB). Measured with a pipe: 563
+ * records in 13.8 s where the rate demands
+ * 575, i.e. 12 gaps of 24 ms - a click
+ * about once a second, while the standalone
+ * --pcm file path loses none.
+ *
+ * SO_SNDBUF/SO_RCVBUF on a unix socket are
+ * tunable, so the same fix costs one call
+ * and gives seconds of slack instead of
+ * 341 ms. MPEGVIEW_PCMBUF sets the size
+ * (bytes, default 1 MB = 5.4 s).
+ */
+ if (socketpair(AF_UNIX, SOCK_STREAM, 0,
+ g_pfd2) == 0) {
+ const char *bs = getenv("MPEGVIEW_PCMBUF");
+ int want = bs && *bs ? atoi(bs) : 1048576;
+ if (want < 65536)
+ want = 65536;
+ setsockopt(g_pfd2[0], SOL_SOCKET,
+ SO_RCVBUF, &want, sizeof(want));
+ setsockopt(g_pfd2[1], SOL_SOCKET,
+ SO_SNDBUF, &want, sizeof(want));
+ {
+ int got = 0;
+ socklen_t gl = sizeof(got);
+ getsockopt(g_pfd2[0], SOL_SOCKET,
+ SO_RCVBUF, &got, &gl);
+ fprintf(stderr, "pcm socket: asked "
+ "%d, got %d bytes "
+ "(%.1f s of audio)\n",
+ want, got,
+ (double)got / 192000.0);
+ }
+ /* argv[0] must stay the program name! */
+ av[n++] = (char *)"--pcmfd";
+ av[n++] = (char *)"3";
+ setenv("SPLITAV", "1", 1);
+ setenv("RAWCAPTYPE", "1", 1);
+ setenv("RAWAUDIO", "0x03", 1);
+ } else {
+ perror("socketpair(pcm)");
+ g_pfd2[0] = -1;
+ }
+ }
+ av[n++] = (char *)"-c"; av[n++] = (char *)fw_mpeg;
+ av[n++] = (char *)"-o"; av[n++] = (char *)"-";
+ /*
+ * ★ INPUT=svideo selects the S jack instead of the RCA.
+ *
+ * ★ MEASURED 2026-10-25 with a recorder in the S
+ * jack: the jack is luma In1 + chroma In5
+ * (0x103=0xd0) and shows a real picture. The RCA
+ * reaches the decoder as Y/C through the NEC pair
+ * (luma In2 / chroma In6, 0x103=0xe1). Both use
+ * 0x401 bits1-2 = 2 (Y/C mode).
+ *
+ * INPUT=svideo -> -S <pin> (default pin 0 = chroma In5)
+ * INPUT=composite -> -C (default)
+ * INPUTPIN=<n> chroma pin for S-Video (0..3 = In5..In8;
+ * only In5 is measured)
+ */
+ {
+ const char *in = getenv("INPUT");
+ const char *pin = getenv("INPUTPIN");
+ if (in && *in && (!strncmp(in, "sv", 2) ||
+ !strcmp(in, "S")))
+ g_svideo = 1; /* so the bar shows the truth */
+ if (in && *in && (!strncmp(in, "sv", 2) ||
+ !strcmp(in, "S"))) {
+ av[n++] = (char *)"-S";
+ av[n++] = (char *)(pin && *pin ? pin : "0");
+ fprintf(stderr, "input: S-Video "
+ "(luma In1, chroma In%s)\n",
+ pin && *pin ? pin : "5");
+ } else {
+ av[n++] = (char *)"-C";
+ }
+ }
+ if (opt_raw) av[n++] = (char *)"-r";
+ /*
+ * MPEGCAP_EXTRA="--pcm /tmp/live.wav ..." - pass extra
+ * flags through to kare (space separated). Used to
+ * combine the one-pass split with the live view:
+ * SPLITAV=1 RAWCAPTYPE=1 RAWAUDIO=0x03 \
+ * MPEGCAP_EXTRA="--pcm /tmp/live.wav" spoon -r
+ * the video arrives here clean (the PCM records are taken
+ * out by the splitter) and the audio grows in the WAV.
+ */
+ {
+ const char *ex = getenv("MPEGCAP_EXTRA");
+ if (ex && *ex && n < 24) {
+ static char extrabuf[512];
+ char *tok;
+ snprintf(extrabuf, sizeof(extrabuf), "%s", ex);
+ for (tok = strtok(extrabuf, " ");
+ tok && n < 24;
+ tok = strtok(NULL, " "))
+ av[n++] = tok;
+ }
+ }
+ av[n] = NULL;
+#if defined(_WIN32)
+ /* no fork(): spawn with our stdout already on the pipe */
+ cap = win_spawn(kare_path, av, pfd[1]);
+ if (cap <= 0) {
+ fprintf(stderr, "cannot start %s\n", kare_path);
+ return 1;
+ }
+#else
+ cap = fork();
+ if (cap == 0) {
+ dup2(pfd[1], 1);
+ close(pfd[0]);
+ close(pfd[1]);
+ if (g_pfd2[0] >= 0) {
+ dup2(g_pfd2[1], 3);
+ close(g_pfd2[0]);
+ close(g_pfd2[1]);
+ }
+ execv(kare_path, av);
+ execvp("kare", av);
+ perror("exec kare");
+ _exit(127);
+ }
+#endif
+ }
+ if (cap < 0) { perror("fork"); return 1; }
+ close(pfd[1]);
+ if (g_pfd2[0] >= 0) {
+ close(g_pfd2[1]);
+ fcntl(g_pfd2[0], F_SETFL,
+ fcntl(g_pfd2[0], F_GETFL) | O_NONBLOCK);
+ g_pcmin = g_pfd2[0];
+ fprintf(stderr, "raw audio: PCM on fd %d\n", g_pcmin);
+ }
+ g_fd = pfd[0];
+ g_usepipe = 1;
+ g_ctl = fopen(g_ctlpath, "a");
+ if (!g_ctl)
+ fprintf(stderr, "live control: cannot open %s\n",
+ g_ctlpath);
+ else
+ fprintf(stderr, "live control: %s (press p for keys)\n",
+ g_ctlpath);
+ fprintf(stderr, "kare -> pipe (no live file)\n");
+ } else {
+ g_fd = open(live, O_RDONLY);
+ if (g_fd < 0) { perror(live); return 1; }
+ }
+
+ /* -f <complete file>: start at byte 0 so stream detection sees the
+ * pack header + sequence header from the beginning. The live-edge
+ * jump below only applies to a growing capture file (the pipe needs
+ * neither: it has no history). */
+ if (opt_file) {
+ struct stat fst;
+ g_pos = 0;
+ /* complete file: the whole thing is readable, so the seek
+ * guard must allow it (it only grows if something appends) */
+ if (fstat(g_fd, &fst) == 0)
+ g_maxpos = fst.st_size;
+ else
+ g_maxpos = 0;
+ } else if (!g_usepipe) {
+
+ /*
+ * ★ Live edge: NEVER start at byte 0 — that replays the whole
+ * history as lag. Jump to the newest decodable point:
+ * MPEG-PS: the last sequence header (00 00 01 b3) preceded by
+ * its pack header, searched backward in the tail.
+ * y4m: the last whole FRAME (header line + W*H*3/2).
+ * This mirrors what kare-live.py does, but in-process.
+ */
+ {
+ off_t end = lseek(g_fd, 0, SEEK_END);
+ /* unsigned char: the MPEG start-code bytes (0xb3/0xba) are >127,
+ * and a signed char comparison against them is always false
+ * (that is why the old live-edge scan could never match). */
+ unsigned char tail[4 << 20];
+ off_t start = end - (off_t)sizeof(tail);
+ if (start < 0) start = 0;
+ ssize_t got = pread(g_fd, tail, (size_t)(end - start), start);
+ if (opt_raw) {
+ /* y4m: locate header line length, then last frame */
+ unsigned char *hl = memmem(tail, (size_t)got, "YUV4MPEG2", 9);
+ if (hl) {
+ unsigned char *nl = memchr(hl, '\n',
+ (size_t)got - (hl - tail));
+ if (nl) {
+ size_t hlen = (size_t)(nl - tail) + 1;
+ int w = 720, h2 = 480;
+ unsigned char *p = hl;
+ while (p < nl) {
+ if (*p == 'W') w = atoi((const char *)p + 1);
+ else if (*p == 'H') h2 = atoi((const char *)p + 1);
+ p = memchr(p, ' ',
+ (size_t)(nl - p));
+ if (!p) break;
+ p++;
+ }
+ size_t fb = 6 +
+ (size_t)w * h2 * 3 / 2;
+ off_t body_end = start + got - (off_t)hlen;
+ off_t k = (body_end) / (off_t)fb;
+ off_t pos = (off_t)hlen + k * (off_t)fb;
+ if (pos > start + got) pos = start;
+ g_pos = pos;
+ if (g_pos > g_maxpos)
+ g_maxpos = g_pos;
+ fprintf(stderr, "y4m edge: frame %lld "
+ "at %lld\n", (long long)k,
+ (long long)pos);
+ }
+ }
+ } else {
+ /* MPEG: last 00 00 01 b3 with a pack header before it */
+ unsigned char *seq = NULL;
+ for (ssize_t i = got - 4; i >= 0; i--) {
+ if (tail[i] == 0 && tail[i+1] == 0 &&
+ tail[i+2] == 1 && tail[i+3] == 0xb3) {
+ seq = tail + i;
+ break;
+ }
+ }
+ if (seq) {
+ /* back up to the preceding pack start */
+ unsigned char *pk = NULL;
+ for (ssize_t j = seq - tail - 1;
+ j >= 3; j--) {
+ if (tail[j] == 0 && tail[j+1] == 0 &&
+ tail[j+2] == 1 && tail[j+3] == 0xba) {
+ pk = tail + j;
+ break;
+ }
+ }
+ off_t pos = start + (pk ? pk - tail
+ : seq - tail);
+ g_pos = pos;
+ if (g_pos > g_maxpos)
+ g_maxpos = g_pos;
+ fprintf(stderr, "mpeg edge: seq at %lld, "
+ "starting %lld\n",
+ (long long)(start + (seq - tail)),
+ (long long)pos);
+ } else {
+ g_pos = 0;
+ g_maxpos = 0;
+ }
+ } /* MPEG else */
+ } /* live-edge block */
+ } /* opt_file else */
+
+ /*
+ * Audio device selection is MANUAL on purpose (2026-10-24).
+ *
+ * An auto-picker was tried and removed: it can only see what
+ * /dev/sndstat claims is playable, not which output the speakers are
+ * actually wired to, so it silently chose the wrong unit. The user
+ * picks: MPEGVIEW_DSP=/dev/dspN.
+ *
+ * One trap is still worth reporting rather than obeying: SDL's OSS
+ * backend treats a NUMERIC AUDIODEV as a card index and then fails
+ * with "dsp: No such audio device", which is what a leftover
+ * `export AUDIODEV=11` looks like. Measured:
+ * AUDIODEV=11 -> SDL_Init(AUDIO) = -1
+ * AUDIODEV=/dev/dsp4 -> 0
+ */
+ {
+ const char *dsp = getenv("MPEGVIEW_DSP");
+ if (dsp && *dsp) {
+ if (isdigit((unsigned char)*dsp)) {
+ char dev[32];
+ snprintf(dev, sizeof(dev), "/dev/dsp%d",
+ atoi(dsp));
+ setenv("AUDIODEV", dev, 1);
+ fprintf(stderr, "audio device: %s (from "
+ "MPEGVIEW_DSP=%s)\n", dev, dsp);
+ } else {
+ setenv("AUDIODEV", dsp, 1);
+ fprintf(stderr, "audio device: %s "
+ "(MPEGVIEW_DSP)\n", dsp);
+ }
+ } else {
+ const char *cur = getenv("AUDIODEV");
+ if (cur && *cur && isdigit((unsigned char)*cur)) {
+ fprintf(stderr, "audio device: AUDIODEV=%s is a "
+ "bare number and SDL cannot open it\n",
+ cur);
+ unsetenv("AUDIODEV");
+ }
+ fprintf(stderr, "audio device: %s\n",
+ getenv("AUDIODEV") ? getenv("AUDIODEV")
+ : "/dev/dsp (= hw.snd.default_unit)");
+ }
+ }
+
+
+ /*
+ * ★ Bring AUDIO and VIDEO up SEPARATELY (2026-10-23).
+ *
+ * SDL_Init(VIDEO|AUDIO) is one transaction: if VIDEO fails, SDL rolls
+ * the whole call back, so AUDIO is left uninitialised and the next
+ * SDL_OpenAudioDevice reports only "Audio subsystem is not
+ * initialized" - with the real reason ("<driver> not available",
+ * "No such file or directory") thrown away. Measured here:
+ * SDL_VIDEODRIVER=doesnotexist -> SDL_Init(VIDEO|AUDIO) = -1,
+ * SDL_WasInit = 0x4000 (EVENTS only, audio gone).
+ *
+ * The two subsystems are independent, so init them independently:
+ * a video problem must not cost the sound, and each failure names
+ * itself.
+ */
+ {
+ if (g_audio_on) {
+ if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) {
+ g_audio_ok = 0;
+ fprintf(stderr, "audio init failed: %s "
+ "(device %s) - no sound this run; "
+ "set MPEGVIEW_DSP=/dev/dsp4\n",
+ SDL_GetError(),
+ getenv("AUDIODEV") ? getenv("AUDIODEV")
+ : "/dev/dsp");
+ } else
+ g_audio_ok = 1;
+ if (g_audio_ok)
+ fprintf(stderr, "audio driver: %s\n",
+ SDL_GetCurrentAudioDriver()
+ ? SDL_GetCurrentAudioDriver() : "?");
+ }
+ if (!opt_novideo) {
+ if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
+ fprintf(stderr, "video init failed: %s\n",
+ SDL_GetError());
+ }
+ if (!g_audio_on && opt_novideo) {
+ /* -W with no audio requested: still need EVENTS */
+ if (SDL_Init(SDL_INIT_EVENTS) < 0)
+ fprintf(stderr, "SDL_Init: %s\n", SDL_GetError());
+ }
+ }
+
+ if (g_audio_on && g_audio_ok) {
+ const char *av_ = getenv("MPEGVIEW_AUDIOVOL");
+ if (av_) {
+ int v = atoi(av_);
+ if (v < 0) v = 0;
+ if (v > 200) v = 200;
+ g_again = v;
+ }
+ SDL_AudioSpec want;
+ memset(&want, 0, sizeof(want));
+ want.freq = 48000;
+ want.format = AUDIO_S16SYS;
+ want.channels = 2;
+ want.samples = 2048;
+ g_adev = SDL_OpenAudioDevice(NULL, 0, &want, NULL, 0);
+ if (!g_adev)
+ fprintf(stderr, "raw audio: SDL_OpenAudioDevice: %s\n",
+ SDL_GetError());
+ else {
+ SDL_PauseAudioDevice(g_adev, 0);
+ fprintf(stderr, "raw audio: 48000 Hz 2 ch via SDL "
+ "(volume %d%%)\n", g_again);
+ }
+ }
+
+ if (g_pcmin >= 0) {
+ /*
+ * The splitter emits the y4m header only once it has seen the
+ * first PCM record (a few tens of ms). ffmpeg's probe would
+ * otherwise look at an empty pipe and report "video=-1", so
+ * wait (without consuming) until the pipe actually has data.
+ */
+ struct pollfd pf;
+ pf.fd = g_fd;
+ pf.events = POLLIN;
+ {
+ /*
+ * The splitter writes the y4m header immediately but the
+ * first 518,400-byte frame only once the first PCM record
+ * arrives (~35 ms). Probing with just those ~50 header
+ * bytes makes ffmpeg report "video=-1" (measured:
+ * readable=50), so wait until real frame data is queued.
+ */
+ int waited = 0;
+ for (;;) {
+ int avail = 0;
+ if (poll(&pf, 1, 1000) > 0)
+ ioctl(g_fd, FIONREAD, &avail);
+ if (avail >= 65536 || waited >= 5000)
+ break;
+ waited += 100;
+ }
+ }
+ }
+
+ unsigned char *aviobuf = av_malloc(PROBE_SIZE);
+ AVIOContext *avio = avio_alloc_context(aviobuf, PROBE_SIZE, 0, NULL,
+ fio_read, NULL, fio_seek);
+ AVFormatContext *fc = avformat_alloc_context();
+ fc->pb = avio;
+
+ avformat_network_init();
+ int rc = avformat_open_input(&fc, live, NULL, NULL);
+ if (rc < 0) {
+ char e[128]; av_strerror(rc, e, sizeof(e));
+ fprintf(stderr, "open_input: %s\n", e);
+ return 1;
+ }
+ /* do NOT let it scan the (huge fake) file */
+ fc->probesize = 4 * 1024 * 1024;
+ fc->max_analyze_duration = 2 * AV_TIME_BASE;
+ if (avformat_find_stream_info(fc, NULL) < 0)
+ fprintf(stderr, "stream_info failed (continuing)\n");
+
+ int vi = -1, ai = -1;
+ for (i = 0; i < (int)fc->nb_streams; i++) {
+ if (vi < 0 && fc->streams[i]->codecpar->codec_type ==
+ AVMEDIA_TYPE_VIDEO) vi = i;
+ if (ai < 0 && fc->streams[i]->codecpar->codec_type ==
+ AVMEDIA_TYPE_AUDIO) ai = i;
+ }
+ if (opt_novideo) vi = -1;
+ if (!opt_audio) ai = -1;
+ fprintf(stderr, "streams: video=%d audio=%d\n", vi, ai);
+
+ AVCodecContext *vc = NULL, *ac = NULL;
+ const AVCodec *vcod = NULL, *acod = NULL;
+ if (vi >= 0) {
+ vcod = avcodec_find_decoder(fc->streams[vi]->codecpar->codec_id);
+ vc = avcodec_alloc_context3(vcod);
+ avcodec_parameters_to_context(vc, fc->streams[vi]->codecpar);
+ avcodec_open2(vc, vcod, NULL);
+ }
+ if (ai >= 0) {
+ acod = avcodec_find_decoder(fc->streams[ai]->codecpar->codec_id);
+ ac = avcodec_alloc_context3(acod);
+ avcodec_parameters_to_context(ac, fc->streams[ai]->codecpar);
+ avcodec_open2(ac, acod, NULL);
+
+ /* audio out: resample to S16 stereo at the stream rate.
+ * ★ The device may NOT grant what we asked (different rate,
+ * channels, or sample format). Feeding our S16 stereo @ stream
+ * rate into a device running anything else = wrong pitch at best,
+ * full-scale noise at worst. So the resampler targets what SDL
+ * actually opened (got), not what we wanted. */
+ SDL_AudioSpec want;
+ memset(&want, 0, sizeof(want));
+ want.freq = ac->sample_rate;
+ want.format = AUDIO_S16SYS;
+ want.channels = ac->ch_layout.nb_channels > 2 ? 2
+ : ac->ch_layout.nb_channels;
+ want.samples = 256; /* ~5 ms */
+ want.callback = audio_cb;
+ SDL_AudioSpec got;
+ if (SDL_OpenAudio(&want, &got) < 0) {
+ fprintf(stderr, "SDL audio: %s (audio off)\n",
+ SDL_GetError());
+ ai = -1;
+ } else if (got.format != AUDIO_S16SYS) {
+ fprintf(stderr, "SDL audio: device gave format 0x%x, "
+ "need S16 (audio off)\n", got.format);
+ SDL_CloseAudio();
+ ai = -1;
+ } else {
+ int out_ch = (got.channels >= 2) ? 2 : 1;
+ g_aspec = got;
+ g_abuf_sz = (size_t)got.freq * (size_t)out_ch * 2 * 2;
+ g_abuf = calloc(1, g_abuf_sz);
+ g_abuf_target = (size_t)got.freq *
+ (size_t)out_ch * 2u / 4u; /* 250 ms */
+ {
+ const char *ab = getenv("MPEGVIEW_ABUF");
+ if (ab) {
+ long ms = atol(ab);
+ if (ms < 20) ms = 20;
+ if (ms > 3000) ms = 3000;
+ g_abuf_target = (size_t)got.freq *
+ (size_t)out_ch * 2u *
+ (size_t)ms / 1000u;
+ }
+ }
+ fprintf(stderr, "audio buffer target: %zu ms "
+ "(ring %zu ms, dev samples %u)\n",
+ g_abuf_target * 1000u /
+ ((size_t)got.freq * (size_t)out_ch * 2u),
+ g_abuf_sz * 1000u /
+ ((size_t)got.freq * (size_t)out_ch * 2u),
+ got.samples);
+ g_amtx = SDL_CreateMutex();
+ SDL_PauseAudio(0);
+ fprintf(stderr, "audio out: %d Hz %d ch (OSS)\n",
+ got.freq, got.channels);
+ audio_filters_init((double)got.freq);
+ /* stash the granted layout for the resampler below */
+ ac->sample_rate = ac->sample_rate; /* unchanged: input side */
+ g_aspec.channels = (Uint8)out_ch;
+ }
+ }
+ struct SwrContext *swr = NULL;
+ static int g_out_ch = 2, g_out_rate = 48000;
+ if (ai >= 0) {
+ AVChannelLayout out_ch =
+ (g_aspec.channels == 1) ? (AVChannelLayout)AV_CHANNEL_LAYOUT_MONO
+ : (AVChannelLayout)AV_CHANNEL_LAYOUT_STEREO;
+ g_out_ch = (g_aspec.channels == 1) ? 1 : 2;
+ g_out_rate = g_aspec.freq;
+ AVChannelLayout in_ch = (ac->ch_layout.nb_channels == 1)
+ ? (AVChannelLayout)AV_CHANNEL_LAYOUT_MONO
+ : (AVChannelLayout)AV_CHANNEL_LAYOUT_STEREO;
+ swr_alloc_set_opts2(&swr,
+ &out_ch, AV_SAMPLE_FMT_S16, g_out_rate,
+ &in_ch, ac->sample_fmt, ac->sample_rate,
+ 0, NULL);
+ swr_init(swr);
+ }
+
+ AVPacket *pkt = av_packet_alloc();
+ AVFrame *fr = av_frame_alloc();
+ int64_t a_pts0 = AV_NOPTS_VALUE, v_pts0 = AV_NOPTS_VALUE;
+ int64_t last_vpts = AV_NOPTS_VALUE;
+
+ while (!g_stop) {
+ /* raw PCM from kare (fd 3) -> SDL queue, in parallel with the
+ * video below (ivtv's two-device split) */
+ if (g_pcmin >= 0) {
+ for (;;) {
+ ssize_t r = read(g_pcmin, g_pcmbuf,
+ sizeof(g_pcmbuf));
+ if (r > 0) {
+ /*
+ * ★ Level meter (2026-10-23). "The sound
+ * has no range" has two completely different
+ * causes and only a meter separates them:
+ * - the raw PCM already sits at 0 dBFS
+ * (analogue input too hot -> the whole
+ * programme is compressed against the
+ * rail, and no digital gain helps), or
+ * - the level is fine and the volume
+ * scaling is eating the resolution
+ * (MPEGVIEW_AUDIOVOL=25 is -12 dB in
+ * software on int16 = two bits gone).
+ * Printed every ~2 s, measured BEFORE the
+ * scaling, so it describes the stream.
+ */
+ {
+ static unsigned long nacc;
+ static unsigned long bytes_acc;
+ static double peak, sq;
+ int16_t *m = (int16_t *)g_pcmbuf;
+ size_t k, ns = (size_t)r / 2;
+ for (k = 0; k < ns; k++) {
+ double v = m[k] < 0 ?
+ -(double)m[k] : (double)m[k];
+ if (v > peak) peak = v;
+ sq += v * v;
+ }
+ nacc += ns;
+ bytes_acc += (unsigned long)r;
+ /* 48 kHz stereo s16: one second */
+ if (nacc >= 96000) {
+ double rms = sqrt(sq / nacc);
+ /*
+ * kB/s is the tell for DROPPED
+ * records: the capture writes
+ * 48 kHz x 2 ch x 2 B = 187.5
+ * KiB/s, and kare drops a
+ * record rather than block when
+ * the pipe is full. A dip here
+ * is an audible click/gap.
+ */
+ fprintf(stderr, "audio level: "
+ "peak %.1f dBFS rms %.1f "
+ "dBFS crest %.1f dB "
+ "%.1f kB/s (gain %d%%)\n",
+ 20 * log10((peak + 1) / 32768.0),
+ 20 * log10((rms + 1) / 32768.0),
+ 20 * log10((peak + 1) / (rms + 1)),
+ (double)bytes_acc / 1024.0, g_again);
+ nacc = 0;
+ bytes_acc = 0;
+ peak = 0;
+ sq = 0;
+ }
+ }
+ if (g_adev) {
+ if (g_again != 100) {
+ int16_t *sp =
+ (int16_t *)g_pcmbuf;
+ size_t n =
+ (size_t)r / 2, q;
+ for (q = 0; q < n; q++) {
+ int32_t v =
+ (int32_t)sp[q] *
+ g_again / 100;
+ if (v > 32767) v = 32767;
+ if (v < -32768) v = -32768;
+ sp[q] = (int16_t)v;
+ }
+ }
+ SDL_QueueAudio(g_adev,
+ g_pcmbuf, (Uint32)r);
+ }
+ } else {
+ break;
+ }
+ }
+ }
+ /* housekeep window events + live parameter keys */
+ if (!opt_novideo) {
+ SDL_Event ev;
+ while (SDL_PollEvent(&ev)) {
+ if (ev.type == SDL_QUIT)
+ g_stop = 1;
+ else if (ev.type == SDL_MOUSEBUTTONDOWN &&
+ ev.button.button == SDL_BUTTON_LEFT)
+ bar_click(ev.button.x, ev.button.y);
+ else if (ev.type == SDL_KEYDOWN)
+ key_action(ev.key.keysym.sym,
+ (ev.key.keysym.mod & KMOD_SHIFT)
+ ? 1 : 0);
+ }
+ }
+ rc = av_read_frame(fc, pkt);
+ if (rc == AVERROR(EAGAIN)) { usleep(POLL_US); continue; }
+ if (rc < 0) {
+ /* treat as transient (growing file) */
+ usleep(POLL_US);
+ continue;
+ }
+ {
+ static double t_log;
+ double tn = SDL_GetTicks() / 1000.0;
+ if (tn - t_log > 2.0 && g_abuf_target) {
+ size_t p = audio_pending();
+ double denom = (double)g_out_rate *
+ (double)g_out_ch * 2.0;
+ t_log = tn;
+ fprintf(stderr, "audio-ahead: %.0f ms "
+ "(pending %zu B) video-delay %.0f ms "
+ "(queued %d)\n",
+ denom > 0 ? p / denom * 1000.0 : 0.0, p,
+ vdq_delay_ms(), g_vq_n);
+ }
+ }
+ vdq_flush();
+ if (pkt->stream_index == vi && vc) {
+ if (avcodec_send_packet(vc, pkt) >= 0) {
+ while (avcodec_receive_frame(vc, fr) >= 0) {
+ vdq_push(fr);
+ last_vpts = fr->pts;
+ av_frame_unref(fr);
+ }
+ }
+ } else if (pkt->stream_index == ai && ac) {
+ if (avcodec_send_packet(ac, pkt) >= 0) {
+ while (avcodec_receive_frame(ac, fr) >= 0) {
+ if (a_pts0 == AV_NOPTS_VALUE)
+ a_pts0 = fr->pts;
+ /* pace: if the audio ring is way ahead
+ * (join), drop; if full, wait */
+ int guard = 0;
+ while (audio_pending() >
+ g_abuf_target &&
+ !g_stop && guard++ < 2000)
+ usleep(1000);
+ /* convert with buffer */
+ int dstcap = fr->nb_samples * 4;
+ uint8_t *dst = malloc((size_t)dstcap);
+ uint8_t *d2[1] = { dst };
+ int n2 = swr_convert(swr, d2,
+ dstcap / 4,
+ (const uint8_t **)fr->data,
+ fr->nb_samples);
+ if (n2 > 0) {
+ audio_filters_apply(
+ (int16_t *)dst,
+ (size_t)n2 *
+ (size_t)g_out_ch);
+ }
+ if (0) {
+ /*
+ * ★ One-pole DC blocker on the
+ * PCM sent to OSS (2026-10-16):
+ * the capture carries a
+ * low-frequency rumble that the
+ * encoder path leaves in.
+ * ~30 Hz corner; the audible
+ * band is untouched.
+ * MPEGVIEW_NODC=1 disables.
+ */
+ int16_t *pp = (int16_t *)dst;
+ int q;
+ for (q = 0; q < n2 * g_out_ch; q++) {
+ float x = (float)pp[q];
+ float y = x - dc_x1 +
+ 0.9950f * dc_y1;
+ dc_x1 = x;
+ dc_y1 = y;
+ if (y > 32767.0f) y = 32767.0f;
+ if (y < -32768.0f) y = -32768.0f;
+ pp[q] = (int16_t)y;
+ }
+ }
+ if (n2 > 0) {
+ size_t nb = (size_t)n2 *
+ (size_t)g_out_ch * 2;
+ size_t first =
+ g_abuf_sz - g_awrite;
+ if (first > nb) first = nb;
+ memcpy(g_abuf + g_awrite, dst,
+ first);
+ if (nb > first)
+ memcpy(g_abuf,
+ dst + first,
+ nb - first);
+ g_awrite = (g_awrite + nb) %
+ g_abuf_sz;
+ }
+ free(dst);
+ av_frame_unref(fr);
+ }
+ }
+ }
+ av_packet_unref(pkt);
+ (void)v_pts0; (void)last_vpts; (void)a_pts0;
+ }
+
+ fprintf(stderr, "stopping\n");
+ /*
+ * Close our end of the pipe FIRST: kare may be blocked writing a
+ * raw (15 MB/s) frame into a full pipe, and while we hold the read
+ * end open it can never see the close -- it would sit there instead
+ * of running its own shutdown (which is where STOP_CAPTURE is sent).
+ * Then give it a bounded grace period before SIGKILL, so a stuck
+ * child can never hang the player.
+ */
+ if (g_usepipe && g_fd >= 0) {
+ close(g_fd);
+ g_fd = -1;
+ }
+ /*
+ * Graceful shutdown through the control channel: kare's "Q" command
+ * stops the capture properly, which is what sends CX2341X_ENC_STOP_CAPTURE
+ * (0x82) and leaves the encoder idle for the next run. Works on every
+ * platform -- Windows has no SIGTERM, so this is the only clean stop there.
+ */
+ if (g_ctl && cap > 0)
+ ctl_send("Q");
+ if (cap > 0) {
+ int i;
+ kill(cap, SIGTERM);
+ for (i = 0; i < 40; i++) { /* up to ~2 s */
+ if (waitpid(cap, NULL, WNOHANG) == cap)
+ break;
+ usleep(50000);
+ }
+ if (i == 40) {
+ fprintf(stderr, "kare did not exit; killing it\n");
+ kill(cap, SIGKILL);
+ waitpid(cap, NULL, 0);
+ }
+ }
+ return 0;
+}
diff --git a/src/test_cx.c b/src/test_cx.c
new file mode 100644
index 0000000..6612264
--- /dev/null
+++ b/src/test_cx.c
@@ -0,0 +1,174 @@
+/*
+ * test_cx.c - bring-up / protocol self-test for mpegcap
+ *
+ * Steps through the CX23416 init exactly as the known-good reference
+ * (yamori813 mpeg-usb mpegcapt.c / Linux pvrusb2) but prints every stage,
+ * so we can see where the real hardware diverges.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include "pvrusb2.h"
+
+static void step(const char *s) { printf("--- %s\n", s); fflush(stdout); }
+static void msleep(int ms)
+{
+ struct timespec ts = { ms / 1000, (long)(ms % 1000) * 1000000L };
+ nanosleep(&ts, NULL);
+}
+
+static int i2c_dump(pvr2_dev *p, uint16_t reg, int len)
+{
+ uint8_t buf[64];
+ int i;
+ if (pvr2_i2c_read(p, CX2584X_I2C_ADDR, reg, buf, len) < 0) {
+ printf(" i2c read %04x failed\n", reg);
+ return -1;
+ }
+ printf(" i2c %04x:", reg);
+ for (i = 0; i < len; i++) printf(" %02x", buf[i]);
+ printf("\n");
+ return 0;
+}
+
+int main(int argc, char **argv)
+{
+ pvr2_dev *p;
+ uint8_t *fw = NULL;
+ size_t fwlen = 0;
+ const char *fwp = argc > 1 ? argv[1] : "firmware/cx23416/cx_1_swapped.bin";
+ const char *fwp2 = argc > 2 ? argv[2] : NULL;
+ uint32_t v;
+ uint8_t c1;
+ int r;
+
+ p = calloc(1, sizeof(*p));
+ pvr2_init(p);
+ p->verbose = 1;
+
+ if (pvr2_find_device(p, DEFAULT_VID, DEFAULT_PID) < 0) {
+ fprintf(stderr, "device not found\n");
+ return 1;
+ }
+
+ step("USB speed");
+ r = pvr2_get_usb_speed(p);
+ printf(" speed byte 0x%02x (expect 0x80 = high speed)\n", r);
+
+ step("FX2 command 0xde (encoder resume)");
+ pvr2_simple_cmd(p, 0xde, NULL, 0);
+
+ step("FX2 command 0x0b (get usb speed, read response)");
+ {
+ uint8_t b[64];
+ int n;
+ pvr2_simple_cmd(p, 0x0b, NULL, 0);
+ n = bulk_cmd_in(p, b, sizeof(b));
+ printf(" read %d bytes: %02x\n", n, n > 0 ? b[0] : 0);
+ }
+
+ step("FX2 command 0xeb (eeprom addr)");
+ {
+ uint8_t b[64];
+ int n;
+ pvr2_simple_cmd(p, 0xeb, NULL, 0);
+ n = bulk_cmd_in(p, b, sizeof(b));
+ printf(" read %d bytes: %02x\n", n, n > 0 ? b[0] : 0);
+ }
+
+ step("I2C device id (0x0100, 2 bytes)");
+ i2c_dump(p, 0x0100, 2);
+
+ step("I2C video decoder status");
+ i2c_dump(p, 0x040d, 1);
+ i2c_dump(p, 0x040e, 1);
+
+ step("register 0x0048 <- 0xffffffff");
+ printf(" 0x0048 readback: ");
+ if (pvr2_read_reg(p, 0x0048, &v) == 0) printf("%08x\n", v);
+ else printf("FAILED\n");
+
+ step("gpio dir/out, deep reset");
+ pvr2_write_reg(p, 0x0048, 0xffffffff);
+ pvr2_gpio_dir(p, 0xffffffff, 0x00000088);
+ pvr2_gpio_out(p, 0xffffffff, 0x00000008);
+ pvr2_simple_cmd(p, 0xdd, NULL, 0);
+ msleep(100);
+ pvr2_write_reg(p, 0xa064, 0x00000000);
+ pvr2_gpio_dir(p, 0xffffffff, 0x00000408);
+ pvr2_gpio_out(p, 0xffffffff, 0x00000008);
+ pvr2_write_reg(p, 0x9058, 0xffffffed);
+ pvr2_write_reg(p, 0x9054, 0xfffffffd);
+ pvr2_write_reg(p, 0x07f8, 0x80000800);
+ pvr2_write_reg(p, 0x07fc, 0x0000001a);
+ pvr2_write_reg(p, 0x0700, 0x00000000);
+ pvr2_write_reg(p, 0xaa00, 0x00000000);
+ pvr2_write_reg(p, 0xaa04, 0x00057810);
+ pvr2_write_reg(p, 0xaa10, 0x00148500);
+ pvr2_write_reg(p, 0xaa18, 0x00840000);
+
+ step("0x52 FWPOST1, 0x06 MEMSEL");
+ pvr2_simple_cmd(p, 0x52, NULL, 0);
+ pvr2_simple_cmd(p, 0x06, &(uint8_t){0}, 1);
+ msleep(100);
+
+ step("reset 0x9054/0x9058 sanity read");
+ printf(" 0x9054: ");
+ if (pvr2_read_reg(p, 0x9054, &v) == 0) printf("%08x\n", v); else printf("FAILED\n");
+ printf(" 0x9058: ");
+ if (pvr2_read_reg(p, 0x9058, &v) == 0) printf("%08x\n", v); else printf("FAILED\n");
+
+ step("load CX23416 firmware");
+ if (pvr2_load_file(fwp, &fw, &fwlen) < 0) return 1;
+ printf(" %s (%zu bytes)\n", fwp, fwlen);
+ if (pvr2_upload_firmware2(p, fw, fwlen) < 0) {
+ fprintf(stderr, "upload failed\n");
+ return 1;
+ }
+
+ step("post: 0x9054 <- ffffffff, 0x9058 <- fffffffe8, MEMSEL");
+ pvr2_write_reg(p, 0x9054, 0xffffffff);
+ pvr2_write_reg(p, 0x9058, 0xffffffe8);
+ pvr2_simple_cmd(p, 0x06, &(uint8_t){0}, 1);
+ msleep(200);
+
+ step("read back 0x9054 / 0x9058");
+ printf(" 0x9054: ");
+ if (pvr2_read_reg(p, 0x9054, &v) == 0) printf("%08x\n", v); else printf("FAILED\n");
+ printf(" 0x9058: ");
+ if (pvr2_read_reg(p, 0x9058, &v) == 0) printf("%08x\n", v); else printf("FAILED\n");
+
+ step("MBOX raw read at 0x44 (4 words)");
+ {
+ uint32_t w[4];
+ int i;
+ if (pvr2_mbox_read(p, 0x44, w, 4) == 0) {
+ for (i = 0; i < 4; i++) printf(" mbox[%d] = %08x\n", i, w[i]);
+ } else printf(" FAILED\n");
+ }
+
+ step("PING (0x80)");
+ if (pvr2_enc_ping(p) == 0) {
+ printf(" PING OK\n");
+ step("GET_VERSION (0xc4)");
+ if (pvr2_enc_get_version(p, &v) == 0)
+ printf(" version %u.%u.%u (raw %08x)\n",
+ (v >> 24) & 0xff, (v >> 16) & 0xff, v & 0xffff, v);
+ else
+ printf(" GET_VERSION failed\n");
+ } else {
+ printf(" PING FAILED\n");
+ }
+
+ /* Optional: try alternate firmware if given */
+ if (fwp2) {
+ printf("\n=== (skipping alt firmware retry; power cycle needed) ===\n");
+ }
+ (void)c1;
+ free(fw);
+ pvr2_exit(p);
+ free(p);
+ return 0;
+}
diff --git a/src/test_mbox.c b/src/test_mbox.c
new file mode 100644
index 0000000..f991761
--- /dev/null
+++ b/src/test_mbox.c
@@ -0,0 +1,113 @@
+/*
+ * test_mbox.c - isolate the MBOX read/write path
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include "pvrusb2.h"
+
+static void msleep(int ms){struct timespec ts={ms/1000,(long)(ms%1000)*1000000L};nanosleep(&ts,NULL);}
+
+int main(int argc, char **argv)
+{
+ pvr2_dev *p = calloc(1, sizeof(*p));
+ uint8_t *fw; size_t fwlen;
+ const char *fwp = argc > 1 ? argv[1] : "firmware/cx23416/cx_1_swapped.bin";
+ uint8_t in[256];
+ int n;
+
+ pvr2_init(p);
+ p->verbose = 1;
+ pvr2_find_device(p, DEFAULT_VID, DEFAULT_PID);
+
+ /* ---- exactly the mpegcapt.c sequence ---- */
+ pvr2_simple_cmd(p, 0xde, NULL, 0);
+ pvr2_simple_cmd(p, 0x0b, NULL, 0);
+ (void)bulk_cmd_in(p, in, sizeof(in));
+ pvr2_simple_cmd(p, 0xeb, NULL, 0);
+ (void)bulk_cmd_in(p, in, sizeof(in));
+
+ pvr2_write_reg(p, 0x0048, 0xffffffff);
+ pvr2_gpio_dir(p, 0xffffffff, 0x00000088);
+ pvr2_gpio_out(p, 0xffffffff, 0x00000008);
+ pvr2_simple_cmd(p, 0xdd, NULL, 0);
+ pvr2_write_reg(p, 0xa064, 0);
+ pvr2_gpio_dir(p, 0xffffffff, 0x00000408);
+ pvr2_gpio_out(p, 0xffffffff, 0x00000008);
+ pvr2_write_reg(p, 0x9058, 0xffffffed);
+ pvr2_write_reg(p, 0x9054, 0xfffffffd);
+ pvr2_write_reg(p, 0x07f8, 0x80000800);
+ pvr2_write_reg(p, 0x07fc, 0x1a);
+ pvr2_write_reg(p, 0x0700, 0);
+ pvr2_write_reg(p, 0xaa00, 0);
+ pvr2_write_reg(p, 0xaa04, 0x57810);
+ pvr2_write_reg(p, 0xaa10, 0x148500);
+ pvr2_write_reg(p, 0xaa18, 0x840000);
+ pvr2_simple_cmd(p, 0x52, NULL, 0);
+ pvr2_simple_cmd(p, 0x06, &(uint8_t){0}, 1);
+
+ if (pvr2_load_file(fwp, &fw, &fwlen) < 0) return 1;
+ if (pvr2_upload_firmware2(p, fw, fwlen) < 0) return 1;
+
+ pvr2_write_reg(p, 0x9054, 0xffffffff);
+ pvr2_write_reg(p, 0x9058, 0xffffffe8);
+ pvr2_simple_cmd(p, 0x06, &(uint8_t){0}, 1);
+
+ /* --- raw MBOX read, exactly like mpegcapt readmem(0x44) --- */
+ printf("\n=== raw single-word MBOX read at 0x44 (mpegcapt style) ===\n");
+ {
+ uint8_t b[8];
+ memset(b, 0, 8);
+ b[0] = 0x02;
+ b[5] = 0x00; b[6] = 0x00; b[7] = 0x44;
+ pvr2_simple_cmd(p, 0, NULL, 0); /* noop to flush? */
+ bulk_cmd_out(p, b, 8);
+ n = bulk_cmd_in(p, in, sizeof(in));
+ printf("read %d bytes:", n);
+ { int i; for (i = 0; i < n && i < 8; i++) printf(" %02x", in[i]); }
+ printf("\n");
+ }
+
+ /* --- write a known pattern to MBOX then read it back --- */
+ printf("\n=== MBOX write/readback test (addr 0x44, 4 words) ===\n");
+ {
+ uint32_t wr[4] = { 0x11223344, 0x55667788, 0x99aabbcc, 0xddeeff00 };
+ uint32_t rd[4] = {0};
+ int i;
+ if (pvr2_mbox_write(p, 0x44, wr, 4) < 0) printf("write FAILED\n");
+ msleep(50);
+ if (pvr2_mbox_read(p, 0x44, rd, 4) < 0) printf("read FAILED\n");
+ for (i = 0; i < 4; i++)
+ printf(" wr %08x -> rd %08x %s\n", wr[i], rd[i],
+ wr[i] == rd[i] ? "OK" : "MISMATCH");
+ }
+
+ /* --- now try the PING handshake with verbose tracing --- */
+ printf("\n=== PING handshake ===\n");
+ {
+ uint32_t data[16];
+ uint32_t stat;
+ int i;
+ for (i = 0; i < 16; i++) data[i] = 0;
+ data[0] = 0; data[1] = 0x80; data[2] = 0; data[3] = 0x00060000;
+ printf("writing 12 words...\n");
+ if (pvr2_mbox_write(p, 0x44, data, 12) < 0) printf(" write fail\n");
+ {
+ uint32_t go = 3;
+ printf("writing go word (3)...\n");
+ if (pvr2_mbox_write(p, 0x44, &go, 1) < 0) printf(" go fail\n");
+ }
+ for (i = 0; i < 20; i++) {
+ if (pvr2_mbox_read(p, 0x44, &stat, 1) < 0) { printf(" read fail\n"); break; }
+ printf(" poll %d: mbox[0] = %08x%s\n", i, stat,
+ (stat & 4) ? " <-- FIRMWARE_DONE" : "");
+ if (stat & 4) break;
+ msleep(50);
+ }
+ }
+
+ free(fw);
+ pvr2_exit(p);
+ return 0;
+}