diff --git a/ports/c/.gitignore b/ports/c/.gitignore new file mode 100644 index 0000000..6e43550 --- /dev/null +++ b/ports/c/.gitignore @@ -0,0 +1,4 @@ +*.o +prism +examples/encode_decode +hello.png diff --git a/ports/c/CMakeLists.txt b/ports/c/CMakeLists.txt new file mode 100644 index 0000000..0e82d95 --- /dev/null +++ b/ports/c/CMakeLists.txt @@ -0,0 +1,21 @@ +# Optional CMake build for the Comb Code C port (the Makefile is the primary +# build; this is an equivalent alternative). +cmake_minimum_required(VERSION 3.16) +project(CombCode VERSION 1.0.0 LANGUAGES C) +# Comb Code, Copyright (c) 2026 Avi Shor. Free to use, with or without credit. + +set(CMAKE_C_STANDARD 11) + +find_package(ZLIB REQUIRED) + +add_library(combcode STATIC + prism.c prism_crypto.c prism_ecdsa.c prism_secure.c + prism_parts.c prism_cards.c prism_issuers.c) +target_link_libraries(combcode PUBLIC ZLIB::ZLIB m) +target_include_directories(combcode PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) + +add_executable(prism cli.c) +target_link_libraries(prism PRIVATE combcode) + +add_executable(encode_decode_example examples/encode_decode.c) +target_link_libraries(encode_decode_example PRIVATE combcode) diff --git a/ports/c/Makefile b/ports/c/Makefile index c2a2110..0541a0e 100644 --- a/ports/c/Makefile +++ b/ports/c/Makefile @@ -32,3 +32,7 @@ clean: rm -f prism *.o .PHONY: clean + +example: examples/encode_decode.c prism.o + $(CC) $(CFLAGS) -I. -o examples/encode_decode examples/encode_decode.c prism.o -lz -lm + ./examples/encode_decode diff --git a/ports/c/README.md b/ports/c/README.md index 24beecf..1f1c118 100644 --- a/ports/c/README.md +++ b/ports/c/README.md @@ -122,10 +122,41 @@ Byte-compatible with comb-issuers.js, comb-parts.js and comb-cards.js: PRISM-TICKET/1 payloads; built payloads are byte-identical to the JS builders (escaping included). -## Not in this port (yet) +## Library use + +The public C API is `prism.h` (encoder/decoder), `prism_secure.h` (Comb Code +Secure), `prism_parts.h` (multi-part files), `prism_cards.h` (Wi-Fi / vCard / +ticket payloads) and `prism_issuers.h` (ticket issuers). All functions are +documented at their declarations. Example (`examples/encode_decode.c`, +build and run with `make example`): + +```c +#include "prism.h" + +char err[256]; +const char *text = "Hello from Comb Code"; +prism_encode_png((const uint8_t *)text, strlen(text), -1, 1, + PRISM_MODE_COLOR, PRISM_TYPE_TEXT, 12, "hello.png", err, sizeof err); +uint8_t *out; size_t out_len; int out_type; +prism_decode_png("hello.png", &out, &out_len, &out_type, err, sizeof err); +printf("%.*s +", (int)out_len, out); /* Hello from Comb Code */ +free(out); +``` + +### API reference (encoder/decoder, `prism.h`) + +- `prism_encode_png(data, len, size, ecc, mode, type, scale, out_png, err, errlen)` — + encode payload bytes and write a PNG. `size` -1 = automatic or 0..5; + `ecc` 0..3 (10/20/30/40% repair data); `mode` color or black-and-white; + `type` text or binary; `scale` pixels per cell unit. +- `prism_encode_rgba(...)` — same, to an in-memory RGBA image. +- `prism_decode_png(in_png, &out, &out_len, &out_type, err, errlen)` — + decode a clean PNG; the payload is only returned when its CRC-32 passes. +- `prism_capacity_payload(size, ecc, mode)` — maximum payload bytes. -The phone-camera reading pipeline (glare, blur, perspective — that stays on -the website's reader pages) is being ported next. +The phone-camera reader (photos: glare, blur, perspective) is in `reader/`, +with its own README. ## License diff --git a/ports/c/examples/encode_decode.c b/ports/c/examples/encode_decode.c new file mode 100644 index 0000000..492a171 --- /dev/null +++ b/ports/c/examples/encode_decode.c @@ -0,0 +1,32 @@ +/* Comb Code C example: encode a text payload to a PNG, decode it back. */ +#include +#include +#include +#include "../prism.h" + +int main(void) { + char err[256]; + const char *text = "Hello from Comb Code"; + + /* Encode: automatic size, 20% repair data, color mode, 12 px per cell unit. */ + if (prism_encode_png((const uint8_t *)text, strlen(text), -1, 1, + PRISM_MODE_COLOR, PRISM_TYPE_TEXT, 12, + "hello.png", err, sizeof err) != 0) { + fprintf(stderr, "encode failed: %s\n", err); + return 1; + } + printf("encoded %zu bytes -> hello.png\n", strlen(text)); + + /* Decode it back. */ + uint8_t *out; size_t out_len; int out_type; + if (prism_decode_png("hello.png", &out, &out_len, &out_type, err, sizeof err) != 0) { + fprintf(stderr, "decode failed: %s\n", err); + return 1; + } + printf("decoded %zu bytes: %.*s\n", out_len, (int)out_len, out); + + int ok = out_len == strlen(text) && memcmp(out, text, out_len) == 0; + free(out); + printf("round-trip %s\n", ok ? "OK" : "MISMATCH"); + return ok ? 0 : 1; +} diff --git a/ports/c/reader/.gitignore b/ports/c/reader/.gitignore new file mode 100644 index 0000000..924c169 --- /dev/null +++ b/ports/c/reader/.gitignore @@ -0,0 +1,6 @@ +*.o +*.a +obj/ +bin/ +cli +chain772* diff --git a/ports/c/reader/Makefile b/ports/c/reader/Makefile new file mode 100644 index 0000000..4a687b3 --- /dev/null +++ b/ports/c/reader/Makefile @@ -0,0 +1,16 @@ +CC ?= cc +# -ffp-contract=off keeps floating point bit-identical to the JavaScript reader. +CFLAGS ?= -O2 -ffp-contract=off -std=gnu11 -Wall + +SRC = prism_foundations.c prism_jsmath.c prism_detect.c prism_image.c prism_classify.c \ + prism_decode.c prism_mix.c prism_read.c prism_distfit.c prism_chain.c + +all: cli + +cli: $(SRC) cli.c + $(CC) $(CFLAGS) -I. -o $@ cli.c $(SRC) -lm + +clean: + rm -f cli + +.PHONY: all clean diff --git a/ports/c/reader/README.md b/ports/c/reader/README.md new file mode 100644 index 0000000..a33c789 --- /dev/null +++ b/ports/c/reader/README.md @@ -0,0 +1,36 @@ +# Comb Code camera reader — C (C11) port + +A C11 port of the live Comb Code photo/camera reader: detection, hypothesis +search, palette-mix recovery, distance-fit recovery and the full retry chain. +It reads real photos, not only clean PNGs. The clean-PNG encoder/decoder is in +the parent folder. + +Build: `make` (produces `cli`). The Makefile passes `-ffp-contract=off` so +floating point stays bit-identical with the JavaScript reader. + +Run: `./cli scene.raw`, where the file is 8 bytes little-endian width and +height followed by RGBA bytes. Prints `OK `, `OKBIN ` or `FAIL`. +A result is only returned when the header CRC and payload CRC-32 pass. + +## Verified status + +Method: 772 synthetic scenes from the bench kit, run sequentially, each result +compared to the live JavaScript reader's result for the same image +(`../../reader-verify/verify_vs_live.py`). + +| Result | Scenes | +|---|---| +| Read, payload identical to live reader | 728 | +| Both fail | 44 | +| Live reader reads, port does not | 0 | +| Wrong payload | 0 | +| Port reads, live reader does not | 0 | + +The live reader reads 728 of the 772 scenes; the port matches it on every +scene. Timing: the reader stops a page read after 6 seconds, as the live one +does. Run verification one process at a time; under heavy parallel load a few +borderline scenes time out. This is a synthetic-scene result, not a +physical-camera result. + +Comb Code, Copyright (c) 2026 Avi Shor. Free to use, with or without credit. +No warranty. diff --git a/ports/c/reader/cli.c b/ports/c/reader/cli.c new file mode 100644 index 0000000..fdebd5a --- /dev/null +++ b/ports/c/reader/cli.c @@ -0,0 +1,23 @@ +/* prism-reader-cli: read a Comb Code from a raw RGBA file (8-byte LE w,h + RGBA). */ +#include +#include +#include +#include "prism_chain.h" +int main(int argc, char **argv) { + (void)argc; + FILE *f = fopen(argv[1], "rb"); + if (!f) return 2; + uint32_t w, h; + if (fread(&w, 4, 1, f) != 1 || fread(&h, 4, 1, f) != 1) return 2; + uint8_t *rgba = malloc((size_t)w * h * 4); + if (fread(rgba, 4, (size_t)w * h, f) != (size_t)w * h) return 2; + fclose(f); + PrismRead r; + if (prism_chain_read(rgba, (int)w, (int)h, &r) == 0 && r.ok) { + if (r.payload.text) { printf("OK %s\n", r.payload.text); } + else { printf("OKBIN "); for (int i = 0; i < r.payload.n_bytes; i++) printf("%02x", r.payload.bytes[i]); printf("\n"); } + return 0; + } + printf("FAIL\n"); + return 0; +} diff --git a/ports/c/reader/prism_chain.c b/ports/c/reader/prism_chain.c new file mode 100644 index 0000000..2a48655 --- /dev/null +++ b/ports/c/reader/prism_chain.c @@ -0,0 +1,939 @@ +/* prism_chain.c - C port of the reader page-side retry chain (fr-new.html lines 165-531). + Mirrors the live page: plain roiRead -> mix roiRead -> front-stats heuristic -> 27-filter + retry chain -> __ok second pass. + Port fidelity notes: + - Pure-JS filters are ported bit-exactly (double math, Float32Array->float with rounding on + store, Uint8ClampedArray->u8c(): clamp then round-half-to-even, js_* V8-exact math). + - Canvas smooth-'high' resizes (zoom/_zoomcrop/zoomauto/zoomw/_unsharp) are NOT bit-portable: + approximated with Mitchell-Netravali (B=C=1/3) per Chromium Skia kHigh semantics. + - Canvas NN resizes (zooman, smoothing=false) use Skia NN mapping src=floor((dst+0.5)*scale). + - Budget gates (performance.now CAPs, per-filter worker budgets, 20s wall cap) are no-ops in C: + the C worker read has no deadline. Documented divergence. + - Flags (mix/calmed10/dd/pq/veil/min-radius) drive prism_read.c globals as the page does. */ +#include +#include +#include +#include +#include "prism_reader.h" +#include "prism_jsmath.h" +#include "prism_chain.h" +#include +#include + +extern int prism_flag_mix, prism_flag_calmed, prism_flag_dd, prism_flag_pq, prism_flag_veil; +extern double prism_cfg_min_radius; + +/* ---------- CImg ---------- */ +CImg* cimg_new(int w, int h){ CImg* c=(CImg*)malloc(sizeof(CImg)); c->w=w; c->h=h; c->borrowed=0; + c->px=(uint8_t*)calloc((size_t)w*h*4,1); return c; } +CImg* cimg_wrap(const CImg* src){ CImg* c=(CImg*)malloc(sizeof(CImg)); c->w=src->w; c->h=src->h; + c->px=(uint8_t*)src->px; c->borrowed=1; return c; } +CImg* cimg_clone(const CImg* src){ CImg* c=cimg_new(src->w,src->h); + memcpy(c->px,src->px,(size_t)src->w*src->h*4); return c; } +void cimg_free(CImg* c){ if(!c)return; if(!c->borrowed)free(c->px); free(c); } + +static inline uint8_t u8c(double v){ if(!(v>0))return 0; if(v>255)return 255; return (uint8_t)lrint(v); } +static double wall_s(void){ struct timespec ts; clock_gettime(CLOCK_MONOTONIC,&ts); return ts.tv_sec+ts.tv_nsec/1e9; } +/* Page budget(): shared per-image wall cap CAP=14000ms spans the v2 transforms; once exceeded + they return null. Timing-dependent (documented approximation of the phone's wall clock). */ +static double budget_t0=-1; +static int budget_ok(void){ if(budget_t0<0)budget_t0=wall_s(); return wall_s()-budget_t0<14.0; } +static inline double jsround(double x){ return floor(x+0.5); } + +/* ---------- PrismRoi (fr-new 173-209): bbox, crop, upNN. Bit-exact. + bbox: downsampled saliency (median per channel over g-grid, L1>90 mask, 3x3 density >=3, + largest component >=16 cells), bbox + margin 25%, square-ish window, NULL if >40% of frame. */ +static int* roi_bbox(const CImg* img){ /* returns malloc'd [4] {sx,sy,w,h} or NULL */ + int W=img->w, H=img->h; const uint8_t* d=img->px; + int g=(int)fmax(1,floor(fmax(W,H)/200)), gw=(W+g-1)/g, gh=(H+g-1)/g, N=gw*gh; + uint8_t* P=(uint8_t*)malloc((size_t)N*3); + int32_t h0[256]={0}, h1[256]={0}, h2[256]={0}; + for(int y=0,k=0;y>1, m0=255,m1=255,m2=255, s=0; + for(int v=0;v<256;v++){s+=h0[v]; if(s>half){m0=v;break;}} s=0; + for(int v=0;v<256;v++){s+=h1[v]; if(s>half){m1=v;break;}} s=0; + for(int v=0;v<256;v++){s+=h2[v]; if(s>half){m2=v;break;}} + uint8_t* outm=(uint8_t*)calloc(N,1); + for(int k=0;k90)outm[k]=1; } + uint8_t* den=(uint8_t*)calloc(N,1); + for(int y=0;y=gh)continue; + for(int dx=-1;dx<=1;dx++){ int xx=x+dx; if(xx>=0&&xx=3)den[y*gw+x]=1; } + int32_t* lab=(int32_t*)malloc((size_t)N*4); + for(int i=0;i=0)continue; + int id=nsizes++, sz=0, sp=0; + stk[sp++]=y*gw+x; lab[y*gw+x]=id; + while(sp){ int p=stk[--sp], cx=p%gw, cy=(p-cx)/gw; sz++; + if(cx+1=0&&den[p-1]&&lab[p-1]<0){lab[p-1]=id;stk[sp++]=p-1;} + if(cy+1=0&&den[p-gw]&&lab[p-gw]<0){lab[p-gw]=id;stk[sp++]=p-gw;} } + sizes[id]=sz; } + int* res=NULL; + if(nsizes){ + int best=0; for(int i=1;isizes[best])best=i; + if(sizes[best]>=16){ + int x0=gw,x1=0,y0=gh,y1=0; + for(int y=0;yx1)x1=x; if(yy1)y1=y; } + int w=(x1-x0+1)*g, h=(y1-y0+1)*g; + int mg=(int)jsround(fmax(w,h)*.25); + double cx=x0*g+w/2.0, cy=y0*g+h/2.0, ss=fmax(w,h)+2*mg; + int sx=(int)fmax(0,jsround(cx-ss/2)), sy=(int)fmax(0,jsround(cy-ss/2)); + int ex=(int)fmin(W,jsround(cx+ss/2)), ey=(int)fmin(H,jsround(cy+ss/2)); + if(!((double)(ex-sx)*(ey-sy)>0.4*W*H)){ + res=(int*)malloc(4*sizeof(int)); + res[0]=sx; res[1]=sy; res[2]=ex-sx; res[3]=ey-sy; } } } + free(P); free(outm); free(den); free(lab); free(stk); free(sizes); + return res; +} +static CImg* roi_crop(const CImg* img, int sx, int sy, int sw, int sh){ + CImg* o=cimg_new(sw,sh); + for(int y=0;y=img->h)yy=img->h-1; + for(int x=0;x=img->w)xx=img->w-1; + int q=(yy*img->w+xx)*4, p=(y*sw+x)*4; + o->px[p]=img->px[q]; o->px[p+1]=img->px[q+1]; o->px[p+2]=img->px[q+2]; o->px[p+3]=img->px[q+3]; } } + return o; +} +static CImg* upNN(const CImg* img, double s){ + int w=img->w,h=img->h,W2=(int)jsround(w*s),H2=(int)jsround(h*s); + CImg* o=cimg_new(W2,H2); + for(int y=0;yh-1)sy=h-1; + for(int x=0;xw-1)sx=w-1; + int pp=(sy*w+sx)*4, q=(y*W2+x)*4; + o->px[q]=img->px[pp]; o->px[q+1]=img->px[pp+1]; o->px[q+2]=img->px[pp+2]; o->px[q+3]=255; } } + return o; +} + +/* ---------- canvas resizers (approximation layer) ---------- */ +static double mitchell(double x){ const double B=1.0/3, C=1.0/3; x=fabs(x); + if(x<1) return ((12-9*B-6*C)*x*x*x + (-18+12*B+6*C)*x*x + (6-2*B))/6; + if(x<2) return ((-B-6*C)*x*x*x + (6*B+30*C)*x*x + (-12*B-48*C)*x + (8*B+24*C))/6; + return 0; } +/* separable Mitchell upscale, clamped edges, RGB only, alpha=255. Approximates Chromium + canvas imageSmoothingQuality='high' (Skia kHigh cubic). NOT bit-exact. */ +static CImg* canvas_resize_smooth(const CImg* img, int nw, int nh){ + int w=img->w, h=img->h; + CImg* o=cimg_new(nw,nh); + double sx=(double)w/nw, sy=(double)h/nh; + double* t2=(double*)malloc((size_t)nw*h*3*sizeof(double)); + for(int y=0;yw-1)jj=w-1; + int p=(y*w+jj)*4; + a[0]+=img->px[p]*wt; a[1]+=img->px[p+1]*wt; a[2]+=img->px[p+2]*wt; ws+=wt; } + for(int c=0;c<3;c++)t2[(y*nw+x)*3+c]=ws?a[c]/ws:0; } + for(int y=0;yh-1)jj=h-1; + for(int c=0;c<3;c++)a[c]+=t2[(jj*nw+x)*3+c]*wt; ws+=wt; } + int p=(y*nw+x)*4; + for(int c=0;c<3;c++)o->px[p+c]=u8c(ws?a[c]/ws:0); + o->px[p+3]=255; } + free(t2); return o; +} +/* Skia NN (imageSmoothingEnabled=false): src = floor((dst+0.5)*scale). */ +static CImg* canvas_resize_nn(const CImg* img, int nw, int nh){ + int w=img->w,h=img->h; CImg* o=cimg_new(nw,nh); + for(int y=0;yh-1)sy=h-1; + for(int x=0;xw-1)sx=w-1; + int pp=(sy*w+sx)*4, q=(y*nw+x)*4; + o->px[q]=img->px[pp]; o->px[q+1]=img->px[pp+1]; o->px[q+2]=img->px[pp+2]; o->px[q+3]=255; } } + return o; +} + +/* ---------- core filters (fr-new 211-321) ---------- */ +/* crop src rect (x0,y0,s,s) out of img (clamped), resize smooth to SxS. Mirrors drawImage(canvas, + x0,y0,s,s,0,0,S,S). x0,y0 from Math.round are exact; fractional src rect never occurs here. */ +static CImg* zoomcrop(const CImg* img, double frac, double scale){ + int w=img->w,h=img->h; + int s=(int)jsround(fmin(w,h)*frac); + int x0=(int)jsround((w-s)/2.0), y0=(int)jsround((h-s)/2.0); + int S=(int)jsround(s*scale); + CImg* cr=roi_crop(img,x0,y0,s,s); + CImg* r=canvas_resize_smooth(cr,S,S); cimg_free(cr); return r; +} +static CImg* f_zoom(const CImg* img){ return zoomcrop(img,0.45,3); } +static CImg* f_zoomw(const CImg* img){ if(!budget_ok())return NULL; return zoomcrop(img,0.6,2.5); } + +static CImg* f_lift(const CImg* img){ + int w=img->w,h=img->h,N=w*h; const uint8_t* d=img->px; + uint32_t hist[256]={0}; + for(int i=0;i=th){hi=v;break;}} + double g=255.0/fmax(30,hi); + CImg* o=cimg_new(w,h); + for(int i=0,p=0;ipx[p]=u8c(fmin(255,d[p]*g)); o->px[p+1]=u8c(fmin(255,d[p+1]*g)); + o->px[p+2]=u8c(fmin(255,d[p+2]*g)); o->px[p+3]=255; } + return o; +} +static CImg* f_liftdn(const CImg* img){ + CImg* a=f_lift(img); + int w=a->w,h=a->h,N=w*h; const uint8_t* d=a->px; + static const int WT[5]={1,4,6,4,1}; + float* tmp=(float*)malloc((size_t)N*3*sizeof(float)); + for(int y=0;yw-1)xx=w-1; + int wt=WT[dx+2], p=(y*w+xx)*4; sr+=d[p]*wt; sg+=d[p+1]*wt; sb+=d[p+2]*wt; sw+=wt;} + int q=(y*w+x)*3; tmp[q]=(float)(sr/sw); tmp[q+1]=(float)(sg/sw); tmp[q+2]=(float)(sb/sw);} + CImg* o=cimg_new(w,h); + for(int y=0;yh-1)yy=h-1; + int wt=WT[dy+2], q=(yy*w+x)*3; sr+=tmp[q]*wt; sg+=tmp[q+1]*wt; sb+=tmp[q+2]*wt; sw+=wt;} + int p=(y*w+x)*4; o->px[p]=u8c(sr/sw); o->px[p+1]=u8c(sg/sw); o->px[p+2]=u8c(sb/sw); o->px[p+3]=255;} + free(tmp); cimg_free(a); return o; +} +static CImg* unsharp_amt(const CImg* img, double amt){ + int w=img->w,h=img->h; const uint8_t* d=img->px; + CImg* o=cimg_new(w,h); + for(int y=0;y=0&&yy=0&&xxpx[p+c]=u8c(v<0?0:v>255?255:v);} + o->px[p+3]=255;} + return o; +} + +/* gradient grid analysis shared by zoomauto/zooman; fills gx,gy,sg (best window) */ +static void grid_best(const CImg* img, int* bgx, int* bgy, int* bsg){ + int w=img->w,h=img->h; const uint8_t* d=img->px; + int gw=(int)fmax(32,jsround(w/8.0)), gh=(int)fmax(32,jsround(h/8.0)); + float* G=(float*)malloc((size_t)gw*gh*sizeof(float)); + for(int gy=0;gybestnorm){bestnorm=norm;bx=gx;by=gy;bs=sg;} } } + free(G); *bgx=bx; *bgy=by; *bsg=bs; +} +static CImg* f_zoomauto(const CImg* img){ + int w=img->w,h=img->h; + int gx,gy,sg; grid_best(img,&gx,&gy,&sg); + int gw=(int)fmax(32,jsround(w/8.0)), gh=(int)fmax(32,jsround(h/8.0)); + double px=(double)gx/gw*w, py=(double)gy/gh*h, ps=(double)sg/gw*w; + double m=ps*0.8; + int x0=(int)fmax(0,jsround(px-m)), y0=(int)fmax(0,jsround(py-m)); + int side=(int)fmin(fmin(w-x0,h-y0),jsround(ps+2*m)); + int S=(int)fmin(1200,jsround(side*5)); + CImg* cr=roi_crop(img,x0,y0,side,side); + CImg* r=canvas_resize_smooth(cr,S,S); cimg_free(cr); + CImg* u=unsharp_amt(r,1.0); cimg_free(r); return u; +} +static CImg* f_zooman(const CImg* img){ + int w=img->w,h=img->h; + int gx,gy,sg; grid_best(img,&gx,&gy,&sg); + int gw=(int)fmax(32,jsround(w/8.0)), gh=(int)fmax(32,jsround(h/8.0)); + double px=(double)gx/gw*w, py=(double)gy/gh*h, ps=(double)sg/gw*w; + double m=ps*0.8; + int x0=(int)fmax(0,jsround(px-m)), y0=(int)fmax(0,jsround(py-m)); + int side=(int)fmin(fmin(w-x0,h-y0),jsround(ps+2*m)); + int S=(int)fmin(1400,jsround(side*6)); + CImg* cr=roi_crop(img,x0,y0,side,side); + CImg* r=canvas_resize_nn(cr,S,S); cimg_free(cr); return r; +} +static CImg* f_crplain(const CImg* img){ + int w=img->w,h=img->h,N=w*h; const uint8_t* d=img->px; + float* lum=(float*)malloc((size_t)N*4), *amp=(float*)malloc((size_t)N*4); + for(int i=0,p=0;i=0)s-=amp[y*w+x-R-1]; + bl[y*w+x]=(float)(s/(fmin(w-1,x+R)-fmax(0,x-R-1)));}} + for(int x=0;x=0)s-=bl[(y-R-1)*w+x]; + tmp[y*w+x]=(float)(s/(fmin(h-1,y+R)-fmax(0,y-R-1)));}} + CImg* o=cimg_new(w,h); + for(int i=0,p=0;i255){double s=255/m2; r*=s; g*=s; b*=s;} + o->px[p]=u8c(r); o->px[p+1]=u8c(g); o->px[p+2]=u8c(b); o->px[p+3]=255;} + free(lum); free(amp); free(tmp); free(bl); return o; +} + +/* ---------- v2 helpers: gaussian conv, toF/toImg, unsharpG ---------- */ +static float* gk(int* outr, double sig){ int r=(int)fmin(16,ceil(sig*3)); *outr=r; + float* k=(float*)malloc((2*r+1)*sizeof(float)); double s=0; + for(int i=-r;i<=r;i++){ double v=js_exp(-(double)i*i/(2*sig*sig)); k[i+r]=(float)v; s+=v; } + /* JS: s accumulates the double v, NOT the rounded k[] entry */ + for(int i=0;i<2*r+1;i++)k[i]=(float)(k[i]/s); return k; } +static float* cv1(const float* src, int W, int H, const float* k, int r, int horiz){ + float* out=(float*)malloc((size_t)W*H*3*sizeof(float)); + for(int y=0;yW-1?W-1:x+i):x; + int yy=horiz?y:(y+i<0?0:y+i>H-1?H-1:y+i); + double w=k[i+r]; size_t p=((size_t)yy*W+xx)*3; + a0+=src[p]*w; a1+=src[p+1]*w; a2+=src[p+2]*w; } + out[b]=(float)a0; out[b+1]=(float)a1; out[b+2]=(float)a2; } + return out; } +static float* gconv(const float* src, int W, int H, double sig){ + int r; float* k=gk(&r,sig); + float* t=cv1(src,W,H,k,r,1); float* o=cv1(t,W,H,k,r,0); + free(k); free(t); return o; } +static float* toF(const CImg* img){ size_t N=(size_t)img->w*img->h; + float* f=(float*)malloc(N*3*sizeof(float)); const uint8_t* d=img->px; + for(size_t i=0,j=0;ipx[i]=u8c(f[j]<0?0:f[j]>255?255:f[j]); + o->px[i+1]=u8c(f[j+1]<0?0:f[j+1]>255?255:f[j+1]); + o->px[i+2]=u8c(f[j+2]<0?0:f[j+2]>255?255:f[j+2]); o->px[i+3]=255; } + return o; } +static CImg* unsharpG(const CImg* img, double sig, double amt){ + int W=img->w,H=img->h; float* f=toF(img); float* bl=gconv(f,W,H,sig); + for(size_t i=0;i<(size_t)W*H*3;i++)f[i]=(float)(f[i]+amt*(f[i]-bl[i])); + free(bl); CImg* o=toImg(f,W,H); free(f); return o; } +static CImg* f_gs3a2(const CImg* img){ if(!budget_ok())return NULL; return unsharpG(img,3,2); } +static CImg* f_deblkS(const CImg* img){ if(!budget_ok())return NULL; return unsharpG(img,1.2,1.5); } + +/* ---------- saliencyCrop: returns crop or NULL (caller falls back to img) ---------- */ +static CImg* saliency_crop(const CImg* img, double marginFrac){ + int W=img->w,H=img->h; const uint8_t* d=img->px; + int g=(int)fmax(1,floor(fmax(W,H)/200)), gw=(W+g-1)/g, gh=(H+g-1)/g; + int npx=gw*gh; + uint8_t* px=(uint8_t*)malloc((size_t)npx*3); + for(int y=0;y=0&&a[j]>v){a[j+1]=a[j];j--;}a[j+1]=v;} + m[c]=a[npx>>1]; free(a); } + uint8_t* outm=(uint8_t*)calloc(npx,1); + for(int y=0;y90)outm[y*gw+x]=1; } + uint8_t* den=(uint8_t*)calloc(npx,1); + for(int y=0;y=0&&yy=0&&xx=3)den[y*gw+x]=1; } + int32_t* lab=(int32_t*)malloc((size_t)npx*4); + for(int i=0;i=0)continue; + int id=nsizes++, sz=0, sp=0; + stx[sp]=x; sty[sp]=y; sp++; lab[y*gw+x]=id; + while(sp){ sp--; int cx=stx[sp], cy=sty[sp]; sz++; + static const int D[4][2]={{1,0},{-1,0},{0,1},{0,-1}}; + for(int k=0;k<4;k++){ int xx=cx+D[k][0], yy=cy+D[k][1]; + if(xx>=0&&xx=0&&yysizes[best])best=i; + if(sizes[best]>=16){ + int x0=gw,x1=0,y0=gh,y1=0; + for(int y=0;yx1)x1=x; if(yy1)y1=y; } + int w=(x1-x0+1)*g, h=(y1-y0+1)*g; + int mg=(int)jsround(fmax(w,h)*marginFrac); + double cx=(x0*g+w/2.0), cy=(y0*g+h/2.0), s=fmax(w,h)+2*mg; + int sx=(int)fmax(0,jsround(cx-s/2)), sy=(int)fmax(0,jsround(cy-s/2)); + int ex=(int)fmin(W,jsround(cx+s/2)), ey=(int)fmin(H,jsround(cy+s/2)); + if(!((double)(ex-sx)*(ey-sy)>0.6*W*H)){ + int cw=ex-sx, ch=ey-sy; res=cimg_new(cw,ch); + for(int y=0;ypx+(size_t)y*cw*4, img->px+si, (size_t)cw*4); } } } } + free(px); free(outm); free(den); free(lab); free(sizes); free(stx); free(sty); + return res; +} + +/* ---------- Lucy-Richardson ---------- */ +static CImg* lrG(const CImg* img, double sig, int iters){ + int W=img->w,H=img->h; size_t L=(size_t)W*H*3; + float* y=toF(img); float* est=(float*)malloc(L*4); memcpy(est,y,L*4); + int r; float* k=gk(&r,sig); + for(int it=0;itw,H=img->h; float* y=toF(img); + double a=angDeg*M_PI/180, dx=js_cos(a), dy=js_sin(a); + int offs[64][2]; int noff=0; + for(int t=-(L-1)/2;t<=(L-1)/2;t++){ + int ox=(int)jsround(dx*t), oy=(int)jsround(dy*t); + int dup=0; for(int i=0;iW-1)x2=W-1; + int y2=yy+offs[i][1]; if(y2<0)y2=0; if(y2>H-1)y2=H-1; + size_t p=((size_t)y2*W+x2)*3; a0+=est[p]; a1+=est[p+1]; a2+=est[p+2]; } + size_t b=((size_t)yy*W+xx)*3; + obuf[b]=(float)(a0*kw); obuf[b+1]=(float)(a1*kw); obuf[b+2]=(float)(a2*kw); } + float* ratio=(float*)malloc(len*4); + for(size_t i=0;iW-1)x2=W-1; + int y2=yy+offs[i][1]; if(y2<0)y2=0; if(y2>H-1)y2=H-1; + size_t p=((size_t)y2*W+x2)*3; a0+=ratio[p]; a1+=ratio[p+1]; a2+=ratio[p+2]; } + size_t b=((size_t)yy*W+xx)*3; + obuf[b]=(float)(a0*kw); obuf[b+1]=(float)(a1*kw); obuf[b+2]=(float)(a2*kw); } + for(size_t i=0;iw,H=img->h; const uint8_t* d=img->px; + float* g=(float*)malloc((size_t)W*H*sizeof(float)); + for(int i=0;i-iy)?0:-iy, yhi=(H-1-ix)?0:-ix, xhi=(W-1>1; for(;j&bit;bit>>=1)j^=bit; j^=bit; + if(iw,H=img->h,N=1; while(N<(W>H?W:H))N<<=1; + double a=angDeg*M_PI/180, dx=js_cos(a), dy=js_sin(a); + size_t NN=(size_t)N*N; + double* kr=(double*)calloc(NN,8), *ki=(double*)calloc(NN,8); + double tot=0; + for(double t=-(L-1)/2.0;t<=(L-1)/2.0+1e-9;t+=.25){ + double fx=dx*t, fy=dy*t; + int x0=(int)floor(fx), y0=(int)floor(fy); + double ax=fx-x0, ay=fy-y0; + static const int U[4][2]={{0,0},{1,0},{0,1},{1,1}}; + double ws[4]; ws[0]=(1-ax)*(1-ay); ws[1]=ax*(1-ay); ws[2]=(1-ax)*ay; ws[3]=ax*ay; + for(int u=0;u<4;u++){ int yy=((y0+U[u][1])%N+N)%N, xx=((x0+U[u][0])%N+N)%N; + kr[(size_t)yy*N+xx]+=ws[u]; tot+=ws[u]; } } + for(size_t i=0;ipx[((size_t)(ypx[((size_t)y*W+x)*4+c]=u8c(v<0?0:v>255?255:v); } } + for(size_t i=3;i<(size_t)W*H*4;i+=4)out->px[i]=255; + free(kr); free(ki); free(re); free(im); return out; +} + +/* ---------- ml/mlw/mlg wrappers (saliency crop with img fallback) ---------- */ +static CImg* f_ml(const CImg* img, double ang){ + if(!budget_ok())return NULL; + CImg* c=saliency_crop(img,.15); if(!c)c=cimg_wrap(img); + CImg* o=lrLine(c,19,ang,8); cimg_free(c); return o; } +static CImg* f_mlw(const CImg* img, int L){ + if(!budget_ok())return NULL; + CImg* c=saliency_crop(img,.15); if(!c)c=cimg_wrap(img); + int ang=est_motion_angle(c); + CImg* o=wiener_line(c,L,ang,.003); cimg_free(c); return o; } +static CImg* f_mlg(const CImg* img, int L){ + CImg* c=saliency_crop(img,.15); if(!c)c=cimg_wrap(img); + int ang=est_motion_angle(c); double rt=last_ratio; + if(!(rt<0.72)){ cimg_free(c); return NULL; } + if(!budget_ok()){ cimg_free(c); return NULL; } + prism_flag_calmed=1; /* sets __calmed10 for the FOLLOWING read attempt */ + CImg* o=wiener_line(c,L,ang,.003); cimg_free(c); return o; } +static CImg* f_lr2(const CImg* img){ + if(!budget_ok())return NULL; + CImg* c=saliency_crop(img,.15); if(!c)c=cimg_wrap(img); + CImg* o=lrG(c,2,6); cimg_free(c); return o; } + +/* ---------- llBoost ---------- */ +static CImg* f_llb(const CImg* img){ + int w=img->w,h=img->h,n=w*h; const uint8_t* d=img->px; + double sum=0; for(int i=0;i45)return NULL; + if(!budget_ok())return NULL; + int r=(int)ceil(4.5), klen=2*r+1; + float* k=(float*)malloc(klen*sizeof(float)); double ks=0; + for(int i=-r;i<=r;i++){ k[i+r]=(float)js_exp(-(double)i*i/(2*1.5*1.5)); ks+=k[i+r]; } + for(int i=0;i=w?w-1:xx; + size_t o=((size_t)y*w+xx)*3; double c=k[j+r]; + r0+=a[o]*c; g0+=a[o+1]*c; b0+=a[o+2]*c; } + size_t o=((size_t)y*w+x)*3; b[o]=(float)r0; b[o+1]=(float)g0; b[o+2]=(float)b0; } + for(int y=0;y=h?h-1:yy; + size_t o=((size_t)yy*w+x)*3; double c=k[j+r]; + r0+=b[o]*c; g0+=b[o+1]*c; b0+=b[o+2]*c; } + size_t o=((size_t)y*w+x)*3; a[o]=(float)r0; a[o+1]=(float)g0; a[o+2]=(float)b0; } + uint32_t hist[256]={0}; + for(size_t i=0;i<(size_t)n*3;i+=3)for(int c=0;c<3;c++){ + int v=(int)jsround(a[i+c]); if(v<0)v=0; if(v>255)v=255; hist[v]++; } + double acc=0; int lo=0,hi=255; double tot=(double)n*3, pl=tot*.02; + for(int v=0;v<256;v++){acc+=hist[v]; if(acc>=pl){lo=v;break;}} + acc=0; for(int v=255;v>=0;v--){acc+=hist[v]; if(acc>=pl){hi=v;break;}} + if(hi-lo<4){ free(k);free(a);free(b); return NULL; } + uint8_t lut[256]; + for(int v=0;v<256;v++){ double t=(double)(v-lo)/(hi-lo); t=t<0?0:t>1?1:t; + lut[v]=u8c(js_pow(t,.6)*255); } + CImg* out=cimg_new(w,h); + for(int i=0;ipx[i*4]=lut[i0<0?0:i0>255?255:i0]; + out->px[i*4+1]=lut[i1<0?0:i1>255?255:i1]; + out->px[i*4+2]=lut[i2<0?0:i2>255?255:i2]; + out->px[i*4+3]=255; } + free(k); free(a); free(b); return out; +} + +/* ---------- glNorm ---------- */ +static CImg* f_gln(const CImg* img){ if(!budget_ok())return NULL; + int w=img->w,h=img->h; const uint8_t* d=img->px; + int hw=w>>1, hh=h>>1, n=hw*hh, K=10; + float* ch[3]; for(int c=0;c<3;c++){ ch[c]=(float*)malloc((size_t)n*4); + for(int y=0;yhw-1?hw-1:x+K; + for(int j=j0;j<=j1;j++){ double b=a[y*hw+j]; v=pass?(v>b?v:b):(vhh-1?hh-1:y+K; + for(int j=j0;j<=j1;j++){ double b=t[j*hw+x]; v=pass?(v>b?v:b):(v=hw)continue; + v+=(double)r[y*hw+xx]*kb[j+R]; wt+=kb[j+R]; } + t2[y*hw+x]=(float)(v/wt); } + for(int y=0;y=hh)continue; + v+=(double)t2[yy*hw+x]*kb[j+R]; wt+=kb[j+R]; } + r2[y*hw+x]=(float)(v/wt); } + free(t2); free(kb); free(r); + if(pass)hi[c]=r2; else lo[c]=r2; } + CImg* out=cimg_new(w,h); + for(int y=0;ypx[o+c]=u8c((d[o+c]-l)/fmax(hg-l,25)*255); } + out->px[o+3]=255; } } + for(int c=0;c<3;c++){free(ch[c]);free(lo[c]);free(hi[c]);} + return out; +} + +/* ---------- glmk: glare inversion (block-min floor) ---------- */ +static CImg* glmk(const CImg* img, int blk, int sm, int gam){ + int w=img->w,h=img->h,N=w*h; const uint8_t* d=img->px; + float* mn=(float*)malloc((size_t)N*4); + for(int i=0,p=0;i=0&&yy=0&&xxpx[p]=u8c((d[p]-Bc)*sc); o->px[p+1]=u8c((d[p+1]-Bc)*sc); + o->px[p+2]=u8c((d[p+2]-Bc)*sc); o->px[p+3]=255; } } + free(g); free(mn); return o; +} +static CImg* f_gl3(const CImg* img){ return glmk(img,16,2,10); } +static CImg* f_gl5(const CImg* img){ return glmk(img,20,2,10); } +static CImg* f_gl6(const CImg* img){ return glmk(img,12,3,10); } +static CImg* f_gl7(const CImg* img){ return glmk(img,8,1,20); } + +/* ---------- flag-only filters ---------- */ +static CImg* f_cenon(const CImg* img){ prism_flag_dd=1; prism_flag_pq=1; return cimg_wrap(img); } +static CImg* f_calmedon(const CImg* img){ prism_flag_calmed=1; return cimg_wrap(img); } +static CImg* f_veil(const CImg* img){ prism_flag_veil=1; prism_flag_pq=1; return cimg_wrap(img); } + +/* ---------- filter dispatch by chain name ---------- */ +static CImg* apply_filter(const char* nm, const CImg* img){ + if(!strcmp(nm,"cenon"))return f_cenon(img); + if(!strcmp(nm,"llb"))return f_llb(img); + if(!strcmp(nm,"zoom"))return f_zoom(img); + if(!strcmp(nm,"mlg19"))return f_mlg(img,19); + if(!strcmp(nm,"mlg31"))return f_mlg(img,31); + if(!strcmp(nm,"mlg31probe"))return f_mlg(img,31); /* e0ec151: alias, runs ahead of the chain */ + if(!strcmp(nm,"gl5"))return f_gl5(img); + if(!strcmp(nm,"gl3"))return f_gl3(img); + if(!strcmp(nm,"liftdn"))return f_liftdn(img); + if(!strcmp(nm,"crplain"))return f_crplain(img); + if(!strcmp(nm,"zoomauto"))return f_zoomauto(img); + if(!strcmp(nm,"zooman"))return f_zooman(img); + if(!strcmp(nm,"gl6"))return f_gl6(img); + if(!strcmp(nm,"gl7"))return f_gl7(img); + if(!strcmp(nm,"gln"))return f_gln(img); + if(!strcmp(nm,"calmedon"))return f_calmedon(img); + if(!strcmp(nm,"gs3a2"))return f_gs3a2(img); + if(!strcmp(nm,"deblkS"))return f_deblkS(img); + if(!strcmp(nm,"zoomw"))return f_zoomw(img); + if(!strcmp(nm,"mlw19"))return f_mlw(img,19); + if(!strcmp(nm,"mlw31"))return f_mlw(img,31); + if(!strcmp(nm,"lr2"))return f_lr2(img); + if(!strcmp(nm,"veil"))return f_veil(img); + if(!strcmp(nm,"ml112"))return f_ml(img,112); + if(!strcmp(nm,"ml45"))return f_ml(img,45); + if(!strcmp(nm,"ml0"))return f_ml(img,0); + if(!strcmp(nm,"ml90"))return f_ml(img,90); + if(!strcmp(nm,"ml135"))return f_ml(img,135); + return NULL; +} + +/* ---------- worker read wrapper ---------- */ +static int wrk(const CImg* img, PrismRead* out){ + prism_cfg_min_radius = prism_flag_mix ? 0.55 : 4; /* worker onmessage: CFG.minRadius = mix?0.55:4 */ + return prism_fast_read(img->px, img->w, img->h, out); +} +/* roiRead (e0ec151 207): initialBox + __directInitial small-code fallback. + 0 on success, 1 on "stopped" (overall cap), -1 on ordinary failure. */ +static int roi_read2(const CImg* image, PrismRead* out, const int* ibox, int direct_initial){ + int* b = NULL; + if(ibox){ b=malloc(4*sizeof(int)); memcpy(b,ibox,4*sizeof(int)); } + else b=roi_bbox(image); + if(b){ + int sx=b[0],sy=b[1],bw=b[2],bh=b[3]; + if(prism_flag_mix){ int dx=sx%2,dy=sy%2; sx-=dx; sy-=dy; bw+=dx; bh+=dy; } + CImg* c=roi_crop(image,sx,sy,bw,bh); + int m=c->w>c->h?c->w:c->h; + if(m<400 && !prism_flag_mix){ CImg* u=upNN(c,fmin(6,400.0/m)); cimg_free(c); c=u; } + int rc=wrk(c,out); + cimg_free(c); + if(rc==0){ free(b); return 0; } + /* catch: stopped rethrows; else small-code directInitial fallback */ + if(prism_cap_stopped){ free(b); return 1; } + if(direct_initial && !prism_flag_mix && prism_fb_ms==450 && (bw>bh?bw:bh)<260){ + double sv=prism_fb_ms; + prism_flag_mix=1; prism_flag_direct=1; prism_fb_ms=6000; + rc=wrk(image,out); + prism_flag_mix=0; prism_flag_direct=0; prism_fb_ms=sv; + if(rc==0){ free(b); return 0; } + if(prism_cap_stopped){ free(b); return 1; } /* /stopped|already/ rethrows */ + } + free(b); + /* any other failure falls through to the full image */ + } + return wrk(image,out)?(prism_cap_stopped?1:-1):0; +} +static int roi_read(const CImg* image, PrismRead* out){ return roi_read2(image,out,NULL,0); } + +/* ---------- front-stats heuristic (fr-new 523, unchanged in e0ec151) ---------- */ +static void front_stats(const CImg* img, const char* front[3], int* nfront, double* out_aniso, double* out_grad){ + int W=img->w,H=img->h; const uint8_t* D=img->px; + uint32_t hh[256]={0}, hn[1100]={0}; + double sm=0,gxs=0,gys=0,sts=0; + int32_t* rowL=(int32_t*)calloc((size_t)W*3,4); + for(int y=0;y0)gxs+=abs(s-rowL[(y%3)*W+x-1]); + if(y>0)gys+=abs(s-rowL[((y+2)%3)*W+x]); + if(y>1&&x>0&&x=.98*N){p98=i;break;}} + double nz=0; c=0; long tot=0; + for(int i=0;i<1100;i++)tot+=hn[i]; + for(int i=0;i<1100;i++){c+=hn[i]; if(c>=tot/2.0){nz=i/3.0;break;}} + *nfront=0; + if(mean<30&&p98<45){ if(nz<15.2){front[0]="llb";front[1]="liftdn";} + else{front[0]="liftdn";front[1]="llb";} *nfront=2; } + else if(nz>15){ front[0]="liftdn"; *nfront=1; } + else if(sts/N>=44&&p98>=228&&p98<=240&&nz>=3&&nz<=3.6){ + front[0]="calmedon";front[1]="gs3a2";front[2]="lr2"; *nfront=3; } + else if(grad<1.6&&nz<3.5){ + if(aniso>=1.4){front[0]="mlg19";front[1]="mlg31";front[2]="gs3a2";} + else{front[0]="calmedon";front[1]="gs3a2";front[2]="mlg31";} + *nfront=3; } +} + +/* ---------- chain driver: AsyncPrismReader.read (e0ec151 511 + 519-520 wrappers) ---------- */ +static void flags_reset(void){ + prism_flag_calmed=0; prism_flag_dd=0; prism_flag_pq=0; prism_flag_veil=0; prism_flag_mix=0; + prism_flag_direct=0; +} +int prism_chain_read(const uint8_t* rgba, int w, int h, PrismRead* out){ + static const char* chain0[27]={"cenon","llb","zoom","mlg19","mlg31","gl5","gl3","liftdn", + "crplain","zoomauto","zooman","gl6","gl7","gln","calmedon","gs3a2","deblkS","zoomw", + "mlw19","mlw31","lr2","veil","ml112","ml45","ml0","ml90","ml135"}; + CImg* img=cimg_new(w,h); memcpy(img->px,rgba,(size_t)w*h*4); + flags_reset(); budget_t0=-1; prism_cap_stopped=0; + prism_page_cap_s=wall_s()+6.0; /* __overallCap147 wrapper */ + int r=-1; + /* attempt 1: fb=450, __directInitial, precomputed __initialBox/__small */ + int* ibox=roi_bbox(img); + const int small = ibox && (ibox[2]>ibox[3]?ibox[2]:ibox[3])<260; + prism_fb_ms=450; + r=roi_read2(img,out,ibox,1); + prism_fb_ms=0; + if(ibox){ free(ibox); ibox=NULL; } + if(r==0) goto done; + if(prism_cap_stopped) goto done; /* stopped rethrows */ + r=-1; + /* glare fast pre-chain (skipped for small codes) */ + { + const char* fast[5]; int nfast=0; + int* b2=roi_bbox(img); + const int skipg = b2 && (b2[2]>b2[3]?b2[2]:b2[3])<260; + if(b2)free(b2); + if(!skipg){ + const uint8_t* D=img->px; double sum=0; long n=0,dark=0,clip=0,texture=0; + uint32_t hh[256]={0}; + for(size_t k=0;k<(size_t)w*h*4;k+=64){ + double v=(D[k]+D[k+1]+D[k+2])/3.0; hh[(int)jsround(v)]++; sum+=v; n++; + if(v<15)dark++; if(v>254)clip++; + if(k>=4){ double pv=(D[k-4]+D[k-3]+D[k-2])/3.0; if(fabs(v-pv)>=1.5)texture++; } + } + int p98=255; long q=0; + for(int j=0;j<256;j++){ q+=hh[j]; if(q>=.98*n){ p98=j; break; } } + if(p98>=245 && (double)dark/n<.0001 && (double)clip/n>.03 && (double)texture/n>.5){ + fast[0]="gl7"; fast[1]="cenon"; fast[2]="gln"; fast[3]="veil"; fast[4]="veilcalm"; + nfast=5; + } + } + for(int i=0;ipx; double sm=0,hi=0; long nn=0; + for(size_t k=0;k<(size_t)w*h*4;k+=64){ + double v=(D[k]+D[k+1]+D[k+2])/3.0; sm+=v; if(v>hi)hi=v; nn++; + } + if(sm/nn<90 && hi<180){ + CImg* tmp=apply_filter("liftdn",img); + if(tmp){ + prism_fb_ms=450; r=roi_read2(tmp,out,NULL,0); prism_fb_ms=0; + cimg_free(tmp); + if(r==0) goto done; + if(prism_cap_stopped) goto done; + } + } + prism_flag_mix=1; prism_fb_ms=6000; + r=roi_read2(img,out,NULL,0); + prism_flag_mix=0; prism_fb_ms=0; + if(r==0) goto done; + if(prism_cap_stopped) goto done; + } + /* front-stats heuristic + calmedon pre-chains (e0ec151 519) */ + { + const char* front[3]; int nfront=0; double aniso=0, grad=0; + front_stats(img,front,&nfront,&aniso,&grad); + char fs[96]=""; + for(int i=0;i=1.2 && grad>=1.35){ + const int pc=prism_flag_calmed; prism_flag_calmed=1; + CImg* im=apply_filter("mlw19",img); + if(im){ + prism_fb_ms=450; r=roi_read2(im,out,NULL,0); prism_fb_ms=0; + cimg_free(im); + if(r==0){ prism_flag_calmed=pc; goto done; } + if(prism_cap_stopped){ prism_flag_calmed=pc; goto done; } + } + prism_flag_calmed=pc; prism_fb_ms=0; + } + const int probe = !strcmp(fs,"calmedon,gs3a2,mlg31"); + const char* chain[31]; int nc=0; + if(probe)chain[nc++]="mlg31probe"; + for(int i=0;iprism_page_cap_s) goto done; /* page throws stopped */ + if(wall_s()-chain_t0>20.0)break; + const char* nm=chain[i]; + CImg* im2=apply_filter(nm,img); + if(!im2)continue; + if(strcmp(nm,"cenon")&&strcmp(nm,"veil"))oklist[nok++]=nm; + r=roi_read(im2,out); + if(r==0){ cimg_free(im2); goto done; } + cimg_free(im2); + if(prism_cap_stopped) goto done; + if(!strcmp(nm,"cenon")){ prism_flag_dd=0; prism_flag_pq=0; } + if(!strcmp(nm,"veil")){ prism_flag_veil=0; prism_flag_pq=0; } + } + prism_flag_calmed=0; /* page resets __calmed10 before the second pass */ + budget_t0=-1; /* page __budgetReset() between passes */ + for(int i=0;iprism_page_cap_s) goto done; + if(wall_s()-chain_t0>20.0)break; + CImg* im3=apply_filter(oklist[i],img); + if(!im3)continue; + r=roi_read(im3,out); + if(r==0){ cimg_free(im3); goto done; } + cimg_free(im3); + if(prism_cap_stopped) goto done; + } + } + /* final direct mix attempt for non-small codes (e0ec151: moved after the chain) */ + if(!small){ + prism_flag_mix=1; prism_fb_ms=6000; + r=roi_read2(img,out,NULL,0); + prism_flag_mix=0; prism_fb_ms=0; + } +done: + flags_reset(); + prism_page_cap_s=0; + cimg_free(img); + return r==0?0:-1; +} + +/* ---- test hooks (not part of the shipped API) ---- */ +CImg* prism_chain_apply(const char* nm, const CImg* img){ return apply_filter(nm, img); } diff --git a/ports/c/reader/prism_chain.h b/ports/c/reader/prism_chain.h new file mode 100644 index 0000000..0ed5662 --- /dev/null +++ b/ports/c/reader/prism_chain.h @@ -0,0 +1,16 @@ +/* prism_chain.h - page-side retry chain port (see prism_chain.c header for fidelity notes) */ +#ifndef PRISM_CHAIN_H +#define PRISM_CHAIN_H +#include +#include "prism_reader.h" +typedef struct { int w, h; uint8_t* px; int borrowed; } CImg; +CImg* cimg_new(int w, int h); +CImg* cimg_wrap(const CImg* src); +CImg* cimg_clone(const CImg* src); +void cimg_free(CImg* c); +/* Full page flow: plain roiRead -> mix roiRead -> front stats + 27-filter chain -> second pass. + Returns 0 with out->ok on read, -1 on failure (out->err set). Flags reset on every exit. */ +int prism_chain_read(const uint8_t* rgba, int w, int h, PrismRead* out); +#endif +/* test hook: apply one named chain filter (NULL on skip). Not shipped API. */ +CImg* prism_chain_apply(const char* nm, const CImg* img); diff --git a/ports/c/reader/prism_classify.c b/ports/c/reader/prism_classify.c new file mode 100644 index 0000000..dca7f78 --- /dev/null +++ b/ports/c/reader/prism_classify.c @@ -0,0 +1,847 @@ +/* prism_classify.c - exact port of r721 worker classify layer: + * sA (kdtree), X (mesh eval), QA (buildMesh), CA (calibrate), BA (llr), + * fA (header), cA, uA (classify incl. Veil and DD branches). + * Mirror of worker globals via prism_flag_* . Compile with -ffp-contract=off. */ +#include "prism_reader.h" +#include "prism_jsmath.h" +#include +#include +#include +#include + +int prism_flag_calmed = 0, prism_flag_dd = 0, prism_flag_veil = 0, prism_flag_mix = 0, prism_flag_pq = 0; +int prism_flag_direct = 0; +double prism_page_cap_s = 0; +int prism_cap_stopped = 0; + +static const char *ERR_SING = "geometry:Singular geometry"; + +/* ---- n(): sort ascending in place, return A[n>>1] ---- */ +static int cmp_d_(const void *pa, const void *pb) { + double a = *(const double *)pa, b = *(const double *)pb; + return (a > b) - (a < b); +} +static double median_js(double *A, int n) { qsort(A, n, sizeof(double), cmp_d_); return A[n >> 1]; } + +/* ---- clamp I(A, e=0, t=1) ---- */ +static double clamp01(double A) { return fmax(0, fmin(1, A)); } + +/* ---- sA(): kdtree over (x,y) arrays ---- */ +typedef struct KdNode { int id, axis; struct KdNode *left, *right; } KdNode; +typedef struct { const double *xs, *ys; int n; KdNode *nodes; KdNode *root; } KdTree; + +static const double *kd_xs_, *kd_ys_; +static int cmp_kd_(const void *pa, const void *pb) { + int a = *(const int *)pa, b = *(const int *)pb; + /* comparator filled in per-axis via kd_axis_ */ + extern int kd_axis_; + double d = (kd_axis_ ? kd_ys_[a] - kd_ys_[b] : kd_xs_[a] - kd_xs_[b]); + if (d) return d < 0 ? -1 : 1; + return a - b; +} +int kd_axis_; +static KdNode *kd_build_rec(KdNode *pool, int *pn, int *ids, int n, int axis) { + if (!n) return NULL; + kd_axis_ = axis; + qsort(ids, n, sizeof(int), cmp_kd_); + int a = n >> 1; + KdNode *nd = &pool[(*pn)++]; + nd->id = ids[a]; nd->axis = axis; + nd->left = kd_build_rec(pool, pn, ids, a, 1 - axis); + nd->right = kd_build_rec(pool, pn, ids + a + 1, n - a - 1, 1 - axis); + return nd; +} +static void kd_build(KdTree *t, const double *xs, const double *ys, int n) { + t->xs = xs; t->ys = ys; t->n = n; + kd_xs_ = xs; kd_ys_ = ys; + t->nodes = malloc((size_t)(n ? n : 1) * sizeof(KdNode)); + int *ids = malloc((size_t)(n ? n : 1) * sizeof(int)); + for (int i = 0; i < n; i++) ids[i] = i; + int pn = 0; + t->root = kd_build_rec(t->nodes, &pn, ids, n, 0); + free(ids); +} +static void kd_free(KdTree *t) { free(t->nodes); t->nodes = 0; t->root = 0; } + +typedef struct { int id; double d; } KdHit; +static void kd_query_rec(const KdTree *t, const KdNode *l, double r, double o, int a, int excl, KdHit *g, int *gn) { + if (!l) return; + double hx = t->xs[l->id], hy = t->ys[l->id]; + double n2 = hx - r, s = hy - o, C = n2 * n2 + s * s; + if (l->id != excl) { + int A2 = 0; + for (; A2 < *gn && (g[A2].d < C || (g[A2].d == C && g[A2].id < l->id)); A2++); + if (A2 < a) { + int newn = *gn + 1; if (newn > a) newn = a; + for (int k = newn - 1; k > A2; k--) g[k] = g[k - 1]; + g[A2].id = l->id; g[A2].d = C; + *gn = newn; + } + } + double Q = l->axis ? o - hy : r - hx; + const KdNode *E = Q < 0 ? l->left : l->right, *B = Q < 0 ? l->right : l->left; + kd_query_rec(t, E, r, o, a, excl, g, gn); + if (*gn < a || Q * Q <= g[*gn - 1].d) kd_query_rec(t, B, r, o, a, excl, g, gn); +} +/* returns up to a hits sorted by (d,id), JS sA.query() order */ +static int kd_query(const KdTree *t, double x, double y, int a, int excl, KdHit *g) { + int gn = 0; + kd_query_rec(t, t->root, x, y, a, excl, g, &gn); + return gn; +} + +/* ---- mesh (X + QA) ---- */ +typedef struct PrismMesh PrismMeshT; /* defined in prism_reader.h */ + +void mesh_eval(const PrismMesh *m, double x, double y, double out[2]) { + if (!m || !m->n) { out[0] = 0; out[1] = 0; return; } + KdHit g[4]; + int gn = kd_query((const KdTree *)m->tree, x, y, 4, -1, g); + double a = 0, i2 = 0, s = 0; + for (int k = 0; k < gn; k++) { + double e = 1 / (g[k].d + 0.05); + a += m->pts[g[k].id].dx * e; i2 += m->pts[g[k].id].dy * e; s += e; + } + out[0] = a / s; out[1] = i2 / s; +} + +void mesh_free(PrismMesh *m) { + if (!m) return; + free(m->pts); + if (m->tree_ok) { KdTree *tr = (KdTree *)m->tree; free((void *)tr->xs); free((void *)tr->ys); kd_free(tr); free(tr); } + free(m); +} + +/* EA(): edge vector of the map at (e,t) in direction (r,o) */ +static void edge_vec(const PrismMap *A, double e, double t, double r, double o, double out[2]) { + double ax, ay, bx, by; + map_point(A, e, t, &ax, &ay); + map_point(A, e + r, t + o, &bx, &by); + out[0] = bx - ax; out[1] = by - ay; +} + +/* QA(A=frame, e=map, t=layout, r=mode, o=white, a=prev mesh); dense: 0.8*g gate + all known cells */ +static PrismMesh *qa_build(const PrismFrame *A, const PrismMap *e, const PrismLayout *t, int r, const double o[3], const PrismMesh *a, int dense) { + double lab[9][3], pal[9][3]; + pal_dump(pal, lab); + double ev[2]; + edge_vec(e, t->W / 2, t->H / 2, 1, 0, ev); + double g = js_hypot2(ev[0], ev[1]); + PrismMesh *m = calloc(1, sizeof(PrismMesh)); + m->cap = t->n_known; m->pts = malloc((size_t)t->n_known * sizeof(PrismMeshPt)); + for (int ci = 0; ci < t->n_known; ci++) { + const PrismCell *tc = t->known[ci]; + if (!dense && tc->role != ROLE_PILOT) continue; + double i2[2], I2[2] = {0, 0}; + map_point(e, tc->x, tc->y, &i2[0], &i2[1]); + if (a) mesh_eval(a, tc->x, tc->y, I2); + double h = 1.0 / 0.0; + double ndx = 0, ndy = 0; + int s = known_symbol(tc, r); + for (int e2 = -2; e2 <= 2; e2++) + for (int r2 = -2; r2 <= 2; r2++) { + double a2 = I2[0] + 0.3 * r2 * g, l2 = I2[1] + 0.3 * e2 * g; + double C[3], U2[3]; + frame_sample(A, i2[0] + a2, i2[1] + l2, C); + C[0] /= o[0]; C[1] /= o[1]; C[2] /= o[2]; + lab_of(C, U2); + double Q = lab_dist2(U2, lab[s]); + double E = (0.2 * (a2 * a2 + l2 * l2)) / (g * g); + if (Q + E < h) { h = Q + E; ndx = a2; ndy = l2; } + } + m->pts[m->n].x = tc->x; m->pts[m->n].y = tc->y; + m->pts[m->n].dx = ndx; m->pts[m->n].dy = ndy; + m->n++; + } + /* outlier rejection: 8-NN median displacement, gate (dense? 0.8 : 0.3)*g */ + if (m->n) { + double *xs = malloc((size_t)m->n * sizeof(double)), *ys = malloc((size_t)m->n * sizeof(double)); + for (int i = 0; i < m->n; i++) { xs[i] = m->pts[i].x; ys[i] = m->pts[i].y; } + KdTree tr; kd_build(&tr, xs, ys, m->n); + double gate = (dense ? 0.8 : 0.3) * g; + char *keepf = malloc((size_t)m->n); + for (int i = 0; i < m->n; i++) { + KdHit hits[8]; + int hn = kd_query(&tr, m->pts[i].x, m->pts[i].y, 8, i, hits); + int keep = 1; + double mx = 0, my = 0; + if (hn) { + double *dxs = malloc((size_t)hn * sizeof(double)), *dys = malloc((size_t)hn * sizeof(double)); + for (int k = 0; k < hn; k++) { dxs[k] = m->pts[hits[k].id].dx; dys[k] = m->pts[hits[k].id].dy; } + mx = median_js(dxs, hn); my = median_js(dys, hn); + free(dxs); free(dys); + keep = js_hypot2(m->pts[i].dx - mx, m->pts[i].dy - my) <= gate; + } + keepf[i] = (char)keep; + } + int w = 0; + for (int i = 0; i < m->n; i++) if (keepf[i]) m->pts[w++] = m->pts[i]; + free(keepf); + m->n = w; + kd_free(&tr); free(xs); free(ys); + } + /* build the persistent tree for mesh_eval */ + { + double *xs = malloc((size_t)(m->n ? m->n : 1) * sizeof(double)), *ys = malloc((size_t)(m->n ? m->n : 1) * sizeof(double)); + for (int i = 0; i < m->n; i++) { xs[i] = m->pts[i].x; ys[i] = m->pts[i].y; } + KdTree *tr = malloc(sizeof(KdTree)); + kd_build(tr, xs, ys, m->n); + m->tree = tr; + m->tree_ok = 1; + } + return m; +} +PrismMesh *qa_build_mesh(const PrismFrame *A, const PrismMap *e, const PrismLayout *t, int r, const double o[3], const PrismMesh *a) { return qa_build(A, e, t, r, o, a, 0); } +PrismMesh *qa_build_dense_mesh(const PrismFrame *A, const PrismMap *e, const PrismLayout *t, int r, const double o[3], const PrismMesh *a) { return qa_build(A, e, t, r, o, a, 1); } + +/* ---- CA(): calibrate ---- */ +static void calib_tree_build(PrismCalib *cb) { + double *xs = malloc((size_t)(cb->n_refs ? cb->n_refs : 1) * sizeof(double)); + double *ys = malloc((size_t)(cb->n_refs ? cb->n_refs : 1) * sizeof(double)); + for (int i = 0; i < cb->n_refs; i++) { xs[i] = cb->refs[i].c->x; ys[i] = cb->refs[i].c->y; } + KdTree *tr = malloc(sizeof(KdTree)); + kd_build(tr, xs, ys, cb->n_refs); + cb->tree = tr; +} + +int prism_calibrate(const PrismFrame *A, const PrismMap *e, const PrismLayout *t, int r, const double o[3], const PrismMesh *a, PrismCalib *out, const char **err) { + double pal[9][3], lab[9][3]; + pal_dump(pal, lab); + memset(out, 0, sizeof(*out)); + /* refs: known cells, keep if symbol 8 or not all channels > glareThreshold */ + out->refs = malloc((size_t)(t->n_known ? t->n_known : 1) * sizeof(PrismRef)); + for (int ci = 0; ci < t->n_known; ci++) { + const PrismCell *tc = t->known[ci]; + int s = known_symbol(tc, r); + double mdx = 0, mdy = 0, smp[3]; + if (a) { double mv[2]; mesh_eval(a, tc->x, tc->y, mv); mdx = mv[0]; mdy = mv[1]; } + sample_cell_ex(A, e, tc, o, mdx, mdy, 0, smp); + if (!(8 == s || !(smp[0] > 0.9 && smp[1] > 0.9 && smp[2] > 0.9))) continue; + PrismRef *rf = &out->refs[out->n_refs]; + rf->c = tc; + rf->o[0] = smp[0]; rf->o[1] = smp[1]; rf->o[2] = smp[2]; + rf->E[0] = pal[s][0]; rf->E[1] = pal[s][1]; rf->E[2] = pal[s][2]; + out->n_refs++; + } + /* normal equations */ + double g[4][4] = {{0}}, h[3][4] = {{0}}; + for (int ri = 0; ri < out->n_refs; ri++) { + double e2[4] = {out->refs[ri].o[0], out->refs[ri].o[1], out->refs[ri].o[2], 1}; + for (int t2 = 0; t2 < 4; t2++) { + for (int A2 = 0; A2 < 4; A2++) g[t2][A2] += e2[t2] * e2[A2]; + for (int r2 = 0; r2 < 3; r2++) h[r2][t2] += e2[t2] * out->refs[ri].E[r2]; + } + } + for (int A2 = 0; A2 < 4; A2++) g[A2][A2] += 0.001; + for (int c = 0; c < 3; c++) { + double gflat[16]; + for (int i2 = 0; i2 < 4; i2++) for (int j = 0; j < 4; j++) gflat[i2 * 4 + j] = g[i2][j]; + if (prism_solve_n(4, gflat, h[c], out->M[c]) != 0) { *err = ERR_SING; return -1; } + } + /* residuals */ + for (int ri = 0; ri < out->n_refs; ri++) { + double *o2 = out->refs[ri].o, *E2 = out->refs[ri].E; + for (int c = 0; c < 3; c++) { + double v = out->M[c][0] * o2[0] + out->M[c][1] * o2[1] + out->M[c][2] * o2[2] + out->M[c][3]; + out->refs[ri].res[c] = E2[c] - v; + } + } + calib_tree_build(out); + /* sigma from pilot residuals */ + double *B = malloc((size_t)(out->n_refs ? out->n_refs : 1) * sizeof(double)); + int nb = 0; + for (int ri = 0; ri < out->n_refs; ri++) { + if (out->refs[ri].c->role != ROLE_PILOT) continue; + double cor[3], u1[3], u2[3]; + calib_correction(out, out->refs[ri].o, out->refs[ri].c, cor); + lab_of(cor, u1); lab_of(out->refs[ri].E, u2); + B[nb++] = sqrt(lab_dist2(u1, u2)); + } + double med = nb ? median_js(B, nb) : 6; + out->sigma = fmax(6, 1.4 * med); + free(B); + return 0; +} + +void calib_correction(const PrismCalib *cb, const double rgb[3], const PrismCell *c, double out[3]) { + double t2[3]; + for (int i = 0; i < 3; i++) t2[i] = cb->M[i][0] * rgb[0] + cb->M[i][1] * rgb[1] + cb->M[i][2] * rgb[2] + cb->M[i][3]; + const KdTree *Q = (const KdTree *)cb->tree; + if (prism_flag_calmed) { + KdHit hits[10]; + int hn = kd_query(Q, c->x, c->y, 10, -1, hits); + for (int i = 0; i < 3; i++) { + double *rr = malloc((size_t)(hn ? hn : 1) * sizeof(double)); + for (int k = 0; k < hn; k++) rr[k] = cb->refs[hits[k].id].res[i]; + double m2 = hn ? median_js(rr, hn) : 0; /* n([]) would be undefined; worker never has <10 refs in calmed mode */ + free(rr); + out[i] = clamp01(t2[i] + m2); + } + return; + } + KdHit hits[6]; + int hn = kd_query(Q, c->x, c->y, 6, -1, hits); + double o2 = 0, a2[3] = {0, 0, 0}; + for (int k = 0; k < hn; k++) { + double w = 1 / (hits[k].d + 0.05); + o2 += w; + for (int i = 0; i < 3; i++) a2[i] += w * cb->refs[hits[k].id].res[i]; + } + for (int i = 0; i < 3; i++) out[i] = clamp01(t2[i] + a2[i] / o2); +} + +void calib_free(PrismCalib *cb) { + if (!cb) return; + free(cb->refs); + if (cb->tree) { + KdTree *tr = (KdTree *)cb->tree; + free((void *)tr->xs); free((void *)tr->ys); + kd_free(tr); free(tr); + } + memset(cb, 0, sizeof(*cb)); +} + +/* ---- BA(): llr ---- */ +void llr_bits(const double rgb[3], int mode, double sigma, int glare, double out[3]) { + if (glare) { out[0] = 0; out[1] = 0; out[2] = 0; return; } + double lab[9][3], pal[9][3], o2[3], h2[8], i2[8]; + pal_dump(pal, lab); + lab_of(rgb, o2); + int na = mode ? 2 : 8; + for (int k = 0; k < na; k++) { + int A2 = mode ? (k ? 8 : 0) : k; + i2[k] = -lab_dist2(o2, lab[A2]) / (2 * sigma * sigma); + } + double g2 = i2[0]; + for (int k = 1; k < na; k++) if (i2[k] > g2) g2 = i2[k]; + for (int k = 0; k < na; k++) h2[k] = js_exp(i2[k] - g2); + int nvals = mode ? 1 : 3; + for (int A2 = 0; A2 < nvals; A2++) { + double t2 = 1e-6, r2 = 1e-6; + for (int k = 0; k < na; k++) { + int v = mode ? (k ? 8 : 0) : k; + int bit = mode ? (0 == v ? 1 : 0) : ((v ^ (v >> 1)) >> (2 - A2)) & 1; + if (bit) t2 += h2[k]; else r2 += h2[k]; + } + out[A2] = fmax(-12, fmin(12, js_log(r2 / t2))); + } +} + +/* ---- fA(): header decode from 24 soft bits (float array) ---- */ +int header_decode24(const float *A, PrismHeader *out, const char **err) { + uint8_t e[24]; + for (int i = 0; i < 24; i++) e[i] = A[i] < 0 ? 1 : 0; + int t2 = 0; + int o = 0, a = 0, i2 = 0, g = 0, l = 0, I = 0; + for (int k = 0; k < 3; k++) o = (o << 1) | e[t2++]; + for (int k = 0; k < 2; k++) a = (a << 1) | e[t2++]; + i2 = e[t2++]; g = e[t2++]; + for (int k = 0; k < 13; k++) l = (l << 1) | e[t2++]; + for (int k = 0; k < 4; k++) I = (I << 1) | e[t2++]; + if (crc4_bits(e, 20) != I || o > 5) { *err = "header:Header checksum did not pass"; return -1; } + PrismCapacity cap; + capacity_get(o, a, i2, &cap); + if (l > cap.payload) { *err = "header:Invalid length"; return -1; } + out->size = o; out->ecc = a; out->mode = i2; out->type = g; out->length = l; + return 0; +} + +/* cA table */ +static int cA_[24]; +static int cA_ready_ = 0; +static void cA_init(void) { + if (cA_ready_) return; + for (int e = 0; e < 24; e++) { + if (e >= 20) { cA_[e] = 1 << (23 - e); continue; } + uint8_t t2[20] = {0}; t2[e] = 1; + cA_[e] = crc4_bits(t2, 20); + } + cA_ready_ = 1; +} + +/* header candidate search: port of the n = (function(A,e,t){...})(h, r.size, o) closure */ +typedef struct { PrismHeader h; double cost; } HCand; +static int cmp_hcost_(const void *pa, const void *pb) { + double d = ((const HCand *)pa)->cost - ((const HCand *)pb)->cost; + return d < 0 ? -1 : d > 0 ? 1 : 0; +} +static HCand hc_[600]; static int nhc_; +static const float *h_hdr_; /* original soft bits (cost source) */ +static float r2_[24]; /* h with forced size/mode bits */ +static int size_, mode_; +static void header_try(const int *subset, int ns) { + int i2; + { + uint8_t ib[24]; + for (int k = 0; k < 24; k++) ib[k] = r2_[k] < 0 ? 1 : 0; + i2 = crc4_bits(ib, 20); + int tail = 0; + for (int k = 20; k < 24; k++) tail = (tail << 1) | ib[k]; + i2 ^= tail; + } + for (int k = 0; k < ns; k++) { + int A3 = subset[k]; + if ((r2_[A3] < 0) != (-r2_[A3] < 0)) i2 ^= cA_[A3]; + } + if (i2) return; + float l2[24]; memcpy(l2, r2_, sizeof l2); + double I2 = 0; + for (int k = 0; k < ns; k++) { l2[subset[k]] = -l2[subset[k]]; I2 += fabs((double)h_hdr_[subset[k]]); } + PrismHeader hd; const char *e2 = 0; + if (header_decode24(l2, &hd, &e2) == 0 && hd.size == size_ && hd.mode == mode_ && nhc_ < 600) { + hc_[nhc_].h = hd; hc_[nhc_].cost = I2; nhc_++; + } +} +/* returns sorted+deduped candidates (up to 12) */ +typedef struct { PrismHeader v[12]; int n; } HList; +static void header_candidates(const float h[24], int size, int mode, HList *out) { + cA_init(); + h_hdr_ = h; size_ = size; mode_ = mode; + memcpy(r2_, h, sizeof r2_); + for (int A2 = 0; A2 < 3; A2++) r2_[A2] = ((size >> (2 - A2)) & 1) ? -36.f : 36.f; + r2_[5] = mode ? -36.f : 36.f; + int o2[20]; int no = 0; + for (int k = 0; k < 24; k++) if (k != 0 && k != 1 && k != 2 && k != 5) o2[no++] = k; + /* stable sort by fabs(h[k]) asc (insertion) */ + for (int i = 1; i < no; i++) { + int c = o2[i], j = i - 1; + while (j >= 0 && fabs((double)h[o2[j]]) > fabs((double)h[c])) { o2[j + 1] = o2[j]; j--; } + o2[j + 1] = c; + } + if (no > 12) no = 12; + nhc_ = 0; + header_try(0, 0); + for (int A2 = 0; A2 < no; A2++) { + header_try(&o2[A2], 1); + for (int e2 = A2 + 1; e2 < no; e2++) { + int s2[2] = {o2[A2], o2[e2]}; + header_try(s2, 2); + for (int t2 = e2 + 1; t2 < no; t2++) { + int s3[3] = {o2[A2], o2[e2], o2[t2]}; + header_try(s3, 3); + } + } + } + /* stable sort by cost (insertion; qsort not stable) */ + for (int i = 1; i < nhc_; i++) { + HCand c = hc_[i]; int j = i - 1; + while (j >= 0 && hc_[j].cost > c.cost) { hc_[j + 1] = hc_[j]; j--; } + hc_[j + 1] = c; + } + /* dedupe by header tuple, keep first; slice 12 */ + out->n = 0; + for (int i = 0; i < nhc_ && out->n < 12; i++) { + int dup = 0; + for (int j = 0; j < out->n; j++) + if (!memcmp(&out->v[j], &hc_[i].h, sizeof(PrismHeader))) { dup = 1; break; } + if (!dup) out->v[out->n++] = hc_[i].h; + } +} + +/* ---- uA(): classify ---- */ +static int uA_impl(const PrismFrame *A, const PrismMap *e, const PrismLayout *r, int o, const double a[3], const PrismMesh *mesh, PrismClassify *out, const char **err, int z) { + memset(out, 0, sizeof(*out)); + if (prism_flag_mix && !o) { + /* uA mix branch: mixRecover(A, mixFit(A, e, r), r) */ + prism_fast_deadline_set(prism_overall_deadline_get()); /* JS uA mix branch */ + double *fit = prism_mix_fit(A, e->h, r); + int *symbols = malloc((size_t)(r->n_cells + 1) * sizeof(int)); + PrismPayload *z = prism_mix_recover(A, fit, r, symbols); + free(fit); free(symbols); + if (z) { + out->mix_decoded = z; + out->header = z->header; + out->headers[0] = z->header; out->n_headers = 1; + out->stream = NULL; out->n_stream = 0; + out->known_match = 1; out->sigma = 6; + return 0; + } + } + PrismCalib cb; + if (z) { memset(&cb, 0, sizeof cb); cb.sigma = 6; } /* uAZ: identity calib */ + else if (prism_calibrate(A, e, r, o, a, mesh, &cb, err) != 0) return -1; + float h[24] = {0}; + for (int hi = 0; hi < r->n_headers; hi++) { + const PrismCell *tc = r->headers[hi]; + double mdx = 0, mdy = 0, smp[3], cor[3], llr[3]; + if (mesh) { double mv[2]; mesh_eval(mesh, tc->x, tc->y, mv); mdx = mv[0]; mdy = mv[1]; } + sample_cell_ex(A, e, tc, a, mdx, mdy, z, smp); + if (z) memcpy(cor, smp, sizeof cor); else calib_correction(&cb, smp, tc, cor); + llr_bits(cor, 1, cb.sigma, 0, llr); + h[tc->header % 24] = (float)((double)h[tc->header % 24] + llr[0]); + } + memcpy(out->hb, h, sizeof h); + HList n; + header_candidates(h, r->size, o, &n); + /* filter: candidates with length 0 must equal fA(h) */ + int w2 = 0; + for (int i = 0; i < n.n; i++) { + if (n.v[i].length != 0) { n.v[w2++] = n.v[i]; continue; } + PrismHeader hd; const char *e2 = 0; + if (header_decode24(h, &hd, &e2) == 0 && !memcmp(&hd, &n.v[i], sizeof(PrismHeader))) n.v[w2++] = n.v[i]; + } + n.n = w2; + if (!n.n) { calib_free(&cb); *err = "header:Header checksum did not pass"; return -1; } + PrismHeader s = n.v[0]; + if (s.size != r->size || s.mode != o) { calib_free(&cb); *err = "header:Header conflicts with geometry"; return -1; } + out->header = s; + out->n_headers = n.n; + memcpy(out->headers, n.v, n.n * sizeof(PrismHeader)); + /* data loop */ + int stride = o ? 1 : 3; + out->n_stream = r->n_data * stride; + out->stream = malloc((size_t)out->n_stream * sizeof(float)); + out->points = malloc((size_t)r->n_data * sizeof(PrismPointConf)); + out->n_points = r->n_data; + out->ext_glare = malloc((size_t)r->n_data * sizeof(int)); out->n_ext_glare = 0; + out->glare_samples = malloc((size_t)r->n_data * sizeof(PrismGlareSample)); out->n_glare = 0; + int f = 0; + for (int di = 0; di < r->n_data; di++) { + const PrismCell *tc = r->data[di]; + double mdx = 0, mdy = 0, I2[3], h2[3], s2[3]; + if (mesh) { double mv[2]; mesh_eval(mesh, tc->x, tc->y, mv); mdx = mv[0]; mdy = mv[1]; } + sample_cell_ex(A, e, tc, a, mdx, mdy, z, I2); + if (z) memcpy(h2, I2, sizeof h2); else calib_correction(&cb, I2, tc, h2); + int n2 = !o && I2[0] > 0.9 && I2[1] > 0.9 && I2[2] > 0.9; + llr_bits(h2, o, cb.sigma, n2, s2); + int ns = o ? 1 : 3; + if (!o && r->size <= 1 && !n2 && I2[0] > 0.7 && I2[1] > 0.7 && I2[2] > 0.7) + out->ext_glare[out->n_ext_glare++] = f; + if (n2 && r->size <= 1) { + out->glare_samples[out->n_glare].at = f; + out->glare_samples[out->n_glare].cv[0] = h2[0]; + out->glare_samples[out->n_glare].cv[1] = h2[1]; + out->glare_samples[out->n_glare].cv[2] = h2[2]; + out->n_glare++; + } + for (int A2 = 0; A2 < ns; A2++) out->stream[f++] = (float)s2[A2]; + double mn = fabs(s2[0]); + for (int A2 = 1; A2 < ns; A2++) if (fabs(s2[A2]) < mn) mn = fabs(s2[A2]); + out->points[di].x = tc->x; out->points[di].y = tc->y; + out->points[di].confidence = mn / 12; + } + /* Veil branch (PrismVeil && !o) */ + if (prism_flag_veil && !o) { + double pal[9][3], lab[9][3]; + pal_dump(pal, lab); + double vP[8][3]; + for (int s2 = 0; s2 < 8; s2++) + for (int c = 0; c < 3; c++) vP[s2][c] = js_pow(fmax(0, fmin(1, pal[s2][c])), 0.4545); + /* vB basis (28 terms) */ + #define VB(x, y, q) do { \ + double u = (2.0 * (x)) / r->W - 1, w2 = (2.0 * (y)) / r->H - 1; \ + int n_ = 0; \ + for (int d = 0; d <= 6; d++) for (int k = 0; k <= d; k++) \ + (q)[n_++] = js_pow(u, d - k) * js_pow(w2, k); \ + } while (0) + typedef struct { double b[28], o[3]; int s; double w; } VPt; + VPt *vA = malloc((size_t)r->n_known * sizeof(VPt)); int nvA = 0; + for (int ci = 0; ci < r->n_known; ci++) { + const PrismCell *tc = r->known[ci]; + int s2 = known_symbol(tc, o); + if (s2 < 0 || s2 >= 8) continue; + double mdx = 0, mdy = 0, smp[3]; + if (mesh) { double mv[2]; mesh_eval(mesh, tc->x, tc->y, mv); mdx = mv[0]; mdy = mv[1]; } + sample_cell_ex(A, e, tc, a, mdx, mdy, z, smp); + VB(tc->x, tc->y, vA[nvA].b); + for (int c = 0; c < 3; c++) vA[nvA].o[c] = js_pow(fmax(0, fmin(1, smp[c])), 0.4545); + vA[nvA].s = s2; vA[nvA].w = 1; + nvA++; + } + VPt *vX = malloc((size_t)r->n_data * sizeof(VPt)); + for (int di = 0; di < r->n_data; di++) { + const PrismCell *tc = r->data[di]; + double mdx = 0, mdy = 0, smp[3]; + if (mesh) { double mv[2]; mesh_eval(mesh, tc->x, tc->y, mv); mdx = mv[0]; mdy = mv[1]; } + sample_cell_ex(A, e, tc, a, mdx, mdy, z, smp); + VB(tc->x, tc->y, vX[di].b); + for (int c = 0; c < 3; c++) vX[di].o[c] = js_pow(fmax(0, fmin(1, smp[c])), 0.4545); + vX[di].s = 0; vX[di].w = 1; + } + if (nvA >= 40) { + const int vN = 28, vM = 56; + /* vS: Gaussian elim, no pivot threshold (dv || 1e-12) */ + void vS(double **Mx, double *y, double *z) { + for (int c = 0; c < vM; c++) { + int p2 = c; + for (int k = c + 1; k < vM; k++) if (fabs(Mx[k][c]) > fabs(Mx[p2][c])) p2 = k; + double *tm = Mx[c]; Mx[c] = Mx[p2]; Mx[p2] = tm; + double ty = y[c]; y[c] = y[p2]; y[p2] = ty; + double dv = Mx[c][c]; if (!(dv != 0.0)) dv = 1e-12; + for (int k = c + 1; k < vM; k++) { + double f2 = Mx[k][c] / dv; + if (f2) { + for (int j = c; j < vM; j++) Mx[k][j] -= f2 * Mx[c][j]; + y[k] -= f2 * y[c]; + } + } + } + for (int c = 0; c < vM; c++) z[c] = 0; + for (int c = vM - 1; c >= 0; c--) { + double sm = y[c]; + for (int j = c + 1; j < vM; j++) sm -= Mx[c][j] * z[j]; + double dv = Mx[c][c]; if (!(dv != 0.0)) dv = 1e-12; + z[c] = sm / dv; + } + } + /* vF: weighted least squares, 3 channels -> cf[3][56] */ + double cf[3][56]; + int npts_cap = nvA + r->n_data; + VPt *pts = malloc((size_t)npts_cap * sizeof(VPt)); + void vF(const VPt *pts2, int npts, double cf2[3][56]) { + for (int c = 0; c < 3; c++) { + double *Mx = calloc((size_t)vM * vM, sizeof(double)); + double *y = calloc(vM, sizeof(double)); + double f2[56]; + for (int p2 = 0; p2 < npts; p2++) { + const VPt *pp = &pts2[p2]; + if (!(pp->w > 0)) continue; + double pc = vP[pp->s][c]; + for (int k = 0; k < vN; k++) { f2[k] = pp->b[k] * pc; f2[vN + k] = pp->b[k]; } + for (int k = 0; k < vM; k++) { + double fk = pp->w * f2[k]; + if (fk == 0) continue; + double *row = Mx + (size_t)k * vM; + for (int j = 0; j <= k; j++) row[j] += fk * f2[j]; + y[k] += fk * pp->o[c]; + } + } + for (int k = 0; k < vM; k++) { + for (int j = k + 1; j < vM; j++) Mx[(size_t)k * vM + j] = Mx[(size_t)j * vM + k]; + Mx[(size_t)k * vM + k] += 1e-6; + } + double **rows = malloc((size_t)vM * sizeof(double *)); + for (int k = 0; k < vM; k++) rows[k] = Mx + (size_t)k * vM; + double z[56]; + vS(rows, y, z); + memcpy(cf2[c], z, sizeof z); + free(rows); free(Mx); free(y); + } + } + /* vC: distances to 8 symbols */ + void vC(double cf2[3][56], const VPt *p2, double outd[8]) { + for (int s2 = 0; s2 < 8; s2++) { + double d = 0; + for (int c = 0; c < 3; c++) { + double av = 0, bv = 0; + for (int k = 0; k < vN; k++) { av += cf2[c][k] * p2->b[k]; bv += cf2[c][vN + k] * p2->b[k]; } + double df = vP[s2][c] * av + bv - p2->o[c]; + d += df * df; + } + outd[s2] = sqrt(d); + } + } + int vNn = r->n_data; + double *vDs = malloc((size_t)vNn * 8 * sizeof(double)); + int *vPr = malloc((size_t)vNn * sizeof(int)); + double *vMg = malloc((size_t)vNn * sizeof(double)); + void vCl(double cf2[3][56]) { + for (int k = 0; k < vNn; k++) { + double *d = vDs + (size_t)k * 8; + vC(cf2, &vX[k], d); + int b0 = 0, b1 = -1; + for (int s2 = 1; s2 < 8; s2++) { + if (d[s2] < d[b0]) { b1 = b0; b0 = s2; } + else if (b1 < 0 || d[s2] < d[b1]) b1 = s2; + } + vPr[k] = b0; vMg[k] = d[b1] - d[b0]; + } + } + /* initial: vA only, w=1 */ + memcpy(pts, vA, (size_t)nvA * sizeof(VPt)); + vF(pts, nvA, cf); + vCl(cf); + for (int it = 0; it < 3; it++) { + int np = 0; + for (int i = 0; i < nvA; i++) { pts[np] = vA[i]; pts[np].w = 1; np++; } + for (int k = 0; k < vNn; k++) { + pts[np] = vX[k]; + pts[np].s = vPr[k]; + pts[np].w = fmin(1, vMg[k] / 0.078); + np++; + } + vF(pts, np, cf); + vCl(cf); + } + double *vBest = malloc((size_t)(vNn ? vNn : 1) * sizeof(double)); + for (int k = 0; k < vNn; k++) vBest[k] = vDs[(size_t)k * 8 + vPr[k]]; + double vSg = 0.015; + if (vNn) { + double med = median_js(vBest, vNn); + vSg = fmax(0.015, (1.3 * med) / 1.54); + } + for (int k = 0; k < vNn; k++) { + double *d = vDs + (size_t)k * 8; + double mn = d[0]; + for (int s2 = 1; s2 < 8; s2++) if (d[s2] < mn) mn = d[s2]; + double pp[8]; + for (int s2 = 0; s2 < 8; s2++) pp[s2] = js_exp(-(d[s2] * d[s2] - mn * mn) / (2 * vSg * vSg)); + for (int b = 0; b < 3; b++) { + double n0 = 1e-9, n1 = 1e-9; + for (int s2 = 0; s2 < 8; s2++) { + if (((s2 ^ (s2 >> 1)) >> (2 - b)) & 1) n1 += pp[s2]; else n0 += pp[s2]; + } + out->stream[k * 3 + b] = (float)fmax(-12, fmin(12, js_log(n0 / n1))); + } + double mnc = fabs((double)out->stream[k * 3]); + if (fabs((double)out->stream[k * 3 + 1]) < mnc) mnc = fabs((double)out->stream[k * 3 + 1]); + if (fabs((double)out->stream[k * 3 + 2]) < mnc) mnc = fabs((double)out->stream[k * 3 + 2]); + out->points[k].confidence = mnc / 12; + } + free(vBest); free(vDs); free(vPr); free(vMg); free(pts); + } + free(vA); free(vX); + #undef VB + } + /* DD branch (PrismDD && !o) */ + if (prism_flag_dd && !o) { + double pal[9][3], lab[9][3]; + pal_dump(pal, lab); + /* G gamma */ + /* I3: 3x3 inverse via cofactors */ + typedef struct { double m[3], v[9], dt; } Gauss8; + /* est: weighted mean + cov inverse */ + int est(const double (*P2)[3], const double *W2, int n2, Gauss8 *g2) { + double sw = 0, m2[3] = {0, 0, 0}; + for (int j = 0; j < n2; j++) { sw += W2[j]; for (int k = 0; k < 3; k++) m2[k] += W2[j] * P2[j][k]; } + for (int k = 0; k < 3; k++) m2[k] /= sw; + double cm[9] = {0}; + for (int j = 0; j < n2; j++) + for (int x = 0; x < 3; x++) + for (int y = 0; y < 3; y++) + cm[x * 3 + y] += W2[j] * (P2[j][x] - m2[x]) * (P2[j][y] - m2[y]); + for (int k = 0; k < 9; k++) cm[k] = cm[k] / sw + (k % 4 == 0 ? 3e-4 : 0); + double p0 = cm[0], p1 = cm[1], p2 = cm[2], p3 = cm[3], p4 = cm[4], p5 = cm[5], p6 = cm[6], p7 = cm[7], p8 = cm[8]; + double A1 = p4 * p8 - p5 * p7, B1 = -(p3 * p8 - p5 * p6), C1 = p3 * p7 - p4 * p6; + double dt = p0 * A1 + p1 * B1 + p2 * C1; + g2->dt = dt; + g2->m[0] = m2[0]; g2->m[1] = m2[1]; g2->m[2] = m2[2]; + g2->v[0] = A1 / dt; + g2->v[1] = -(p1 * p8 - p2 * p7) / dt; + g2->v[2] = (p1 * p5 - p2 * p4) / dt; + g2->v[3] = B1 / dt; + g2->v[4] = (p0 * p8 - p2 * p6) / dt; + g2->v[5] = -(p0 * p5 - p2 * p3) / dt; + g2->v[6] = C1 / dt; + g2->v[7] = -(p0 * p7 - p1 * p6) / dt; + g2->v[8] = (p0 * p4 - p1 * p3) / dt; + return 0; + } + double (*K2[8])[3] = {0}; int nK[8] = {0}, capK[8] = {0}; + for (int ri = 0; ri < cb.n_refs; ri++) { + int s2 = known_symbol(cb.refs[ri].c, o); + if (s2 < 0 || s2 > 7) continue; + if (nK[s2] == capK[s2]) { capK[s2] = capK[s2] ? capK[s2] * 2 : 16; K2[s2] = realloc(K2[s2], (size_t)capK[s2] * sizeof *K2[s2]); } + for (int c = 0; c < 3; c++) K2[s2][nK[s2]][c] = js_pow(fmax(0, fmin(1, cb.refs[ri].o[c])), 0.4545); + nK[s2]++; + } + int okk = 1; + for (int s2 = 0; s2 < 8; s2++) if (nK[s2] < 6) okk = 0; + if (okk && nK[0] && isfinite(K2[0][0][0])) { + Gauss8 M[8]; + double *ones = malloc(1 * sizeof(double)); + for (int s2 = 0; s2 < 8; s2++) { + ones = realloc(ones, (size_t)nK[s2] * sizeof(double)); + for (int i = 0; i < nK[s2]; i++) ones[i] = 1; + est(K2[s2], ones, nK[s2], &M[s2]); + } + free(ones); + /* DU/DK: data cells whose stream triple isn't all-zero */ + double (*DU)[3] = malloc((size_t)r->n_data * sizeof *DU); + int *DK = malloc((size_t)r->n_data * sizeof(int)); + int nDU = 0, ddf = 0, ddk = 0; + for (int di = 0; di < r->n_data; di++) { + if (!((double)out->stream[ddf] == 0 && (double)out->stream[ddf + 1] == 0 && (double)out->stream[ddf + 2] == 0)) { + const PrismCell *tc = r->data[di]; + double mdx = 0, mdy = 0, smp[3]; + if (mesh) { double mv[2]; mesh_eval(mesh, tc->x, tc->y, mv); mdx = mv[0]; mdy = mv[1]; } + sample_cell_ex(A, e, tc, a, mdx, mdy, z, smp); + for (int c = 0; c < 3; c++) DU[nDU][c] = js_pow(fmax(0, fmin(1, smp[c])), 0.4545); + DK[nDU] = ddk; + nDU++; + } + ddf += 3; ddk++; + } + /* PO: softmax of Gaussian log-likelihoods over 8 classes */ + void PO(const double u[3], double pp[8]) { + double ll[8]; + for (int s2 = 0; s2 < 8; s2++) { + double d0 = u[0] - M[s2].m[0], d1 = u[1] - M[s2].m[1], d2 = u[2] - M[s2].m[2]; + const double *v = M[s2].v; + ll[s2] = -0.5 * (d0 * (v[0] * d0 + v[1] * d1 + v[2] * d2) + + d1 * (v[3] * d0 + v[4] * d1 + v[5] * d2) + + d2 * (v[6] * d0 + v[7] * d1 + v[8] * d2)) - + 0.5 * js_log(fmax(1e-12, M[s2].dt)); + } + double mx = ll[0]; + for (int s2 = 1; s2 < 8; s2++) if (ll[s2] > mx) mx = ll[s2]; + double sm = 0; + for (int s2 = 0; s2 < 8; s2++) { pp[s2] = js_exp(ll[s2] - mx); sm += pp[s2]; } + for (int s2 = 0; s2 < 8; s2++) pp[s2] /= sm; + } + /* 3 EM iterations */ + for (int it = 0; it < 3; it++) { + double (*PS)[8] = malloc((size_t)nDU * sizeof *PS); + for (int j = 0; j < nDU; j++) PO(DU[j], PS[j]); + for (int s2 = 0; s2 < 8; s2++) { + int n2 = nDU + nK[s2]; + double (*P2)[3] = malloc((size_t)n2 * sizeof *P2); + double *W2 = malloc((size_t)n2 * sizeof(double)); + for (int j = 0; j < nDU; j++) { memcpy(P2[j], DU[j], 3 * sizeof(double)); W2[j] = PS[j][s2] + 1e-9; } + for (int j = 0; j < nK[s2]; j++) { memcpy(P2[nDU + j], K2[s2][j], 3 * sizeof(double)); W2[nDU + j] = 1; } + est(P2, W2, n2, &M[s2]); + free(P2); free(W2); + } + free(PS); + } + for (int j = 0; j < nDU; j++) { + double pp[8]; + PO(DU[j], pp); + int f2 = DK[j] * 3; + for (int b = 0; b < 3; b++) { + double n0 = 1e-6, n1 = 1e-6; + for (int s2 = 0; s2 < 8; s2++) { + if (((s2 ^ (s2 >> 1)) >> (2 - b)) & 1) n1 += pp[s2]; else n0 += pp[s2]; + } + out->stream[f2 + b] = (float)fmax(-12, fmin(12, js_log(n0 / n1))); + } + double mnc = fabs((double)out->stream[DK[j] * 3]); + if (fabs((double)out->stream[DK[j] * 3 + 1]) < mnc) mnc = fabs((double)out->stream[DK[j] * 3 + 1]); + if (fabs((double)out->stream[DK[j] * 3 + 2]) < mnc) mnc = fabs((double)out->stream[DK[j] * 3 + 2]); + out->points[DK[j]].confidence = mnc / 12; + } + free(DU); free(DK); + } + for (int s2 = 0; s2 < 8; s2++) free(K2[s2]); + } + /* knownMatch */ + { + int c = 0; + for (int ri = 0; ri < cb.n_refs; ri++) { + double cor[3]; + calib_correction(&cb, cb.refs[ri].o, cb.refs[ri].c, cor); + double d2; + if (nearest_sym(cor, o, &d2) == known_symbol(cb.refs[ri].c, o)) c++; + } + out->known_match = cb.n_refs ? (double)c / cb.n_refs : (0.0 / 0.0); + } + out->sigma = cb.sigma; + calib_free(&cb); + return 0; +} + +int uA_classify(const PrismFrame *A, const PrismMap *e, const PrismLayout *r, int o, const double a[3], const PrismMesh *mesh, PrismClassify *out, const char **err) { + return uA_impl(A, e, r, o, a, mesh, out, err, 0); +} + +/* uAZ(): uA with identity calibration (sigma 6) and single-center samples (earlyTry148) */ +int uAZ_classify(const PrismFrame *A, const PrismMap *e, const PrismLayout *r, int o, const double a[3], const PrismMesh *mesh, PrismClassify *out, const char **err) { + return uA_impl(A, e, r, o, a, mesh, out, err, 1); +} + +void classify_free(PrismClassify *c) { + if (!c) return; + free(c->stream); free(c->ext_glare); free(c->glare_samples); free(c->points); + if (c->mix_decoded) { payload_free(c->mix_decoded); free(c->mix_decoded); } + memset(c, 0, sizeof(*c)); +} diff --git a/ports/c/reader/prism_decode.c b/ports/c/reader/prism_decode.c new file mode 100644 index 0000000..a161cd4 --- /dev/null +++ b/ports/c/reader/prism_decode.c @@ -0,0 +1,479 @@ +/* prism_decode.c - bit-exact C port of the worker stream-decode layer: + * PADK, padVote, PLcd, PLfb, dA2, dA0, dA, wA, mA. + * Float discipline: JS numbers are doubles; Float32Array stores round to + * float32. All soft-stream arithmetic follows that. */ +#include +#include +#include +#include +#include +#include "prism_reader.h" + +/* ---- budget (e()) ---- */ +static double budget_deadline; /* 0 = disabled */ +static double now_seconds(void) { + struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); + return (double)ts.tv_sec + (double)ts.tv_nsec / 1e9; +} +void prism_budget_set(double seconds_from_now) { + budget_deadline = seconds_from_now > 0 ? now_seconds() + seconds_from_now : 0; +} + +/* ---- PrismFastDeadline / PrismOverallDeadline (0 = disabled, JS Infinity) ---- */ +static double fast_deadline, overall_deadline; +double prism_now_seconds(void) { return now_seconds(); } +void prism_fast_deadline_set(double v) { fast_deadline = v; } +double prism_fast_deadline_get(void) { return fast_deadline; } +void prism_overall_deadline_set(double v) { overall_deadline = v; } +double prism_overall_deadline_get(void) { return overall_deadline; } +int prism_fast_deadline_hit(void) { return fast_deadline && now_seconds() > fast_deadline; } +static int budget_check(PrismErr *err) { /* e(): -1 throw when exceeded */ + if (budget_deadline && now_seconds() > budget_deadline) { + if (err) { strcpy(err->stage, "budget"); strcpy(err->msg, "Image needs a clearer view. Processing limit reached."); } + return -1; + } + return 0; +} + +/* ---- PADK ---- */ +static int PADK(int o) { + uint32_t x = (uint32_t)((int32_t)(o + (int32_t)0x9e3779b9)) * (uint32_t)0x85ebca6b; + x ^= x >> 13; + x *= (uint32_t)0xc2b2ae35; + x ^= x >> 16; + return (int)(x & 255); +} + +static int dA2(const PrismHeader *A, const float *r, int PK, PrismPayload *out, PrismErr *err); + +/* ---- padVote ---- */ +static int pad_vote(const PrismHeader *h, const float *st) { /* true default */ + if (!(h->length > 0)) return 1; + PrismCapacity c; capacity_get(h->size, h->ecc, h->mode, &c); + uint8_t by[8192]; + for (int i = 0; i < c.n; i++) { + int v = 0; + for (int k = 0; k < 8; k++) v = (v << 1) | (st[8 * i + k] < 0 ? 1 : 0); + by[i] = (uint8_t)v; + } + int offs[32], a = 0, maxn = 0; + for (int j = 0; j < c.n_blocks; j++) { offs[j] = a; a += c.blocks[j].k; if (c.blocks[j].n > maxn) maxn = c.blocks[j].n; } + int at = 0, z = 0, q = 0; + for (int p = 0; p < maxn; p++) + for (int j = 0; j < c.n_blocks; j++) { + const PrismBlock *b = &c.blocks[j]; + if (p < b->n) { + if (p < b->k && offs[j] + p >= h->length + 4) { + int v = by[at]; + if (v == 0) z++; + if (v == PADK(offs[j] + p)) q++; + } + at++; + } + } + return q >= z; +} + +/* ---- PLcd: data cells sorted center-distance desc (b = floor(sqrt(dx^2+dy^2)/3)), index asc tie ---- */ +typedef struct { const PrismCell *c; int k; int b; } CdEnt; +static int cmp_cd(const void *pa, const void *pb) { + const CdEnt *p = pa, *q = pb; + if (p->b != q->b) return q->b - p->b; + return p->k - q->k; +} + +/* ---- RS candidate bookkeeping for dA2 ---- */ +typedef struct { uint8_t data[256]; int corrected, erasures; double score; int seq; } RsCand; +typedef struct { + int n, nsym, k, offset; + uint8_t bytes[256]; float conf[256]; uint8_t masks[256]; + int order[256]; + RsCand cands[8]; int n_cands, cand_seq; + uint8_t tried[128]; +} RsBlock; + +typedef struct { + const PrismHeader *A; + RsBlock *l; int n_blocks; + long attempts; /* h */ + long valid; /* n */ + uint8_t *found; /* payload bytes when CRC passes */ + int f_corrected, f_erasures; + long crc_tried; /* e */ +} D2Ctx; + +static void cand_push(RsBlock *e, const uint8_t *data, int corrected, int erasures, double score) { + for (int i = 0; i < e->n_cands; i++) { + if (!memcmp(e->cands[i].data, data, (size_t)e->k)) return; /* dedupe */ + } + if (e->n_cands == 8) { + /* JS push + sort + truncate to 8: keep only if it beats the worst */ + if (!(score < e->cands[7].score)) return; + } + RsCand *c = &e->cands[e->n_cands < 8 ? e->n_cands++ : 7]; + memcpy(c->data, data, (size_t)e->k); + c->corrected = corrected; c->erasures = erasures; c->score = score; c->seq = e->cand_seq++; + /* stable sort by score asc (insertion sort, ties keep earlier seq first) */ + for (int i = e->n_cands - 1; i > 0; i--) { + if (e->cands[i].score < e->cands[i - 1].score) { RsCand tmp = e->cands[i]; e->cands[i] = e->cands[i - 1]; e->cands[i - 1] = tmp; } + else break; + } +} + +/* utf-8 fatal validation (TextDecoder fatal:true) */ +static int utf8_valid(const uint8_t *p, int n) { + int i = 0; + while (i < n) { + uint8_t b = p[i]; + if (b < 0x80) { i++; continue; } + int need; uint32_t minc, c; + if ((b & 0xe0) == 0xc0) { need = 1; c = b & 0x1f; minc = 0x80; } + else if ((b & 0xf0) == 0xe0) { need = 2; c = b & 0x0f; minc = 0x800; } + else if ((b & 0xf8) == 0xf0) { need = 3; c = b & 0x07; minc = 0x10000; } + else return 0; + if (i + need >= n) return 0; + for (int k = 1; k <= need; k++) { + uint8_t cb = p[i + k]; + if ((cb & 0xc0) != 0x80) return 0; + c = (c << 6) | (cb & 0x3f); + } + if (c < minc || c > 0x10ffff || (c >= 0xd800 && c <= 0xdfff)) return 0; + i += need + 1; + } + return 1; +} + +/* Q(): DFS over candidate combinations, CRC check, cap 1024 */ +static void d2_dfs(D2Ctx *cx, int o, uint8_t *a, int na, int ic, int ig) { + if (cx->found || cx->crc_tried >= 1024) return; + if (o == cx->n_blocks) { + cx->crc_tried++; + int len = cx->A->length; + uint32_t want = 0; + for (int e = len; e < len + 4; e++) want = (want << 8) | a[e]; + if (crc32_bytes(a, (size_t)len) == want) { + if (!cx->A->type && !utf8_valid(a, len)) return; + cx->found = malloc((size_t)len); + memcpy(cx->found, a, (size_t)len); + cx->f_corrected = ic; cx->f_erasures = ig; + } + return; + } + RsBlock *b = &cx->l[o]; + for (int i = 0; i < b->n_cands; i++) { + memcpy(a + na, b->cands[i].data, (size_t)b->k); + d2_dfs(cx, o + 1, a, na + b->k, ic + b->cands[i].corrected, ig + b->cands[i].erasures); + if (cx->found || cx->crc_tried >= 1024) return; + } +} +static int d2_combine(D2Ctx *cx, uint8_t *work) { /* Q(): 1 when found */ + for (int i = 0; i < cx->n_blocks; i++) if (!cx->l[i].n_cands) return 0; + d2_dfs(cx, 0, work, 0, 0, 0); + return cx->found != NULL; +} + +/* dA2 */ +static int dA2_impl(const PrismHeader *A, const float *r, int PK, int z, PrismPayload *out, PrismErr *err) { + PrismCapacity o; capacity_get(A->size, A->ecc, A->mode, &o); + RsBlock *l = calloc((size_t)o.n_blocks, sizeof(RsBlock)); + D2Ctx cx = { .A = A, .l = l, .n_blocks = o.n_blocks }; + int I = 0; + for (int bi = 0; bi < o.n_blocks; bi++) l[bi].n = o.blocks[bi].n, l[bi].nsym = o.blocks[bi].nsym, l[bi].k = o.blocks[bi].k; + /* interleaved de-interleave in column order */ + int maxn = 0; for (int bi = 0; bi < o.n_blocks; bi++) if (l[bi].n > maxn) maxn = l[bi].n; + /* assemble hard bytes + conf + masks per stream byte */ + uint8_t *ab = malloc((size_t)o.n); float *cf = malloc((size_t)o.n * sizeof(float)); uint8_t *mk = malloc((size_t)o.n); + for (int i = 0; i < o.n; i++) { + int e = 0; float t = 12; + for (int k = 0; k < 8; k++) { + float a = r[8 * i + k]; + e = (e << 1) | (a < 0 ? 1 : 0); + if (a == 0) mk[i] |= 1 << (7 - k); + if (fabsf(a) < t) t = fabsf(a); + } + ab[i] = (uint8_t)e; cf[i] = t; + } + for (int p = 0; p < maxn; p++) + for (int bi = 0; bi < o.n_blocks; bi++) + if (p < l[bi].n) { l[bi].bytes[p] = ab[I]; l[bi].conf[p] = cf[I]; l[bi].masks[p] = mk[I]; I++; } + free(ab); free(cf); free(mk); + int s = 0; + for (int bi = 0; bi < o.n_blocks; bi++) { + RsBlock *e = &l[bi]; + e->offset = s; + for (int t = 0; t < e->k; t++) + if (A->length > 0 && s + t >= A->length + 4) { + e->bytes[t] = (uint8_t)(PK ? PADK(s + t) : 0); + e->conf[t] = 12; e->masks[t] = 0; + } + s += e->k; + for (int i = 0; i < e->n; i++) e->order[i] = i; + /* stable sort by conf asc (insertion; JS sort stable) */ + for (int i = 1; i < e->n; i++) { + int v = e->order[i], j = i - 1; + while (j >= 0 && e->conf[e->order[j]] > e->conf[v]) { e->order[j + 1] = e->order[j]; j--; } + e->order[j + 1] = v; + } + } + uint8_t *work = malloc((size_t)o.k + 8); + /* C(e, r) with padding verification inline */ + #define D2_TRY(e_, r_) do { \ + RsBlock *eb = (e_); int rc_ = (r_); \ + if (!eb->tried[rc_]) { \ + eb->tried[rc_] = 1; cx.attempts++; \ + uint8_t buf[256]; memcpy(buf, eb->bytes, (size_t)eb->n); \ + int eras[128]; for (int i = 0; i < rc_; i++) eras[i] = eb->order[i]; \ + const char *rerr = NULL; \ + int corr = rs_decode(buf, eb->n, eb->nsym, eras, rc_, &rerr); \ + if (corr >= 0) { \ + int padok = 1; \ + for (int t = 0; t < eb->k; t++) \ + if (eb->offset + t >= A->length + 4 && (PK ? PADK(eb->offset + t) : 0) != buf[t]) { padok = 0; break; } \ + if (padok) { \ + cx.valid++; \ + double sc = 0; \ + for (int i = 0; i < eb->n; i++) if (buf[i] != eb->bytes[i]) sc += 0.02 + eb->conf[i]; \ + cand_push(eb, buf, corr, rc_, sc); \ + } \ + } \ + } \ + } while (0) + + if (z) { /* dA2Z: direct check only (erasures 0 per block), then combine */ + for (int bi = 0; bi < o.n_blocks; bi++) D2_TRY(&l[bi], 0); + if (d2_combine(&cx, work)) goto done; + free(work); free(l); + strcpy(err->stage, "RS"); strcpy(err->msg, "Direct check did not pass"); + return -1; + } + /* ladder 1: 0, .25, .5, .75, 1 of nsym (deduped), break when candidates */ + for (int bi = 0; bi < o.n_blocks; bi++) { + RsBlock *e = &l[bi]; + int prev = -1; + for (int fi = 0; fi < 5; fi++) { + /* JS Math.round: half up (toward +inf) */ + int v = (int)floor((double)e->nsym * ((double)fi / 4.0) + 0.5); + if (v == prev) continue; + prev = v; + D2_TRY(e, v); + if (e->n_cands) break; + } + } + if (d2_combine(&cx, work)) goto done; + /* ladder 2: 0..nsym step 2 */ + for (int bi = 0; bi < o.n_blocks; bi++) { + RsBlock *e = &l[bi]; + for (int r = 0; r <= e->nsym; r += 2) D2_TRY(e, r); + } + if (d2_combine(&cx, work)) goto done; + /* bit-erasure RS for small sizes */ + if (A->size <= 1) { + for (int bi = 0; bi < o.n_blocks; bi++) { + RsBlock *t = &l[bi]; + if (budget_check(err)) { free(l); free(work); return -1; } + uint8_t rb[256]; const char *rerr = NULL; + int corr = rs_recover_bits(t->bytes, t->masks, t->n, t->nsym, rb, &rerr); + if (corr < 0) continue; + int bad = 0; + for (int e = 0; e < t->k; e++) + if (t->offset + e >= A->length + 4 && (PK ? PADK(t->offset + e) : 0) != rb[e]) { bad = 1; break; } + if (bad) continue; + int dup = 0; + for (int i = 0; i < t->n_cands; i++) if (!memcmp(t->cands[i].data, rb, (size_t)t->k)) { dup = 1; break; } + if (!dup) { + if (t->n_cands < 8) { + RsCand *c = &t->cands[t->n_cands++]; + memcpy(c->data, rb, (size_t)t->k); + c->corrected = corr; c->erasures = 0; c->score = 0; c->seq = t->cand_seq++; + /* JS pushes WITHOUT re-sorting here */ + } + } + } + if (d2_combine(&cx, work)) goto done; + } + free(work); + int some_empty = 0; + for (int bi = 0; bi < o.n_blocks; bi++) if (!l[bi].n_cands) some_empty = 1; + free(l); + if (some_empty) { strcpy(err->stage, "RS"); strcpy(err->msg, "Error correction could not recover this image"); } + else { strcpy(err->stage, "CRC"); strcpy(err->msg, "Payload checksum did not pass"); } + return -1; +done:; + int len = A->length; + out->bytes = cx.found; out->n_bytes = len; + out->header = *A; + out->corrected = cx.f_corrected; out->erasures = cx.f_erasures; + if (!A->type) { + out->text = malloc((size_t)len + 1); + memcpy(out->text, cx.found, (size_t)len); out->text[len] = 0; + } else out->text = NULL; + free(l); free(work); + return 0; + #undef D2_TRY +} + +/* dA0 */ +static int dA0(const PrismHeader *A, const float *r, PrismPayload *out, PrismErr *err) { + int t = pad_vote(A, r); + PrismErr e1; + if (!dA2(A, r, t, out, err)) return 0; + e1 = *err; + if (!dA2(A, r, !t, out, err)) return 0; + *err = e1; + return -1; +} + +static int dA2(const PrismHeader *A, const float *r, int PK, PrismPayload *out, PrismErr *err) { + return dA2_impl(A, r, PK, 0, out, err); +} +static int dA2Z(const PrismHeader *A, const float *r, int PK, PrismPayload *out, PrismErr *err) { + return dA2_impl(A, r, PK, 1, out, err); +} + +/* dAZ: padVote then dA2Z(+PK), on fail dA2Z(!PK), rethrow first error */ +int prism_dAZ(const PrismHeader *A, const float *r, PrismPayload *out, PrismErr *err) { + int t = pad_vote(A, r); + PrismErr e1; + if (!dA2Z(A, r, t, out, err)) return 0; + e1 = *err; + if (!dA2Z(A, r, !t, out, err)) return 0; + *err = e1; + return -1; +} + +/* PLfb: center-distance reordered erasure fallback */ +static int plfb(const PrismHeader *h, const float *st, PrismPayload *out, PrismErr *err) { + const PrismLayout *l = layout_get(h->size); + int N = l->n_data, m = h->mode ? 1 : 3; + CdEnt *cd = malloc((size_t)N * sizeof(CdEnt)); + double cx = l->W / 2, cy = l->H / 2; + for (int k = 0; k < N; k++) { + double dx = l->data[k]->x - cx, dy = l->data[k]->y - cy; + cd[k].c = l->data[k]; cd[k].k = k; + cd[k].b = (int)floor(sqrt(dx * dx + dy * dy) / 3); + } + qsort(cd, (size_t)N, sizeof(CdEnt), cmp_cd); + float *s2 = malloc((size_t)N * m * sizeof(float)); + for (int k = 0; k < N; k++) { + int p = -1; /* l.pos: data-list position of this cell index */ + for (int i = 0; i < N; i++) if (l->data[i]->index == cd[k].c->index) { p = i; break; } + for (int j = 0; j < m; j++) s2[k * m + j] = st[p * m + j]; + } + int n1 = (int)floor((double)N * 0.12); + double ga = 0, gc = 0; long gb = 0, gd = 0; + for (int k = 0; k < N; k++) { + double v = 0; + for (int j = 0; j < m; j++) v += fabs((double)s2[k * m + j]); + if (k >= N - n1) { ga += v; gb++; } + else if (k < N / 2) { gc += v; gd++; } + } + if (ga / (double)gb > (0.9 * gc) / (double)gd) { free(cd); free(s2); strcpy(err->stage, "logo"); strcpy(err->msg, "center-distance gate"); return -1; } + static const double fr[4] = {0.1, 0.18, 0.26, 0.34}; + PrismErr last = *err; + for (int fi = 0; fi < 4; fi++) { + float *s3 = malloc((size_t)N * m * sizeof(float)); + memcpy(s3, s2, (size_t)N * m * sizeof(float)); + for (int k = (int)floor((double)N * (1 - fr[fi])); k < N; k++) + for (int j = 0; j < m; j++) s3[k * m + j] = 0; + int rc = dA0(h, s3, out, err); + free(s3); + if (!rc) { free(cd); free(s2); return 0; } + last = *err; + } + free(cd); free(s2); + *err = last; + return -1; +} + +int prism_nologo = 0; /* globalThis.PRISM_NOLOGO */ + +/* dA */ +int prism_decode_stream(const PrismHeader *h, const float *st, PrismPayload *out, PrismErr *err) { + PrismErr e1; + if (!dA0(h, st, out, err)) return 0; + e1 = *err; + if (!prism_nologo) { + if (!plfb(h, st, out, err)) return 0; + } + *err = e1; + return -1; +} + +/* wA */ +static int wA(const PrismClassify *A, const float *stream, PrismPayload *out, PrismErr *err) { + PrismErr last; int have_last = 0; + int nh = A->n_headers ? A->n_headers : 1; + for (int ri = 0; ri < nh; ri++) { + const PrismHeader *r = A->n_headers ? &A->headers[ri] : &A->header; + if (budget_check(err)) return -1; + for (int o = 0; o < 2; o++) { + const float *a = stream; + float *white = NULL; + if (o) { + prism_rng g; rng_seed(&g, 49374); + white = malloc((size_t)A->n_stream * sizeof(float)); + for (int i = 0; i < A->n_stream; i++) white[i] = rng_next(&g) < 0.5 ? -stream[i] : stream[i]; + a = white; + } + int rc = prism_decode_stream(r, a, out, err); + free(white); + if (!rc) { out->variant = o ? "generator-whitened" : "original"; return 0; } + last = *err; have_last = 1; + } + } + if (have_last) *err = last; + else { strcpy(err->stage, "header"); strcpy(err->msg, "Header checksum did not pass"); } + return -1; +} + +/* mA */ +int prism_decode_class(const PrismClassify *A, PrismPayload *out, PrismErr *err) { + if (A->mix_decoded) { /* deep copy: caller owns out (JS shares the object) */ + *out = *A->mix_decoded; + out->bytes = malloc((size_t)out->n_bytes); memcpy(out->bytes, A->mix_decoded->bytes, (size_t)out->n_bytes); + out->text = A->mix_decoded->text ? strdup(A->mix_decoded->text) : NULL; + return 0; + } + PrismErr t; + if (!wA(A, A->stream, out, &t)) return 0; + /* glare-sample retry */ + if (!A->n_glare || A->known_match < 0.85) { *err = t; goto outer; } + if (budget_check(err)) return -1; + { + float *r = malloc((size_t)A->n_stream * sizeof(float)); + memcpy(r, A->stream, (size_t)A->n_stream * sizeof(float)); + for (int i = 0; i < A->n_glare; i++) { + double llr[3]; + llr_bits(A->glare_samples[i].cv, 0, A->sigma, 0, llr); + for (int j = 0; j < 3; j++) { + int at = A->glare_samples[i].at + j; + if (at >= 0 && at < A->n_stream) r[at] = (float)(0.001 * llr[j]); + } + } + int rc = wA(A, r, out, &t); + free(r); + if (!rc) return 0; + } +outer: + if (!A->n_ext_glare || A->known_match < 0.85) { *err = t; return -1; } + if (budget_check(err)) return -1; + { + float *r = malloc((size_t)A->n_stream * sizeof(float)); + memcpy(r, A->stream, (size_t)A->n_stream * sizeof(float)); + for (int i = 0; i < A->n_ext_glare; i++) + for (int j = 0; j < 3; j++) { + int at = A->ext_glare[i] + j; + if (at >= 0 && at < A->n_stream) r[at] = 0; + } + int rc = wA(A, r, out, &t); + free(r); + if (!rc) return 0; + } + *err = t; + return -1; +} + +void payload_free(PrismPayload *p) { + free(p->bytes); free(p->text); + p->bytes = NULL; p->text = NULL; +} diff --git a/ports/c/reader/prism_detect.c b/ports/c/reader/prism_detect.c new file mode 100644 index 0000000..bb04ad7 --- /dev/null +++ b/ports/c/reader/prism_detect.c @@ -0,0 +1,668 @@ +/* prism_detect.c - exact port of r721 detect: lApq (quad detect), lA (legacy boundary). + All float32/double semantics replicated: Float32Array stores round to float, + accumulations in double. JS Math.* via prism_jsmath. */ +#include +#include +#include +#include +#include "prism_reader.h" +#include "prism_jsmath.h" +#include "prism_detect.h" +#include + +static double clampd(double v, double lo, double hi) { return v < lo ? lo : (v > hi ? hi : v); } + +/* sRGB encode q() = srgb_q from image layer */ +extern double srgb_q(double A); + +/* ---- dynamic int-point list ---- */ +typedef struct { int *x, *y; int n, cap; } IPts; +static void ipush(IPts *a, int x, int y) { + if (a->n == a->cap) { a->cap = a->cap ? a->cap * 2 : 256; a->x = realloc(a->x, a->cap * sizeof(int)); a->y = realloc(a->y, a->cap * sizeof(int)); } + a->x[a->n] = x; a->y[a->n] = y; a->n++; +} +static void ifree(IPts *a) { free(a->x); free(a->y); a->x = a->y = 0; a->n = a->cap = 0; } +/* JS tA() sorts the boundary array in place (x, then y) before building the hull; + * the component keeps that sorted array and iA's float sums run in this order. + * Boundary pixels are unique, so any correct sort gives the identical order. */ +static int cmp_xy_(const void *pa, const void *pb) { + const int *a = pa, *b = pb; + if (a[0] != b[0]) return a[0] < b[0] ? -1 : 1; + if (a[1] != b[1]) return a[1] < b[1] ? -1 : 1; + return 0; +} +static void isort_xy(IPts *a) { + int (*p)[2] = malloc((size_t)a->n * sizeof *p); + for (int i = 0; i < a->n; i++) { p[i][0] = a->x[i]; p[i][1] = a->y[i]; } + qsort(p, a->n, sizeof *p, cmp_xy_); + for (int i = 0; i < a->n; i++) { a->x[i] = p[i][0]; a->y[i] = p[i][1]; } + free(p); +} + +/* ---- dynamic double-point list ---- */ +typedef struct { double *x, *y; int n, cap; } DPts; +static void dpush(DPts *a, double x, double y) { + if (a->n == a->cap) { a->cap = a->cap ? a->cap * 2 : 64; a->x = realloc(a->x, a->cap * sizeof(double)); a->y = realloc(a->y, a->cap * sizeof(double)); } + a->x[a->n] = x; a->y[a->n] = y; a->n++; +} +static void dfree(DPts *a) { free(a->x); free(a->y); a->x = a->y = 0; a->n = a->cap = 0; } + +/* cross product eA on int points */ +static long long icr(long ax, long ay, long bx, long by, long cx, long cy) { + return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax); +} +/* eA on doubles */ +static double dcr(double ax, double ay, double bx, double by, double cx, double cy) { + return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax); +} + +/* tA: convex hull of int points (monotone chain), JS semantics: + sorts a COPY by (x,y); lower then upper; pops both ends; concat. */ +static void hull_of(const int *xs, const int *ys, int n, IPts *out) { + int *ix = malloc(n * sizeof(int)); + for (int i = 0; i < n; i++) ix[i] = i; + /* stable sort by (x,y) */ + for (int i = 1; i < n; i++) { int k = ix[i], j = i - 1; while (j >= 0 && (xs[ix[j]] > xs[k] || (xs[ix[j]] == xs[k] && ys[ix[j]] > ys[k]))) { ix[j + 1] = ix[j]; j--; } ix[j + 1] = k; } + IPts lo = {0}, up = {0}; + for (int i = 0; i < n; i++) { + int p = ix[i]; + while (lo.n >= 2 && icr(lo.x[lo.n - 2], lo.y[lo.n - 2], lo.x[lo.n - 1], lo.y[lo.n - 1], xs[p], ys[p]) <= 0) lo.n--; + ipush(&lo, xs[p], ys[p]); + } + for (int i = n - 1; i >= 0; i--) { + int p = ix[i]; + while (up.n >= 2 && icr(up.x[up.n - 2], up.y[up.n - 2], up.x[up.n - 1], up.y[up.n - 1], xs[p], ys[p]) <= 0) up.n--; + ipush(&up, xs[p], ys[p]); + } + lo.n--; up.n--; + for (int i = 0; i < lo.n; i++) ipush(out, lo.x[i], lo.y[i]); + for (int i = 0; i < up.n; i++) ipush(out, up.x[i], up.y[i]); + ifree(&lo); ifree(&up); + free(ix); +} + +/* rA: polygon area (int points) */ +static double poly_area_i(const int *xs, const int *ys, int n) { + double a = 0; + for (int i = 0; i < n; i++) { + int j = (i + 1) % n; + a += (double)xs[i] * ys[j] - (double)ys[i] * xs[j]; + } + return fabs(a) / 2; +} + +/* iA: line fit -> out[3] = {g=-sin(t), l=cos(t), c=g*mx+l*my} */ +static void line_fit(const double *xs, const double *ys, int n, double out[3]) { + double e = 0, t = 0; + for (int i = 0; i < n; i++) { e += xs[i]; t += ys[i]; } + e /= n; t /= n; + double r = 0, o = 0, a = 0; + for (int i = 0; i < n; i++) { + double A = xs[i] - e, g = ys[i] - t; + r += A * A; o += A * g; a += g * g; + } + double i2 = 0.5 * js_atan2(2 * o, r - a); + double g = -js_sin(i2), l = js_cos(i2); + out[0] = g; out[1] = l; out[2] = g * e + l * t; +} +/* iA over int points */ +static void line_fit_i(const int *xs, const int *ys, int n, double out[3]) { + double e = 0, t = 0; + for (int i = 0; i < n; i++) { e += xs[i]; t += ys[i]; } + e /= n; t /= n; + double r = 0, o = 0, a = 0; + for (int i = 0; i < n; i++) { + double A = xs[i] - e, g = ys[i] - t; + r += A * A; o += A * g; a += g * g; + } + double i2 = 0.5 * js_atan2(2 * o, r - a); + double g = -js_sin(i2), l = js_cos(i2); + out[0] = g; out[1] = l; out[2] = g * e + l * t; +} + +/* gA: line intersection; returns 0 ok, -1 parallel */ +static int line_isect(const double A[3], const double B[3], double *x, double *y) { + double t = A[0] * B[1] - A[1] * B[0]; + if (fabs(t) < 1e-6) return -1; + *x = (A[2] * B[1] - A[1] * B[2]) / t; + *y = (A[0] * B[2] - A[2] * B[0]) / t; + return 0; +} + +/* oA: separable morphology with clamped window. o=1 dilate(or), 0 erode(and). */ +static void morph_u8(const uint8_t *A, int e, int t, int r, int o, uint8_t *out) { + uint8_t *a = malloc((size_t)e * t); + for (int i = 0; i < t; i++) + for (int x = 0; x < e; x++) { + int g = o ? 0 : 1; + for (int d = -r; d <= r; d++) { + int rr = (int)clampd(x + d, 0, e - 1); + if (o) g |= A[i * e + rr]; else g &= A[i * e + rr]; + } + a[i * e + x] = (uint8_t)g; + } + for (int i = 0; i < t; i++) + for (int x = 0; x < e; x++) { + int g = o ? 0 : 1; + for (int d = -r; d <= r; d++) { + int rr = (int)clampd(i + d, 0, t - 1); + if (o) g |= a[rr * e + x]; else g &= a[rr * e + x]; + } + out[i * e + x] = (uint8_t)g; + } + free(a); +} + +/* aA: separable smooth (box mean, o=0) or sliding max (o=1), radius r, clamped window. + Float32 in/out; sums in double; deque max exactly as JS. */ +static void smooth_f32(const float *A, int e, int t, int r, int o, float *out) { + float *a = malloc((size_t)e * t * sizeof(float)); + for (int i = 0; i < t; i++) { + /* horizontal */ + double l = 0; + int g = 0, tn = 0; + int *qx = malloc((e + 2 * r + 2) * sizeof(int)); float *qv = malloc((e + 2 * r + 2) * sizeof(float)); + for (int h = -r; h < e + r; h++) { + float n = A[i * e + (int)clampd(h, 0, e - 1)]; + if (o) { + while (tn > g && qv[tn - 1] <= n) tn--; + qx[tn] = h; qv[tn] = n; tn++; + while (qx[g] < h - 2 * r) g++; + } else { + l += n; + if (h > r) l -= A[i * e + (int)clampd(h - 2 * r - 1, 0, e - 1)]; + } + if (h >= r) a[i * e + h - r] = o ? qv[g] : (float)(l / (2 * r + 1)); + } + free(qx); free(qv); + } + for (int x = 0; x < e; x++) { + /* vertical */ + double l = 0; + int g = 0, tn = 0; + int *qy = malloc((t + 2 * r + 2) * sizeof(int)); float *qv = malloc((t + 2 * r + 2) * sizeof(float)); + for (int n2 = -r; n2 < t + r; n2++) { + float s = a[(int)clampd(n2, 0, t - 1) * e + x]; + if (o) { + while (tn > g && qv[tn - 1] <= s) tn--; + qy[tn] = n2; qv[tn] = s; tn++; + while (qy[g] < n2 - 2 * r) g++; + } else { + l += s; + if (n2 > r) l -= a[(int)clampd(n2 - 2 * r - 1, 0, t - 1) * e + x]; + } + if (n2 >= r) out[(n2 - r) * e + x] = o ? qv[g] : (float)(l / (2 * r + 1)); + } + free(qy); free(qv); + } + free(a); +} + +/* lApq-local box: edge-aware mean, radius r; Float32 in/out, double sums */ +static float *box_local(const float *a, int w, int h, int r) { + size_t n = (size_t)w * h; + float *t = malloc(n * sizeof(float)), *o = malloc(n * sizeof(float)); + for (int y = 0; y < h; y++) + for (int x = 0; x < w; x++) { + double s = 0; int c = 0; + for (int d = -r; d <= r; d++) { + int xx = x + d; + if (xx >= 0 && xx < w) { s += a[y * w + xx]; c++; } + } + t[y * w + x] = (float)(s / c); + } + for (int y = 0; y < h; y++) + for (int x = 0; x < w; x++) { + double s = 0; int c = 0; + for (int d = -r; d <= r; d++) { + int yy = y + d; + if (yy >= 0 && yy < h) { s += t[yy * w + x]; c++; } + } + o[y * w + x] = (float)(s / c); + } + free(t); + return o; +} + +/* candidate output list */ +void cand_push(PrismCandList *l, const double q[4][2], int sz, int r0) { + if (l->n == l->cap) { l->cap = l->cap ? l->cap * 2 : 32; l->v = realloc(l->v, l->cap * sizeof(PrismCand)); } + memcpy(l->v[l->n].p, q, sizeof(double) * 8); + l->v[l->n].sz = sz; l->v[l->n].r0 = r0; + l->n++; +} +void cand_free(PrismCandList *l) { free(l->v); l->v = 0; l->n = l->cap = 0; } + +/* ---- lApq: quad detection ---- */ +int detect_lapq(const PrismFrame *f, PrismCandList *out) { + int sc = (int)fmax(1, floor(fmax(f->w, f->h) / 360 + 0.5)); /* Math.round */ + int w = f->w / sc, h = f->h / sc; + size_t n = (size_t)w * h; + float *S = malloc(n * sizeof(float)); + for (int y = 0; y < h; y++) + for (int x = 0; x < w; x++) { + size_t i = ((size_t)(y * sc + (sc >> 1)) * f->w + x * sc + (sc >> 1)) * 3; + float m = f->p[i]; + if (f->p[i + 1] < m) m = f->p[i + 1]; + if (f->p[i + 2] < m) m = f->p[i + 2]; + S[y * w + x] = (float)js_pow(m, 0.4545); + } + float *Sb = box_local(S, w, h, 2); + free(S); S = Sb; + /* Otsu */ + double hist[256] = {0}; + for (size_t i = 0; i < n; i++) { + int b = (int)floor((double)S[i] * 255 + 0.5); + if (b < 0) b = 0; if (b > 255) b = 255; + hist[b]++; + } + double sum = 0; + for (int i = 0; i < 256; i++) sum += i * hist[i]; + double wb = 0, sb = 0, bt = 0; + int th0 = 128; + for (int i = 0; i < 256; i++) { + wb += hist[i]; + if (!wb) continue; + double wf = n - wb; + if (!wf) break; + sb += i * hist[i]; + double mb = sb / wb, mf = (sum - sb) / wf, v = wb * wf * (mb - mf) * (mb - mf); + if (v > bt) { bt = v; th0 = i; } + } + const double mg = 5.196; + static const int dths[4] = {0, 14, 28, -14}; + for (int di = 0; di < 4; di++) { + int th = th0 + dths[di]; + float *m = malloc(n * sizeof(float)); + for (size_t i = 0; i < n; i++) m[i] = (double)S[i] * 255 > th ? 1 : 0; + float *mb2 = box_local(m, w, h, 2); + free(m); m = mb2; + float *m2 = malloc(n * sizeof(float)); + for (size_t i = 0; i < n; i++) m2[i] = (double)m[i] > 0.01 ? 1 : 0; + float *m2b = box_local(m2, w, h, 2); + free(m2); m2 = m2b; + uint8_t *mk = malloc(n); + for (size_t i = 0; i < n; i++) mk[i] = (double)m2[i] > 0.99 ? 1 : 0; + free(m); free(m2); + uint8_t *seen = calloc(n, 1); + int *qu = malloc(n * sizeof(int)); + double bestA = 0; + IPts bestHull = {0}; + for (size_t k = 0; k < n; k++) { + if (!mk[k] || seen[k]) continue; + int hd = 0, tl = 1; + IPts bd = {0}; + qu[0] = (int)k; seen[k] = 1; + while (hd < tl) { + int p = qu[hd++], x = p % w, y = (p - x) / w; + int ed = 0; + int qs[4]; int nq = 0; + qs[nq++] = x > 0 ? p - 1 : -1; + qs[nq++] = x < w - 1 ? p + 1 : -1; + qs[nq++] = y > 0 ? p - w : -1; + qs[nq++] = y < h - 1 ? p + w : -1; + for (int qi = 0; qi < 4; qi++) { + int q = qs[qi]; + if (q < 0 || !mk[q]) { ed = 1; continue; } + if (!seen[q]) { seen[q] = 1; qu[tl++] = q; } + } + if (ed) ipush(&bd, x, y); + } + if (tl < 0.03 * (double)n || tl > 0.9 * (double)n) { ifree(&bd); continue; } + /* sort bd by (x,y) - stable */ + for (int i = 1; i < bd.n; i++) { + int kx = bd.x[i], ky = bd.y[i], j = i - 1; + while (j >= 0 && (bd.x[j] > kx || (bd.x[j] == kx && bd.y[j] > ky))) { bd.x[j + 1] = bd.x[j]; bd.y[j + 1] = bd.y[j]; j--; } + bd.x[j + 1] = kx; bd.y[j + 1] = ky; + } + /* hull */ + IPts hl = {0}; + { + /* lower */ + IPts lo = {0}, up = {0}; + for (int i = 0; i < bd.n; i++) { + while (lo.n >= 2 && icr(lo.x[lo.n - 2], lo.y[lo.n - 2], lo.x[lo.n - 1], lo.y[lo.n - 1], bd.x[i], bd.y[i]) <= 0) lo.n--; + ipush(&lo, bd.x[i], bd.y[i]); + } + for (int i = bd.n - 1; i >= 0; i--) { + while (up.n >= 2 && icr(up.x[up.n - 2], up.y[up.n - 2], up.x[up.n - 1], up.y[up.n - 1], bd.x[i], bd.y[i]) <= 0) up.n--; + ipush(&up, bd.x[i], bd.y[i]); + } + lo.n--; up.n--; + for (int i = 0; i < lo.n; i++) ipush(&hl, lo.x[i], lo.y[i]); + for (int i = 0; i < up.n; i++) ipush(&hl, up.x[i], up.y[i]); + ifree(&lo); ifree(&up); + } + if (hl.n < 4) { ifree(&hl); ifree(&bd); continue; } + double ar = poly_area_i(hl.x, hl.y, hl.n); + if (ar > bestA) { + bestA = ar; + ifree(&bestHull); + bestHull = hl; + /* keep bd of best? JS keeps bestBd but never uses it later */ + } else { + ifree(&hl); + } + ifree(&bd); + } + free(seen); free(qu); free(mk); + if (!bestHull.n) continue; + /* polygon simplify to 4 (int arithmetic) */ + IPts po = {0}; + for (int i = 0; i < bestHull.n; i++) ipush(&po, bestHull.x[i], bestHull.y[i]); + ifree(&bestHull); + while (po.n > 4) { + long long mn = (long long)1e18; int at = 0; + for (int i = 0; i < po.n; i++) { + int ai = (i + po.n - 1) % po.n, bi = (i + 1) % po.n; + long long v = llabs(icr(po.x[ai], po.y[ai], po.x[bi], po.y[bi], po.x[i], po.y[i])); + if (v < mn) { mn = v; at = i; } + } + memmove(po.x + at, po.x + at + 1, (po.n - at - 1) * sizeof(int)); + memmove(po.y + at, po.y + at + 1, (po.n - at - 1) * sizeof(int)); + po.n--; + } + long long sa = 0; + for (int i = 0; i < 4; i++) { + int j = (i + 1) % 4; + sa += (long long)po.x[i] * po.y[j] - (long long)po.x[j] * po.y[i]; + } + if (sa < 0) { + for (int i = 0; i < 2; i++) { int tx = po.x[i], ty = po.y[i]; po.x[i] = po.x[3 - i]; po.y[i] = po.y[3 - i]; po.x[3 - i] = tx; po.y[3 - i] = ty; } + } + /* scale to full res */ + DPts P = {0}; + for (int i = 0; i < 4; i++) dpush(&P, (po.x[i] + 0.5) * sc, (po.y[i] + 0.5) * sc); + ifree(&po); + /* edge refinement */ + { + double ln[4][4]; int lok[4]; + for (int i = 0; i < 4; i++) { + double ax = P.x[i], ay = P.y[i], bx = P.x[(i + 1) % 4], by = P.y[(i + 1) % 4]; + double dx = bx - ax, dy = by - ay; + double L = js_hypot2(dx, dy); + double nx = dy / L, ny = -dx / L; + DPts pts = {0}; + for (double t = 0.15; t <= 0.851; t += 0.035) { + double px = ax + t * dx, py = ay + t * dy; + double vi = 0, vo = 0; int ci = 0, co = 0, bad = 0; + for (double d = -3 * sc - 2; d <= -2 * sc; d += 1) { + double v = detect_gx(f, px + nx * d, py + ny * d); + if (v < 0) { bad = 1; break; } + vi += v; ci++; + } + if (!bad) for (double d = 2 * sc; d <= 3 * sc + 2; d += 1) { + double v = detect_gx(f, px + nx * d, py + ny * d); + if (v < 0) { bad = 1; break; } + vo += v; co++; + } + if (bad) continue; + vi /= ci; vo /= co; + if (vi - vo < 0.06) continue; + double mid = (vi + vo) / 2; + double prev = detect_gx(f, px - nx * 5 * sc, py - ny * 5 * sc), pd = -5 * sc; + if (prev < 0) continue; + double hit = 0; int have = 0; + for (double d = -5 * sc + 0.5; d <= 5 * sc; d += 0.5) { + double v = detect_gx(f, px + nx * d, py + ny * d); + if (v < 0) break; + if (prev >= mid && v < mid) { hit = pd + ((prev - mid) / (prev - v)) * (d - pd); have = 1; break; } + prev = v; pd = d; + } + if (have) dpush(&pts, px + nx * hit, py + ny * hit); + } + if (pts.n < 6) { lok[i] = 0; dfree(&pts); continue; } + double fl[4] = {0, 0, 0, 0}; + for (int it = 0; it < 3; it++) { + double mx = 0, my = 0; + for (int p2 = 0; p2 < pts.n; p2++) { mx += pts.x[p2]; my += pts.y[p2]; } + mx /= pts.n; my /= pts.n; + double sxx = 0, sxy = 0, syy = 0; + for (int p2 = 0; p2 < pts.n; p2++) { + double u = pts.x[p2] - mx, v = pts.y[p2] - my; + sxx += u * u; sxy += u * v; syy += v * v; + } + double tt = 0.5 * js_atan2(2 * sxy, sxx - syy); + double cx = js_cos(tt), cy = js_sin(tt); + fl[0] = mx; fl[1] = my; fl[2] = cx; fl[3] = cy; + /* filter */ + DPts kept = {0}; + for (int p2 = 0; p2 < pts.n; p2++) + if (fabs((pts.x[p2] - mx) * cy - (pts.y[p2] - my) * cx) < 2) dpush(&kept, pts.x[p2], pts.y[p2]); + if (kept.n < 6 || kept.n == pts.n) { dfree(&kept); break; } + dfree(&pts); pts = kept; + } + memcpy(ln[i], fl, sizeof fl); + lok[i] = 1; + dfree(&pts); + } + /* new corners */ + double np[4][2]; + for (int i = 0; i < 4; i++) { + int i1 = (i + 3) % 4, i2 = i; + if (!lok[i1] || !lok[i2]) { np[i][0] = P.x[i]; np[i][1] = P.y[i]; continue; } + double *l1 = ln[i1], *l2 = ln[i2]; + double det = l1[2] * l2[3] - l1[3] * l2[2]; + if (fabs(det) < 0.1) { np[i][0] = P.x[i]; np[i][1] = P.y[i]; continue; } + double t = ((l2[0] - l1[0]) * l2[3] - (l2[1] - l1[1]) * l2[2]) / det; + double x = l1[0] + t * l1[2], y = l1[1] + t * l1[3]; + if (js_hypot2(x - P.x[i], y - P.y[i]) < 14 * sc) { np[i][0] = x; np[i][1] = y; } + else { np[i][0] = P.x[i]; np[i][1] = P.y[i]; } + } + for (int i = 0; i < 4; i++) { P.x[i] = np[i][0]; P.y[i] = np[i][1]; } + } + /* candidates for each size and rotation */ + for (int sz = 0; sz < 6; sz++) { + const PrismLayout *l = layout_get(sz); + double PW = l->W + 2 * mg, PH = l->H + 2 * mg; + for (int r = 0; r < 4; r++) { + double q[4][2]; + for (int i = 0; i < 4; i++) { q[i][0] = P.x[(i + r) % 4]; q[i][1] = P.y[(i + r) % 4]; } + double src[4][2] = {{0, 0}, {PW, 0}, {PW, PH}, {0, PH}}; + PrismMap hh; + if (homography(src, q, &hh) != 0) continue; + double c[4][2]; + double cc[4][2] = {{mg, mg}, {l->W + mg, mg}, {l->W + mg, l->H + mg}, {mg, l->H + mg}}; + for (int i = 0; i < 4; i++) map_point(&hh, cc[i][0], cc[i][1], &c[i][0], &c[i][1]); + cand_push(out, c, sz, 1); + } + } + dfree(&P); + } + free(S); + return 0; +} + +/* gx used by lApq edge refinement: min-channel bilinear, pow 0.4545; -1 if out of bounds */ +double detect_gx(const PrismFrame *f, double x, double y) { + if (x < 0 || y < 0 || x > f->w - 1.001 || y > f->h - 1.001) return -1; + int x0 = (int)x, y0 = (int)y; + double tx = x - x0, ty = y - y0; + size_t i = ((size_t)y0 * f->w + x0) * 3, j = i + (size_t)f->w * 3; + double mni = f->p[i]; if (f->p[i + 1] < mni) mni = f->p[i + 1]; if (f->p[i + 2] < mni) mni = f->p[i + 2]; + double mni3 = f->p[i + 3]; if (f->p[i + 4] < mni3) mni3 = f->p[i + 4]; if (f->p[i + 5] < mni3) mni3 = f->p[i + 5]; + double mnj = f->p[j]; if (f->p[j + 1] < mnj) mnj = f->p[j + 1]; if (f->p[j + 2] < mnj) mnj = f->p[j + 2]; + double mnj3 = f->p[j + 3]; if (f->p[j + 4] < mnj3) mnj3 = f->p[j + 4]; if (f->p[j + 5] < mnj3) mnj3 = f->p[j + 5]; + double v = (mni * (1 - tx) + mni3 * tx) * (1 - ty) + (mnj * (1 - tx) + mnj3 * tx) * ty; + if (v < 0) v = 0; + return js_pow(v, 0.4545); +} + +/* ---- lA: legacy boundary detect. Returns 0 ok, -1 "no code", -2 "no edges". ---- */ +int detect_la(const PrismFrame *A, PrismCandList *out) { + const double detectionWidth = 320, saturation = 0.25, darkness = 0.55; + double e = fmin(1, detectionWidth / fmax(A->w, A->h)); + int r = (int)floor(A->w * e + 0.5), o = (int)floor(A->h * e + 0.5); + size_t n = (size_t)r * o; + float *a = malloc(n * sizeof(float)), *i8 = malloc(n * sizeof(float)); + static double QT[8194]; static int qt_init = 0; + if (!qt_init) { for (int k = 0; k < 8194; k++) QT[k] = srgb_q(k / 8192.0); qt_init = 1; } + { + const float *P = A->p; + int W3 = 3 * A->w; + double XM = A->w - 1, YM = A->h - 1; + for (int t = 0; t < o; t++) { + double Y = t / e; + for (int o2 = 0; o2 < r; o2++) { + double X = o2 / e; + double l, I; + if (X < 0 || Y < 0 || X >= XM || Y >= YM) { l = 1; I = 1; } + else { + int x0 = (int)floor(X), y0 = (int)floor(Y); + double fx = X - x0, fy = Y - y0; + size_t b = 3 * ((size_t)y0 * A->w + x0); + double c0 = (P[b] * (1 - fx) + P[b + 3] * fx) * (1 - fy) + (P[b + W3] * (1 - fx) + P[b + W3 + 3] * fx) * fy; + double c1 = (P[b + 1] * (1 - fx) + P[b + 4] * fx) * (1 - fy) + (P[b + W3 + 1] * (1 - fx) + P[b + W3 + 4] * fx) * fy; + double c2 = (P[b + 2] * (1 - fx) + P[b + 5] * fx) * (1 - fy) + (P[b + W3 + 2] * (1 - fx) + P[b + W3 + 5] * fx) * fy; + l = c0 > c1 ? (c0 > c2 ? c0 : c2) : c1 > c2 ? c1 : c2; + I = c0 < c1 ? (c0 < c2 ? c0 : c2) : c1 < c2 ? c1 : c2; + double ql; + if (!(l < 1)) ql = srgb_q(l); + else { double u = l * 8192; int k = (int)u; ql = QT[k] + (QT[k + 1] - QT[k]) * (u - k); } + if (I == l) I = ql; + else if (!(I < 1)) I = srgb_q(I); + else { double u = I * 8192; int k = (int)u; I = QT[k] + (QT[k + 1] - QT[k]) * (u - k); } + l = ql; + } + a[t * r + o2] = (float)l; + i8[t * r + o2] = (float)(l ? (l - I) / l : 0); + } + } + } + float *g1 = malloc(n * sizeof(float)); + smooth_f32(a, r, o, 7, 1, g1); + float *g = malloc(n * sizeof(float)); + smooth_f32(g1, r, o, 15, 0, g); + free(g1); + uint8_t *I = malloc(n); + for (size_t i = 0; i < n; i++) + I[i] = ((double)i8[i] > saturation && (double)a[i] > 0.15) || (double)a[i] < darkness * fmax((double)g[i], 0.4) ? 1 : 0; + free(g); + uint8_t *I2 = malloc(n); + morph_u8(I, r, o, 2, 1, I2); + uint8_t *I3 = malloc(n); + morph_u8(I2, r, o, 2, 0, I3); + free(I); free(I2); I = I3; + /* components */ + uint8_t *h8 = calloc(n, 1); + int *nq = malloc(n * sizeof(int)); + typedef struct { IPts hu; int tail; double ar; IPts boundary; int ord; } Comp; + Comp *comps = malloc(64 * sizeof(Comp)); + int ncomp = 0, ccap = 64; + for (size_t Ai = 0; Ai < n; Ai++) { + if (!I[Ai] || h8[Ai]) continue; + int e2 = 0, t2 = 1; + IPts bd = {0}; + nq[0] = (int)Ai; h8[Ai] = 1; + while (e2 < t2) { + int A2 = nq[e2++], ix = A2 % r, gy = A2 / r, l2 = 0; + int es[4]; + es[0] = ix > 0 ? A2 - 1 : -1; + es[1] = ix < r - 1 ? A2 + 1 : -1; + es[2] = gy > 0 ? A2 - r : -1; + es[3] = gy < o - 1 ? A2 + r : -1; + for (int q2 = 0; q2 < 4; q2++) { + int e3 = es[q2]; + if (e3 < 0 || !I[e3]) l2 = 1; + else if (!h8[e3]) { h8[e3] = 1; nq[t2++] = e3; } + } + if (l2) ipush(&bd, ix, gy); + } + if (t2 < 100) { ifree(&bd); continue; } + isort_xy(&bd); /* tA(a) sorts a in place; boundary stays sorted */ + IPts hu = {0}; + hull_of(bd.x, bd.y, bd.n, &hu); + if (hu.n == 0) { ifree(&hu); ifree(&bd); continue; } + double ar = poly_area_i(hu.x, hu.y, hu.n); + int mnx = hu.x[0], mxx = hu.x[0], mny = hu.y[0], mxy = hu.y[0]; + for (int i2 = 1; i2 < hu.n; i2++) { + if (hu.x[i2] < mnx) mnx = hu.x[i2]; if (hu.x[i2] > mxx) mxx = hu.x[i2]; + if (hu.y[i2] < mny) mny = hu.y[i2]; if (hu.y[i2] > mxy) mxy = hu.y[i2]; + } + double Q = (double)(mxx - mnx) / (double)(mxy - mny); + if ((double)t2 / ar < 0.04 || Q < 0.4 || Q > 2.5) { ifree(&hu); ifree(&bd); continue; } + if (ncomp == ccap) { ccap *= 2; comps = realloc(comps, ccap * sizeof(Comp)); } + comps[ncomp].hu = hu; comps[ncomp].tail = t2; comps[ncomp].ar = ar; comps[ncomp].boundary = bd; comps[ncomp].ord = ncomp; + ncomp++; + } + free(h8); free(nq); free(I); + if (!ncomp) { free(a); free(i8); free(comps); return -1; } + /* stable sort desc by ar */ + for (int i = 1; i < ncomp; i++) { Comp c = comps[i]; int j = i - 1; while (j >= 0 && comps[j].ar < c.ar) { comps[j + 1] = comps[j]; j--; } comps[j + 1] = c; } + int found = 0; + for (int ci = 0; ci < ncomp && ci < 3; ci++) { + Comp *cp = &comps[ci]; + /* simplify: t = hull as double points */ + DPts t = {0}; + for (int i = 0; i < cp->hu.n; i++) dpush(&t, cp->hu.x[i], cp->hu.y[i]); + while (t.n > 4) { + double best = 1.0 / 0.0; int at = 0; + for (int i = 0; i < t.n; i++) { + int pi = (i + t.n - 1) % t.n, ni = (i + 1) % t.n; + double v = fabs(dcr(t.x[pi], t.y[pi], t.x[i], t.y[i], t.x[ni], t.y[ni])) / js_hypot2(t.x[ni] - t.x[pi], t.y[ni] - t.y[pi]); + if (v < best) { best = v; at = i; } + } + if (best > 0.7) break; + memmove(t.x + at, t.x + at + 1, (t.n - at - 1) * sizeof(double)); + memmove(t.y + at, t.y + at + 1, (t.n - at - 1) * sizeof(double)); + t.n--; + } + /* edges: 4 longest */ + typedef struct { int i; double ax, ay, bx, by, len; } Edge; + Edge *edges = malloc(t.n * sizeof(Edge)); + for (int i = 0; i < t.n; i++) { + int ni = (i + 1) % t.n; + edges[i].i = i; edges[i].ax = t.x[i]; edges[i].ay = t.y[i]; + edges[i].bx = t.x[ni]; edges[i].by = t.y[ni]; + edges[i].len = js_hypot2(t.x[i] - t.x[ni], t.y[i] - t.y[ni]); + } + /* sort desc len (stable), take 4, sort asc i (stable) */ + for (int i = 1; i < t.n; i++) { Edge c = edges[i]; int j = i - 1; while (j >= 0 && edges[j].len < c.len) { edges[j + 1] = edges[j]; j--; } edges[j + 1] = c; } + Edge four[4]; + for (int i = 0; i < 4; i++) four[i] = edges[i]; + for (int i = 1; i < 4; i++) { Edge c = four[i]; int j = i - 1; while (j >= 0 && four[j].i > c.i) { four[j + 1] = four[j]; j--; } four[j + 1] = c; } + free(edges); + double ls[4][3]; + int ok = 1; + for (int i = 0; i < 4; i++) { + double dx = four[i].bx - four[i].ax, dy = four[i].by - four[i].ay; + double l = js_hypot2(dx, dy); + /* boundary filter |eA|/l < 2 */ + double *fx = malloc(cp->boundary.n * sizeof(double)), *fy = malloc(cp->boundary.n * sizeof(double)); + int fn = 0; + for (int b = 0; b < cp->boundary.n; b++) + if (fabs(dcr(four[i].ax, four[i].ay, four[i].bx, four[i].by, cp->boundary.x[b], cp->boundary.y[b])) / l < 2) { + fx[fn] = cp->boundary.x[b]; fy[fn] = cp->boundary.y[b]; fn++; + } + if (fn >= 2) line_fit(fx, fy, fn, ls[i]); + else { double ex[2] = {four[i].ax, four[i].bx}, ey[2] = {four[i].ay, four[i].by}; line_fit(ex, ey, 2, ls[i]); } + free(fx); free(fy); + } + /* corners */ + double quad[4][2]; + for (int i = 0; i < 4; i++) { + if (line_isect(ls[(i + 3) % 4], ls[i], &quad[i][0], &quad[i][1]) != 0) { ok = 0; break; } + quad[i][0] = (quad[i][0] + 0.5) / e; + quad[i][1] = (quad[i][1] + 0.5) / e; + } + if (ok) { cand_push(out, quad, -1, 0); found++; } + dfree(&t); + } + for (int i = 0; i < ncomp; i++) { ifree(&comps[i].hu); ifree(&comps[i].boundary); } + free(comps); free(a); free(i8); + if (!found) return -2; + return 0; +} + +/* lAp: lApq candidates + lA candidates (errors swallowed as in JS) */ +int detect_lap(const PrismFrame *f, PrismCandList *out, char *err, size_t errlen) { + int na = out->n; + detect_lapq(f, out); /* lApq never throws in JS except OOM */ + int ra = out->n - na; + int rb = detect_la(f, out); + if (rb != 0 && ra == 0) { + if (err) snprintf(err, errlen, "%s", rb == -1 ? "No code found. Use a plain background with a wide white margin." : "Could not fit four edges"); + return rb; + } + return 0; +} diff --git a/ports/c/reader/prism_detect.h b/ports/c/reader/prism_detect.h new file mode 100644 index 0000000..6b14bf2 --- /dev/null +++ b/ports/c/reader/prism_detect.h @@ -0,0 +1,13 @@ +#ifndef PRISM_DETECT_H +#define PRISM_DETECT_H +#include "prism_reader.h" +#include +typedef struct { double p[4][2]; int sz; int r0; } PrismCand; /* sz=-1: unknown (legacy lA) */ +typedef struct { PrismCand *v; int n, cap; } PrismCandList; +void cand_push(PrismCandList *l, const double q[4][2], int sz, int r0); +void cand_free(PrismCandList *l); +int detect_lapq(const PrismFrame *f, PrismCandList *out); /* lApq */ +int detect_la(const PrismFrame *f, PrismCandList *out); /* lA: 0 ok, -1 no code, -2 no edges */ +int detect_lap(const PrismFrame *f, PrismCandList *out, char *err, size_t errlen); /* lAp */ +double detect_gx(const PrismFrame *f, double x, double y); +#endif diff --git a/ports/c/reader/prism_distfit.c b/ports/c/reader/prism_distfit.c new file mode 100644 index 0000000..a78a31d --- /dev/null +++ b/ports/c/reader/prism_distfit.c @@ -0,0 +1,1097 @@ +/* prism_distfit.c - PrismLocal.normalize + PrismDistance.fields + + * detectTexture + PrismDistFit.read, bit-exact port of the readable JS + * fallbacks in the r721 worker (Build 136, commit 362c870d). The WASM + * implementations were verified bit-identical to these fallbacks (fields, + * normalize, morph, cost) on clean/blur/small/bent scenes. + * + * Skipped as dead code: the 19x19 sample grid in DistFit.read (its result + * is discarded in the JS). Budget checks inert (oracle freezes the clock). + */ +#include "prism_reader.h" +#include "prism_detect.h" +#include +#include +#include +#include + +extern double js_hypot2(double x, double y); +extern double js_atan2(double y, double x); +extern double js_sin(double x); +extern double js_cos(double x); + +static double clamp01(double A) { return A < 0 ? 0 : A > 1 ? 1 : A; } +static double eA_(const double A[2], const double e[2], const double t[2]) { + return (e[0] - A[0]) * (t[1] - A[1]) - (e[1] - A[1]) * (t[0] - A[0]); +} +static int js_round(double x) { return (int)floor(x + 0.5); } /* positive x */ + +/* oA: separable morphology, clamped window. o=1 dilate, 0 erode. */ +static void morph_u8(const uint8_t *A, int e, int t, int r, int o, uint8_t *out) { + uint8_t *a = malloc((size_t)e * t); + for (int i = 0; i < t; i++) + for (int tt = 0; tt < e; tt++) { + int g = o ? 0 : 1; + for (int da = -r; da <= r; da++) { + int rr = tt + da; if (rr < 0) rr = 0; if (rr > e - 1) rr = e - 1; + if (o) g |= A[i * e + rr]; else g &= A[i * e + rr]; + } + a[i * e + tt] = (uint8_t)g; + } + for (int A2 = 0; A2 < t; A2++) + for (int g2 = 0; g2 < e; g2++) { + int l = o ? 0 : 1; + for (int di = -r; di <= r; di++) { + int rr = A2 + di; if (rr < 0) rr = 0; if (rr > t - 1) rr = t - 1; + if (o) l |= a[rr * e + g2]; else l &= a[rr * e + g2]; + } + out[A2 * e + g2] = (uint8_t)l; + } + free(a); +} + +/* ---- PrismLocal.normalize ---- */ +void prism_local_normalize(const uint8_t *rgba, int w, int h, uint8_t *out) { + size_t n = (size_t)w * h; + uint32_t hist[3][256] = {{0}}; + float *ch[3]; + for (int e = 0; e < 3; e++) ch[e] = malloc(n * sizeof(float)); + for (size_t A = 0; A < n * 4; A += 4) + for (int e = 0; e < 3; e++) { hist[e][rgba[A + e]]++; ch[e][A / 4] = (float)rgba[A + e]; } + int blk[3]; + for (int e = 0; e < 3; e++) { + uint32_t r = 0; blk[e] = 0; + for (int o = 0; o < 256; o++) + if ((r += hist[e][o], r > (double)w * h * 0.02)) { blk[e] = o; break; } + } + int rp = js_round(0.035 * (w < h ? w : h)); + float *mn[3]; + for (int e = 0; e < 3; e++) { + /* moving-min, separable, deque */ + float *o = malloc(n * sizeof(float)), *a2 = malloc(n * sizeof(float)); + int i2 = (w > h ? w : h) + 2 * rp + 1; + int *gq = malloc(i2 * sizeof(int)); + float *lq = malloc(i2 * sizeof(float)); + for (int yy = 0; yy < h; yy++) { + int t = 0, i3 = 0; + size_t I = (size_t)yy * w; + for (int a = -rp; a < w + rp; a++) { + int ci = a < 0 ? 0 : a > w - 1 ? w - 1 : a; + float hv = ch[e][I + ci]; + for (; i3 > t && lq[i3 - 1] <= hv;) i3--; + gq[i3] = a; lq[i3++] = hv; + for (; gq[t] < a - 2 * rp;) t++; + if (a >= rp) o[I + a - rp] = lq[t]; + } + } + for (int xx = 0; xx < w; xx++) { + int i3 = 0, I3 = 0; + for (int hh = -rp; hh < h + rp; hh++) { + int ci = hh < 0 ? 0 : hh > h - 1 ? h - 1 : hh; + float nv = o[(size_t)ci * w + xx]; + for (; I3 > i3 && lq[I3 - 1] <= nv;) I3--; + gq[I3] = hh; lq[I3++] = nv; + for (; gq[i3] < hh - 2 * rp;) i3++; + if (hh >= rp) a2[(size_t)(hh - rp) * w + xx] = lq[i3]; + } + } + mn[e] = a2; + free(o); free(gq); free(lq); + } + for (size_t A = 0; A < n; A++) { + for (int e = 0; e < 3; e++) { + double d = (255.0 * (ch[e][A] - blk[e])) / fmax(30, mn[e][A] - blk[e]); + if (d < 0) d = 0; if (d > 255) d = 255; + out[4 * A + e] = (uint8_t)nearbyint(d); /* Uint8ClampedArray ties-to-even */ + } + out[4 * A + 3] = 255; + } + for (int e = 0; e < 3; e++) { free(ch[e]); free(mn[e]); } +} + +/* ---- PrismDistance.fields ---- */ +typedef struct { + float *maps[9]; + int w, h; + double scale; +} DFields; + +static void fields_free(DFields *f) { for (int k = 0; k < 9; k++) free(f->maps[k]); } + +static void chamfer(float *A, int t, int r) { + for (int e = 0; e < r; e++) + for (int rr = 0; rr < t; rr++) { + size_t o = (size_t)e * t + rr; + double a = A[o]; + if (rr) { double v = A[o - 1] + 1; if (v < a) a = v; } + if (e) { double v = A[o - t] + 1; if (v < a) a = v; } + if (rr && e) { double v = A[o - t - 1] + 1.414; if (v < a) a = v; } + if (rr < t - 1 && e) { double v = A[o - t + 1] + 1.414; if (v < a) a = v; } + A[o] = (float)a; + } + for (int e = r - 1; e >= 0; e--) + for (int o2 = t - 1; o2 >= 0; o2--) { + size_t a2 = (size_t)e * t + o2; + double i = A[a2]; + if (o2 < t - 1) { double v = A[a2 + 1] + 1; if (v < i) i = v; } + if (e < r - 1) { double v = A[a2 + t] + 1; if (v < i) i = v; } + if (o2 < t - 1 && e < r - 1) { double v = A[a2 + t + 1] + 1.414; if (v < i) i = v; } + if (o2 && e < r - 1) { double v = A[a2 + t - 1] + 1.414; if (v < i) i = v; } + A[a2] = (float)i; + } +} + +static void fields_compute(const uint8_t *rgba, int W, int H, DFields *F) { + double e = fmin(1, 240.0 / (W > H ? W : H)); + int t = js_round(W * e), r = js_round(H * e); + uint32_t o[3][256] = {{0}}; + for (size_t e2 = 0; e2 < (size_t)W * H * 4; e2 += 16) + for (int tt = 0; tt < 3; tt++) o[tt][rgba[e2 + tt]]++; + double a = ceil((double)W * H * 4 / 16); + double lo[3], hi[3]; + for (int c = 0; c < 3; c++) { + uint32_t rr = 0; + double elo = 0, ehi = 255; + for (int tt = 0; tt < 256; tt++) + if ((rr += o[c][tt], rr >= 0.02 * a)) { elo = tt; break; } + rr = 0; + for (int e2 = 0; e2 < 256; e2++) + if ((rr += o[c][e2], rr >= 0.98 * a)) { ehi = e2; break; } + lo[c] = elo; hi[c] = ehi; + } + size_t n = (size_t)t * r; + for (int k = 0; k < 9; k++) { + F->maps[k] = malloc(n * sizeof(float)); + for (size_t i = 0; i < n; i++) F->maps[k][i] = 1e3f; + } + /* memoized nearest on quantized normalized color */ + int memo_cap = 32768 * 4, memo_n = 0; + uint32_t *memo_k = malloc(memo_cap * sizeof(uint32_t)); + int *memo_v = malloc(memo_cap * sizeof(int)); + for (int yy = 0; yy < r; yy++) + for (int xx = 0; xx < t; xx++) { + size_t a2 = 4 * ((size_t)(int)(yy / e) * W + (int)(xx / e)); + double I[3]; + for (int c = 0; c < 3; c++) + I[c] = clamp01((rgba[a2 + c] - lo[c]) / fmax(20, hi[c] - lo[c])); + uint32_t key = 32 * (32 * (uint32_t)js_round(31 * I[0]) + (uint32_t)js_round(31 * I[1])) + (uint32_t)js_round(31 * I[2]); + int sym = -1; + for (int m = 0; m < memo_n; m++) if (memo_k[m] == key) { sym = memo_v[m]; break; } + if (sym < 0) { + double lin[3] = { prism_lin_s(I[0]), prism_lin_s(I[1]), prism_lin_s(I[2]) }; + double d; + sym = nearest_sym(lin, 0, &d); + if (memo_n == memo_cap) { memo_cap *= 2; memo_k = realloc(memo_k, memo_cap * 4); memo_v = realloc(memo_v, memo_cap * 4); } + memo_k[memo_n] = key; memo_v[memo_n] = sym; memo_n++; + } + F->maps[sym][(size_t)yy * t + xx] = 0; + } + free(memo_k); free(memo_v); + for (int k = 0; k < 9; k++) chamfer(F->maps[k], t, r); + for (int k = 0; k < 9; k++) { + float *ef = malloc(n * sizeof(float)); + for (size_t i = 0; i < n; i++) ef[i] = F->maps[k][i] == 0 ? 1e3f : 0; + chamfer(ef, t, r); + for (size_t i = 0; i < n; i++) + F->maps[k][i] = (float)(F->maps[k][i] / 0.6 + 0.7 * fmax(0, 1.7 - ef[i] / 0.6)); + free(ef); + } + F->w = t; F->h = r; F->scale = e; +} + +static double fields_at(const DFields *F, int sym, double o, double a) { + a *= F->scale; o *= F->scale; + if (o < 0 || a < 0 || o >= F->w - 1 || a >= F->h - 1) return 12; + int i = (int)floor(o), l = (int)floor(a); + double I = o - i, h = a - l; + const float *n = F->maps[sym]; + size_t s = (size_t)l * F->w + i; + return (n[s] * (1 - I) + n[s + 1] * I) * (1 - h) + + (n[s + F->w] * (1 - I) + n[s + F->w + 1] * I) * h; +} + +/* ---- detectTexture ---- */ +typedef struct { double p[4][2]; } DTQuad; +typedef struct { DTQuad *v; int n, cap; } DTQuadList; +static void dtq_push(DTQuadList *l, const double q[4][2]) { + if (l->n == l->cap) { l->cap = l->cap ? l->cap * 2 : 16; l->v = realloc(l->v, l->cap * sizeof(DTQuad)); } + memcpy(l->v[l->n++].p, q, sizeof l->v[0].p); +} + +/* convex hull (tA): sorts pts in place; returns hull in out (max n), count */ +static int hull_tA(double (*A)[2], int n, double (*out)[2]) { + for (int i = 0; i < n - 1; i++) /* stable not needed: JS sort by x||y; use insertion on doubles */ + for (int j = i + 1; j < n; j++) + if (A[j][0] < A[i][0] || (A[j][0] == A[i][0] && A[j][1] < A[i][1])) { + double t0 = A[i][0], t1 = A[i][1]; + A[i][0] = A[j][0]; A[i][1] = A[j][1]; A[j][0] = t0; A[j][1] = t1; + } + double (*e)[2] = malloc(2 * (n + 1) * sizeof *e); + double (*t)[2] = malloc(2 * (n + 1) * sizeof *t); + int ne = 0, nt = 0; + for (int i = 0; i < n; i++) { + for (; ne > 1 && eA_(e[ne - 2], e[ne - 1], A[i]) <= 0;) ne--; + e[ne][0] = A[i][0]; e[ne][1] = A[i][1]; ne++; + } + for (int i = n - 1; i >= 0; i--) { + for (; nt > 1 && eA_(t[nt - 2], t[nt - 1], A[i]) <= 0;) nt--; + t[nt][0] = A[i][0]; t[nt][1] = A[i][1]; nt++; + } + ne--; nt--; /* pop both */ + int k = 0; + for (int i = 0; i < ne; i++) { out[k][0] = e[i][0]; out[k][1] = e[i][1]; k++; } + for (int i = 0; i < nt; i++) { out[k][0] = t[i][0]; out[k][1] = t[i][1]; k++; } + free(e); free(t); + return k; +} + +static double area_rA(const double (*A)[2], int n) { + double s = 0; + for (int i = 0; i < n; i++) { + int j = (i + 1) % n; + s += A[i][0] * A[j][1] - A[i][1] * A[j][0]; + } + return fabs(s) / 2; +} + +/* iA: total-least-squares line -> [g, l, c] with g*x + l*y = c */ +static void line_iA(const double (*A)[2], int n, double out[3]) { + double e = 0, t = 0; + for (int i = 0; i < n; i++) { e += A[i][0]; t += A[i][1]; } + e /= n; t /= n; + double r = 0, o = 0, a = 0; + for (int i = 0; i < n; i++) { + double dx = A[i][0] - e, dy = A[i][1] - t; + r += dx * dx; o += dx * dy; a += dy * dy; + } + double i2 = 0.5 * js_atan2(2 * o, r - a); + double g = -js_sin(i2), l = js_cos(i2); + out[0] = g; out[1] = l; out[2] = g * e + l * t; +} + +/* gA: intersect normal-form lines; -1 if parallel (JS throws "Parallel edges") */ +static int isect_gA(const double A[3], const double e[3], double out[2]) { + double t = A[0] * e[1] - A[1] * e[0]; + if (fabs(t) < 1e-6) return -1; + out[0] = (A[2] * e[1] - A[1] * e[2]) / t; + out[1] = (A[0] * e[2] - A[2] * e[0]) / t; + return 0; +} + +/* detectTexture: edge map at <=320px, texture box filter, morph close, + * 4-conn components, hull + quad fits. cfg: edge/threshold/radius with + * defaults 0.13 / 0.33 / 4 (use_=0 -> default). */ +static int detect_texture(const PrismFrame *A, double edge, int use_edge, + double thresh, int use_thresh, int radius, int use_radius, + DTQuadList *out, char *err, size_t errlen) { + double r_edge = use_edge ? edge : 0.13; + double t = fmin(1, 320.0 / (A->w > A->h ? A->w : A->h)); + int i = js_round(A->w * t), g = js_round(A->h * t); + /* resampled gamma image l (float32 storage) */ + float *l = malloc((size_t)i * g * 3 * sizeof(float)); + for (int rr = 0; rr < g; rr++) + for (int oo = 0; oo < i; oo++) { + double a = oo / t, gg = rr / t; + size_t I = 3 * ((size_t)rr * i + oo); + if (a < 0 || gg < 0 || a >= A->w - 1 || gg >= A->h - 1) { + l[I] = l[I + 1] = l[I + 2] = (float)srgb_q(1); + continue; + } + int hh = (int)floor(a), nn = (int)floor(gg); + double s = a - hh, C = gg - nn; + size_t Q = 3 * ((size_t)nn * A->w + hh); + for (int e = 0; e < 3; e++) + l[I + e] = (float)srgb_q( + (A->p[Q + e] * (1 - s) + A->p[Q + 3 + e] * s) * (1 - C) + + (A->p[3 * A->w + Q + e] * (1 - s) + A->p[3 * A->w + 3 + Q + e] * s) * C); + } + /* edge map */ + float *Ie = calloc((size_t)i * g, sizeof(float)); + for (int A2 = 1; A2 < g - 1; A2++) + for (int e2 = 1; e2 < i - 1; e2++) { + size_t tt = 3 * ((size_t)A2 * i + e2); + double r = 0; + for (int A3 = 0; A3 < 2; A3++) { + size_t e3 = tt + (A3 ? 3 * i : 3); + double o = 0; + for (int A4 = 0; A4 < 3; A4++) o += (l[tt + A4] - l[e3 + A4]) * (l[tt + A4] - l[e3 + A4]); + double sq = sqrt(o); + if (sq > r) r = sq; + } + Ie[(size_t)A2 * i + e2] = r > r_edge ? 1 : 0; + } + free(l); + /* integral (float32 storage, double row accumulator) */ + float *hI = calloc((size_t)(i + 1) * (g + 1), sizeof(float)); + for (int A2 = 0; A2 < g; A2++) { + double e2 = 0; + for (int t2 = 0; t2 < i; t2++) { + e2 += Ie[(size_t)A2 * i + t2]; + hI[(size_t)(A2 + 1) * (i + 1) + t2 + 1] = (float)(hI[(size_t)A2 * (i + 1) + t2 + 1] + e2); + } + } + free(Ie); + /* texture box filter */ + uint8_t *hb = malloc((size_t)g * i); + int n2 = use_radius ? radius : 4; + double thr = use_thresh ? thresh : 0.33; + for (int A2 = 0; A2 < g; A2++) + for (int e2 = 0; e2 < i; e2++) { + int tt = e2 - n2 > 0 ? e2 - n2 : 0; + int rr = e2 + n2 + 1 < i ? e2 + n2 + 1 : i; + int oo = A2 - n2 > 0 ? A2 - n2 : 0; + int aa = A2 + n2 + 1 < g ? A2 + n2 + 1 : g; + double iv = hI[(size_t)aa * (i + 1) + rr] - hI[(size_t)oo * (i + 1) + rr] - + hI[(size_t)aa * (i + 1) + tt] + hI[(size_t)oo * (i + 1) + tt]; + hb[(size_t)A2 * i + e2] = iv / ((rr - tt) * (aa - oo)) > thr ? 1 : 0; + } + free(hI); + /* morph close r=1 */ + uint8_t *h2 = malloc((size_t)g * i); + morph_u8(hb, i, g, 1, 1, h2); + morph_u8(h2, i, g, 1, 0, hb); + free(h2); + /* connected components */ + uint8_t *seen = calloc((size_t)g * i, 1); + int *queue = malloc((size_t)g * i * sizeof(int)); + double (*boundary)[2] = malloc((size_t)g * i * sizeof *boundary); + double (*hull)[2] = malloc((size_t)g * i * sizeof *hull); + typedef struct { double (*hu)[2]; int nhu; int tail; double (*bnd)[2]; int nbnd; double ar; } Region; + Region regs[64]; int nreg = 0; + for (size_t A2 = 0; A2 < (size_t)g * i; A2++) { + if (!hb[A2] || seen[A2]) continue; + int e2 = 0, t2 = 1, nb = 0; + queue[0] = (int)A2; seen[A2] = 1; + while (e2 < t2) { + int cur = queue[e2++]; + int oo = cur % i, aa = cur / i; + int isb = 0; + for (int e3 = 0; e3 < 4; e3++) { + int rr = e3 == 0 ? (oo > 0 ? cur - 1 : -1) + : e3 == 1 ? (oo < i - 1 ? cur + 1 : -1) + : e3 == 2 ? (aa > 0 ? cur - i : -1) + : (aa < g - 1 ? cur + i : -1); + if (rr < 0 || !hb[rr]) isb = 1; + else if (!seen[rr]) { seen[rr] = 1; queue[t2++] = rr; } + } + if (isb) { boundary[nb][0] = oo; boundary[nb][1] = aa; nb++; } + } + if (t2 < 100) continue; + memcpy(hull, boundary, nb * sizeof *hull); + int nhu = hull_tA(hull, nb, hull); /* sorts in place, hull in front */ + /* JS tA sorts the boundary array itself in place; later boundary + * filters (iA fits) iterate it in that sorted order. Match it. */ + for (int a4 = 0; a4 < nb - 1; a4++) + for (int b4 = a4 + 1; b4 < nb; b4++) + if (boundary[b4][0] < boundary[a4][0] || + (boundary[b4][0] == boundary[a4][0] && boundary[b4][1] < boundary[a4][1])) { + double tx = boundary[a4][0], ty = boundary[a4][1]; + boundary[a4][0] = boundary[b4][0]; boundary[a4][1] = boundary[b4][1]; + boundary[b4][0] = tx; boundary[b4][1] = ty; + } + double ar = area_rA(hull, nhu); + double minx = 1e300, maxx = -1e300, miny = 1e300, maxy = -1e300; + for (int k = 0; k < nhu; k++) { + if (hull[k][0] < minx) minx = hull[k][0]; if (hull[k][0] > maxx) maxx = hull[k][0]; + if (hull[k][1] < miny) miny = hull[k][1]; if (hull[k][1] > maxy) maxy = hull[k][1]; + } + double asp = (maxx - minx) / (maxy - miny); + if (t2 / ar < 0.04 || asp < 0.4 || asp > 2.5) continue; + if (nreg < 64) { + regs[nreg].hu = malloc(nhu * sizeof *regs[nreg].hu); + memcpy(regs[nreg].hu, hull, nhu * sizeof *regs[nreg].hu); + regs[nreg].nhu = nhu; regs[nreg].tail = t2; regs[nreg].ar = ar; + regs[nreg].bnd = malloc(nb * sizeof *regs[nreg].bnd); + memcpy(regs[nreg].bnd, boundary, nb * sizeof *regs[nreg].bnd); + regs[nreg].nbnd = nb; + nreg++; + } + } + free(boundary); free(hull); free(queue); free(seen); free(hb); + /* sort regions by area desc (stable) */ + for (int a2 = 0; a2 < nreg - 1; a2++) + for (int b2 = a2 + 1; b2 < nreg; b2++) + if (regs[b2].ar > regs[a2].ar) { Region tmp = regs[a2]; regs[a2] = regs[b2]; regs[b2] = tmp; } + if (!nreg) { + snprintf(err, errlen, "No code found. Use a plain background with a wide white margin."); + return -1; + } + for (int ri = 0; ri < nreg && ri < 3; ri++) { + Region *R = ®s[ri]; + int nhu = R->nhu; + /* min-area rect (rotating calipers over hull edges) */ + double best = 1.0 / 0.0, bq[4][2]; int have = 0; + for (int rr = 0; rr < nhu; rr++) { + double *o = R->hu[rr], *a2 = R->hu[(rr + 1) % nhu]; + double g2 = a2[0] - o[0], l2 = a2[1] - o[1]; + double I2 = js_hypot2(g2, l2); + g2 /= I2; l2 /= I2; + double smin = 1e300, smax = -1e300, nmin = 1e300, nmax = -1e300; + for (int k = 0; k < nhu; k++) { + double hp = R->hu[k][0] * g2 + R->hu[k][1] * l2; + double np = -R->hu[k][0] * l2 + R->hu[k][1] * g2; + if (hp < smin) smin = hp; if (hp > smax) smax = hp; + if (np < nmin) nmin = np; if (np > nmax) nmax = np; + } + double B = (smax - smin) * (nmax - nmin); + if (B < best) { + best = B; have = 1; + double corners[4][2] = {{smin, nmin}, {smax, nmin}, {smax, nmax}, {smin, nmax}}; + for (int k = 0; k < 4; k++) { + bq[k][0] = (corners[k][0] * g2 - corners[k][1] * l2 + 0.5) / t; + bq[k][1] = (corners[k][0] * l2 + corners[k][1] * g2 + 0.5) / t; + } + } + } + if (have) dtq_push(out, (const double (*)[2])bq); + /* simplify hull copy to 4 vertices (max(0.1, len) variant) */ + double (*r2)[2] = malloc(nhu * sizeof *r2); + memcpy(r2, R->hu, nhu * sizeof *r2); + int nr = nhu; + while (nr > 4) { + double bestc = 1.0 / 0.0; int be = 0; + for (int tt = 0; tt < nr; tt++) { + double *po = r2[(tt + nr - 1) % nr], *pa = r2[(tt + 1) % nr]; + double ic = fabs(eA_(po, r2[tt], pa)) / fmax(0.1, js_hypot2(pa[0] - po[0], pa[1] - po[1])); + if (ic < bestc) { bestc = ic; be = tt; } + } + memmove(r2 + be, r2 + be + 1, (nr - be - 1) * sizeof *r2); nr--; + } + if (nr == 4) { + double q4[4][2]; + for (int k = 0; k < 4; k++) { q4[k][0] = (r2[k][0] + 0.5) / t; q4[k][1] = (r2[k][1] + 0.5) / t; } + dtq_push(out, (const double (*)[2])q4); + /* edge-refined quad */ + double lines[4][3]; int ok = 1; + for (int tt = 0; tt < 4 && ok; tt++) { + double *o = r2[tt], *a2 = r2[(tt + 1) % 4]; + int ii = -1, gg = -1; + for (int k = 0; k < nhu; k++) { + if (R->hu[k][0] == o[0] && R->hu[k][1] == o[1]) ii = k; + if (R->hu[k][0] == a2[0] && R->hu[k][1] == a2[1]) gg = k; + } + double bestg = 0; int bi = -1; + for (int e2 = ii; e2 != gg; e2 = (e2 + 1) % nhu) { + double *t3 = R->hu[e2], *r3 = R->hu[(e2 + 1) % nhu]; + double o2 = js_hypot2(t3[0] - r3[0], t3[1] - r3[1]); + if (o2 > bestg) { bestg = o2; bi = e2; } + } + double hh[2], nn[2]; + if (bi >= 0) { memcpy(hh, R->hu[bi], 16); memcpy(nn, R->hu[(bi + 1) % nhu], 16); } + else { memcpy(hh, o, 16); memcpy(nn, a2, 16); } + double (*spts)[2] = malloc(R->nbnd * sizeof *spts); + int ns = 0; + for (int k = 0; k < R->nbnd; k++) + if (fabs(eA_(hh, nn, R->bnd[k])) / fmax(1, bestg) < 2) { spts[ns][0] = R->bnd[k][0]; spts[ns][1] = R->bnd[k][1]; ns++; } + if (ns > 2) line_iA(spts, ns, lines[tt]); + else { double pts[2][2] = {{hh[0], hh[1]}, {nn[0], nn[1]}}; line_iA(pts, 2, lines[tt]); } + free(spts); + } + double tq[4][2]; + for (int tt = 0; tt < 4 && ok; tt++) + if (isect_gA(lines[(tt + 3) % 4], lines[tt], tq[tt]) != 0) ok = 0; + if (ok) { + double aq = area_rA(tq, 4); + if (aq > 0.6 * R->ar && aq < 1.5 * R->ar) { + double q5[4][2]; + for (int k = 0; k < 4; k++) { q5[k][0] = (tq[k][0] + 0.5) / t; q5[k][1] = (tq[k][1] + 0.5) / t; } + dtq_push(out, (const double (*)[2])q5); + } + } + } + free(r2); + /* second simplify pass (plain len, break > 0.7), top-4 edges */ + double (*o2)[2] = malloc(nhu * sizeof *o2); + memcpy(o2, R->hu, nhu * sizeof *o2); + int no = nhu; + while (no > 4) { + double bestc = 1.0 / 0.0; int be = 0; + for (int tt = 0; tt < no; tt++) { + double *pr = o2[(tt + no - 1) % no], *pa = o2[(tt + 1) % no]; + double ic = fabs(eA_(pr, o2[tt], pa)) / js_hypot2(pa[0] - pr[0], pa[1] - pr[1]); + if (ic < bestc) { bestc = ic; be = tt; } + } + if (bestc > 0.7) break; + memmove(o2 + be, o2 + be + 1, (no - be - 1) * sizeof *o2); no--; + } + /* segments sorted len desc, top 4, re-sort by index */ + typedef struct { int idx; double len; } Seg; + Seg *segs = malloc(no * sizeof *segs); + for (int e2 = 0; e2 < no; e2++) + segs[e2] = (Seg){ e2, js_hypot2(o2[e2][0] - o2[(e2 + 1) % no][0], o2[e2][1] - o2[(e2 + 1) % no][1]) }; + for (int a3 = 0; a3 < no - 1; a3++) + for (int b3 = a3 + 1; b3 < no; b3++) + if (segs[b3].len > segs[a3].len) { Seg tmp = segs[a3]; segs[a3] = segs[b3]; segs[b3] = tmp; } + /* stable sort len desc (strict > keeps tie order) */ + Seg top[4]; + int ntake = no < 4 ? no : 4; + for (int k = 0; k < ntake; k++) top[k] = segs[k]; + free(segs); + for (int a3 = 0; a3 < ntake - 1; a3++) + for (int b3 = a3 + 1; b3 < ntake; b3++) + if (top[b3].idx < top[a3].idx) { Seg tmp = top[a3]; top[a3] = top[b3]; top[b3] = tmp; } + if (ntake == 4) { + double lines[4][3]; int ok = 1; + for (int e2 = 0; e2 < 4 && ok; e2++) { + double *t3 = o2[top[e2].idx], *r3 = o2[(top[e2].idx + 1) % no]; + double l3 = js_hypot2(t3[0] - r3[0], t3[1] - r3[1]); + double (*spts)[2] = malloc(R->nbnd * sizeof *spts); + int ns = 0; + for (int k = 0; k < R->nbnd; k++) + if (fabs(eA_(t3, r3, R->bnd[k])) / l3 < 2) { spts[ns][0] = R->bnd[k][0]; spts[ns][1] = R->bnd[k][1]; ns++; } + if (ns >= 2) line_iA(spts, ns, lines[e2]); + else { double pts[2][2] = {{t3[0], t3[1]}, {r3[0], r3[1]}}; line_iA(pts, 2, lines[e2]); } + free(spts); + } + double tq[4][2]; + for (int e2 = 0; e2 < 4 && ok; e2++) + if (isect_gA(lines[(e2 + 3) % 4], lines[e2], tq[e2]) != 0) ok = 0; + if (ok) { + double q6[4][2]; + for (int k = 0; k < 4; k++) { q6[k][0] = (tq[k][0] + 0.5) / t; q6[k][1] = (tq[k][1] + 0.5) / t; } + dtq_push(out, (const double (*)[2])q6); + } + } + free(o2); + } + for (int ri = 0; ri < nreg; ri++) { free(regs[ri].hu); free(regs[ri].bnd); } + if (!out->n) { + snprintf(err, errlen, "Could not fit four edges"); + return -1; + } + return 0; +} + + +/* split uA's "stage:message" err string (local copy; prism_read.c's is static) */ +static void df_split_err(const char *s, PrismErr *e) { + const char *c = strchr(s, ':'); + if (c) { + size_t n = (size_t)(c - s); + if (n >= sizeof e->stage) n = sizeof e->stage - 1; + memcpy(e->stage, s, n); e->stage[n] = 0; + snprintf(e->msg, sizeof e->msg, "%s", c + 1); + } else { + snprintf(e->stage, sizeof e->stage, "undefined"); + snprintf(e->msg, sizeof e->msg, "%s", s); + } +} + +/* ---- PrismDistFit.read ---- */ + +typedef struct { + PrismMap h; + const PrismLayout *l; + double quad[4][2]; + double score, cost; + int seq; +} DFHyp; + +static int df_cmp(const void *pa, const void *pb) { + const DFHyp *A = pa, *e = pb; + if (A->score != e->score) return A->score < e->score ? 1 : -1; + if (A->cost != e->cost) return A->cost > e->cost ? 1 : -1; + return A->seq - e->seq; +} + +/* rank i(): 48-subsample cost/score (readable fallback) */ +static void df_rank(const DFields *F, const PrismMap *c, const PrismLayout *t, double *cost, double *score) { + int nk = t->n_known; + int step = nk / 48; if (step < 1) step = 1; + double r = 0; int o = 0; + for (int a = 0; a < nk; a += step) { + const PrismCell *cell = t->known[a]; + double gx, gy; + map_point(c, cell->x, cell->y, &gx, &gy); + double l2 = fields_at(F, known_symbol(cell, 0), gx, gy); + double v = l2 * l2; if (v > 25) v = 25; + r += v; o++; + } + *cost = r / o; + *score = 1 / (1 + r / o); +} + +/* score I(): 160-subsample known + header bits (readable fallback) */ +static double df_score(const DFields *F, const PrismMap *R, const PrismLayout *S, + const PrismCell **J, int nj) { + double *A = malloc(nj * sizeof(double)); + for (int k = 0; k < nj; k++) { + double gx, gy; + map_point(R, J[k]->x, J[k]->y, &gx, &gy); + double o = fields_at(F, known_symbol(J[k], 0), gx, gy); + double v = o * o; if (v > 64) v = 64; + A[k] = v; + } + for (int a = 0; a < nj - 1; a++) /* stable ascending */ + for (int b = a + 1; b < nj; b++) + if (A[b] < A[a]) { double t2 = A[a]; A[a] = A[b]; A[b] = t2; } + int t = (int)floor(0.85 * nj); + double r = 0; + for (int k = 0; k < t; k++) r += A[k]; + r /= t; + free(A); + double o = 0; + for (int A2 = 0; A2 < 24; A2++) { + double t2 = 0, r2 = 0; + for (int k = 0; k < S->n_headers; k++) { + const PrismCell *hc = S->headers[k]; + if (hc->header % 24 != A2) continue; + double gx, gy; + map_point(R, hc->x, hc->y, &gx, &gy); + double a3 = fields_at(F, 8, gx, gy), i3 = fields_at(F, 0, gx, gy); + double v1 = a3 * a3; if (v1 > 36) v1 = 36; + double v2 = i3 * i3; if (v2 > 36) v2 = 36; + t2 += v1; r2 += v2; + } + o += t2 < r2 ? t2 : r2; + } + return r + (o / 72) * 0.35; +} + +int prism_distfit_read(const uint8_t *rgba, int w, int h, PrismRead *out) { + memset(out, 0, sizeof *out); + prism_budget_set(15.0); /* JS DistFit.read: Prism.beginDecode(15e3) */ + const double df_t0 = prism_now_seconds(); + DFields F; + fields_compute(rgba, w, h, &F); + PrismFrame *fr = frame_create(w, h, rgba); + /* texture candidates, 3 configs */ + DTQuadList cands = {0}; + char derr[160] = {0}; + detect_texture(fr, 0, 0, 0, 0, 0, 0, &cands, derr, sizeof derr); /* errors swallowed */ + /* config {threshold:0.5, edge:0.13}, then {threshold:0.4, edge:0.2} */ + detect_texture(fr, 0.13, 1, 0.5, 1, 0, 0, &cands, derr, sizeof derr); + detect_texture(fr, 0.2, 1, 0.4, 1, 0, 0, &cands, derr, sizeof derr); + /* dedup: drop quads within 100 sq of ANY earlier quad (any rotation) */ + DTQuadList ded = {0}; + for (int i = 0; i < cands.n; i++) { + int dup = 0; + for (int j = 0; j < i && !dup; j++) + for (int rr = 0; rr < 4 && !dup; rr++) { + double s = 0; + for (int k = 0; k < 4; k++) + s += (cands.v[i].p[k][0] - cands.v[j].p[(k + rr) % 4][0]) * (cands.v[i].p[k][0] - cands.v[j].p[(k + rr) % 4][0]) + + (cands.v[i].p[k][1] - cands.v[j].p[(k + rr) % 4][1]) * (cands.v[i].p[k][1] - cands.v[j].p[(k + rr) % 4][1]); + if (s < 100) dup = 1; + } + if (!dup) dtq_push(&ded, (const double (*)[2])cands.v[i].p); + } + /* scale variants x1, 1.04, 1.08 about centroid */ + DTQuadList vars = {0}; + for (int i = 0; i < ded.n; i++) { + double cx = 0, cy = 0; + for (int k = 0; k < 4; k++) { cx += ded.v[i].p[k][0]; cy += ded.v[i].p[k][1]; } + cx /= 4; cy /= 4; + for (int s2 = 0; s2 < 3; s2++) { + static const double sc[3] = {1, 1.04, 1.08}; + double q[4][2]; + for (int k = 0; k < 4; k++) { + q[k][0] = cx + (ded.v[i].p[k][0] - cx) * sc[s2]; + q[k][1] = cy + (ded.v[i].p[k][1] - cy) * sc[s2]; + } + dtq_push(&vars, (const double (*)[2])q); + } + } + /* hypotheses: per quad x size x rotation, warp pre-search */ + DFHyp *hyps = NULL; int nh = 0, cap = 0; + static const double S1[3] = {-6, 0, 6}, S2[2] = {0, 6}, S3[2] = {0, 3}; + static const double T2[2] = {0, -3}; + for (int ci = 0; ci < vars.n; ci++) + for (int Q = 0; Q < 6; Q++) { + const PrismLayout *E = layout_get(Q); + double src[4][2]; + corners_of(E, src); + for (int B = 0; B < 4; B++) { + double f[4][2]; + for (int k = 0; k < 4; k++) { f[k][0] = vars.v[ci].p[(k + B) % 4][0]; f[k][1] = vars.v[ci].p[(k + B) % 4][1]; } + PrismMap c; + if (homography(src, f, &c) != 0) { + /* JS: uncaught "Singular geometry" propagates out of read */ + snprintf(out->err.stage, sizeof out->err.stage, "undefined"); + snprintf(out->err.msg, sizeof out->err.msg, "Singular geometry"); + free(hyps); free(vars.v); free(ded.v); free(cands.v); + fields_free(&F); frame_free(fr); + return -1; + } + double wcost, wscore; + df_rank(&F, &c, E, &wcost, &wscore); + double u[10] = {0}; + for (int d = 0; d < 3; d++) + for (int y = 0; y < 3; y++) + for (int M = 0; M < 2; M++) + for (int D = 0; D < 2; D++) { + double p[10] = {S1[d], 0, 0, 0, 0, S1[y], S2[M], S3[D], 0, 0}; + c.has_warp = 1; c.warpW = E->W; c.warpH = E->H; + memcpy(c.warpp, p, sizeof p); + double pc, ps; + df_rank(&F, &c, E, &pc, &ps); + if (ps > wscore || (ps == wscore && pc < wcost)) { + wscore = ps; wcost = pc; memcpy(u, p, sizeof u); + } + } + for (int F2 = 0; F2 < 3; F2++) + for (int k2 = 0; k2 < 3; k2++) + for (int G = 0; G < 2; G++) { + double p[10] = {0, 0, S1[F2], S1[k2], 0, 0, 0, 0, T2[G], T2[G]}; + c.has_warp = 1; c.warpW = E->W; c.warpH = E->H; + memcpy(c.warpp, p, sizeof p); + double pc, ps; + df_rank(&F, &c, E, &pc, &ps); + if (ps > wscore) { wscore = ps; wcost = pc; memcpy(u, p, sizeof u); } + } + c.has_warp = 1; c.warpW = E->W; c.warpH = E->H; + memcpy(c.warpp, u, sizeof c.warpp); + if (nh == cap) { cap = cap ? cap * 2 : 128; hyps = realloc(hyps, cap * sizeof *hyps); } + DFHyp *H = &hyps[nh++]; + H->h = c; H->l = E; H->score = wscore; H->cost = wcost; H->seq = nh - 1; + memcpy(H->quad, f, sizeof H->quad); + } + } + free(vars.v); free(ded.v); free(cands.v); + qsort(hyps, nh, sizeof *hyps, df_cmp); + /* dedup by size+quad(2)+warp(0.1) vs earlier */ + DFHyp *kept = malloc((nh ? nh : 1) * sizeof *kept); + int nk2 = 0; + for (int i = 0; i < nh; i++) { + int dup = 0; + for (int j = 0; j < nk2 && !dup; j++) { + if (kept[j].l->size != hyps[i].l->size) continue; + double s = 0; + for (int k = 0; k < 4; k++) + s += (hyps[i].quad[k][0] - kept[j].quad[k][0]) * (hyps[i].quad[k][0] - kept[j].quad[k][0]) + + (hyps[i].quad[k][1] - kept[j].quad[k][1]) * (hyps[i].quad[k][1] - kept[j].quad[k][1]); + if (s >= 2) continue; + int all = 1; + for (int k = 0; k < 10; k++) if (fabs(hyps[i].h.warpp[k] - kept[j].h.warpp[k]) >= 0.1) { all = 0; break; } + if (all) dup = 1; + } + if (!dup) kept[nk2++] = hyps[i]; + } + free(hyps); + snprintf(out->err.stage, sizeof out->err.stage, "undefined"); + snprintf(out->err.msg, sizeof out->err.msg, "Nonlinear geometry did not decode"); + static const double XS[5] = {-8, -4, 0, 4, 8}, OS[5] = {-2, 0, 3, 6, 9}; + static const double SCALES[5] = {2, 1, 0.5, 0.25, 0.125}; + for (int Li = 0; Li < nk2 && Li < 20; Li++) { + if (prism_fast_deadline_hit()) break; /* JS: if (now > PrismFastDeadline) break */ + if (prism_now_seconds() - df_t0 > 15.0) break; /* JS: if (now - t > 15e3) break */ + PrismMap R = kept[Li].h; + const PrismLayout *S = kept[Li].l; + double N[4][2]; + memcpy(N, kept[Li].quad, sizeof N); + double q[3]; + white_balance(fr, &R, S, q); + /* J: known subsample 160 (mod filter) */ + int step = S->n_known / 160; if (step < 1) step = 1; + const PrismCell **J = malloc((S->n_known / step + 2) * sizeof *J); + int nj = 0; + for (int k = 0; k < S->n_known; k++) if (k % step == 0) J[nj++] = S->known[k]; + double W = df_score(&F, &R, S, J, nj); + double *K = R.warpp, P[10]; + memcpy(P, K, sizeof P); + for (int xi = 0; xi < 5; xi++) + for (int oi = 0; oi < 5; oi++) { + int V = fabs(K[2]) + fabs(K[3]) > fabs(K[0]) + fabs(K[5]); + int j2 = V ? 8 : 6; + K[V ? 2 : 0] = XS[xi]; + K[j2] = V ? -OS[oi] : OS[oi]; + double sc = df_score(&F, &R, S, J, nj); + if (sc < W) { W = sc; memcpy(P, K, sizeof P); } + } + memcpy(K, P, sizeof P); + /* scale refine: warp params then quad corners */ + for (int si = 0; si < 5; si++) { + double sc = SCALES[si]; + for (int pass = 0; pass < 3; pass++) { + int improved = 0; + for (int oi = 0; oi < 10; oi++) { + double aA2 = K[oi], iA2 = aA2; + for (int gi = 0; gi < 2; gi++) { + double gA2 = gi ? 1 : -1; + K[oi] = aA2 + gA2 * sc; + if (fabs(K[oi]) > 12) continue; + double lA2 = df_score(&F, &R, S, J, nj); + if (lA2 < W) { W = lA2; iA2 = K[oi]; improved = 1; } + } + K[oi] = iA2; + } + double rA2 = js_hypot2(N[1][0] - N[0][0], N[1][1] - N[0][1]) / S->W; + double src[4][2]; + corners_of(S, src); + for (int IA = 0; IA < 4; IA++) + for (int hA = 0; hA < 2; hA++) { + double nA = N[IA][hA], sA2 = nA; + for (int ci = 0; ci < 2; ci++) { + double CA = ci ? 1 : -1; + N[IA][hA] = nA + CA * sc * rA2 * 0.35; + PrismMap QA; + if (homography(src, N, &QA) != 0) { + snprintf(out->err.stage, sizeof out->err.stage, "undefined"); + snprintf(out->err.msg, sizeof out->err.msg, "Singular geometry"); + free(J); goto next_candidate; + } + QA.has_warp = R.has_warp; QA.warpW = R.warpW; QA.warpH = R.warpH; + memcpy(QA.warpp, R.warpp, sizeof QA.warpp); + PrismMap EA2 = R; + R = QA; + double BA2 = df_score(&F, &R, S, J, nj); + if (BA2 < W) { W = BA2; sA2 = N[IA][hA]; improved = 1; } + else R = EA2; + } + N[IA][hA] = sA2; + { + PrismMap tmp; + if (homography(src, N, &tmp) != 0) { + snprintf(out->err.stage, sizeof out->err.stage, "undefined"); + snprintf(out->err.msg, sizeof out->err.msg, "Singular geometry"); + free(J); goto next_candidate; + } + tmp.has_warp = R.has_warp; tmp.warpW = R.warpW; tmp.warpH = R.warpH; + memcpy(tmp.warpp, R.warpp, sizeof tmp.warpp); + R = tmp; + } + } + if (!improved) break; + } + } + white_balance(fr, &R, S, q); + /* classify + decode with headers.slice(0,3); dense-mesh retry */ + { + PrismClassify cA; + const char *uerr = NULL; + PrismErr g2; snprintf(g2.stage, sizeof g2.stage, "undefined"); g2.msg[0] = 0; + int success = 0; + if (uA_classify(fr, &R, S, 0, q, NULL, &cA, &uerr) != 0) { + df_split_err(uerr, &g2); /* classify throw -> g */ + out->err = g2; + goto next_candidate; + } + { + PrismPayload fA; memset(&fA, 0, sizeof fA); + int have_fA = 0; + if (cA.known_match < 0.65) { /* throw Error("Weak known-cell support") */ + if (cA.known_match < 0.5 || W > 3.5) /* catch rethrows */ + snprintf(g2.msg, sizeof g2.msg, "Weak known-cell support"); + else + goto dense_retry; + } else { + PrismClassify c3 = cA; + if (c3.n_headers > 3) c3.n_headers = 3; + PrismErr pe; + if (prism_decode_class(&c3, &fA, &pe) == 0) have_fA = 1; + else if (cA.known_match < 0.5 || W > 3.5) g2 = pe; /* rethrow mA */ + else { + dense_retry:; + PrismMesh *m1 = qa_build_dense_mesh(fr, &R, S, 0, q, NULL); + PrismMesh *m2 = qa_build_dense_mesh(fr, &R, S, 0, q, m1); + mesh_free(m1); + classify_free(&cA); + uerr = NULL; + if (uA_classify(fr, &R, S, 0, q, m2, &cA, &uerr) != 0) { + mesh_free(m2); + df_split_err(uerr, &g2); /* propagates to g */ + goto cand_close; + } + mesh_free(m2); + if (cA.known_match < 0.7) { + snprintf(g2.msg, sizeof g2.msg, "Weak mesh known-cell support"); + goto cand_close; + } + PrismClassify c4 = cA; + if (c4.n_headers > 3) c4.n_headers = 3; + PrismErr pe2; + if (prism_decode_class(&c4, &fA, &pe2) == 0) have_fA = 1; + else g2 = pe2; /* propagates to g */ + } + } + if (have_fA) { + if (!fA.n_bytes) { + payload_free(&fA); + snprintf(g2.stage, sizeof g2.stage, "undefined"); + snprintf(g2.msg, sizeof g2.msg, "Nonlinear recovery does not accept empty payload hypotheses"); + } else { + out->ok = 1; + out->payload = fA; + out->quality = cA.known_match; + memcpy(out->quad, N, sizeof out->quad); + memcpy(out->h, R.h, sizeof out->h); + out->layout_size = S->size; + out->sigma = cA.sigma; + out->radius = js_hypot2(N[1][0] - N[0][0], N[1][1] - N[0][1]) / S->W; + memcpy(out->warp, R.warpp, sizeof out->warp); + out->reader = "original cells + fitted nonlinear surface"; + success = 1; + } + } + cand_close: + classify_free(&cA); + if (success) { + free(J); free(kept); + fields_free(&F); frame_free(fr); + return 0; + } + out->err = g2; + } + } + next_candidate: + free(J); + } + free(kept); + fields_free(&F); + frame_free(fr); + return -1; +} + +/* PrismFastReader.read: mix gate -> readImage(no export fallback) -> DistFit */ +double prism_fb_ms = 0; /* page __fastBudget posted per attempt */ + +static void set_err_df(PrismRead *out, const char *stage, const char *msg) { + snprintf(out->err.stage, sizeof out->err.stage, "%s", stage); + snprintf(out->err.msg, sizeof out->err.msg, "%s", msg); +} + +int prism_fast_read(const uint8_t *rgba, int w, int h, PrismRead *out) { + memset(out, 0, sizeof *out); + /* PrismFastReader.read(A, FBW): overall r = t + (FBW || 950); + fast deadline = t + (FBW ? round(FBW*0.66) : 700) for the readImage phase */ + const double fb = prism_fb_ms; + const double t = prism_now_seconds(); + /* e0ec151: read() throws "stopped" when the page overall cap already passed */ + if (prism_page_cap_s > 0 && t > prism_page_cap_s) { + prism_cap_stopped = 1; + set_err_df(out, "fast", "Read stopped: six-second limit reached"); + return -1; + } + double r = t + (fb > 0 ? fb : 950) / 1000.0; + /* the page timer kills the attempt at the overall cap: model as r = min(r, cap); + a past-r outcome then means the attempt died "stopped" */ + int cap_binding = 0; + if (prism_page_cap_s > 0 && prism_page_cap_s < r) { r = prism_page_cap_s; cap_binding = 1; } + prism_overall_deadline_set(r); + prism_fast_deadline_set(t + (fb > 0 ? floor(fb * 0.66 + 0.5) : 700) / 1000.0); + int rc = -1; + if (prism_flag_direct) { + /* e0ec151 worker: PrismDirectOnly -> mixDirect only, else throw */ + PrismMixResult *z = prism_mix_direct(rgba, w, h); + if (z && prism_now_seconds() <= r) { + out->ok = 1; + out->payload = z->payload; + out->quality = z->quality; + memcpy(out->h, z->h, sizeof out->h); + out->radius = z->radius; + out->sigma = z->sigma; + for (int k = 0; k < 4; k++) out->quad[k][0] = out->quad[k][1] = 0.0 / 0.0; + free(z); + rc = 0; + } else { + if (z) { payload_free(&z->payload); free(z); } + if (cap_binding && prism_now_seconds() > r) { + prism_cap_stopped = 1; + set_err_df(out, "fast", "Read stopped: six-second limit reached"); + } else { + set_err_df(out, "fast", "No direct mixing read"); + } + } + prism_fast_deadline_set(0); + prism_overall_deadline_set(0); + return rc; + } + if (prism_flag_mix) { + PrismMixResult *z = prism_mix_direct(rgba, w, h); + if (z) { + out->ok = 1; + out->payload = z->payload; + out->quality = z->quality; + memcpy(out->h, z->h, sizeof out->h); + out->radius = z->radius; + out->sigma = z->sigma; + for (int k = 0; k < 4; k++) out->quad[k][0] = out->quad[k][1] = 0.0 / 0.0; /* JS mix result has no quad */ + free(z); + rc = 0; + } + } + if (rc && prism_read_image(rgba, w, h, 0, out) == 0) rc = 0; + if (rc == 0 && prism_now_seconds() > r) { /* JS success wrapper: past-overall success is an error */ + prism_read_free(out); + memset(out, 0, sizeof *out); + if (cap_binding) { prism_cap_stopped = 1; set_err_df(out, "fast", "Read stopped: six-second limit reached"); } + else set_err_df(out, "fast", "No verified read within one second"); + rc = -1; + } + if (rc) { + PrismErr e1 = out->err; + prism_fast_deadline_set(r); /* DistFit phase runs under the overall deadline */ + uint8_t *norm = malloc((size_t)w * h * 4); + prism_local_normalize(rgba, w, h, norm); + if (prism_now_seconds() > r) { + free(norm); + if (cap_binding) { prism_cap_stopped = 1; set_err_df(out, "fast", "Read stopped: six-second limit reached"); } + else set_err_df(out, "fast", "Fast read budget reached"); + } else { + rc = prism_distfit_read(norm, w, h, out); + free(norm); + if (rc == 0 && prism_now_seconds() > r) { + prism_read_free(out); + memset(out, 0, sizeof *out); + if (cap_binding) { prism_cap_stopped = 1; set_err_df(out, "fast", "Read stopped: six-second limit reached"); } + else set_err_df(out, "fast", "No verified read within one second"); + rc = -1; + } + } + if (rc) (void)e1; /* DistFit error replaces the readImage error */ + } + prism_fast_deadline_set(0); /* JS finally: PrismFastDeadline = Infinity */ + prism_overall_deadline_set(0); + return rc; +} + +/* ---- probe entry points for test_distfit.c ---- */ +int df_probe_fields(const uint8_t *rgba, int W, int H, char *line, size_t cap) { + DFields F; + fields_compute(rgba, W, H, &F); + uint64_t u; memcpy(&u, &F.scale, 8); + int o = snprintf(line, cap, "FIELDS w=%d h=%d scale=%016llx", F.w, F.h, (unsigned long long)u); + for (int k = 0; k < 9; k++) { + uint64_t h2 = 0xcbf29ce484222325ULL; + const uint8_t *p = (const uint8_t *)F.maps[k]; + for (size_t i = 0; i < (size_t)F.w * F.h * 4; i++) { h2 ^= p[i]; h2 *= 0x100000001b3ULL; } + o += snprintf(line + o, cap - o, " m%d=%016llx", k, (unsigned long long)h2); + } + fields_free(&F); + return 0; +} + +int df_probe_texture(const uint8_t *rgba, int W, int H, char (*lines)[4096], int maxlines) { + PrismFrame *fr = frame_create(W, H, rgba); + int n = 0; + for (int cfg = 0; cfg < 3 && n < maxlines; cfg++) { + DTQuadList ql = {0}; + char derr[160] = {0}; + int rc; + if (cfg == 0) rc = detect_texture(fr, 0, 0, 0, 0, 0, 0, &ql, derr, sizeof derr); + else if (cfg == 1) rc = detect_texture(fr, 0.13, 1, 0.5, 1, 0, 0, &ql, derr, sizeof derr); + else rc = detect_texture(fr, 0.2, 1, 0.4, 1, 0, 0, &ql, derr, sizeof derr); + if (rc != 0) { + char em[512]; size_t o = 0; + em[o++] = '"'; + for (const char *p = derr; *p && o + 2 < sizeof em; p++) em[o++] = *p; + em[o++] = '"'; em[o] = 0; + snprintf(lines[n++], 4096, "DT err=%s", em); + } else { + int o = snprintf(lines[n], 4096, "DT n=%d", ql.n); + for (int q = 0; q < ql.n; q++) { + o += snprintf(lines[n] + o, 4096 - o, " q="); + for (int k = 0; k < 4; k++) { + uint64_t u1, u2; + memcpy(&u1, &ql.v[q].p[k][0], 8); memcpy(&u2, &ql.v[q].p[k][1], 8); + o += snprintf(lines[n] + o, 4096 - o, "%s%016llx,%016llx", k ? ";" : "", + (unsigned long long)u1, (unsigned long long)u2); + if (k < 3) { /* separator handled above */ } + } + } + n++; + } + free(ql.v); + } + frame_free(fr); + return n; +} diff --git a/ports/c/reader/prism_foundations.c b/ports/c/reader/prism_foundations.c new file mode 100644 index 0000000..679809d --- /dev/null +++ b/ports/c/reader/prism_foundations.c @@ -0,0 +1,344 @@ +#include "prism_reader.h" +#include +#include +#include + +/* ================= GF(256) ================= */ +static uint8_t EXP[512], LOG[256]; +const uint8_t *gf_exp_table = EXP; +const uint8_t *gf_log_table = LOG; +static int gf_ready = 0; +static void gf_init(void) { + if (gf_ready) return; + int Q = 1; + for (int A = 0; A < 255; A++) { + EXP[A] = (uint8_t)Q; LOG[Q] = (uint8_t)A; Q <<= 1; if (Q & 256) Q ^= 285; + } + for (int A = 255; A < 512; A++) EXP[A] = EXP[A - 255]; + gf_ready = 1; +} +uint8_t gf_mul(uint8_t A, uint8_t e) { gf_init(); return (A && e) ? EXP[LOG[A] + LOG[e]] : 0; } +uint8_t gf_div(uint8_t A, uint8_t e) { gf_init(); return A ? EXP[(LOG[A] + 255 - LOG[e]) % 255] : 0; } +uint8_t gf_peval(const uint8_t *p, int n, uint8_t x) { + uint8_t t = 0; + for (int r = n - 1; r >= 0; r--) t = gf_mul(t, x) ^ p[r]; + return t; +} +void gf_poly_mul(const uint8_t *a, int na, const uint8_t *b, int nb, uint8_t *out) { + for (int r = 0; r < na; r++) + for (int o = 0; o < nb; o++) out[r + o] ^= gf_mul(a[r], b[o]); +} + +/* generator polynomial cache: gen[e] has e+1 coeffs */ +static uint8_t gen_cache[65][66]; +static int gen_done[65]; +static const uint8_t *rs_gen(int e) { + gf_init(); + if (gen_done[e]) return gen_cache[e]; + uint8_t cur[66] = {1}, nxt[66]; + int nc = 1; + for (int A = 0; A < e; A++) { + memset(nxt, 0, nc + 1); + uint8_t f2[2] = {1, EXP[A]}; + gf_poly_mul(cur, nc, f2, 2, nxt); + memcpy(cur, nxt, nc + 1); nc++; + } + memcpy(gen_cache[e], cur, nc); + gen_done[e] = 1; + return gen_cache[e]; +} +void rs_encode(const uint8_t *msg, int len, int e, uint8_t *out) { + const uint8_t *g = rs_gen(e); + memset(out, 0, len + e); + memcpy(out, msg, len); + for (int i = 0; i < len; i++) { + uint8_t A = out[i]; + if (A) for (int o = 1; o <= e; o++) out[i + o] ^= gf_mul(g[o], A); + } + memcpy(out, msg, len); +} +void rs_syndromes(const uint8_t *cw, int len, int e, uint8_t *out) { + gf_init(); + for (int r = 0; r < e; r++) { + uint8_t acc = 0; + for (int t = 0; t < len; t++) acc = gf_mul(acc, EXP[r]) ^ cw[t]; + out[r] = acc; + } +} + +/* Berlekamp-Massey on Forney syndromes i[0..ni); writes locator (len r+1) into out, returns r */ +static int rs_bm(const uint8_t *i, int ni, uint8_t *out) { + uint8_t e2[130] = {0}, t2[130] = {0}; + e2[0] = t2[0] = 1; + int r = 0, o = 1; + uint8_t a = 1; + for (int i2 = 0; i2 < ni; i2++) { + uint8_t g = i[i2]; + for (int t = 1; t <= r; t++) g ^= gf_mul(e2[t], i[i2 - t]); + if (!g) { o++; continue; } + uint8_t l[130]; memcpy(l, e2, sizeof(e2)); + uint8_t I = gf_div(g, a); + for (int A = 0; A + o < ni + 1; A++) e2[A + o] ^= gf_mul(I, t2[A]); + if (2 * r <= i2) { r = i2 + 1 - r; memcpy(t2, l, sizeof(t2)); a = g; o = 1; } + else o++; + } + memcpy(out, e2, r + 1); + return r; +} + +int rs_decode(uint8_t *r, int n, int e, const int *eras, int n_eras, const char **err) { + static const char *msg; + gf_init(); + uint8_t o[130]; + rs_syndromes(r, n, e, o); + int allzero = 1; + for (int i = 0; i < e; i++) if (o[i]) { allzero = 0; break; } + if (allzero) return 0; + if (n_eras > e) { msg = "Too many erasures"; goto fail; } + uint8_t a[130]; int na = 1; a[0] = 1; + uint8_t i_[130]; int ni = e; + memcpy(i_, o, e); + for (int q = 0; q < n_eras; q++) { + int A = eras[q]; + if (A < 0 || A >= n) { msg = "Erasure index"; goto fail; } + uint8_t er = EXP[n - 1 - A]; + uint8_t f2[2] = {1, er}, nxt[130] = {0}; + gf_poly_mul(a, na, f2, 2, nxt); + memcpy(a, nxt, na + 1); na++; + for (int A2 = 0; A2 < ni - 1; A2++) i_[A2] = gf_mul(i_[A2], er) ^ i_[A2 + 1]; + ni--; + } + uint8_t g[130]; + int deg = rs_bm(i_, ni, g); + if (2 * deg + n_eras > e) { msg = "RS correction limit"; goto fail; } + uint8_t l[300] = {0}; /* l = c(a, g) */ + gf_poly_mul(a, na, g, deg + 1, l); + int nl = na + deg; + int I[300], nI = 0; + for (int A = 0; A < n; A++) { + int ev = n - 1 - A; + if (0 == gf_peval(l, nl, EXP[(255 - ev) % 255])) I[nI++] = A; + } + if (nI != nl - 1) { msg = "RS roots"; goto fail; } + uint8_t h2[300] = {0}; /* c(o, l).slice(0, e) */ + { + uint8_t tmp[400] = {0}; + gf_poly_mul(o, e, l, nl, tmp); + memcpy(h2, tmp, e < (int)sizeof(tmp) ? e : (int)sizeof(tmp)); + } + uint8_t dv[300]; int ndv = nl - 1 > 1 ? nl - 1 : 1; + memset(dv, 0, sizeof(dv)); + for (int A = 1; A < nl; A += 2) dv[A - 1] = l[A]; + for (int q = 0; q < nI; q++) { + int A = I[q]; + int ev = n - 1 - A; + uint8_t t_ = EXP[ev], o_ = EXP[(255 - ev) % 255]; + uint8_t num = gf_mul(t_, gf_peval(h2, e, o_)); + uint8_t den = gf_peval(dv, ndv, o_); + if (!den) { msg = "GF division by zero"; goto fail; } + r[A] ^= gf_div(num, den); + } + rs_syndromes(r, n, e, o); + for (int i = 0; i < e; i++) if (o[i]) { msg = "RS syndrome check"; goto fail; } + return nI; +fail: + if (err) *err = msg; + return -1; +} + +int rs_recover_bits(const uint8_t *A, const uint8_t *mask, int n, int t, uint8_t *out, const char **err) { + static const char *msg; + gf_init(); + uint8_t o[600]; + memcpy(o, A, n); + struct { int p, bit; } a[2100]; + int ni = 0; + for (int i = 0; i < n; i++) { + o[i] &= ~mask[i]; + for (int e = 0; e < 8; e++) if (mask[i] & (1 << e)) { a[ni].p = i; a[ni].bit = e; ni++; } + } + int limit = 8 * t < 512 ? 8 * t : 512; + if (!ni || ni > limit) { msg = "Bit erasure count"; goto fail; } + int rows = 8 * t; + int W = (ni + 1 + 31) / 32; + uint32_t *g = calloc((size_t)rows * W, 4); + uint8_t l[130]; + rs_syndromes(o, n, t, l); + for (int A2 = 0; A2 < t; A2++) { + for (int e = 0; e < 8; e++) + if (l[A2] & (1 << e)) g[(8 * A2 + e) * W + (ni >> 5)] |= 1u << (31 & ni); + for (int e = 0; e < ni; e++) { + uint8_t coef = gf_mul((uint8_t)(1 << a[e].bit), EXP[(A2 * (n - 1 - a[e].p)) % 255]); + for (int r2 = 0; r2 < 8; r2++) + if (coef & (1 << r2)) g[(8 * A2 + r2) * W + (e >> 5)] |= 1u << (31 & e); + } + } + int I = 0, h[520]; + for (int A2 = 0; A2 < ni; A2++) { + int t2 = I; + for (; t2 < rows && !((g[t2 * W + (A2 >> 5)] >> (31 & A2)) & 1);) t2++; + if (t2 == rows) { free(g); msg = "Ambiguous bit erasures"; goto fail; } + for (int w = 0; w < W; w++) { uint32_t tmp = g[t2 * W + w]; g[t2 * W + w] = g[I * W + w]; g[I * W + w] = tmp; } + for (int e2 = I + 1; e2 < rows; e2++) + if ((g[e2 * W + (A2 >> 5)] >> (31 & A2)) & 1) + for (int w = A2 >> 5; w < W; w++) g[e2 * W + w] ^= g[I * W + w]; + h[I] = A2; I++; + } + for (int A2 = I; A2 < rows; A2++) + if ((g[A2 * W + (ni >> 5)] >> (31 & ni)) & 1) { free(g); msg = "Inconsistent bit erasures"; goto fail; } + uint8_t n_[520] = {0}; + for (int A2 = I - 1; A2 >= 0; A2--) { + int e = h[A2]; + int t2 = (g[A2 * W + (ni >> 5)] >> (31 & ni)) & 1; + for (int r2 = e + 1; r2 < ni; r2++) + if ((g[A2 * W + (r2 >> 5)] >> (31 & r2)) & 1) t2 ^= n_[r2]; + n_[e] = (uint8_t)t2; + } + free(g); + for (int A2 = 0; A2 < ni; A2++) if (n_[A2]) o[a[A2].p] |= (uint8_t)(1 << a[A2].bit); + rs_syndromes(o, n, t, l); + for (int i = 0; i < t; i++) if (l[i]) { msg = "Bit erasure syndrome check"; goto fail; } + memcpy(out, o, n); + int corr = 0; + for (int i = 0; i < n; i++) if (o[i] != A[i]) corr++; + return corr; +fail: + if (err) *err = msg; + return -1; +} + +/* ================= rng ================= */ +void rng_seed(prism_rng *r, uint32_t seed) { r->s = seed; } +static int32_t imul32(int32_t a, int32_t b) { return (int32_t)((uint32_t)a * (uint32_t)b); } +double rng_next(prism_rng *r) { + int32_t A = (int32_t)r->s; + A = (int32_t)((uint32_t)A + 1831565813u); + r->s = (uint32_t)A; + int32_t e = imul32(A ^ (int32_t)((uint32_t)A >> 15), 1 | A); + e = (int32_t)((uint32_t)(e + imul32(e ^ (int32_t)((uint32_t)e >> 7), 61 | e)) ^ (uint32_t)e); + return (double)((uint32_t)(e ^ (int32_t)((uint32_t)e >> 14))) / 4294967296.0; +} + +/* ================= crc ================= */ +static uint32_t CRC32T[256]; +static int crc_ready = 0; +static void crc_init(void) { + if (crc_ready) return; + for (int e = 0; e < 256; e++) { + uint32_t v = (uint32_t)e; + for (int A = 0; A < 8; A++) v = (v & 1) ? (3988292384u ^ (v >> 1)) : (v >> 1); + CRC32T[e] = v; + } + crc_ready = 1; +} +uint32_t crc32_bytes(const uint8_t *p, size_t n) { + crc_init(); + uint32_t e = 4294967295u; + for (size_t t = 0; t < n; t++) e = CRC32T[255 & (e ^ p[t])] ^ (e >> 8); + return (4294967295u ^ e); +} +int crc4_bits(const uint8_t *bits, int n) { + int e = 0; + for (int t = 0; t < n; t++) { + int A = ((e >> 3) & 1) ^ bits[t]; + e = (e << 1) & 15; + if (A) e ^= 3; + } + return e; +} +void bits_push(uint8_t *bits, int *n, uint32_t v, int nbits) { + for (int r = nbits - 1; r >= 0; r--) bits[(*n)++] = (uint8_t)((v >> r) & 1); +} + +/* ================= layout / capacity / header ================= */ +const int PRISM_SIZES[6][2] = {{21, 24}, {29, 33}, {41, 47}, {57, 66}, {81, 94}, {113, 130}}; + +static PrismLayout LAY[6]; +static int lay_done[6]; +const PrismLayout *layout_get(int size) { + if (lay_done[size]) return &LAY[size]; + PrismLayout *L = &LAY[size]; + int C = PRISM_SIZES[size][0], R = PRISM_SIZES[size][1]; + const double r = PRISM_SQRT3; + int n = C * R; + L->cells = calloc(n, sizeof(PrismCell)); + L->n_cells = n; + PrismCell **scan_data = malloc(n * sizeof(PrismCell *)); + int n_scan = 0, n_known = 0; + for (int A = 0; A < R; A++) + for (int a = 0; a < C; a++) { + PrismCell *s = &L->cells[A * C + a]; + int role = ROLE_DATA, sym = -1; + double h2 = (a - 2) / 5.0, n2 = (A - 2) / 5.0; + if (A <= 2 && a <= 2) { role = ROLE_GAP; sym = 8; } + else if (0 == A || A == R - 1 || 0 == a || a == C - 1) { role = ROLE_RING; sym = (5 * A + 3 * a) % 8; } + else if (a % 5 == 2 && A % 5 == 2) { role = ROLE_PILOT; sym = (2 * (int)h2 + 3 * (int)n2) % 9; } + s->i = a; s->j = A; + s->x = r * (a + 0.5 + 0.5 * (1 & A)); + s->y = 1 + 1.5 * A; + s->role = role; s->symbol = sym; s->pi = h2; s->pj = n2; + s->index = A * C + a; s->header = -1; + if (role == ROLE_DATA) scan_data[n_scan++] = s; + else if (role != ROLE_GAP) n_known++; + } + L->headers = malloc(72 * sizeof(PrismCell *)); + L->n_headers = 72; + for (int A = 0; A < 72; A++) { + PrismCell *e = scan_data[(int)floor(((A + 0.5) * n_scan) / 72.0)]; + e->role = ROLE_HEADER; e->header = A; + L->headers[A] = e; + } + int n_data = 0; + for (int q = 0; q < n_scan; q++) if (scan_data[q]->role == ROLE_DATA) n_data++; + L->data = malloc(n_data * sizeof(PrismCell *)); + L->n_data = n_data; + n_data = 0; + for (int q = 0; q < n_scan; q++) if (scan_data[q]->role == ROLE_DATA) L->data[n_data++] = scan_data[q]; + /* Fisher-Yates with rng(24301 ^ size) */ + prism_rng rng; rng_seed(&rng, (uint32_t)(24301 ^ size)); + for (int A = L->n_data - 1; A > 0; A--) { + int e = (int)floor(rng_next(&rng) * (A + 1)); + PrismCell *tmp = L->data[A]; L->data[A] = L->data[e]; L->data[e] = tmp; + } + L->known = malloc(n_known * sizeof(PrismCell *)); + L->n_known = n_known; + n_known = 0; + for (int A = 0; A < R; A++) + for (int a = 0; a < C; a++) { + PrismCell *s = &L->cells[A * C + a]; + if (s->role == ROLE_RING || s->role == ROLE_PILOT) L->known[n_known++] = s; + } + free(scan_data); + L->size = size; L->C = C; L->R = R; + L->W = r * (C + 0.5); + L->H = 2 + 1.5 * (R - 1); + lay_done[size] = 1; + return L; +} + +void capacity_get(int size, int ecc, int mode, PrismCapacity *out) { + const PrismLayout *L = layout_get(size); + static const double FRAC[4] = {0.1, 0.2, 0.3, 0.4}; + int o = (int)floor((L->n_data * (mode ? 1 : 3)) / 8.0); + int a = (o + 254) / 255; + out->n = o; out->n_blocks = a; out->k = 0; + for (int A = 0; A < a; A++) { + int t = o / a + (A < o % a ? 1 : 0); + int ns = 2 * (int)floor(t * FRAC[ecc] / 2.0 + 0.5); + if (ns < 4) ns = 4; + out->blocks[A].n = t; out->blocks[A].nsym = ns; out->blocks[A].k = t - ns; + out->k += t - ns; + } + out->payload = out->k - 4 > 0 ? out->k - 4 : 0; +} + +void header_bits(int size, int ecc, int mode, int type, int len, uint8_t out[24]) { + int n = 0; + bits_push(out, &n, (uint32_t)size, 3); + bits_push(out, &n, (uint32_t)ecc, 2); + bits_push(out, &n, (uint32_t)mode, 1); + bits_push(out, &n, (uint32_t)type, 1); + bits_push(out, &n, (uint32_t)len, 13); + int c = crc4_bits(out, n); + bits_push(out, &n, (uint32_t)c, 4); +} diff --git a/ports/c/reader/prism_image.c b/ports/c/reader/prism_image.c new file mode 100644 index 0000000..b8badf6 --- /dev/null +++ b/ports/c/reader/prism_image.c @@ -0,0 +1,306 @@ +#include "prism_reader.h" +#include +#include +#include +#include + +/* budget hook: r721 throws past PrismFastDeadline; no-op during parity work */ +static void budget(void) {} + +/* sRGB linearize table (N), float32 storage like the JS Float32Array */ +static float LIN[256]; +static int lin_ready = 0; +#include "prism_jsmath.h" +static double lin_s(double A) { return A <= 0.04045 ? A / 12.92 : js_pow((A + 0.055) / 1.055, 2.4); } +double srgb_q(double A) { return A <= 0.0031308 ? 12.92 * A : 1.055 * js_pow(A, 1 / 2.4) - 0.055; } +double prism_lin_s(double A) { return lin_s(A); } + +static void lin_init(void) { + if (lin_ready) return; + for (int i = 0; i < 256; i++) LIN[i] = (float)lin_s(i / 255.0); + lin_ready = 1; +} + +/* 7-point stencil: center + 6 hex at 0.45, same expression order as JS */ +static double STEN[7][2] = {{0, 0}}; +static int sten_ready = 0; +static void sten_init(void) { + /* exact V8/fdlibm doubles of 0.45*cos(e*M_PI/3), 0.45*sin(e*M_PI/3) (verified vs oracle) */ + static const uint64_t bits[6][2] = { + {0x3fdccccccccccccdULL, 0x0000000000000000ULL}, + {0x3fcccccccccccccfULL, 0x3fd8f1083782ab66ULL}, + {0xbfccccccccccccc9ULL, 0x3fd8f1083782ab67ULL}, + {0xbfdccccccccccccdULL, 0x3c8fc4ab28be3f40ULL}, + {0xbfccccccccccccd4ULL, 0xbfd8f1083782ab65ULL}, + {0x3fcccccccccccccfULL, 0xbfd8f1083782ab66ULL}, + }; + if (sten_ready) return; + memcpy(STEN + 1, bits, sizeof(bits)); + sten_ready = 1; +} + + +PrismFrame *frame_create(int w, int h, const uint8_t *rgba) { + lin_init(); sten_init(); + PrismFrame *f = malloc(sizeof(PrismFrame)); + f->w = w; f->h = h; f->image = rgba; + f->p = malloc((size_t)w * h * 3 * sizeof(float)); + size_t e = 0; + for (size_t A = 0; A < (size_t)w * h * 4; A += 4) { + f->p[e++] = LIN[rgba[A]]; + f->p[e++] = LIN[rgba[A + 1]]; + f->p[e++] = LIN[rgba[A + 2]]; + } + return f; +} +void lin_dump(float out[256]) { lin_init(); memcpy(out, LIN, sizeof(LIN)); } +void frame_free(PrismFrame *f) { if (f) { free(f->p); free(f); } } +void stencil_get(double out[7][2]) { sten_init(); memcpy(out, STEN, sizeof(STEN)); } + +void frame_sample(const PrismFrame *A, double t, double r, double out[3]) { + budget(); + if (t < 0 || r < 0 || t >= A->w - 1 || r >= A->h - 1) { out[0] = out[1] = out[2] = 1; return; } + int o = (int)floor(t), a = (int)floor(r); + double i = t - o, g = r - a; + size_t l = 3 * ((size_t)a * A->w + o); + const float *p = A->p; + out[0] = (p[l + 0] * (1 - i) + p[l + 3] * i) * (1 - g) + (p[l + 3 * A->w + 0] * (1 - i) + p[l + 3 * A->w + 3] * i) * g; + out[1] = (p[l + 1] * (1 - i) + p[l + 4] * i) * (1 - g) + (p[l + 3 * A->w + 1] * (1 - i) + p[l + 3 * A->w + 4] * i) * g; + out[2] = (p[l + 2] * (1 - i) + p[l + 5] * i) * (1 - g) + (p[l + 3 * A->w + 2] * (1 - i) + p[l + 3 * A->w + 5] * i) * g; +} + +static int cmp_d(const void *a, const void *b) { double x = *(const double *)a, y = *(const double *)b; return (x > y) - (x < y); } +static double median_n(double *A, int n) { qsort(A, n, sizeof(double), cmp_d); return A[n >> 1]; } +/* O(): NaN check on first 7 then insertion sort median */ +static double median_O(double *A, int n) { + int nan = 0; + for (int i = 0; i < 7 && i < n; i++) if (A[i] != A[i]) { nan = 1; break; } + if (nan) return median_n(A, n); + for (int e = 1; e < n; e++) { + double t = A[e]; + int r = e - 1; + for (; r >= 0 && A[r] > t;) { A[r + 1] = A[r]; r--; } + A[r + 1] = t; + } + return A[n >> 1]; +} + +void map_point(const PrismMap *A, double t, double r, double *ox, double *oy) { + budget(); + if (A->has_warp) { + double i = (2 * t) / A->warpW - 1, g = (2 * r) / A->warpH - 1; + const double *a = A->warpp; + t += (1 - i * i) * (a[0] + a[1] * g) + a[2] * (1 - g * g) + a[6] * i * (1 - i * i) + a[8] * i * (1 - g * g); + r += (1 - g * g) * (a[3] + a[4] * i) + a[5] * (1 - i * i) + a[7] * g * (1 - i * i) + a[9] * g * (1 - g * g); + } + double o = A->h[6] * t + A->h[7] * r + 1; + *ox = (A->h[0] * t + A->h[1] * r + A->h[2]) / o; + *oy = (A->h[3] * t + A->h[4] * r + A->h[5]) / o; +} + +/* W(): Gauss-Jordan with partial pivot; returns 0 ok */ +int prism_solve_n(int n, double *A /* n rows of n */, double *e, double *out) { + double *r = malloc((size_t)n * (n + 1) * sizeof(double)); + for (int i = 0; i < n; i++) { memcpy(r + i * (n + 1), A + i * n, n * sizeof(double)); r[i * (n + 1) + n] = e[i]; } + for (int A2 = 0; A2 < n; A2++) { + int e2 = A2; + for (int o = A2 + 1; o < n; o++) if (fabs(r[o * (n + 1) + A2]) > fabs(r[e2 * (n + 1) + A2])) e2 = o; + if (fabs(r[e2 * (n + 1) + A2]) < 1e-10) { free(r); return -1; } + if (e2 != A2) for (int k = 0; k <= n; k++) { double tmp = r[A2 * (n + 1) + k]; r[A2 * (n + 1) + k] = r[e2 * (n + 1) + k]; r[e2 * (n + 1) + k] = tmp; } + double o = r[A2 * (n + 1) + A2]; + for (int e3 = A2; e3 <= n; e3++) r[A2 * (n + 1) + e3] /= o; + for (int e3 = 0; e3 < n; e3++) + if (e3 != A2) { + o = r[e3 * (n + 1) + A2]; + for (int a = A2; a <= n; a++) r[e3 * (n + 1) + a] -= o * r[A2 * (n + 1) + a]; + } + } + for (int i = 0; i < n; i++) out[i] = r[i * (n + 1) + n]; + free(r); + return 0; +} + +int homography(const double A[4][2], const double e[4][2], PrismMap *out) { + double t[8 * 8], r[8]; + for (int o = 0; o < 4; o++) { + double a = A[o][0], i = A[o][1], g = e[o][0], l = e[o][1]; + double row0[8] = {a, i, 1, 0, 0, 0, -g * a, -g * i}; + double row1[8] = {0, 0, 0, a, i, 1, -l * a, -l * i}; + memcpy(t + o * 16, row0, sizeof(row0)); + memcpy(t + o * 16 + 8, row1, sizeof(row1)); + r[o * 2] = g; r[o * 2 + 1] = l; + } + memset(out, 0, sizeof(*out)); + return prism_solve_n(8, t, r, out->h); +} + +void corners_of(const PrismLayout *l, double out[4][2]) { + out[0][0] = 0; out[0][1] = 0; + out[1][0] = l->W; out[1][1] = 0; + out[2][0] = l->W; out[2][1] = l->H; + out[3][0] = 0; out[3][1] = l->H; +} + +int known_symbol(const PrismCell *A, int e) { + if (e) return (A->role == ROLE_RING || fmod(A->pi + A->pj, 2.0) == 0.0) ? 0 : 8; + return A->symbol; +} + +/* palette: 9 hex colors, linear + Lab */ +static double PAL[9][3], LAB[9][3]; +const double (*PRISM_LAB)[3] = (const double (*)[3])LAB; +static const char *HEX[9] = {"#1B1B1B", "#2E5BFF", "#00B8D9", "#2DB35A", "#F5C518", "#F77F00", "#D7263D", "#B5179E", "#FFFFFF"}; +/* V8 12.4 base::ieee754::cbrt (msun-style, P0-P4 polynomial) - bit-exact vs the Node oracle (300k-value sweep, 0 diffs) */ +#include +#include + + +void lab_of(const double A[3], double out[3]) { + double e = (0.4124564 * A[0] + 0.3575761 * A[1] + 0.1804375 * A[2]) / 0.95047; + double t = 0.2126729 * A[0] + 0.7151522 * A[1] + 0.0721750 * A[2]; + double r = (0.0193339 * A[0] + 0.1191920 * A[1] + 0.9503041 * A[2]) / 1.08883; + double fo; + e = e > 0.008856 ? js_cbrt(e) : 7.787 * e + 16.0 / 116; + fo = t > 0.008856 ? js_cbrt(t) : 7.787 * t + 16.0 / 116; + r = r > 0.008856 ? js_cbrt(r) : 7.787 * r + 16.0 / 116; + out[0] = 116 * fo - 16; + out[1] = 500 * (e - fo); + out[2] = 200 * (fo - r); +} +double lab_dist2(const double A[3], const double e[3]) { + return (A[0] - e[0]) * (A[0] - e[0]) + (A[1] - e[1]) * (A[1] - e[1]) + (A[2] - e[2]) * (A[2] - e[2]); +} +static int pal_ready = 0; +void pal_init(void) { + if (pal_ready) return; + lin_init(); + for (int i = 0; i < 9; i++) { + for (int c = 0; c < 3; c++) { + int v; + sscanf(HEX[i] + 1 + 2 * c, "%2x", &v); + PAL[i][c] = lin_s(v / 255.0); + } + lab_of(PAL[i], LAB[i]); + } + pal_ready = 1; +} + +void pal_dump(double pal[9][3], double lab[9][3]) { pal_init(); memcpy(pal, PAL, sizeof(PAL)); memcpy(lab, LAB, sizeof(LAB)); } +int nearest_sym(const double A[3], int e, double *d) { + pal_init(); + double t[3]; + lab_of(A, t); + int r = -1; + double o = 1.0 / 0.0; + for (int A2 = 0; A2 < 9; A2++) { + if (e && 0 != A2 && 8 != A2) continue; + double a = lab_dist2(t, PRISM_LAB[A2]); + if (a < o) { o = a; r = A2; } + } + if (d) *d = sqrt(o); + return r; +} + +void sample_cell_ex(const PrismFrame *A, const PrismMap *e, const PrismCell *t, const double r[3], double mdx, double mdy, int a, double out[3]) { + sten_init(); + if (a) { + double x, y; + map_point(e, t->x + STEN[0][0], t->y + STEN[0][1], &x, &y); + double s[3]; + frame_sample(A, x + mdx, y + mdy, s); + out[0] = s[0] / r[0]; out[1] = s[1] / r[1]; out[2] = s[2] / r[2]; + return; + } + double g[3][7]; + for (int o = 0; o < 7; o++) { + double x, y, l[3]; + map_point(e, t->x + STEN[o][0], t->y + STEN[o][1], &x, &y); + frame_sample(A, x + mdx, y + mdy, l); + for (int c = 0; c < 3; c++) g[c][o] = l[c] / r[c]; + } + for (int c = 0; c < 3; c++) out[c] = median_O(g[c], 7); +} + +void sample_cell(const PrismFrame *A, const PrismMap *e, const PrismCell *t, const double r[3], int a, double out[3]) { + sample_cell_ex(A, e, t, r, 0, 0, a, out); +} + +void white_balance(const PrismFrame *A, const PrismMap *e, const PrismLayout *t, double out[3]) { + double *r[3]; + int cap = 96, n[3] = {0, 0, 0}; + for (int c = 0; c < 3; c++) r[c] = malloc(cap * sizeof(double)); + for (int o = 0; o < 24; o++) { + double a = (o + 0.5) / 24.0; + double pts[4][2] = {{a * t->W, -2.5}, {a * t->W, t->H + 2.5}, {-2.5, a * t->H}, {t->W + 2.5, a * t->H}}; + for (int q = 0; q < 4; q++) { + double x, y, s[3]; + map_point(e, pts[q][0], pts[q][1], &x, &y); + if (x < 0 || y < 0 || x >= A->w - 1 || y >= A->h - 1) continue; + frame_sample(A, x, y, s); + for (int c = 0; c < 3; c++) r[c][n[c]++] = s[c]; + } + } + for (int c = 0; c < 3; c++) { + double m = n[c] ? median_n(r[c], n[c]) : 1.0; + out[c] = m > 0.08 ? m : 0.08; + free(r[c]); + } +} + +void hypothesis_score(const PrismFrame *A, const PrismMap *t, const PrismLayout *r, int o, const double *a, int i, double *cost, double *score) { + pal_init(); + double g = 0; + int I = 0, l = 0; + int h = r->n_known / ((i && !o) ? 60 : 120); + if (h < 1) h = 1; + for (int e = 0; e < r->n_known; e += h) { + const PrismCell *hc = r->known[e]; + if (o && hc->role == ROLE_RING) continue; + double n[3]; + sample_cell(A, t, hc, a, i, n); + int s = known_symbol(hc, o); + double un[3], Q; + lab_of(n, un); + Q = sqrt(lab_dist2(un, PRISM_LAB[s])); + double d; + int C = nearest_sym(n, o, &d); + g += Q / 30 < 1 ? Q / 30 : 1; + I += C == s ? 1 : 0; + l++; + } + *cost = g / l; + *score = (double)I / l; +} + +double refine_quad(const PrismFrame *A, PrismMap *e, const PrismLayout *t, int r, double o[4][2], const double *a, int *err) { + double i[4][2]; + memcpy(i, o, sizeof(i)); + double g = hypot(i[1][0] - i[0][0], i[1][1] - i[0][1]) / t->W; + double I = 0.5 * g; + double h, sc, src[4][2]; + hypothesis_score(A, e, t, r, a, 0, &h, &sc); + corners_of(t, src); + for (; I > g * 0.03; I *= 0.5) { + for (int round = 0; round < 2; round++) { + int changed = 0; + for (int g2 = 0; g2 < 4; g2++) + for (int l = 0; l < 2; l++) { + double n = i[g2][l], s = n; + for (int Cs = 0; Cs < 2; Cs++) { + double C = Cs ? 1.0 : -1.0; + i[g2][l] = n + C * I; + PrismMap Q; + if (homography(src, (const double (*)[2])i, &Q)) { *err = 1; return h; } + double E, sc2; + hypothesis_score(A, &Q, t, r, a, 0, &E, &sc2); + if (E < h) { h = E; s = i[g2][l]; *e = Q; changed = 1; } + } + i[g2][l] = s; + } + if (!changed) break; + } + } + memcpy(o, i, sizeof(i)); + *err = 0; + return h; +} diff --git a/ports/c/reader/prism_jsmath.c b/ports/c/reader/prism_jsmath.c new file mode 100644 index 0000000..0ca6424 --- /dev/null +++ b/ports/c/reader/prism_jsmath.c @@ -0,0 +1,626 @@ +#include +#include +#include +#include "prism_jsmath.h" + +static double get_hi(double x, uint32_t *lo) { uint64_t u; memcpy(&u,&x,8); if(lo)*lo=(uint32_t)u; double h; uint64_t q=u&0xffffffff00000000ULL; memcpy(&h,&q,8); return h; } +#define EXTRACT(h,l,x) do{uint64_t u;memcpy(&u,&(x),8);h=(int32_t)(u>>32);l=(uint32_t)u;}while(0) +#define GETHW(h,x) do{uint64_t u;memcpy(&u,&(x),8);h=(int32_t)(u>>32);}while(0) +#define SETHW(x,h) do{uint64_t u;memcpy(&u,&(x),8);u=(u&0xffffffffULL)|((uint64_t)(uint32_t)(h)<<32);memcpy(&(x),&u,8);}while(0) +#define SETLW(x,l) do{uint64_t u;memcpy(&u,&(x),8);u=(u&0xffffffff00000000ULL)|(uint32_t)(l);memcpy(&(x),&u,8);}while(0) +#define INSERT(x,h,l) do{uint64_t u=((uint64_t)(uint32_t)(h)<<32)|(uint32_t)(l);memcpy(&(x),&u,8);}while(0) + +/* ---- V8 12.4 base::ieee754::pow (fdlibm e_pow) ---- */ +double js_pow(double x, double y) { + static const double bp[2] = {1.0, 1.5}, + dp_h[2] = {0.0, 5.84962487220764160156e-01}, + dp_l[2] = {0.0, 1.35003920212974897128e-08}, + zero = 0.0, one = 1.0, two = 2.0, + two53 = 9007199254740992.0, + huge = 1.0e300, tiny = 1.0e-300, + L1 = 5.99999999999994648725e-01, L2 = 4.28571428578550184252e-01, + L3 = 3.33333329818377432918e-01, L4 = 2.72728123808534006489e-01, + L5 = 2.30660745775561754067e-01, L6 = 2.06975017800338417784e-01, + P1 = 1.66666666666666019037e-01, P2 = -2.77777777770155933842e-03, + P3 = 6.61375632143793436117e-05, P4 = -1.65339022054652515390e-06, + P5 = 4.13813679705723846039e-08, + lg2 = 6.93147180559945286227e-01, + lg2_h = 6.93147182464599609375e-01, + lg2_l = -1.90465429995776804525e-09, + ovt = 8.0085662595372944372e-0017, + cp = 9.61796693925975554329e-01, + cp_h = 9.61796700954437255859e-01, + cp_l = -7.02846165095275826516e-09, + ivln2 = 1.44269504088896338700e+00, + ivln2_h = 1.44269502162933349609e+00, + ivln2_l = 1.92596299112661746887e-08; + double z, ax, z_h, z_l, p_h, p_l; + double y1, t1, t2, r, s, t, u, v, w; + int i, j, k, yisint, n; + int hx, hy, ix, iy; + unsigned lx, ly; + EXTRACT(hx, lx, x); + EXTRACT(hy, ly, y); + ix = hx & 0x7fffffff; + iy = hy & 0x7fffffff; + if ((iy | ly) == 0) return one; + if (ix > 0x7ff00000 || ((ix == 0x7ff00000) && (lx != 0)) || iy > 0x7ff00000 || + ((iy == 0x7ff00000) && (ly != 0))) return x + y; + yisint = 0; + if (hx < 0) { + if (iy >= 0x43400000) yisint = 2; + else if (iy >= 0x3ff00000) { + k = (iy >> 20) - 0x3ff; + if (k > 20) { + j = (int)(ly >> (52 - k)); + if ((j << (52 - k)) == (int)ly) yisint = 2 - (j & 1); + } else if (ly == 0) { + j = iy >> (20 - k); + if ((j << (20 - k)) == iy) yisint = 2 - (j & 1); + } + } + } + if (ly == 0) { + if (iy == 0x7ff00000) { + if (((ix - 0x3ff00000) | lx) == 0) return y - y; + else if (ix >= 0x3ff00000) return (hy >= 0) ? y : zero; + else return (hy < 0) ? -y : zero; + } + if (iy == 0x3ff00000) { if (hy < 0) return one / x; else return x; } + if (hy == 0x40000000) return x * x; + if (hy == 0x3fe00000) { if (hx >= 0) return sqrt(x); } + } + ax = fabs(x); + if (lx == 0) { + if (ix == 0x7ff00000 || ix == 0 || ix == 0x3ff00000) { + z = ax; + if (hy < 0) z = one / z; + if (hx < 0) { + if (((ix - 0x3ff00000) | yisint) == 0) z = 0.0 / 0.0; + else if (yisint == 1) z = -z; + } + return z; + } + } + n = (hx >> 31) + 1; + if ((n | yisint) == 0) return 0.0 / 0.0; + s = one; + if ((n | (yisint - 1)) == 0) s = -one; + if (iy > 0x41e00000) { + if (iy > 0x43f00000) { + if (ix <= 0x3fefffff) return (hy < 0) ? huge * huge : tiny * tiny; + if (ix >= 0x3ff00000) return (hy > 0) ? huge * huge : tiny * tiny; + } + if (ix < 0x3fefffff) return (hy < 0) ? s * huge * huge : s * tiny * tiny; + if (ix > 0x3ff00000) return (hy > 0) ? s * huge * huge : s * tiny * tiny; + t = ax - one; + w = (t * t) * (0.5 - t * (0.3333333333333333333333 - t * 0.25)); + u = ivln2_h * t; + v = t * ivln2_l - w * ivln2; + t1 = u + v; + SETLW(t1, 0); + t2 = v - (t1 - u); + } else { + double ss, s2, s_h, s_l, t_h, t_l; + n = 0; + if (ix < 0x00100000) { + ax *= two53; + n -= 53; + GETHW(ix, ax); + } + n += ((ix) >> 20) - 0x3ff; + j = ix & 0x000fffff; + ix = j | 0x3ff00000; + if (j <= 0x3988E) k = 0; + else if (j < 0xBB67A) k = 1; + else { k = 0; n += 1; ix -= 0x00100000; } + SETHW(ax, ix); + u = ax - bp[k]; + v = one / (ax + bp[k]); + ss = u * v; + s_h = ss; + SETLW(s_h, 0); + t_h = zero; + SETHW(t_h, ((ix >> 1) | 0x20000000) + 0x00080000 + (k << 18)); + t_l = ax - (t_h - bp[k]); + s_l = v * ((u - s_h * t_h) - s_h * t_l); + s2 = ss * ss; + r = s2 * s2 * (L1 + s2 * (L2 + s2 * (L3 + s2 * (L4 + s2 * (L5 + s2 * L6))))); + r += s_l * (s_h + ss); + s2 = s_h * s_h; + t_h = 3.0 + s2 + r; + SETLW(t_h, 0); + t_l = r - ((t_h - 3.0) - s2); + u = s_h * t_h; + v = s_l * t_h + t_l * ss; + p_h = u + v; + SETLW(p_h, 0); + p_l = v - (p_h - u); + z_h = cp_h * p_h; + z_l = cp_l * p_h + p_l * cp + dp_l[k]; + t = (double)n; + t1 = (((z_h + z_l) + dp_h[k]) + t); + SETLW(t1, 0); + t2 = z_l - (((t1 - t) - dp_h[k]) - z_h); + } + y1 = y; + SETLW(y1, 0); + p_l = (y - y1) * t1 + y * t2; + p_h = y1 * t1; + z = p_l + p_h; + { uint32_t ui; EXTRACT(j, ui, z); i = (int)ui; } + if (j >= 0x40900000) { + if (((j - 0x40900000) | i) != 0) return s * huge * huge; + else { if (p_l + ovt > z - p_h) return s * huge * huge; } + } else if ((j & 0x7fffffff) >= 0x4090cc00) { + if (((j - (int)0xc090cc00) | i) != 0) return s * tiny * tiny; + else { if (p_l <= z - p_h) return s * tiny * tiny; } + } + i = j & 0x7fffffff; + k = (i >> 20) - 0x3ff; + n = 0; + if (i > 0x3fe00000) { + n = j + (int)(0x00100000 >> (k + 1)); + k = ((n & 0x7fffffff) >> 20) - 0x3ff; + t = zero; + SETHW(t, n & ~(0x000fffff >> k)); + n = ((n & 0x000fffff) | 0x00100000) >> (20 - k); + if (j < 0) n = -n; + p_h -= t; + } + t = p_l + p_h; + SETLW(t, 0); + u = t * lg2_h; + v = (p_l - (t - p_h)) * lg2 + t * lg2_l; + z = u + v; + w = v - (z - u); + t = z * z; + t1 = z - t * (P1 + t * (P2 + t * (P3 + t * (P4 + t * P5)))); + r = (z * t1) / ((t1 - two) - (w + z * w)); + z = one - (r - z); + GETHW(j, z); + j += (int)((uint32_t)n << 20); + if ((j >> 20) <= 0) z = scalbn(z, n); + else SETHW(z, j); + return s * z; +} + +/* ---- V8 12.4 cbrt (msun-style); proven 0/300030 diffs ---- */ +double js_cbrt(double x) { + static const double P0 = 1.87595182427177009643, + P1 = -1.88497979543377169875, + P2 = 1.621429720105354466140, + P3 = -0.758397934778766047437, + P4 = 0.145996192886612446982; + uint64_t ux; + memcpy(&ux, &x, 8); + int32_t hx = (int32_t)(ux >> 32); + uint32_t low = (uint32_t)ux; + uint32_t sign = (uint32_t)hx & 0x80000000u; + hx ^= (int32_t)sign; + if (hx >= 0x7ff00000) return x + x; + double t; + if (hx < 0x00100000) { + if ((hx | (int32_t)low) == 0) return x; + uint64_t ut = (uint64_t)0x43500000 << 32; + memcpy(&t, &ut, 8); + t *= x; + uint64_t u2; + memcpy(&u2, &t, 8); + uint32_t high = (uint32_t)(u2 >> 32); + u2 = ((uint64_t)(sign | ((high & 0x7fffffffu) / 3 + 696219795u)) << 32); + memcpy(&t, &u2, 8); + } else { + uint64_t u2 = ((uint64_t)(sign | ((uint32_t)hx / 3 + 715094163u)) << 32); + memcpy(&t, &u2, 8); + } + double r, s, w; + r = (t * t) * (t / x); + t = t * ((P0 + r * (P1 + r * P2)) + ((r * r) * r) * (P3 + r * P4)); + uint64_t bits; + memcpy(&bits, &t, 8); + bits = (bits + 0x80000000ULL) & 0xFFFFFFFFC0000000ULL; + memcpy(&t, &bits, 8); + s = t * t; + r = x / s; + w = t + t; + r = (r - t) / (w + r); + t = t + t * r; + return t; +} + +/* ---- fdlibm s_atan ---- */ +double js_atan(double x) { + static const double atanhi[] = { + 4.63647609000806093515e-01, 7.85398163397448278999e-01, + 9.82793723247329054082e-01, 1.57079632679489655800e+00 }; + static const double atanlo[] = { + 2.26987774529616870924e-17, 3.06161699786838301793e-17, + 1.39033110312309984516e-17, 6.12323399573676603587e-17 }; + static const double aT[] = { + 3.33333333333329318027e-01, -1.99999999998764832476e-01, + 1.42857142725034663711e-01, -1.11111104054623557880e-01, + 9.09088713343650656196e-02, -7.69187620504482999495e-02, + 6.66107313738753120669e-02, -5.83357013379057348645e-02, + 4.97687799461593236017e-02, -3.65315727442169155270e-02, + 1.62858201153657823623e-02 }; + static const double one = 1.0, huge = 1.0e300; + double w, s1, s2, z; + int32_t ix, hx, id; + GETHW(hx, x); + ix = hx & 0x7FFFFFFF; + if (ix >= 0x44100000) { + uint32_t low; uint64_t u; memcpy(&u,&x,8); low=(uint32_t)u; + if (ix > 0x7FF00000 || (ix == 0x7FF00000 && (low != 0))) return x + x; + if (hx > 0) return atanhi[3] + atanlo[3]; + else return -atanhi[3] - atanlo[3]; + } + if (ix < 0x3FDC0000) { + if (ix < 0x3E400000) { if (huge + x > one) return x; } + id = -1; + } else { + x = fabs(x); + if (ix < 0x3FF30000) { + if (ix < 0x3FE60000) { id = 0; x = (2.0 * x - one) / (2.0 + x); } + else { id = 1; x = (x - one) / (x + one); } + } else { + if (ix < 0x40038000) { id = 2; x = (x - 1.5) / (one + 1.5 * x); } + else { id = 3; x = -1.0 / x; } + } + } + z = x * x; + w = z * z; + s1 = z * (aT[0] + w * (aT[2] + w * (aT[4] + w * (aT[6] + w * (aT[8] + w * aT[10]))))); + s2 = w * (aT[1] + w * (aT[3] + w * (aT[5] + w * (aT[7] + w * aT[9])))); + if (id < 0) return x - x * (s1 + s2); + z = atanhi[id] - ((x * (s1 + s2) - atanlo[id]) - x); + return (hx < 0) ? -z : z; +} + +/* ---- fdlibm e_atan2 ---- */ +double js_atan2(double y, double x) { + static const double zero = 0.0, + pi_o_4 = 7.8539816339744827900E-01, + pi_o_2 = 1.5707963267948965580E+00, + pi = 3.1415926535897931160E+00; + static const double tiny = 1.0e-300; + static const double pi_lo = 1.2246467991473531772E-16; + double z; + int32_t k, m, hx, hy, ix, iy; + uint32_t lx, ly; + EXTRACT(hx, lx, x); + ix = hx & 0x7FFFFFFF; + EXTRACT(hy, ly, y); + iy = hy & 0x7FFFFFFF; + if (((ix | (int32_t)((lx | (uint32_t)(-(int32_t)lx)) >> 31)) > 0x7FF00000) || + ((iy | (int32_t)((ly | (uint32_t)(-(int32_t)ly)) >> 31)) > 0x7FF00000)) + return x + y; + if ((uint32_t)(hx - 0x3FF00000) == 0 && lx == 0) return js_atan(y); + m = ((hy >> 31) & 1) | ((hx >> 30) & 2); + if ((iy | ly) == 0) { + switch (m) { + case 0: case 1: return y; + case 2: return pi + tiny; + default: return -pi - tiny; + } + } + if ((ix | lx) == 0) return (hy < 0) ? -pi_o_2 - tiny : pi_o_2 + tiny; + if (ix == 0x7FF00000) { + if (iy == 0x7FF00000) { + switch (m) { + case 0: return pi_o_4 + tiny; + case 1: return -pi_o_4 - tiny; + case 2: return 3.0 * pi_o_4 + tiny; + default: return -3.0 * pi_o_4 - tiny; + } + } else { + switch (m) { + case 0: return zero; + case 1: return -zero; + case 2: return pi + tiny; + default: return -pi - tiny; + } + } + } + if (iy == 0x7FF00000) return (hy < 0) ? -pi_o_2 - tiny : pi_o_2 + tiny; + k = (iy - ix) >> 20; + if (k > 60) { z = pi_o_2 + 0.5 * pi_lo; m &= 1; } + else if (hx < 0 && k < -60) z = 0.0; + else z = js_atan(fabs(y / x)); + switch (m) { + case 0: return z; + case 1: return -z; + case 2: return pi - (z - pi_lo); + default: return (z - pi_lo) - pi; + } +} + +/* ---- __ieee754_rem_pio2 (small/medium paths; huge args unsupported -> trap) ---- */ +static int32_t rem_pio2(double x, double *y) { + static const int32_t npio2_hw[] = { + 0x3FF921FB, 0x400921FB, 0x4012D97C, 0x401921FB, 0x401F6A7A, 0x4022D97C, + 0x4025FDBB, 0x402921FB, 0x402C463A, 0x402F6A7A, 0x4031475C, 0x4032D97C, + 0x40346B9C, 0x4035FDBB, 0x40378FDB, 0x403921FB, 0x403AB41B, 0x403C463A, + 0x403DD85A, 0x403F6A7A, 0x40407E4C, 0x4041475C, 0x4042106C, 0x4042D97C, + 0x4043A28C, 0x40446B9C, 0x404534AC, 0x4045FDBB, 0x4046C6CB, 0x40478FDB, + 0x404858EB, 0x404921FB }; + static const double + half = 5.00000000000000000000e-01, + invpio2 = 6.36619772367581382433e-01, + pio2_1 = 1.57079632673412561417e+00, + pio2_1t = 6.07710050650619224932e-11, + pio2_2 = 6.07710050630396597660e-11, + pio2_2t = 2.02226624879595063154e-21, + pio2_3 = 2.02226624871116645580e-21, + pio2_3t = 8.47842766036889956997e-32; + double z = 0, w, t, r, fn; + int32_t i, j, n, ix, hx; + GETHW(hx, x); + ix = hx & 0x7FFFFFFF; + if (ix <= 0x3FE921FB) { y[0] = x; y[1] = 0; return 0; } + if (ix < 0x4002D97C) { + if (hx > 0) { + z = x - pio2_1; + if (ix != 0x3FF921FB) { y[0] = z - pio2_1t; y[1] = (z - y[0]) - pio2_1t; } + else { z -= pio2_2; y[0] = z - pio2_2t; y[1] = (z - y[0]) - pio2_2t; } + return 1; + } else { + z = x + pio2_1; + if (ix != 0x3FF921FB) { y[0] = z + pio2_1t; y[1] = (z - y[0]) + pio2_1t; } + else { z += pio2_2; y[0] = z + pio2_2t; y[1] = (z - y[0]) + pio2_2t; } + return -1; + } + } + if (ix <= 0x413921FB) { + t = fabs(x); + n = (int32_t)(t * invpio2 + half); + fn = (double)n; + r = t - fn * pio2_1; + w = fn * pio2_1t; + if (n < 32 && ix != npio2_hw[n - 1]) { y[0] = r - w; } + else { + uint32_t high; + j = ix >> 20; + y[0] = r - w; + GETHW(high, y[0]); + i = j - ((int32_t)(high >> 20) & 0x7FF); + if (i > 16) { + t = r; w = fn * pio2_2; r = t - w; + w = fn * pio2_2t - ((t - r) - w); + y[0] = r - w; + GETHW(high, y[0]); + i = j - ((int32_t)(high >> 20) & 0x7FF); + if (i > 49) { + t = r; w = fn * pio2_3; r = t - w; + w = fn * pio2_3t - ((t - r) - w); + y[0] = r - w; + } + } + } + y[1] = (r - y[0]) - w; + if (hx < 0) { y[0] = -y[0]; y[1] = -y[1]; return -n; } + return n; + } + if (ix >= 0x7FF00000) { y[0] = y[1] = x - x; return 0; } + __builtin_trap(); /* huge-arg path (kernel_rem_pio2) not needed by reader */ +} + +static double ksin(double x, double y, int iy) { + static const double + half = 5.00000000000000000000e-01, + S1 = -1.66666666666666324348e-01, + S2 = 8.33333333332248946124e-03, + S3 = -1.98412698298579493134e-04, + S4 = 2.75573137070700676789e-06, + S5 = -2.50507602534068634195e-08, + S6 = 1.58969099521155010221e-10; + double z, r, v; + int32_t ix; + GETHW(ix, x); + ix &= 0x7FFFFFFF; + if (ix < 0x3E400000) { if ((int)x == 0) return x; } + z = x * x; + v = z * x; + r = S2 + z * (S3 + z * (S4 + z * (S5 + z * S6))); + if (iy == 0) return x + v * (S1 + z * r); + return x - ((z * (half * y - v * r) - y) - v * S1); +} + +static double kcos(double x, double y) { + static const double + one = 1.00000000000000000000e+00, + C1 = 4.16666666666666019037e-02, + C2 = -1.38888888888741095749e-03, + C3 = 2.48015872894767294178e-05, + C4 = -2.75573143513906633035e-07, + C5 = 2.08757232129817482790e-09, + C6 = -1.13596475577881948265e-11; + double a, iz, z, r, qx; + int32_t ix; + GETHW(ix, x); + ix &= 0x7FFFFFFF; + if (ix < 0x3E400000) { if ((int)x == 0) return one; } + z = x * x; + r = z * (C1 + z * (C2 + z * (C3 + z * (C4 + z * (C5 + z * C6))))); + if (ix < 0x3FD33333) return one - (0.5 * z - (z * r - x * y)); + if (ix > 0x3FE90000) qx = 0.28125; + else INSERT(qx, ix - 0x00200000, 0); + iz = 0.5 * z - qx; + a = one - qx; + return a - (iz - (z * r - x * y)); +} + +double js_cos(double x) { + double y[2], z = 0.0; + int32_t n, ix; + GETHW(ix, x); + ix &= 0x7FFFFFFF; + if (ix <= 0x3FE921FB) return kcos(x, z); + else if (ix >= 0x7FF00000) return x - x; + if (ix > 0x413921FB) return cos(x); /* huge-arg: never in reader; libm fallback */ + n = rem_pio2(x, y); + switch (n & 3) { + case 0: return kcos(y[0], y[1]); + case 1: return -ksin(y[0], y[1], 1); + case 2: return -kcos(y[0], y[1]); + default: return ksin(y[0], y[1], 1); + } +} + +double js_sin(double x) { + double y[2], z = 0.0; + int32_t n, ix; + GETHW(ix, x); + ix &= 0x7FFFFFFF; + if (ix <= 0x3FE921FB) return ksin(x, z, 0); + else if (ix >= 0x7FF00000) return x - x; + if (ix > 0x413921FB) return sin(x); /* huge-arg: never in reader; libm fallback */ + n = rem_pio2(x, y); + switch (n & 3) { + case 0: return ksin(y[0], y[1], 1); + case 1: return kcos(y[0], y[1]); + case 2: return -ksin(y[0], y[1], 1); + default: return -kcos(y[0], y[1]); + } +} + +/* ---- fdlibm e_exp ---- */ +double js_exp(double x) { + static const double + one = 1.0, + halF[2] = {0.5, -0.5}, + o_threshold = 7.09782712893383973096e+02, + u_threshold = -7.45133219101941108420e+02, + ln2HI[2] = {6.93147180369123816490e-01, -6.93147180369123816490e-01}, + ln2LO[2] = {1.90821492927058770002e-10, -1.90821492927058770002e-10}, + invln2 = 1.44269504088896338700e+00, + P1 = 1.66666666666666019037e-01, + P2 = -2.77777777770155933842e-03, + P3 = 6.61375632143793436117e-05, + P4 = -1.65339022054652515390e-06, + P5 = 4.13813679705723846039e-08, + E = 2.718281828459045; + static const double huge = 1.0e+300, + twom1000 = 9.33263618503218878990e-302, + two1023 = 8.988465674311579539e307; + double y, hi = 0.0, lo = 0.0, c, t, twopk; + int32_t k = 0, xsb; + uint32_t hx; + GETHW(hx, x); + xsb = (hx >> 31) & 1; + hx &= 0x7FFFFFFF; + if (hx >= 0x40862E42) { + if (hx >= 0x7FF00000) { + uint32_t lx; uint64_t u; memcpy(&u,&x,8); lx=(uint32_t)u; + if (((hx & 0xFFFFF) | lx) != 0) return x + x; + else return (xsb == 0) ? x : 0.0; + } + if (x > o_threshold) return huge * huge; + if (x < u_threshold) return twom1000 * twom1000; + } + if (hx > 0x3FD62E42) { + if (hx < 0x3FF0A2B2) { + if (x == 1.0) return E; + hi = x - ln2HI[xsb]; + lo = ln2LO[xsb]; + k = 1 - xsb - xsb; + } else { + k = (int32_t)(invln2 * x + halF[xsb]); + t = k; + hi = x - t * ln2HI[0]; + lo = t * ln2LO[0]; + } + x = hi - lo; + } else if (hx < 0x3E300000) { + if (huge + x > one) return one + x; + } else { + k = 0; + } + t = x * x; + if (k >= -1021) INSERT(twopk, 0x3FF00000 + (int32_t)((uint32_t)k << 20), 0); + else INSERT(twopk, 0x3FF00000 + (int32_t)((uint32_t)(k + 1000) << 20), 0); + c = x - t * (P1 + t * (P2 + t * (P3 + t * (P4 + t * P5)))); + if (k == 0) return one - ((x * c) / (c - 2.0) - x); + y = one - ((lo - (x * c) / (2.0 - c)) - hi); + if (k >= -1021) { + if (k == 1024) return y * 2.0 * two1023; + return y * twopk; + } + return y * twopk * twom1000; +} + +/* ---- fdlibm e_log ---- */ +double js_log(double x) { + static const double + ln2_hi = 6.93147180369123816490e-01, + ln2_lo = 1.90821492927058770002e-10, + two54 = 1.80143985094819840000e+16, + Lg1 = 6.666666666666735130e-01, + Lg2 = 3.999999999940941908e-01, + Lg3 = 2.857142874366239149e-01, + Lg4 = 2.222219843214978396e-01, + Lg5 = 1.818357216161805012e-01, + Lg6 = 1.531383769920937332e-01, + Lg7 = 1.479819860511658591e-01; + static const double zero = 0.0; + double hfsq, f, s, z, R, w, t1, t2, dk; + int32_t k, hx, i, j; + uint32_t lx; + EXTRACT(hx, lx, x); + k = 0; + if (hx < 0x00100000) { + if (((hx & 0x7FFFFFFF) | lx) == 0) return -1.0 / 0.0; + if (hx < 0) return 0.0 / 0.0; + k -= 54; + x *= two54; + GETHW(hx, x); + } + if (hx >= 0x7FF00000) return x + x; + k += (hx >> 20) - 1023; + hx &= 0x000FFFFF; + i = (hx + 0x95F64) & 0x100000; + SETHW(x, hx | (i ^ 0x3FF00000)); + k += (i >> 20); + f = x - 1.0; + if ((0x000FFFFF & (2 + hx)) < 3) { + if (f == zero) { + if (k == 0) return zero; + dk = (double)k; + return dk * ln2_hi + dk * ln2_lo; + } + R = f * f * (0.5 - 0.33333333333333333 * f); + if (k == 0) return f - R; + dk = (double)k; + return dk * ln2_hi - ((R - dk * ln2_lo) - f); + } + s = f / (2.0 + f); + dk = (double)k; + z = s * s; + i = hx - 0x6147A; + w = z * z; + j = 0x6B851 - hx; + t1 = w * (Lg2 + w * (Lg4 + w * Lg6)); + t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7))); + i |= j; + R = t2 + t1; + if (i > 0) { + hfsq = 0.5 * f * f; + if (k == 0) return f - (hfsq - s * (hfsq + R)); + return dk * ln2_hi - ((hfsq - (s * (hfsq + R) + dk * ln2_lo)) - f); + } else { + if (k == 0) return f - s * (f - R); + return dk * ln2_hi - ((s * (f - R) - dk * ln2_lo) - f); + } +} + +/* ---- Math.hypot(x,y): V8 torque algorithm (max-scaled) ---- */ +double js_hypot2(double x, double y) { + x = fabs(x); y = fabs(y); + double max = x > y ? x : y; + if (max == 0) return 0; + if (isinf(max)) return max; + double sum = 0; + if (x != 0) { double v = x / max; sum += v * v; } + if (y != 0) { double v = y / max; sum += v * v; } + return max * sqrt(sum); +} diff --git a/ports/c/reader/prism_jsmath.h b/ports/c/reader/prism_jsmath.h new file mode 100644 index 0000000..dad7678 --- /dev/null +++ b/ports/c/reader/prism_jsmath.h @@ -0,0 +1,14 @@ +/* prism_jsmath.h - exact ports of V8 12.4 math functions (fdlibm-based ieee754.cc). + Node's Math.* != glibc libm; these match Node bit-for-bit. Compile with -ffp-contract=off. */ +#ifndef PRISM_JSMATH_H +#define PRISM_JSMATH_H +double js_pow(double x, double y); +double js_cbrt(double x); +double js_atan(double x); +double js_atan2(double y, double x); +double js_sin(double x); +double js_cos(double x); +double js_exp(double x); +double js_log(double x); +double js_hypot2(double x, double y); /* Math.hypot(x,y) */ +#endif diff --git a/ports/c/reader/prism_mix.c b/ports/c/reader/prism_mix.c new file mode 100644 index 0000000..1edf1ad --- /dev/null +++ b/ports/c/reader/prism_mix.c @@ -0,0 +1,742 @@ +/* prism_mix.c - C port of the worker palette-mixing layer (Build 136): + * mixFit, mixRecover, mixDirect, mixAlternate. + * mixFit/mixRecover/mixDirect are pure double math: bit-exact vs the worker. + * mixAlternate is reproduced in software (exact polygon-area AA + bilinear + * 4x downscale), validated against captured browser output within ~4 luma on + * AA edge pixels; see the implementation comment below. + */ +#include +#include +#include +#include +#include "prism_reader.h" +#include "prism_jsmath.h" + +static const char *MIX_HEX[9] = {"#1B1B1B", "#2E5BFF", "#00B8D9", "#2DB35A", "#F5C518", "#F77F00", "#D7263D", "#B5179E", "#FFFFFF"}; + +static int hex_byte(const char *h, int off) { /* parseInt(h.slice(off, off+2), 16) */ + int v = 0; + for (int i = 0; i < 2; i++) { + char c = h[off + i]; int d; + if (c >= '0' && c <= '9') d = c - '0'; + else if (c >= 'a' && c <= 'f') d = c - 'a' + 10; + else d = c - 'A' + 10; + v = v * 16 + d; + } + return v; +} + +static double mj_round(double x) { return floor(x + 0.5); } /* JS Math.round (ties toward +inf) */ + +/* v offsets: [[0,0], [0.45*cos(k*PI/3), 0.45*sin(k*PI/3)] for k=0..5] */ +static void mix_offsets(double v[7][2]) { + v[0][0] = 0; v[0][1] = 0; + for (int k = 0; k < 6; k++) { + v[k + 1][0] = 0.45 * js_cos((double)k * M_PI / 3); + v[k + 1][1] = 0.45 * js_sin((double)k * M_PI / 3); + } +} + +/* ---------------- mixFit ---------------- */ +double *prism_mix_fit(const PrismFrame *A, const double H[8], const PrismLayout *L) { + const uint8_t *d = A->image; + int W = A->w, Ht = A->h; + double base[8]; memcpy(base, H, sizeof base); + double pal[9]; + for (int s = 0; s < 9; s++) { + int r = hex_byte(MIX_HEX[s], 1), g = hex_byte(MIX_HEX[s], 3), b = hex_byte(MIX_HEX[s], 5); + pal[s] = 0.299 * r + 0.587 * g + 0.114 * b; + } + double v[7][2]; mix_offsets(v); + /* known = ring|pilot */ + int nk = 0; + for (int i = 0; i < L->n_known; i++) { const char *r = NULL; (void)r; nk++; } /* L->known is ring+pilot already */ + (void)nk; + const int n_known = L->n_known; + + /* candidate(p) */ + #define CAND(p_, h_) do { \ + memcpy(h_, base, 8 * sizeof(double)); \ + h_[2] += (p_)[0]; h_[5] += (p_)[1]; \ + h_[0] *= 1 + (p_)[2]; h_[4] *= 1 + (p_)[3]; \ + h_[1] += (p_)[4]; h_[3] += (p_)[5]; \ + } while (0) + + /* lum(x, y): bilinear luma on the original rgba */ + #define LUM(xx_, yy_, out_) do { \ + double x_ = (xx_), y_ = (yy_); \ + int xi_ = (int)floor(x_), yi_ = (int)floor(y_); \ + double fx_ = x_ - xi_, fy_ = y_ - yi_; \ + if (xi_ < 0 || yi_ < 0 || xi_ >= W - 1 || yi_ >= Ht - 1) *(out_) = 255; \ + else { \ + double val_ = 0; \ + for (int dy_ = 0; dy_ < 2; dy_++) for (int dx_ = 0; dx_ < 2; dx_++) { \ + int q_ = ((yi_ + dy_) * W + xi_ + dx_) * 4; \ + val_ += (0.299 * d[q_] + 0.587 * d[q_ + 1] + 0.114 * d[q_ + 2]) * (dx_ ? fx_ : 1 - fx_) * (dy_ ? fy_ : 1 - fy_); \ + } \ + *(out_) = val_; \ + } \ + } while (0) + + /* loss(p) */ + #define LOSS(p_, out_) do { \ + double h_[8]; CAND(p_, h_); \ + PrismMap mm_; memset(&mm_, 0, sizeof mm_); memcpy(mm_.h, h_, 64); \ + double sum_ = 0; \ + for (int ki_ = 0; ki_ < n_known; ki_++) { \ + const PrismCell *c_ = L->known[ki_]; \ + for (int oi_ = 0; oi_ < 7; oi_++) { \ + double qx_, qy_; map_point(&mm_, c_->x + v[oi_][0], c_->y + v[oi_][1], &qx_, &qy_); \ + double lv_; LUM(qx_, qy_, &lv_); \ + double err_ = lv_ - pal[c_->symbol]; \ + sum_ += err_ * err_ < 2500 ? err_ * err_ : 2500; \ + } \ + } \ + *(out_) = sum_; \ + } while (0) + + double p[6] = {0, 0, 0, 0, 0, 0}; + double sc[6] = {1, 1, 1 / L->W, 1 / L->H, 1 / L->H, 1 / L->W}; + double best; LOSS(p, &best); + static const double steps[5] = {0.8, 0.4, 0.2, 0.1, 0.05}; + for (int si = 0; si < 5; si++) + for (int it = 0; it < 4; it++) { + int changed = 0; + for (int k = 0; k < 6; k++) { + double bk = p[k]; + for (int sg = 0; sg < 2; sg++) { + double q[6]; memcpy(q, p, sizeof q); + q[k] += (sg ? 1.0 : -1.0) * steps[si] * sc[k]; + double ls; LOSS(q, &ls); + if (ls < best) { best = ls; bk = q[k]; changed = 1; } + } + p[k] = bk; + } + if (!changed) break; + } + double *out = malloc(8 * sizeof(double)); + CAND(p, out); + #undef LOSS + #undef LUM + #undef CAND + return out; +} + +/* ---------------- mixRecover ---------------- */ +/* insertion-ordered (n, wt) row, JS Map semantics */ +typedef struct { int n; double wt; } RowEnt; +typedef struct { RowEnt *e; int n, cap; } MixRow; +static void row_add(MixRow *r, int n, double wt) { /* row.set(n, (row.get(n)||0)+wt) */ + for (int i = 0; i < r->n; i++) if (r->e[i].n == n) { r->e[i].wt += wt; return; } + if (r->n == r->cap) { r->cap = r->cap ? r->cap * 2 : 8; r->e = realloc(r->e, (size_t)r->cap * sizeof(RowEnt)); } + r->e[r->n].n = n; r->e[r->n].wt = wt; r->n++; +} + +static int mix_symbols_valid; /* globalThis.__mixSymbols: sticky once set */ +PrismPayload *prism_mix_recover(const PrismFrame *A, const double h[8], const PrismLayout *L, int *symbols_out) { + const uint8_t *d = A->image; + int W = A->w, H = A->h; + double pitch = js_hypot2(h[0], h[3]) * sqrt(3); + if (pitch < 1 || pitch > 4.5) return NULL; + int N = L->n_cells; + double pal[9][3]; + for (int s = 0; s < 9; s++) { + double r = hex_byte(MIX_HEX[s], 1), g = hex_byte(MIX_HEX[s], 3), b = hex_byte(MIX_HEX[s], 5); + pal[s][0] = 0.299 * r + 0.587 * g + 0.114 * b; + pal[s][1] = 128 - 0.168736 * r - 0.331264 * g + 0.5 * b; + pal[s][2] = 128 + 0.5 * r - 0.418688 * g - 0.081312 * b; + } + PrismMap mm; memset(&mm, 0, sizeof mm); memcpy(mm.h, h, 64); + double minx = 1e30, miny = 1e30, maxx = -1e30, maxy = -1e30; + for (int i = 0; i < N; i++) { + double px, py; map_point(&mm, L->cells[i].x, L->cells[i].y, &px, &py); + if (px < minx) minx = px; if (px > maxx) maxx = px; + if (py < miny) miny = py; if (py > maxy) maxy = py; + } + int x0 = (int)fmax(0, floor(minx - 6)), y0 = (int)fmax(0, floor(miny - 6)); + int x1 = (int)fmin(W, ceil(maxx + 8)), y1 = (int)fmin(H, ceil(maxy + 8)); + x0 -= x0 % 2; y0 -= y0 % 2; x1 -= x1 % 2; y1 -= y1 % 2; + int w = x1 - x0, ht = y1 - y0; + long M = (long)w * ht; + if (M <= 0 || M > 50000) return NULL; + double a = h[0], b = h[1], c = h[2], dd = h[3], ee = h[4], f = h[5], g = h[6], hh = h[7]; + double inv[9] = { + ee - f * hh, c * hh - b, b * f - c * ee, + f * g - dd, a - c * g, c * dd - a * f, + dd * hh - ee * g, b * dd - a * hh, a * ee - b * dd, + }; + double *obs[3]; + for (int ch = 0; ch < 3; ch++) obs[ch] = malloc((size_t)M * sizeof(double)); + MixRow *rows = calloc((size_t)M, sizeof(MixRow)); + double S3 = sqrt(3); + for (int y = 0; y < ht; y++) + for (int x = 0; x < w; x++) { + int ix = x + x0, iy = y + y0; + long k = (long)y * w + x; + int q = (iy * W + ix) * 4; + double r = d[q], gg = d[q + 1], bb = d[q + 2]; + obs[0][k] = 0.299 * r + 0.587 * gg + 0.114 * bb; + obs[1][k] = 128 - 0.168736 * r - 0.331264 * gg + 0.5 * bb; + obs[2][k] = 128 + 0.5 * r - 0.418688 * gg - 0.081312 * bb; + double z = inv[6] * ix + inv[7] * iy + inv[8]; + double u = (inv[0] * ix + inv[1] * iy + inv[2]) / z; + double vv = (inv[3] * ix + inv[4] * iy + inv[5]) / z; + double tx = (u + 3 * S3) * 10, ty = (vv + 3 * S3) * 10; + int ux = (int)floor(tx), vy = (int)floor(ty); + double fx = tx - ux, fy = ty - vy; + static const int tap[4][2] = {{0, 0}, {1, 0}, {0, 1}, {1, 1}}; + MixRow *row = &rows[k]; + for (int t = 0; t < 4; t++) { + int dx = tap[t][0], dy = tap[t][1]; + double wt = (dx ? fx : 1 - fx) * (dy ? fy : 1 - fy); + for (int sy = 0; sy < 4; sy++) + for (int sx = 0; sx < 4; sx++) { + double uu = (ux + dx + (sx + 0.5) / 4) / 10 - 3 * S3; + double v2 = (vy + dy + (sy + 0.5) / 4) / 10 - 3 * S3; + int jr = (int)mj_round((v2 - 1) / 1.5); + int n = N; + for (int j = jr - 1; j <= jr + 1; j++) { + int ii = (int)mj_round(uu / S3 - 0.5 - 0.5 * (j & 1)); + if (ii < 0 || ii >= L->C || j < 0 || j >= L->R) continue; + double hx = fabs(uu - S3 * (ii + 0.5 + 0.5 * (j & 1))); + double hy = fabs(v2 - 1 - 1.5 * j); + if (hx <= (1.03 * S3) / 2 && hy <= 1.03 - hx / S3) + n = (int)fmax(n == N ? -1 : n, (double)(j * L->C + ii)); + } + row_add(row, n, wt / 16); + } + } + } + /* chroma rows */ + MixRow *chrom = calloc((size_t)M, sizeof(MixRow)); + for (int y = 0; y < ht; y++) + for (int x = 0; x < w; x++) { + MixRow *row = &chrom[(long)y * w + x]; + for (int ky_ = 0; ky_ < 2; ky_++) { + int ky = ky_ == 0 ? y >> 1 : (y >> 1) + (y % 2 ? 1 : -1); + int kymax = (ht >> 1) - 1; + if (ky < 0) ky = 0; if (ky > kymax) ky = kymax; + double wy = ky_ == 0 ? 0.75 : 0.25; + for (int kx_ = 0; kx_ < 2; kx_++) { + int kx = kx_ == 0 ? x >> 1 : (x >> 1) + (x % 2 ? 1 : -1); + int kxmax = (w >> 1) - 1; + if (kx < 0) kx = 0; if (kx > kxmax) kx = kxmax; + double wx = kx_ == 0 ? 0.75 : 0.25; + for (int oy = 0; oy < 2; oy++) + for (int ox = 0; ox < 2; ox++) { + MixRow *src = &rows[(long)(ky * 2 + oy) * w + kx * 2 + ox]; + for (int i = 0; i < src->n; i++) + row_add(row, src->e[i].n, src->e[i].wt * wy * wx * 0.25); + } + } + } + } + /* known / symbols / X */ + int *known = malloc((size_t)(N + 1) * sizeof(int)); + int *symbols = malloc((size_t)(N + 1) * sizeof(int)); + for (int i = 0; i < N; i++) { + int rl = L->cells[i].role; + known[i] = (rl == ROLE_RING || rl == ROLE_PILOT || rl == ROLE_GAP); + symbols[i] = known[i] ? L->cells[i].symbol : 0; + } + known[N] = 1; symbols[N] = 8; + int *unknown = malloc((size_t)N * sizeof(int)); int n_unknown = 0; + for (int k = 0; k < N; k++) if (!known[k]) unknown[n_unknown++] = k; + double (*X)[3] = malloc((size_t)(N + 1) * sizeof *X); + for (int k = 0; k <= N; k++) memcpy(X[k], pal[symbols[k]], 3 * sizeof(double)); + /* per-channel CG */ + RowEnt **col = calloc((size_t)(N + 1), sizeof(RowEnt *)); + int *coln = calloc((size_t)(N + 1), sizeof(int)), *colcap = calloc((size_t)(N + 1), sizeof(int)); + double **resid = malloc(3 * sizeof(double *)); + MixRow *mats[3] = {rows, chrom, chrom}; + /* links = col per channel (same structure, rebuilt per ch like JS) */ + RowEnt ***links = malloc(3 * sizeof(RowEnt **)); + int **linkn = malloc(3 * sizeof(int *)); + for (int ch = 0; ch < 3; ch++) { + MixRow *mat = mats[ch]; + for (int n = 0; n <= N; n++) { coln[n] = 0; } + double *rhs = malloc((size_t)M * sizeof(double)); + memcpy(rhs, obs[ch], (size_t)M * sizeof(double)); + for (long r = 0; r < M; r++) + for (int i = 0; i < mat[r].n; i++) { + int n = mat[r].e[i].n; double wt = mat[r].e[i].wt; + if (coln[n] == colcap[n]) { colcap[n] = colcap[n] ? colcap[n] * 2 : 8; col[n] = realloc(col[n], (size_t)colcap[n] * sizeof(RowEnt)); } + col[n][coln[n]].n = (int)r; col[n][coln[n]].wt = wt; coln[n]++; + if (known[n]) rhs[r] -= wt * X[n][ch]; + } + /* mul(vec) */ + double *vec_out = malloc((size_t)(N + 1) * sizeof(double)); + double *rr = calloc((size_t)(N + 1), sizeof(double)); + for (int ui = 0; ui < n_unknown; ui++) { + int n = unknown[ui]; + for (int i = 0; i < coln[n]; i++) rr[n] += col[n][i].wt * rhs[col[n][i].n]; + } + double *p = malloc((size_t)(N + 1) * sizeof(double)); + memcpy(p, rr, (size_t)(N + 1) * sizeof(double)); + double *sol = calloc((size_t)(N + 1), sizeof(double)); + double rs = 0; + for (int ui = 0; ui < n_unknown; ui++) rs += rr[unknown[ui]] * rr[unknown[ui]]; + for (int it = 0; it < 150 && rs > 1e-8; it++) { + /* ap = mul(p) */ + memset(vec_out, 0, (size_t)(N + 1) * sizeof(double)); + for (long r = 0; r < M; r++) { + double v = 0; + for (int i = 0; i < mat[r].n; i++) if (!known[mat[r].e[i].n]) v += mat[r].e[i].wt * p[mat[r].e[i].n]; + for (int i = 0; i < mat[r].n; i++) if (!known[mat[r].e[i].n]) vec_out[mat[r].e[i].n] += mat[r].e[i].wt * v; + } + for (int ui = 0; ui < n_unknown; ui++) vec_out[unknown[ui]] += 0.0625 * p[unknown[ui]]; + double den = 0; + for (int ui = 0; ui < n_unknown; ui++) den += p[unknown[ui]] * vec_out[unknown[ui]]; + if (den <= 0) break; + double alpha = rs / den; + for (int ui = 0; ui < n_unknown; ui++) { + int n = unknown[ui]; + sol[n] += alpha * p[n]; + rr[n] -= alpha * vec_out[n]; + } + double ns = 0; + for (int ui = 0; ui < n_unknown; ui++) ns += rr[unknown[ui]] * rr[unknown[ui]]; + double beta = ns / rs; + for (int ui = 0; ui < n_unknown; ui++) { int n = unknown[ui]; p[n] = rr[n] + beta * p[n]; } + rs = ns; + } + for (int ui = 0; ui < n_unknown; ui++) X[unknown[ui]][ch] = sol[unknown[ui]]; + links[ch] = malloc((size_t)(N + 1) * sizeof(RowEnt *)); + linkn[ch] = malloc((size_t)(N + 1) * sizeof(int)); + for (int n = 0; n <= N; n++) { links[ch][n] = col[n]; linkn[ch][n] = coln[n]; col[n] = NULL; coln[n] = 0; colcap[n] = 0; } + free(rhs); free(vec_out); free(rr); free(p); free(sol); + } + /* snap to palette */ + for (int ui = 0; ui < n_unknown; ui++) { + int n = unknown[ui]; + int bs = 0; double bc = 1.0 / 0.0; + for (int s = 0; s < 9; s++) { + int role = L->cells[n].role; + if ((role == ROLE_DATA && s == 8) || (role == ROLE_HEADER && s > 0 && s < 8)) continue; + double cost = 0; + for (int ch = 0; ch < 3; ch++) { + double dlt = X[n][ch] - pal[s][ch]; + cost += (ch == 0 ? 8 : 1) * dlt * dlt; + } + if (cost < bc) { bc = cost; bs = s; } + } + symbols[n] = bs; + memcpy(X[n], pal[bs], 3 * sizeof(double)); + } + /* residuals */ + for (int ch = 0; ch < 3; ch++) { + resid[ch] = malloc((size_t)M * sizeof(double)); + MixRow *mat = mats[ch]; + for (long r = 0; r < M; r++) { + double s = 0; + for (int i = 0; i < mat[r].n; i++) s += mat[r].e[i].wt * X[mat[r].e[i].n][ch]; + resid[ch][r] = obs[ch][r] - s; + } + } + /* costs(n) -> out[9] */ + #define COSTS(n_, out_) do { \ + for (int s_ = 0; s_ < 9; s_++) (out_)[s_] = 0; \ + for (int ch_ = 0; ch_ < 3; ch_++) { \ + double sq_ = 0, rv_ = 0; \ + for (int i_ = 0; i_ < linkn[ch_][n_]; i_++) { \ + double wt_ = links[ch_][n_][i_].wt; \ + sq_ += wt_ * wt_; \ + rv_ += wt_ * resid[ch_][links[ch_][n_][i_].n]; \ + } \ + for (int s_ = 0; s_ < 9; s_++) { \ + double dlt_ = pal[s_][ch_] - X[n_][ch_]; \ + (out_)[s_] += (ch_ == 0 ? 8 : 1) * (sq_ * dlt_ * dlt_ - 2 * rv_ * dlt_); \ + } \ + } \ + if (L->cells[n_].role == ROLE_DATA) (out_)[8] = 1e20; \ + else if (L->cells[n_].role == ROLE_HEADER) for (int s_ = 1; s_ < 8; s_++) (out_)[s_] = 1e20; \ + } while (0) + /* refinement iterations */ + for (int it = 0; it < 12; it++) { + int changed = 0; + for (int ui = 0; ui < n_unknown; ui++) { + int n = unknown[ui]; + double cs[9]; COSTS(n, cs); + int bs = 0; double mn = cs[0]; + for (int s = 1; s < 9; s++) if (cs[s] < mn) { mn = cs[s]; bs = s; } + if (bs == symbols[n]) continue; + changed++; + for (int ch = 0; ch < 3; ch++) { + double dlt = pal[bs][ch] - X[n][ch]; + for (int i = 0; i < linkn[ch][n]; i++) resid[ch][links[ch][n][i].n] -= links[ch][n][i].wt * dlt; + } + symbols[n] = bs; + memcpy(X[n], pal[bs], 3 * sizeof(double)); + } + if (!changed) break; + } + if (symbols_out) memcpy(symbols_out, symbols, (size_t)(N + 1) * sizeof(int)); + mix_symbols_valid = 1; /* globalThis.__mixSymbols = symbols */ + /* per-cell costs for header soft bits */ + float hb[24] = {0}; + double (*cs_all)[9] = malloc((size_t)N * sizeof *cs_all); + for (int n = 0; n < N; n++) { + if (known[n]) continue; + COSTS(n, cs_all[n]); + } + for (int i = 0; i < L->n_headers; i++) { + const PrismCell *cc = L->headers[i]; + if (known[cc->index]) continue; /* JS: cs[c.index] null for known -> would throw; headers are never known */ + hb[cc->header % 24] = (float)(hb[cc->header % 24] + (cs_all[cc->index][0] - cs_all[cc->index][8])); + } + PrismHeader header; + const char *herr = NULL; + if (header_decode24(hb, &header, &herr)) goto fail; + if (header.size != L->size || header.mode) goto fail; + static const double temps[3] = {80, 300, 1200}; + PrismPayload *out = NULL; + for (int ti = 0; ti < 3; ti++) { + int nstream = L->n_data * 3; + float *stream = malloc((size_t)nstream * sizeof(float)); + int sp = 0; + for (int i = 0; i < L->n_data; i++) { + const PrismCell *cc = L->data[i]; + double *dd2 = cs_all[cc->index]; + double mn = dd2[0]; + for (int s = 1; s < 9; s++) if (dd2[s] < mn) mn = dd2[s]; + double pp[9]; + for (int s = 0; s < 9; s++) pp[s] = js_exp(-(dd2[s] - mn) / temps[ti]); + for (int bb2 = 0; bb2 < 3; bb2++) { + double n0 = 1e-12, n1 = 1e-12; + for (int s = 0; s < 8; s++) + if (((s ^ (s >> 1)) >> (2 - bb2)) & 1) n1 += pp[s]; + else n0 += pp[s]; + double lv = js_log(n0 / n1); + if (lv < -12) lv = -12; else if (lv > 12) lv = 12; + stream[sp++] = (float)lv; + } + } + out = calloc(1, sizeof(PrismPayload)); + PrismErr perr; + if (!prism_decode_stream(&header, stream, out, &perr)) { + out->variant = "palette mixing"; + free(stream); + goto cleanup_ok; + } + free(out); out = NULL; free(stream); + } +fail:; + /* mirror JS `return null` */ + for (int ch = 0; ch < 3; ch++) { free(obs[ch]); free(resid[ch]); } + for (long r = 0; r < M; r++) { free(rows[r].e); free(chrom[r].e); } + free(rows); free(chrom); free(known); free(symbols); free(unknown); free(X); + for (int ch = 0; ch < 3; ch++) { for (int n = 0; n <= N; n++) free(links[ch][n]); free(links[ch]); free(linkn[ch]); } + free(links); free(linkn); free(col); free(coln); free(colcap); free(resid); free(cs_all); + return NULL; +cleanup_ok:; + for (int ch = 0; ch < 3; ch++) { free(obs[ch]); free(resid[ch]); } + for (long r = 0; r < M; r++) { free(rows[r].e); free(chrom[r].e); } + free(rows); free(chrom); free(known); free(symbols); free(unknown); free(X); + for (int ch = 0; ch < 3; ch++) { for (int n = 0; n <= N; n++) free(links[ch][n]); free(links[ch]); free(linkn[ch]); } + free(links); free(linkn); free(col); free(coln); free(colcap); free(resid); free(cs_all); + /* NOTE: symbols_out was already filled before decode; JS sets __mixSymbols even on success path */ + return out; + #undef COSTS +} + +/* ---------------- mixAlternate ---------------- */ +/* Software reproduction of the browser canvas rasterization used by + * mixAlternate. Probed against Chromium/Skia: + * - hexagon fill: exact polygon-area coverage per big pixel (Skia AA matches + * analytic coverage within +/-1-2 bytes on edge pixels), + * - hexagons painted in cell order, src-over with per-fill byte rounding, + * - drawImage 4x downscale: bilinear sample of the big bytes at + * src coord (4*dst + 1.5), result rounded to byte, + * - luma .299/.587/.114 from bytes. + * Validated vs a captured browser yy (t400_small2_0): max diff ~4 luma on AA + * edge pixels, 0 in fill regions. Not bit-exact (engine AA internals) but + * numerically equivalent for the coordinate-descent loss below. */ + +/* area of convex polygon (vx,vy,n) clipped to pixel square [px,px+1]x[py,py+1] + * via Sutherland-Hodgman + shoelace. */ +static double hex_clip_area(const double *vx, const double *vy, int n, int px, int py) { + double cx[16], cy[16]; int cn = n; + for (int i = 0; i < n; i++) { cx[i] = vx[i]; cy[i] = vy[i]; } + const double nx_[4] = {1, -1, 0, 0}, ny_[4] = {0, 0, 1, -1}; + const double d_[4] = {px, -(double)(px + 1), py, -(double)(py + 1)}; + for (int h = 0; h < 4 && cn; h++) { + double nx = nx_[h], ny = ny_[h], dd = d_[h]; + double ox[16], oy[16]; int on = 0; + for (int i = 0; i < cn; i++) { + double ax = cx[i], ay = cy[i], bx = cx[(i + 1) % cn], by = cy[(i + 1) % cn]; + double fa = nx * ax + ny * ay - dd, fb = nx * bx + ny * by - dd; + if (fa >= 0) { ox[on] = ax; oy[on] = ay; on++; } + if ((fa >= 0) != (fb >= 0)) { + double t = fa / (fa - fb); + ox[on] = ax + t * (bx - ax); oy[on] = ay + t * (by - ay); on++; + } + } + memcpy(cx, ox, on * sizeof(double)); memcpy(cy, oy, on * sizeof(double)); cn = on; + } + if (!cn) return 0.0; + double a = 0.0; + for (int i = 0; i < cn; i++) { + double ax = cx[i], ay = cy[i], bx = cx[(i + 1) % cn], by = cy[(i + 1) % cn]; + a += ax * by - bx * ay; + } + return fabs(a) / 2; +} + +typedef struct { + int W, Ht, BW, BH; + float *yy; /* W*Ht downscaled luma */ + int x0, x1, y0, y1; /* loss window in image pixels */ +} MaltCtx; + +static void malt_cand(const double base[8], const double p[4], double h[8]) { + memcpy(h, base, 8 * sizeof(double)); + h[2] += p[0]; h[5] += p[1]; h[0] *= 1 + p[2]; h[4] *= 1 + p[3]; +} + +static double malt_loss(const MaltCtx *ctx, const PrismFrame *A, const double base[8], + const double p[4], double Q) { + double h[8]; malt_cand(base, p, h); + double a = h[0], b = h[1], c = h[2], d0 = h[3], e = h[4], f = h[5], g = h[6], hh = h[7]; + double iv[9] = {e - f * hh, c * hh - b, b * f - c * e, + f * g - d0, a - c * g, c * d0 - a * f, + d0 * hh - e * g, b * d0 - a * hh, a * e - b * d0}; + const uint8_t *d = A->image; const int AW = A->w; + double sum = 0; long n = 0; + for (int y = ctx->y0; y <= ctx->y1; y++) for (int x = ctx->x0; x <= ctx->x1; x++) { + double z = iv[6] * x + iv[7] * y + iv[8]; + double u = ((iv[0] * x + iv[1] * y + iv[2]) / z + Q) * 10; + double v = ((iv[3] * x + iv[4] * y + iv[5]) / z + Q) * 10; + int ux = (int)floor(u), vy = (int)floor(v); + double fx = u - ux, fy = v - vy; + if (ux < 0 || vy < 0 || ux >= ctx->W - 1 || vy >= ctx->Ht - 1) continue; + long j = (long)vy * ctx->W + ux; + double pred = (ctx->yy[j] * (1 - fx) + ctx->yy[j + 1] * fx) * (1 - fy) + + (ctx->yy[j + ctx->W] * (1 - fx) + ctx->yy[j + ctx->W + 1] * fx) * fy; + long k = ((long)y * AW + x) * 4; + double ob = .299 * d[k] + .587 * d[k + 1] + .114 * d[k + 2]; + double df = ob - pred; sum += df * df > 2000 ? 2000 : df * df; n++; + } + return sum / (n > 1 ? n : 1); +} + +double *prism_mix_alternate(const PrismFrame *A, const double H[8], const PrismLayout *L, const int *symbols) { + const double Q = PRISM_Q; + MaltCtx ctx; memset(&ctx, 0, sizeof(ctx)); + ctx.W = (int)ceil((L->W + 2 * Q) * 10); + ctx.Ht = (int)ceil((L->H + 2 * Q) * 10); + const int scale = 4; + ctx.BW = ctx.W * scale; ctx.BH = ctx.Ht * scale; + uint8_t *big = malloc((size_t)ctx.BW * ctx.BH * 3); + if (!big) { double *o = malloc(8 * sizeof(double)); memcpy(o, H, 8 * sizeof(double)); return o; } + memset(big, 255, (size_t)ctx.BW * ctx.BH * 3); + /* rasterize hexagons in cell order, src-over with per-fill byte rounding */ + for (int ci = 0; ci < L->n_cells; ci++) { + const PrismCell *c = &L->cells[ci]; + int s = symbols[c->index]; + if (s == 8) continue; + int pr = hex_byte(MIX_HEX[s], 1), pg = hex_byte(MIX_HEX[s], 3), pb = hex_byte(MIX_HEX[s], 5); + double vx[6], vy[6], x0 = 1e300, x1 = -1e300, y0 = 1e300, y1 = -1e300; + for (int k = 0; k < 6; k++) { + double ang = (30 + 60 * k) * M_PI / 180; + vx[k] = (c->x + Q + 1.03 * cos(ang)) * 10 * scale; + vy[k] = (c->y + Q + 1.03 * sin(ang)) * 10 * scale; + if (vx[k] < x0) x0 = vx[k]; if (vx[k] > x1) x1 = vx[k]; + if (vy[k] < y0) y0 = vy[k]; if (vy[k] > y1) y1 = vy[k]; + } + int px0 = (int)floor(x0), px1 = (int)ceil(x1), py0 = (int)floor(y0), py1 = (int)ceil(y1); + if (px0 < 0) px0 = 0; if (py0 < 0) py0 = 0; + if (px1 > ctx.BW - 1) px1 = ctx.BW - 1; if (py1 > ctx.BH - 1) py1 = ctx.BH - 1; + for (int py = py0; py <= py1; py++) for (int px = px0; px <= px1; px++) { + double cov = hex_clip_area(vx, vy, 6, px, py); + if (cov <= 0) continue; + if (cov > 1) cov = 1; + uint8_t *bp = big + ((size_t)py * ctx.BW + px) * 3; + bp[0] = (uint8_t)(mj_round(pr * cov + bp[0] * (1 - cov))); + bp[1] = (uint8_t)(mj_round(pg * cov + bp[1] * (1 - cov))); + bp[2] = (uint8_t)(mj_round(pb * cov + bp[2] * (1 - cov))); + } + } + /* 4x drawImage downscale: bilinear bytes at (4*dst+1.5), byte-rounded, luma */ + ctx.yy = malloc((size_t)ctx.W * ctx.Ht * sizeof(float)); + for (int dy = 0; dy < ctx.Ht; dy++) for (int dx = 0; dx < ctx.W; dx++) { + double u = 4 * dx + 1.5, v = 4 * dy + 1.5; + int x0 = (int)floor(u), y0 = (int)floor(v); + double fx = u - x0, fy = v - y0; + const uint8_t *b00 = big + ((size_t)y0 * ctx.BW + x0) * 3; + const uint8_t *b10 = b00 + 3; + const uint8_t *b01 = big + ((size_t)(y0 + 1) * ctx.BW + x0) * 3; + const uint8_t *b11 = b01 + 3; + int o[3]; + for (int ch = 0; ch < 3; ch++) { + double val = (b00[ch] * (1 - fx) + b10[ch] * fx) * (1 - fy) + + (b01[ch] * (1 - fx) + b11[ch] * fx) * fy; + o[ch] = (int)(mj_round(val)); + } + ctx.yy[(size_t)dy * ctx.W + dx] = (float)(.299 * o[0] + .587 * o[1] + .114 * o[2]); + } + free(big); + /* loss window: P(base, cell) bbox clamped to the image */ + { + double mnx = 1e300, mxx = -1e300, mny = 1e300, mxy = -1e300; + for (int ci = 0; ci < L->n_cells; ci++) { + const PrismCell *c = &L->cells[ci]; + double o = H[6] * c->x + H[7] * c->y + 1; + double px = (H[0] * c->x + H[1] * c->y + H[2]) / o; + double py = (H[3] * c->x + H[4] * c->y + H[5]) / o; + if (px < mnx) mnx = px; if (px > mxx) mxx = px; + if (py < mny) mny = py; if (py > mxy) mxy = py; + } + ctx.x0 = (int)floor(mnx); if (ctx.x0 < 0) ctx.x0 = 0; + ctx.x1 = (int)ceil(mxx); if (ctx.x1 > A->w - 1) ctx.x1 = A->w - 1; + ctx.y0 = (int)floor(mny); if (ctx.y0 < 0) ctx.y0 = 0; + ctx.y1 = (int)ceil(mxy); if (ctx.y1 > A->h - 1) ctx.y1 = A->h - 1; + } + /* coordinate descent, exact JS ordering */ + double p[4] = {0, 0, 0, 0}; + double sc[4] = {1, 1, 1 / L->W, 1 / L->H}; + double best = malt_loss(&ctx, A, H, p, Q); + const double steps[4] = {.15, .075, .035, .015}; + for (int si = 0; si < 4; si++) for (int it = 0; it < 3; it++) for (int k = 0; k < 4; k++) { + double bk = p[k]; + for (int sg = 0; sg < 2; sg++) { + double sign = sg == 0 ? -1 : 1; + double q[4]; memcpy(q, p, sizeof(q)); + q[k] += sign * steps[si] * sc[k]; + double ls = malt_loss(&ctx, A, H, q, Q); + if (ls < best) { best = ls; bk = q[k]; } + } + p[k] = bk; + } + free(ctx.yy); + double *out = malloc(8 * sizeof(double)); + malt_cand(H, p, out); + return out; +} + +/* ---------------- mixDirect ---------------- */ +int prism_mix_last_n; /* globalThis.__mxlog */ +PrismMixCand prism_mix_last[8]; + +PrismMixResult *prism_mix_direct(const uint8_t *rgba, int W, int H) { + if ((long)W * H > 800000) return NULL; + const uint8_t *d = rgba; + uint8_t *seen = calloc((size_t)W * H, 1); + typedef struct { int x0, y0, w, h; long n; int seq; } Blob; + Blob *blobs = malloc((size_t)W * H / 16 * sizeof(Blob) + sizeof(Blob)); int nb = 0; + int *qq = malloc((size_t)W * H * sizeof(int)); + for (long k = 0; k < (long)W * H; k++) { + if (seen[k]) continue; + int m3 = d[k * 4] < d[k * 4 + 1] ? d[k * 4] : d[k * 4 + 1]; + if (d[k * 4 + 2] < m3) m3 = d[k * 4 + 2]; + if (m3 < 232) continue; + long qn = 0; + qq[qn++] = (int)k; + seen[k] = 1; + int x0 = W, y0 = H, x1 = 0, y1 = 0; + for (long j = 0; j < qn; j++) { + int p = qq[j], x = p % W, y = p / W; + if (x < x0) x0 = x; if (x > x1) x1 = x; + if (y < y0) y0 = y; if (y > y1) y1 = y; + int ns[4] = {p - 1, p + 1, p - W, p + W}; + for (int t = 0; t < 4; t++) { + int n = ns[t]; + if (n < 0 || n >= W * H || seen[n] || abs((n % W) - x) > 1) continue; + seen[n] = 1; + int m2 = d[n * 4] < d[n * 4 + 1] ? d[n * 4] : d[n * 4 + 1]; + if (d[n * 4 + 2] < m2) m2 = d[n * 4 + 2]; + if (m2 >= 232) qq[qn++] = n; + } + } + int w = x1 - x0 + 1, h = y1 - y0 + 1; + if (w >= 30 && h >= 30 && w < 200 && h < 200 && (double)w / h > 0.85 && (double)w / h < 1.15 && qn > (long)w * h * 0.12) { + blobs[nb].x0 = x0; blobs[nb].y0 = y0; blobs[nb].w = w; blobs[nb].h = h; blobs[nb].n = qn; blobs[nb].seq = nb; + nb++; + } + } + free(qq); free(seen); + /* sort by n desc, stable (index tiebreak) */ + for (int i = 1; i < nb; i++) { + Blob v = blobs[i]; int j = i - 1; + while (j >= 0 && blobs[j].n < v.n) { blobs[j + 1] = blobs[j]; j--; } + blobs[j + 1] = v; + } + PrismFrame *A = frame_create(W, H, rgba); + /* candidates */ + typedef struct { double fit[8]; int size; double score; int seq; } Cand; + Cand cands[8]; int nc = 0; + double q3 = 3 * sqrt(3); + double one3[3] = {1, 1, 1}; + for (int bi = 0; bi < nb && bi < 2; bi++) { + Blob *b = &blobs[bi]; + for (int size = 0; size < 4; size++) { + const PrismLayout *L = layout_get(size); + double sx = (double)b->w / (L->W + 2 * q3), sy = (double)b->h / (L->H + 2 * q3); + double h[8] = {sx, 0, b->x0 + sx * q3, 0, sy, b->y0 + sy * q3, 0, 0}; + double *fit = prism_mix_fit(A, h, L); + double score = 0; int count = 0; + PrismMap fm; memset(&fm, 0, sizeof fm); memcpy(fm.h, fit, 64); + for (int ki = 0; ki < L->n_known; ki++) { + const PrismCell *c = L->known[ki]; + double v[3]; sample_cell_ex(A, &fm, c, one3, 0, 0, 1, v); + double yy = 0; + for (int z = 0; z < 3; z++) { + double gq = v[z] <= 0.0031308 ? 12.92 * v[z] : 1.055 * js_pow(v[z], 1 / 2.4) - 0.055; + v[z] = 255 * gq; + } + yy = 0.299 * v[0] + 0.587 * v[1] + 0.114 * v[2]; + int r = hex_byte(MIX_HEX[c->symbol], 1), g2 = hex_byte(MIX_HEX[c->symbol], 3), bb = hex_byte(MIX_HEX[c->symbol], 5); + double ey = 0.299 * r + 0.587 * g2 + 0.114 * bb; + double df = yy - ey; + score += df * df < 2500 ? df * df : 2500; + count++; + } + memcpy(cands[nc].fit, fit, 64); cands[nc].size = size; cands[nc].score = score / count; cands[nc].seq = nc; + free(fit); + nc++; + } + } + free(blobs); + /* sort score asc stable */ + for (int i = 1; i < nc; i++) { + Cand t = cands[i]; int j = i - 1; + while (j >= 0 && cands[j].score > t.score) { cands[j + 1] = cands[j]; j--; } + cands[j + 1] = t; + } + prism_mix_last_n = nc; + for (int i = 0; i < nc && i < 8; i++) { + prism_mix_last[i].size = cands[i].size; + memcpy(prism_mix_last[i].h, cands[i].fit, 64); + prism_mix_last[i].score = cands[i].score; + } + PrismMixResult *result = NULL; + for (int ci = 0; ci < nc && ci < 3; ci++) { + if (cands[ci].score > 700) continue; + const PrismLayout *L = layout_get(cands[ci].size); + int *symbols = malloc((size_t)(L->n_cells + 1) * sizeof(int)); + PrismPayload *r = prism_mix_recover(A, cands[ci].fit, L, symbols); + double hh[8]; memcpy(hh, cands[ci].fit, 64); + for (int it = 0; !r && mix_symbols_valid && it < 3; it++) { + double *nh = prism_mix_alternate(A, hh, L, symbols); + memcpy(hh, nh, 64); free(nh); + r = prism_mix_recover(A, hh, L, symbols); + } + free(symbols); + if (r) { + result = calloc(1, sizeof(PrismMixResult)); + result->payload = *r; free(r); + result->quality = 1; + memcpy(result->h, cands[ci].fit, 64); + result->radius = js_hypot2(cands[ci].fit[0], cands[ci].fit[3]); + result->sigma = 6; + break; + } + } + frame_free(A); + return result; +} + +void mix_result_free(PrismMixResult *r) { + if (!r) return; + payload_free(&r->payload); + free(r); +} diff --git a/ports/c/reader/prism_read.c b/ports/c/reader/prism_read.c new file mode 100644 index 0000000..80856a5 --- /dev/null +++ b/ports/c/reader/prism_read.c @@ -0,0 +1,458 @@ +/* prism_read.c - readImage legacy hypothesis flow + yA full-canvas generator + * export, bit-exact port of the r721 worker (Build 136, commit 362c870d). + * + * Not ported (page-side or unused by the kit): known-quad entry, fusion + * callback, debug points, budgets (performance.now is inert in the oracle; + * no deadline checks here), PrismPQ path. + */ +#include "prism_reader.h" +#include "prism_detect.h" +#include +#include +#include +#include + +double prism_cfg_min_radius = 4.0; +extern double js_hypot2(double x, double y); /* V8 Math.hypot */ + +static double clamp01(double A) { return A < 0 ? 0 : A > 1 ? 1 : A; } + +/* stage rank C = {detect:0, hypothesis:1, "too small":1, header:2, RS:3, CRC:4} */ +static int stage_rank(const char *s) { + if (!strcmp(s, "hypothesis") || !strcmp(s, "too small")) return 1; + if (!strcmp(s, "header")) return 2; + if (!strcmp(s, "RS")) return 3; + if (!strcmp(s, "CRC")) return 4; + return 0; /* detect and unknown stages: C[e.stage]||0 */ +} + +static void set_err(PrismErr *e, const char *stage, const char *msg) { + snprintf(e->stage, sizeof e->stage, "%s", stage); + snprintf(e->msg, sizeof e->msg, "%s", msg); +} + +/* split uA's "stage:message" err string */ +static void split_err(const char *s, PrismErr *e) { + const char *c = strchr(s, ':'); + if (c) { + size_t n = (size_t)(c - s); + if (n >= sizeof e->stage) n = sizeof e->stage - 1; + memcpy(e->stage, s, n); e->stage[n] = 0; + snprintf(e->msg, sizeof e->msg, "%s", c + 1); + } else { + e->stage[0] = 0; + snprintf(e->msg, sizeof e->msg, "%s", s); + } +} + +void prism_read_free(PrismRead *r) { if (r->ok) payload_free(&r->payload); } + +typedef struct { + PrismMap h; + const PrismLayout *l; + int mode; + double quad[4][2]; + double white[3]; + int rot; + int pp; /* JS i.pp = !!candidate.r0 (lApq candidate) */ + double score, cost; + int seq; +} ReadHyp; + +static int hyp_cmp(const void *pa, const void *pb) { + const ReadHyp *A = pa, *e = pb; + if (A->score != e->score) return A->score < e->score ? 1 : -1; /* desc */ + if (A->cost != e->cost) return A->cost > e->cost ? 1 : -1; /* asc */ + return A->seq - e->seq; /* stable */ +} + +/* fill out from a successful classify+decode (main path) */ +static void fill_result(PrismRead *out, const PrismPayload *w, double quality, + double radius, const double quad[4][2], const PrismMap *h, + const PrismLayout *l, double sigma) { + out->ok = 1; + out->payload = *w; /* take ownership */ + out->quality = quality; + out->radius = radius; + out->sigma = sigma; + memcpy(out->quad, quad, sizeof out->quad); + memcpy(out->h, h->h, sizeof out->h); + out->layout_size = l->size; + out->fallback = NULL; +} + +/* inner legacy read. I frame; mesh retries always on (kit). */ +static int read_inner(const PrismFrame *I, PrismRead *out) { + PrismCandList cands = {0}; + int dr = prism_flag_pq ? detect_lap(I, &cands, NULL, 0) : detect_la(I, &cands); + if (dr != 0) { /* lA throws only when it finds nothing */ + set_err(&out->err, "detect", "Could not fit four edges"); + cand_free(&cands); + return -1; + } + ReadHyp *hyps = NULL; + int nh = 0, cap = 0; + int early_tried = 0; + for (int ci = 0; ci < cands.n; ci++) { + if (prism_fast_deadline_hit()) { + set_err(&out->err, "fast", "Fast read budget reached"); + cand_free(&cands); + free(hyps); + return -1; + } + const PrismCand *e = &cands.v[ci]; + int sz0 = e->sz >= 0 ? e->sz : 0, sz1 = e->sz >= 0 ? e->sz + 1 : 6; + for (int A = sz0; A < sz1; A++) { + const PrismLayout *r = layout_get(A); + double src[4][2]; + corners_of(r, src); + for (int o = 0; o < (e->r0 ? 1 : 4); o++) { + double iq[4][2]; + for (int t = 0; t < 4; t++) { iq[t][0] = e->p[(t + o) % 4][0]; iq[t][1] = e->p[(t + o) % 4][1]; } + PrismMap a; + if (homography(src, iq, &a) != 0) continue; + double g[3]; + white_balance(I, &a, r, g); + for (int m = 0; m < 2; m++) { + double cost, score; + hypothesis_score(I, &a, r, m, g, 1, &cost, &score); + /* earlyTry148: first color hypothesis with size<3 and perfect score */ + if (!early_tried && m == 0 && A < 3 && score == 1.0) { + early_tried = 1; + PrismClassify cl; const char *uerr = NULL; + if (uAZ_classify(I, &a, r, m, g, NULL, &cl, &uerr) == 0) { + PrismPayload w; PrismErr derr = {0}; + if (prism_dAZ(&cl.header, cl.stream, &w, &derr) == 0) { + if (w.n_bytes > 0) { /* JS: dec.bytes.length check */ + fill_result(out, &w, score, + js_hypot2(iq[1][0] - iq[0][0], iq[1][1] - iq[0][1]) / r->W, + (const double (*)[2])iq, &a, r, cl.sigma); + classify_free(&cl); + cand_free(&cands); + free(hyps); + return 0; + } + payload_free(&w); + } + } + classify_free(&cl); + } + if (nh == cap) { cap = cap ? cap * 2 : 64; hyps = realloc(hyps, cap * sizeof *hyps); } + ReadHyp *H = &hyps[nh++]; + H->h = a; H->l = r; H->mode = m; H->rot = o; H->pp = e->r0 ? 1 : 0; + memcpy(H->quad, iq, sizeof H->quad); + memcpy(H->white, g, sizeof g); + H->score = score; H->cost = cost; H->seq = nh - 1; + } + } + } + } + cand_free(&cands); + qsort(hyps, nh, sizeof *hyps, hyp_cmp); /* comparator fully orders: stable */ + if (prism_flag_pq) { + /* PQ: [...h.filter(!pp).slice(0,4), ...h.filter(pp).slice(0,4)] */ + ReadHyp *re = malloc((size_t)nh * sizeof *re); + int nr = 0; + for (int i = 0; i < nh && nr < 4; i++) if (!hyps[i].pp) re[nr++] = hyps[i]; + for (int i = 0, k = 0; i < nh && k < 4; i++) if (hyps[i].pp) { re[nr++] = hyps[i]; k++; } + memcpy(hyps, re, (size_t)nr * sizeof *re); + free(re); + nh = nr; + } else if (nh > 4) nh = 4; /* no PQ: h.slice(0, 4) */ + + PrismErr best = {0}, Q; + int have_best = 0; + set_err(&Q, "hypothesis", "Code pattern not recognized. Try better light or a closer photo."); + + for (int hi = 0; hi < nh; hi++) { + const ReadHyp *A = &hyps[hi]; + PrismMap h = A->h; + const PrismLayout *n = A->l; + int s = A->mode; + double C[4][2], E[3]; + memcpy(C, A->quad, sizeof C); + memcpy(E, A->white, sizeof E); + PrismErr e = {0}; + PrismPayload w; int have_w = 0; + memset(&w, 0, sizeof w); + + /* JS: score>0.92 tightens FastDeadline to max(e, min(overall||e, now + size>=4?850:450)) */ + if (A->score > 0.92) { + double e0 = prism_fast_deadline_get(); + if (e0) { + double od = prism_overall_deadline_get(); + if (!od) od = e0; + double lim = prism_now_seconds() + (n->size >= 4 ? 0.850 : 0.450); + if (lim > od) lim = od; + if (lim > e0) prism_fast_deadline_set(lim); + } + } + /* direct check: score > 0.92, color, small */ + if (A->score > 0.92 && !s && n->size < 4) { + PrismClassify c; + const char *uerr = NULL; + if (uA_classify(I, &h, n, s, E, NULL, &c, &uerr) == 0) { + PrismErr pe; + if (prism_decode_class(&c, &w, &pe) == 0) { + fill_result(out, &w, A->score, + js_hypot2(C[1][0] - C[0][0], C[1][1] - C[0][1]) / n->W, + (const double (*)[2])C, &h, n, c.sigma); + classify_free(&c); + free(hyps); + return 0; + } + } /* any throw: fall through to refine */ + } + + /* refine + re-white + re-score */ + { + int rerr = 0; + refine_quad(I, &h, n, s, C, E, &rerr); + white_balance(I, &h, n, E); + } + double cost2, B; + hypothesis_score(I, &h, n, s, E, 0, &cost2, &B); + if (B < (s ? 0.75 : 0.5)) { + set_err(&e, "hypothesis", "Known cells do not match"); + goto rejected; + } + double f; + { + double ax, ay, bx, by, cx, cy, dx, dy; + map_point(&h, n->W / 2, n->H / 2, &ax, &ay); + map_point(&h, n->W / 2 + 1, n->H / 2, &bx, &by); + map_point(&h, n->W / 2, n->H / 2 + 1, &cx, &cy); + double f1 = js_hypot2(bx - ax, by - ay), f2 = js_hypot2(cx - ax, cy - ay); + f = f1 < f2 ? f1 : f2; + } + if (f < (n->size >= 4 ? 2 : prism_cfg_min_radius)) { + set_err(&e, "too small", "Too small. Move closer or use a larger image."); + goto rejected; + } + + { + PrismClassify c; int have_c = 0; + const char *uerr = NULL; + if (uA_classify(I, &h, n, s, E, NULL, &c, &uerr) == 0) have_c = 1; + else split_err(uerr, &Q); + if (have_c) { + PrismErr pe; + if (prism_decode_class(&c, &w, &pe) == 0) have_w = 1; + else Q = pe; + } + if (!have_w) { /* mesh retries */ + if (have_c) classify_free(&c); + PrismMesh *m1 = qa_build_mesh(I, &h, n, s, E, NULL); + PrismMesh *m2 = qa_build_mesh(I, &h, n, s, E, m1); + mesh_free(m1); + uerr = NULL; + if (uA_classify(I, &h, n, s, E, m2, &c, &uerr) == 0) have_c = 1; + else { split_err(uerr, &Q); have_c = 0; } + mesh_free(m2); + if (have_c) { + PrismErr pe; + if (prism_decode_class(&c, &w, &pe) == 0) have_w = 1; + else Q = pe; + } + } + if (have_w) { + fill_result(out, &w, B, f, (const double (*)[2])C, &h, n, c.sigma); + classify_free(&c); + free(hyps); + return 0; + } + if (have_c) classify_free(&c); + e = Q; + } + + rejected: + if (!have_best || stage_rank(e.stage) > stage_rank(best.stage)) { best = e; have_best = 1; } + /* (Q && e.stage !in {RS,CRC} && Q.stage in {RS,CRC}) || (Q = e) */ + if (!((strcmp(e.stage, "RS") && strcmp(e.stage, "CRC")) && + (!strcmp(Q.stage, "RS") || !strcmp(Q.stage, "CRC")))) + Q = e; + } + free(hyps); + out->err = have_best ? best : Q; + return -1; +} + +int prism_read_image(const uint8_t *rgba, int w, int h, int export_fallback, PrismRead *out) { + memset(out, 0, sizeof *out); + prism_budget_set(2.5); /* JS readImage: g = o + 2500 */ + PrismFrame *I = frame_create(w, h, rgba); + int r = read_inner(I, out); + frame_free(I); + if (r == 0) { + if (!out->payload.n_bytes && out->quality < 0.8) { + payload_free(&out->payload); + out->ok = 0; + set_err(&out->err, "hypothesis", "Empty result lacks a strong code-pattern match"); + r = -1; + } else return 0; + } + if (export_fallback) { + PrismRead g; + if (prism_read_generator(rgba, w, h, &g) == 0) { *out = g; return 0; } + } + return -1; +} + +/* ---- yA: full-canvas generator curve fit ---- */ + +typedef struct { + int size; + const PrismLayout *l; + double r; /* radius C */ + double h[8]; /* B */ + double loss, skew, curve; + int seq; +} GenCand; + +static double gen_loss(const PrismFrame *r, const PrismLayout *s, double C, + const PrismCell **Q, int nq, double skew, double curve) { + static double t[9][1024][3]; + int nt[9] = {0}; + double a = tan(skew * M_PI / 180); + for (int qi = 0; qi < nq; qi++) { + const PrismCell *A = Q[qi]; + double i = (A->y + PRISM_Q) * C; + double g = a * (i / r->h - 0.5) * i + sin(i / r->h * M_PI) * curve * r->w * 0.08; + double v[3]; + frame_sample(r, (A->x + PRISM_Q) * C + g, i, v); + int b = A->symbol; + t[b][nt[b]][0] = srgb_q(v[0]); + t[b][nt[b]][1] = srgb_q(v[1]); + t[b][nt[b]][2] = srgb_q(v[2]); + nt[b]++; + } + double mean[9][3], I[3] = {0, 0, 0}; + int h = 0; + for (int A = 0; A < 9; A++) { + mean[A][0] = mean[A][1] = mean[A][2] = 0; + if (nt[A]) { + for (int k = 0; k < nt[A]; k++) + for (int e = 0; e < 3; e++) mean[A][e] += t[A][k][e]; + for (int e = 0; e < 3; e++) { mean[A][e] /= nt[A]; I[e] += mean[A][e]; } + h++; + } + } + for (int e = 0; e < 3; e++) I[e] /= h; + double l = 0, g = 0; + for (int A = 0; A < 9; A++) + if (nt[A]) { + for (int e = 0; e < 3; e++) l += (mean[A][e] - I[e]) * (mean[A][e] - I[e]); + for (int k = 0; k < nt[A]; k++) + for (int e = 0; e < 3; e++) g += (t[A][k][e] - mean[A][e]) * (t[A][k][e] - mean[A][e]); + } + if (l < 0.02) return 1e6; + return g / nq / (l / h); +} + +static int cand_cmp(const void *pa, const void *pb) { + const GenCand *A = pa, *e = pb; + if (A->loss != e->loss) return A->loss > e->loss ? 1 : -1; + return A->seq - e->seq; +} + +int prism_read_generator(const uint8_t *rgba, int w, int h, PrismRead *out) { + memset(out, 0, sizeof *out); + PrismFrame *r = frame_create(w, h, rgba); + GenCand cands[6]; + int nc = 0; + for (int n = 0; n < 6; n++) { + const PrismLayout *s = layout_get(n); + double C = (r->w / (s->W + 2 * PRISM_Q) + r->h / (s->H + 2 * PRISM_Q)) / 2; + if (C < prism_cfg_min_radius) continue; + if (fabs((s->W + 2 * PRISM_Q) * C - r->w) > 2) continue; + if (fabs((s->H + 2 * PRISM_Q) * C - r->h) > 2) continue; + /* ring|pilot, subsampled to <= 180 */ + static const PrismCell *Q[1024]; + int nq0 = s->n_known; + int E = nq0 / 180; if (E < 1) E = 1; /* Math.max(1, Math.floor(len/180)) */ + int nq = 0; + for (int i = 0; i < nq0; i++) + if (i % E == 0) { if (nq >= 1024) { fprintf(stderr, "Q overflow\n"); exit(2); } Q[nq++] = s->known[i]; } + GenCand *F = &cands[nc]; + F->size = n; F->l = s; F->r = C; F->seq = nc; + F->h[0] = C; F->h[1] = 0; F->h[2] = PRISM_Q * C; F->h[3] = 0; + F->h[4] = C; F->h[5] = PRISM_Q * C; F->h[6] = 0; F->h[7] = 0; + F->loss = 1.0 / 0.0; F->skew = 0; F->curve = 0; + for (double m = -18; m <= 18; m += 3) + for (double w2 = 0; w2 <= 1.001; w2 += 0.1) { + double u = gen_loss(r, s, C, Q, nq, m, w2); + if (u < F->loss) { F->loss = u; F->skew = m; F->curve = w2; } + } + double csk = F->skew, ccv = F->curve; + for (double d = -3; d <= 3.001; d += 0.3) + for (double y = -0.1; y <= 0.1001; y += 0.01) { + double M = csk + d, D = ccv + y; + double p = gen_loss(r, s, C, Q, nq, M, D); + if (p < F->loss) { F->loss = p; F->skew = M; F->curve = D; } + } + nc++; + } + qsort(cands, nc, sizeof *cands, cand_cmp); + set_err(&out->err, "hypothesis", "Full-canvas export geometry did not match"); + for (int ci = 0; ci < nc && ci < 2; ci++) { + const GenCand *F = &cands[ci]; + if (F->loss > 0.45) continue; + /* rectify */ + uint8_t *N = malloc((size_t)w * h * 4); + double U = tan(F->skew * M_PI / 180); + for (int H = 0; H < h; H++) + for (int W = 0; W < w; W++) { + double K = U * ((double)H / h - 0.5) * H + sin((double)H / h * M_PI) * F->curve * w * 0.08; + double v[3]; + frame_sample(r, W + K, H, v); + size_t z = 4 * ((size_t)H * w + W); + for (int X = 0; X < 3; X++) { + double d = 255 * clamp01(srgb_q(v[X])); + N[z + X] = (uint8_t)nearbyint(d); /* Uint8ClampedArray: ties to even */ + } + N[z + 3] = 255; + } + PrismFrame *J = frame_create(w, h, N); + free(N); + PrismMap L; memset(&L, 0, sizeof L); + memcpy(L.h, F->h, sizeof L.h); + double x[3]; + white_balance(J, &L, F->l, x); + PrismClassify O; + const char *uerr = NULL; + if (uA_classify(J, &L, F->l, 0, x, NULL, &O, &uerr) == 0) { + PrismPayload V; + PrismErr pe; + if (prism_decode_class(&O, &V, &pe) == 0) { + if (!V.n_bytes) { + payload_free(&V); + classify_free(&O); + frame_free(J); + set_err(&out->err, "header", "Empty payload needs a direct high-confidence header"); + continue; + } + out->ok = 1; + out->payload = V; + out->quality = O.known_match; + out->radius = F->r; + out->sigma = O.sigma; + double src[4][2]; + corners_of(F->l, src); + for (int k = 0; k < 4; k++) map_point(&L, src[k][0], src[k][1], &out->quad[k][0], &out->quad[k][1]); + memcpy(out->h, F->h, sizeof out->h); + out->layout_size = F->size; + out->fallback = "full-canvas generator curve model"; + out->fit_skew = F->skew; out->fit_curve = F->curve; out->fit_loss = F->loss; + classify_free(&O); + frame_free(J); + frame_free(r); + return 0; + } + out->err = pe; + classify_free(&O); + } else split_err(uerr, &out->err); + frame_free(J); + } + frame_free(r); + return -1; +} diff --git a/ports/c/reader/prism_reader.h b/ports/c/reader/prism_reader.h new file mode 100644 index 0000000..5056654 --- /dev/null +++ b/ports/c/reader/prism_reader.h @@ -0,0 +1,256 @@ +/* prism_reader.h - r721 (Build 135) reader, C port. Foundations layer. + * Bit-exact port of the r721 worker (fast-reader.html HEAD). */ +#ifndef PRISM_READER_H +#define PRISM_READER_H + +#include +#include + +/* ---- GF(256), poly 0x11d ---- */ +uint8_t gf_mul(uint8_t a, uint8_t b); +uint8_t gf_div(uint8_t a, uint8_t b); /* b!=0 required */ +uint8_t gf_peval(const uint8_t *p, int n, uint8_t x); /* constant-first Horner */ +extern const uint8_t *gf_exp_table; /* 512 */ +extern const uint8_t *gf_log_table; /* 256 */ + +/* poly ops on constant-first coefficient arrays */ +void gf_poly_mul(const uint8_t *a, int na, const uint8_t *b, int nb, uint8_t *out); /* out len na+nb-1, zeroed by caller */ + +/* RS encode: msg[0..len) + e parity -> out[0..len+e) */ +void rs_encode(const uint8_t *msg, int len, int e, uint8_t *out); +/* syndromes: out[0..e) */ +void rs_syndromes(const uint8_t *cw, int len, int e, uint8_t *out); +/* rsDecode fallback d(): decodes in place into r (len n). eras may be NULL. + * Returns corrected count >=0, or -1 on throw (err set to JS message). */ +int rs_decode(uint8_t *r, int n, int e, const int *eras, int n_eras, const char **err); +/* rsRecoverBits y(): A = true bytes (len n), mask (len n). Solves masked bits. + * Writes recovered bytes into out (len n). Returns corrected count or -1 (err). */ +int rs_recover_bits(const uint8_t *A, const uint8_t *mask, int n, int t, uint8_t *out, const char **err); + +/* ---- rng (mulberry32 variant, closure-seeded) ---- */ +typedef struct { uint32_t s; } prism_rng; +void rng_seed(prism_rng *r, uint32_t seed); +double rng_next(prism_rng *r); /* [0,1) */ + +/* ---- crc ---- */ +uint32_t crc32_bytes(const uint8_t *p, size_t n); /* D() */ +int crc4_bits(const uint8_t *bits, int n); /* p() */ + +/* ---- bit writer: push v's top nbits MSB-first ---- */ +void bits_push(uint8_t *bits, int *n, uint32_t v, int nbits); /* F() */ + +/* ---- sizes / layout / capacity / header ---- */ +extern const int PRISM_SIZES[6][2]; /* [C, R] */ +#define PRISM_SQRT3 1.7320508075688772 +#define PRISM_Q (3.0 * PRISM_SQRT3) + +enum { ROLE_DATA = 0, ROLE_GAP = 1, ROLE_RING = 2, ROLE_PILOT = 3, ROLE_HEADER = 4 }; + +typedef struct { + int i, j; /* col, row */ + double x, y; /* lattice position */ + int role; + int symbol; /* gap=8, ring=(5j+3i)%8, pilot=(2pi+3pj)%9, data=-1 */ + double pi, pj; /* pilot lattice coords (fractional on non-pilot cells) */ + int index; /* position in cells[] */ + int header; /* header bit index 0..71, else -1 */ +} PrismCell; + +typedef struct { + int size, C, R; + double W, H; + int n_cells; + PrismCell *cells; + int n_headers; /* 72 */ + PrismCell **headers; + int n_data; /* post-header, shuffled */ + PrismCell **data; + int n_known; /* ring+pilot, scan order */ + PrismCell **known; +} PrismLayout; + +const PrismLayout *layout_get(int size); /* G(), cached */ + +typedef struct { int n, nsym, k; } PrismBlock; +typedef struct { + int n; /* total stream bytes */ + int n_blocks; + PrismBlock blocks[32]; + int k; /* sum k */ + int payload; /* k - 4 */ +} PrismCapacity; + +void capacity_get(int size, int ecc, int mode, PrismCapacity *out); /* b() */ +/* header bits L(): 24 bits (size3|ecc2|mode1|type1|len13|crc4), MSB-first */ +void header_bits(int size, int ecc, int mode, int type, int len, uint8_t out[24]); + + +/* ---- image layer (frame, sampling, scoring, geometry) ---- */ +typedef struct { + int w, h; + float *p; /* interleaved RGB, linear */ + const uint8_t *image; /* original RGBA */ +} PrismFrame; + +PrismFrame *frame_create(int w, int h, const uint8_t *rgba); /* T() */ +void frame_free(PrismFrame *f); +void stencil_get(double out[7][2]); +void frame_sample(const PrismFrame *f, double x, double y, double out[3]); /* Z() */ + +typedef struct { + double h[8]; + int has_warp; + double warpW, warpH, warpp[10]; +} PrismMap; + +void map_point(const PrismMap *m, double x, double y, double *ox, double *oy); /* P() */ +int homography(const double src[4][2], const double dst[4][2], PrismMap *out); /* K(), 0 ok / -1 singular */ +void corners_of(const PrismLayout *l, double out[4][2]); /* Y() */ +int known_symbol(const PrismCell *c, int mode); /* R() */ + +void pal_init(void); +void lab_of(const double rgb[3], double out[3]); /* U() */ +double lab_dist2(const double a[3], const double b[3]); /* H() */ +int nearest_sym(const double rgb[3], int mode, double *d); /* _() */ +extern const double (*PRISM_LAB)[3]; + +void white_balance(const PrismFrame *f, const PrismMap *m, const PrismLayout *l, double out[3]); /* j() */ +void sample_cell(const PrismFrame *f, const PrismMap *m, const PrismCell *c, const double white[3], int center, double out[3]); /* V() */ +void sample_cell_ex(const PrismFrame *f, const PrismMap *m, const PrismCell *c, const double white[3], double mdx, double mdy, int center, double out[3]); /* V() with mesh offset */ +void hypothesis_score(const PrismFrame *f, const PrismMap *m, const PrismLayout *l, int mode, const double white[3], int center, double *cost, double *score); /* $() */ +double refine_quad(const PrismFrame *f, PrismMap *m, const PrismLayout *l, int mode, double quad[4][2], const double white[3], int *err); /* AA() */ +int prism_solve_n(int n, double *A, double *e, double *out); /* W(), 0 ok / -1 singular */ +void pal_dump(double pal[9][3], double lab[9][3]); /* J and x */ + +/* ---- classify layer (CA/QA/X/BA/fA/uA) ---- */ +extern int prism_flag_calmed, prism_flag_dd, prism_flag_veil, prism_flag_mix, prism_flag_pq; +extern int prism_flag_direct; /* worker __directOnly (e0ec151): mixDirect only */ +extern double prism_page_cap_s; /* page __overallCap147 as absolute wall_s (0 = off) */ +extern int prism_cap_stopped; /* set when an attempt died to the overall cap ("stopped") */ + +typedef struct { double x, y, dx, dy; } PrismMeshPt; +typedef struct PrismMesh { int n, cap; PrismMeshPt *pts; void *tree; int tree_ok; } PrismMesh; +void mesh_eval(const PrismMesh *m, double x, double y, double out[2]); /* X() */ +PrismMesh *qa_build_mesh(const PrismFrame *f, const PrismMap *m, const PrismLayout *l, int mode, const double white[3], const PrismMesh *prev); /* QA() */ +PrismMesh *qa_build_dense_mesh(const PrismFrame *f, const PrismMap *m, const PrismLayout *l, int mode, const double white[3], const PrismMesh *prev); /* buildDenseMesh (0.8*g gate, all known) */ +void mesh_free(PrismMesh *m); + +typedef struct { + const PrismCell *c; + double o[3]; /* V() sample */ + double E[3]; /* expected palette J[R(c,mode)] */ + double res[3]; /* residual after correction */ +} PrismRef; + +typedef struct { + double M[3][4]; /* s: per-channel affine */ + double sigma; + PrismRef *refs; int n_refs; + void *tree; /* kdtree over refs keyed on cell x,y */ +} PrismCalib; + +int prism_calibrate(const PrismFrame *f, const PrismMap *m, const PrismLayout *l, int mode, const double white[3], const PrismMesh *mesh, PrismCalib *out, const char **err); /* CA() */ +void calib_correction(const PrismCalib *cb, const double rgb[3], const PrismCell *c, double out[3]); /* E() */ +void calib_free(PrismCalib *cb); + +void llr_bits(const double rgb[3], int mode, double sigma, int glare, double out[3]); /* BA(): 1 value in binary mode, 3 in color */ + +typedef struct { int size, ecc, mode, type, length; } PrismHeader; +int header_decode24(const float *soft24, PrismHeader *out, const char **err); /* fA(): 0 ok / -1 throw */ + +typedef struct { double x, y, confidence; } PrismPointConf; +typedef struct { int at; double cv[3]; } PrismGlareSample; + +/* ---- decode layer (prism_decode.c) ---- */ +typedef struct { char stage[24]; char msg[160]; } PrismErr; + +typedef struct PrismPayload { + uint8_t *bytes; int n_bytes; + char *text; /* utf-8 copy when header.type == 0, else NULL */ + PrismHeader header; + int corrected, erasures; + const char *variant; /* "original" | "generator-whitened" | "palette mixing" */ +} PrismPayload; + +void prism_budget_set(double seconds_from_now); /* 0 disables; e()/g deadline */ +/* fb machinery: PrismFastDeadline/PrismOverallDeadline mirrors (0 = disabled) */ +double prism_now_seconds(void); +void prism_fast_deadline_set(double abs_s); +double prism_fast_deadline_get(void); +void prism_overall_deadline_set(double abs_s); +double prism_overall_deadline_get(void); +int prism_fast_deadline_hit(void); +extern double prism_fb_ms; /* page __fastBudget posted per attempt (0 = default 950/700) */ +int prism_decode_stream(const PrismHeader *h, const float *st, PrismPayload *out, PrismErr *err); /* dA() */ +int prism_dAZ(const PrismHeader *h, const float *st, PrismPayload *out, PrismErr *err); /* dAZ(): padVote + dA2Z direct check, both paddings */ +void payload_free(PrismPayload *p); +extern int prism_nologo; /* globalThis.PRISM_NOLOGO */ + +/* ---- mix layer (prism_mix.c) ---- */ +typedef struct { int size; double h[8]; double score; } PrismMixCand; +typedef struct { + PrismPayload payload; /* owned */ + int quality; + double h[8]; + double radius, sigma; +} PrismMixResult; +double *prism_mix_fit(const PrismFrame *A, const double H[8], const PrismLayout *L); /* mixFit: malloc'd h */ +PrismPayload *prism_mix_recover(const PrismFrame *A, const double h[8], const PrismLayout *L, int *symbols_out); /* mixRecover: NULL on failure */ +double *prism_mix_alternate(const PrismFrame *A, const double H[8], const PrismLayout *L, const int *symbols); /* mixAlternate: software canvas reproduction */ +PrismMixResult *prism_mix_direct(const uint8_t *rgba, int W, int H); /* mixDirect */ +void mix_result_free(PrismMixResult *r); +extern int prism_mix_last_n; /* globalThis.__mxlog */ +extern PrismMixCand prism_mix_last[8]; + +typedef struct { + PrismHeader header; + PrismHeader headers[12]; int n_headers; + float *stream; int n_stream; + int *ext_glare; int n_ext_glare; /* Q: stream offsets */ + PrismGlareSample *glare_samples; int n_glare; /* E */ + float hb[24]; + double sigma; + PrismPointConf *points; int n_points; + double known_match; + PrismPayload *mix_decoded; /* mix-mode predecoded result (mA shortcut) */ +} PrismClassify; + +int uA_classify(const PrismFrame *f, const PrismMap *m, const PrismLayout *l, int mode, const double white[3], const PrismMesh *mesh, PrismClassify *out, const char **err); /* uA(): 0 ok / -1 throw (err is stage:message) */ +int uAZ_classify(const PrismFrame *f, const PrismMap *m, const PrismLayout *l, int mode, const double white[3], const PrismMesh *mesh, PrismClassify *out, const char **err); /* uAZ(): identity calib + center samples */ +void classify_free(PrismClassify *c); +int prism_decode_class(const PrismClassify *A, PrismPayload *out, PrismErr *err); /* mA() */ + +/* ---- read layer (prism_read.c): readImage legacy flow + yA generator export ---- */ +double srgb_q(double A); /* q() */ +extern double prism_cfg_min_radius; /* CFG.minRadius (4; 0.55 in mix mode) */ + +typedef struct { + int ok; + PrismPayload payload; /* owned when ok */ + double quality, radius, sigma; + double quad[4][2]; + double h[8]; + int layout_size; + const char *fallback; /* static string or NULL */ + double fit_skew, fit_curve, fit_loss; /* yA only */ + double warp[10]; /* DistFit success */ + const char *reader; /* DistFit success */ + PrismErr err; /* when !ok */ +} PrismRead; + +void prism_read_free(PrismRead *r); +/* readImage(): legacy hypothesis flow; export_fallback != 0 tries yA on failure. */ +int prism_read_image(const uint8_t *rgba, int w, int h, int export_fallback, PrismRead *out); +/* yA(): full-canvas generator curve fit. */ +int prism_read_generator(const uint8_t *rgba, int w, int h, PrismRead *out); + +/* ---- DistFit bounded-search reader (prism_distfit.c) ---- */ +double prism_lin_s(double A); /* S(): srgb -> linear */ +/* PrismLocal.normalize(): ImageData -> ImageData (out = w*h*4). */ +void prism_local_normalize(const uint8_t *rgba, int w, int h, uint8_t *out); +/* PrismDistFit.read(): nonlinear surface fit reader over normalized input. */ +int prism_distfit_read(const uint8_t *rgba, int w, int h, PrismRead *out); +/* PrismFastReader.read(): mix gate -> readImage(no export fallback) -> DistFit. */ +int prism_fast_read(const uint8_t *rgba, int w, int h, PrismRead *out); + +#endif