# PNG Row Filter Desk contract v1

Original Renchao Wu /work:png-row-filter-desk:v1 /Apache-2.0. Freeze before expected fixture generation and core implementation. Investigate five PNG byte predictors and a declared row-choice heuristic, then actually encode all six lossless PNGs. No training, pretrained model, new compression algorithm or universal compression/PNG conformance claim.

## Typed input and source

Input object exactly {width,height,rgba}: width and height numeric integers1..32; rgba flat ordinary Array with exactly4*width*height numeric integers0..255, no bool/string/null/nonfinite/extra keys/sparse values. Text parser accepts at most20,000 UTF16 units of JSON; CLI at most20,000 actualbytes and regular finalnonsymlink input. JSON duplicate names use normal lastvalue semantics, not duplicatekey validator. Snapshot synchronously before any async hash/compression. No image/PNG upload, remoteURL, Canvas pixel import, runtimefile access, base64 request, colorprofile transformation or inferredpremultiplication. A preview displays the supplied unpremultiplied RGBA bytes with browser rendering; equal decoded bytes do not promise identical display across color-managed systems.

Eight original fixed examples, no outcome selection: 16x12default formula eachpixel(x,y) RGBA [17*x mod256,23*y mod256,((x<8?32:224)+7*y)mod256, (x+y)%4==0?0:255]; zero4x3; white4x3 all255; verticalramp8x4 [31*x,31*x,31*x,255]; horizontalramp4x8 [31*y,31*y,31*y,255]; checker8x8 withRGB0/255 by(x+y)%2 and alpha alternating0/255 byx; 1x5 narrowbytes [0,255,1,254,128,127,129,126,255,0,255,0,1,2,3,4,254,253,252,251]; onepixelRGBA[17,201,129,0]. Preserve invisible RGB wherealpha0, allRGBA unchanged. Add pre-core deterministic random/smallbyte/wrapping/Paethtie fixtures, complete expected rows for all six strategies, readonlyfixture freeze.

## Filters and row choice

For each byte i of row y, bpp4. Raw x=rgba[y*width*4+i]; a=rawsame row i−4 ifi>=4 else0; b=raw previousrow samei ify>0 else0; c=raw previousrow i−4 ify>0 andi>=4 else0. Predictors: None0, Suba, Upb, Average floor((a+b)/2) with wide nonoverflow sum, Paethp=a+b−c; choosea if|p−a|<=|p−b| and<=|p−c|, otherwiseb if|p−b|<=|p−c|, otherwisec. Ties prioritizea,thenb,thenc. Exact integer arithmetic throughout, wrappingonlyfinalresidual. Filtered f=(x−predictor)mod256 nonnegative0..255; signed residual=f<128?f:f−256; score=sum(abs(signedresidual)) perrow. Compute allfive scores fromoriginalbytes, not previousfilteredrow. Strategies fixed-none/sub/up/average/paeth choose type0..4 everyrow; heuristic choosesminimum rowscore, tieslowesttype. Rowtypechoicesmayvary, no globalcompressedsize guarantee. No claim PNG standard requires this exactheuristic or canonical compression.

For each six strategy, full row object: y, filtertype, filtername, allfive integer row scores, selectedscore, everybyte {row_byte,column,channel,raw,left,up,upper_left,predictor,filtered,signed,reconstructed}, filteredrowhex, reconstructedrowhex. Reconstruction sequentially uses decoded priorpixel/row ratherthaninputraw forneighbors; recon=(f+reconstructedpredictor)mod256. Full reconstructed RGBA hex/SHA, byteequal flag; rowtype prefix included in scanlinebytes, not the score. Unfiltered/sourcebytes4wh vs filteredbytesh*(4w+1); null newpixelcount semantics notneeded. Allbytesretained with no partial cap (inputbounds limitwholedata).

## Real PNG encoding

For each six strategy concatenate per-row filtertypebyte then filteredrowbytes. Actually call platform CompressionStream('deflate') once perstrategy; this is zlib-wrapped DEFLATE, not rawdeflate/gzip/manualzlib or sixnewtrainingruns. Record full scanlinehex/SHA, compressedIDAThex/SHA/bytecount, completePNGhex/SHA/bytecount. Assemble PNG signature13780... standard8bytes; exactlyIHDR13B(widthheight bigendian,uint8bitdepth8,colortype6,compression0,filter0,interlace0), oneIDAT with actualcompresseddata, oneIENDempty. Everychunk length uint32bigendian excludeslength/type/CRC, PNGCRC32 overtype+data with standard reflectedpolynomial0xEDB88320, initial/finalxorallones. Record allthreechunk offset/type/data_length/storedCRC(hex8)/computedCRC/equality; noancillary/colorprofile/gamma/APNG/palette16bit/interlace/chunkingstrategy. Generatedwirebytecount57+compressedIDATlength (signature8+IHDR25+IDAT12+IEND12).

Actualsize comparison withinthisoneplatformoperation: min completePNGbytecount and all tiedstrategyids, fixed strategy ordernone/sub/up/average/paeth/heuristic. Report perstrategy diffvsnone, heuristic gapvsbest, scoretotal. Report allsix, including ties, heuristicworse and simple-nonewins. Sameinputmust always reconstruct exactraw, but compressedbytes mayvaryacrossengines/platformversions evenat samefixedAPI; no universalcanonical bytehash/size/reproducibility claim. When PNGByteidentity withinoneexactdownloadreadback ischecked, distinguish fromcrossenginecompressionequality. If compressionnotavailable/fails reject whole report, do notreturnfabricatedpartialsuccess. CSVdeclaredselectedstrategyallrowsummary, notwholebytes. PNGdownloadonlyselectsactualbytesalreadyinthewholereport, no generationorresize.

## Async/UI/verification

Core asynchronous encode snapshots inputbeforefirstawait; optionalAbortSignal cancellationcheck betweenstrategiesandbeforefinalreport, cooperative notmid-platform synchronous operation cancellation. UIintentgeneration checks ensure oldercompletedresults/errors cannotoverwriteedit/clear/newrun/restore/examplechoice. Old results/rows/exports clearwhenediting/newrun/error. Initialexamples loading auxiliary, mathematicaldefaultavailablelocally, delayedexamplesuccess/503 mustnotclobberedited/computed/clear/restoredrequests. Defaults declaredabove beforefirstresults. UIactualinputrgba, 6sizeoutputs, selectedstrategyfullrowscores, bytefilterwithrow/channel/paging (fullJSONnottruncated), decodedpreview+PNGpreview, allchunks/CRC, heuristiccounterexamples/explicitbounds. NoURLfetchbesidesownstaticexamples, upload/store/telemetry/serverinference.

Independent Python per-byte predictor and fullunfilter fromeach generatedPNG, stdlibbinasciiCRC/zlibdecompressobj EOF/trailer/Adler andstructIHDR. Python compressed stream allowedtodiffer, semanticreferenceusescandidatecompressedbytes strictlyverifiesallwirefields/outputsize/resultsummary ratherthanmanufacturingequivalentcompressedhash. Complete prefrozenexpectedfilterfixturesexact; freshcases fullschema/bytefields/roundtrip/PNGCRC/decompressbounded, allPaethties andsumoverflow/signed128/wrap/firstpixel/firstrow. Newtyped/asyncsnapshot/cancel/coreCLIcaps/exclusivewx0600actualsubprocess tests. RealCUAwholeJSON/selectedPNG/all6defaultPNG/CSV and decodedpixelreadback (notvisualcoloridentity), oldinputgenerationrace/realexamplesgates andtypedClear, actual3753901280/focus/scroll/PNGpreview/screenshots. Independentreviewexistingauthorizedtotaloutputcompleteexactpackandnewcases/nativebeforeacceptedcount. No publish under currenthold.

## Primary source

W3C PNG Third Edition published2025-06-24 (actualcurrentofficialread2026-11-05), sections5.3chunklayout/5.5CRC/9.1–9.4filterfunctions/ties/10zlibIDATstream/11.2.1IHDR/11.2.3IDAT/11.2.4IEND/12.7filterselection. Readactualofficialpage throughtrustedCUA, no copiedcode/prose/imageassets. Algorithms arestandard, implementation/sourceexamplesoriginal. Pythonzlib/CompressionStream notbundled/newalgorithm. BoundedsmallRGBAencoder notarbitraryPNGparser/optimizer/allPNGvalidator/securitytool.
