summaryrefslogtreecommitdiff
path: root/src/hm12.c
diff options
context:
space:
mode:
authorCharlie Root <root@dangofactory.local>2026-10-25 10:15:31 +0900
committerCharlie Root <root@dangofactory.local>2026-10-25 10:15:31 +0900
commit7318435b737394904bb1c5ce9fe013b0eee1882f (patch)
tree41adf14909f5f8d15c8e1c5db361e6ea0ac97598 /src/hm12.c
downloadmpegcap-baseline-1016.tar.gz
mpegcap-baseline-1016.zip
kare / spoon - CX23416 + FX2 USB MPEG capture toolHEADbaseline-1016
Capture tool for the I-O DATA GV-MVP/RZ2 (04bb:0514): Conexant CX23416 MPEG encoder behind an EZ-USB FX2 bridge, with a CX25837 video decoder (I2C 0x44) and a WM8739 audio ADC (I2C 0x1a). libusb-1.0, C99, built with GNU make on FreeBSD/Linux. kare capture: MPEG-2 PS or raw HM12 (y4m), MPEG audio, --pcm WAV, live parameter control through CTLFILE spoon live viewer: pipe -> ffmpeg -> SDL2, clickable control bar, resizable window, raw PCM playback on -r State at this commit: - MPEG-2 PS 720x480 ~6.5 Mbit/s, colour, mp2 48 kHz stereo 224 kbit/s - raw HM12 (NV12_16L16, 518,416-byte frames) with selective median denoise - S-Video works: luma In1 + chroma In5 (0x103=0xd0); RCA is In2+In6 (0xe1) - VBI cropped: 0x0474=24 with 0x0477=28 (they must move together, +4) - audio: never issue an I2C READ to the WM8739 (write-only part) History note: this repository was squashed to a single commit on 2026-10-25 because the earlier history carried the CX23416 firmware images and the vendor trees. Those still exist on the working copy (firmware/, ref/) and are in .gitignore; only src/, include/, Makefile, README.md and .gitignore are versioned. The pre-squash history is preserved locally as a bundle.
Diffstat (limited to 'src/hm12.c')
-rw-r--r--src/hm12.c510
1 files changed, 510 insertions, 0 deletions
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;
+}