code wiki / _hdl_build / nx_png_lum.nx
nx_png_lum.nx source
↩ module page · 52 lines · 2455 B
1// nx_png_lum.nx -- sovereign PNG mean-luminance probe over a content rectangle. Turns "the page looks dark"
2// into a NUMBER (mean luma 0..255) measured from the actual rendered pixels -- the "show proof not I can see"
3// tool for the S21 browser dogfood before/after. usage: nx_png_lum <file.png>. Samples y[100..h-40] x[60..w-40]
4// (skips the white browser chrome bar at top). license_tier: ORIGINAL
5import "nx_syscalls.nx"
6import "nx_png_decoder.nx"
7
8func hw(s: *u8) -> i64 { var n: i64=0; while s[n]!=(0 as u8){n=n+1} sys_write(1,s,n); return 0 }
9func pn(v: i64) -> i64 { let t: *u8=sys_mmap(24); var m: i64=v; if m<0{sys_write(1,"-" as *u8,1);m=0-m} var k: i64=0; if m==0{t[0]=48 as u8;k=1} while m>0{t[k]=(48+(m%10)) as u8;m=m/10;k=k+1} let b: *u8=sys_mmap(24); var j: i64=0; while j<k{b[j]=t[k-1-j];j=j+1} sys_write(1,b,k); return 0 }
10
11func main(argc: i64, argv: *i64) -> i64 {
12 if argc < 2 { hw("usage: nx_png_lum <file.png>\n" as *u8); sys_exit(2); return 2 }
13 let lb: *i64 = sys_mmap(16) as *i64
14 let buf: *u8 = sys_read_file(argv[1] as *u8, lb)
15 if (buf as i64) == 0 { hw("cannot read\n" as *u8); sys_exit(3); return 3 }
16 let res: *NxPngResult = nx_png_decode(buf, lb[0])
17 if (res as i64) == 0 { hw("decode null\n" as *u8); sys_exit(4); return 4 }
18 if res.error_code != 0 { hw("decode err=" as *u8); pn(res.error_code); hw("\n" as *u8); sys_exit(5); return 5 }
19 let hdr: *NxPngHeader = res.header
20 let w: i64 = hdr.width
21 let h: i64 = hdr.height
22 let nc: i64 = res.n_channels
23 let px: *u8 = res.pixels
24 var y0: i64 = 100
25 var y1: i64 = h - 40
26 var x0: i64 = 60
27 var x1: i64 = w - 40
28 if y1 <= y0 { y0 = 0; y1 = h }
29 if x1 <= x0 { x0 = 0; x1 = w }
30 var sum: i64 = 0
31 var cnt: i64 = 0
32 var y: i64 = y0
33 while y < y1 {
34 var x: i64 = x0
35 while x < x1 {
36 let o: i64 = (y * w + x) * nc
37 let r: i64 = px[o] as i64
38 let g: i64 = px[o+1] as i64
39 let b: i64 = px[o+2] as i64
40 sum = sum + (r + g + b) / 3
41 cnt = cnt + 1
42 x = x + 1
43 }
44 y = y + 1
45 }
46 var mean: i64 = 0
47 if cnt > 0 { mean = sum / cnt }
48 hw("png " as *u8); hw(argv[1] as *u8); hw(" " as *u8); pn(w); hw("x" as *u8); pn(h); hw(" content mean-luma=" as *u8); pn(mean); hw("/255 " as *u8)
49 if mean < 90 { hw("(DARK theme)\n" as *u8) } else { hw("(LIGHT/white)\n" as *u8) }
50 sys_exit(0)
51 return 0
52}