Skip to content

armgit / facex

Public Imported from GitHub
0

Full face stack that runs entirely in the browser. Detection, 576-point 3D mesh, recognition, anti-spoof, smile — all WebAssembly, zero server. Apache 2.0.

nn2: open-source the pure-C YOLO + MiniFASNet inference engine (Apache 2.0)

facex9d18300482bc
diff --git a/.gitignore b/.gitignore
index 3e1e686..e4b9f92 100644
--- a/.gitignore
+++ b/.gitignore
@@ -21,8 +21,11 @@ training/runs/
training/Silent-Face-Anti-Spoofing/
training/nn2-mirror/
-# === Proprietary inference engine — never publish ===
-nn2/
+# nn2/ is published (Apache 2.0). Only ignore generated artifacts inside it.
+nn2/build/
+nn2/*.exe
+nn2/*.o
+nn2/weights/*.bin
# === Caches ===
__pycache__/
diff --git a/README.md b/README.md
index 14263b1..93f57fa 100644
--- a/README.md
+++ b/README.md
@@ -46,7 +46,7 @@ FaceX is one piece of a larger pure-C stack we built for IP-camera workloads. Ev
| **NexusDecode** | H.264 + H.265 decoder, RTSP client | **184 KB** | 6,300 fps, **46× FFmpeg** | libav / FFmpeg |
| **NexusEncode** | H.265/HEVC encoder | ~250 KB | x265-medium quality, 131 fps | x265 |
| **NXV codec** | Surveillance-tuned video format | 121 KB | **3× smaller** than H.265, instant seek, change-map | H.265 + custom container |
-| **nn2** (proprietary) | YOLOv8 + MiniFASNet inference engine | 520 KB | 8.5 ms @ 320, **1.5–2× ONNX RT** | onnxruntime |
+| **nn2** | YOLOv8 + MiniFASNet inference engine | 520 KB | 8.5 ms @ 320, **1.5–2× ONNX RT** | onnxruntime |
| **FaceX (this repo)** | Detect + landmarks + embed + spoof | 148 KB native / 17 MB WASM | 3 ms/face | dlib, FaceNet, InsightFace |
**Pipeline numbers (one Intel i5 CPU):**
@@ -167,11 +167,11 @@ Measured on Intel i5-11500 (6 cores, AVX-512 + VNNI):
### Speed — anti-spoof (MiniFASNet V2+V1SE ensemble)
-Same model, ported to our proprietary nn2 engine:
+Same model, ported to our `nn2` C engine (Apache 2.0, source in [`nn2/`](nn2/)):
| Engine | Single model | Ensemble | Speedup |
|--------|-------------:|---------:|--------:|
-| **nn2** (ours) | **0.70 ms** | **1.43 ms** | -- |
+| **nn2** | **0.70 ms** | **1.43 ms** | -- |
| ONNX Runtime 1.23 | 1.33 ms | 2.92 ms | **2.03× slower** |
Byte-identical predictions to PyTorch / ONNX on the same input.
@@ -400,8 +400,8 @@ touch disk in plaintext on the target machine.
## Limitations
- **Native build** — currently x86-64 (AVX2 / AVX-512 / VNNI). ARM NEON
- paths exist; full ARM build script is on the roadmap, ESP32 / RISC-V
- PIE 128 next.
+ paths exist in `nn2/src/gemm_neon.h`; full ARM build script is on the
+ roadmap, ESP32 / RISC-V PIE 128 next.
- **Browser pipeline** — uses `onnxruntime-web` with WebCrypto-decrypted
ONNX. WebGPU backend is supported by ORT but not yet wired into the
demo; would drop inference by another 3–5×.
@@ -462,6 +462,11 @@ predictions at **2× speed** vs ONNX Runtime.
```
include/ — public C API (facex.h, facex_mfn.h, ...)
src/ — recognition engine + AES weight crypto
+nn2/ — pure-C YOLO + MiniFASNet inference engine
+ (1.5–2× ONNX, Apache 2.0)
+ src/ — gemm, conv, ops, antispoof_ops, minifasnet
+ include/ — public API headers
+ tools/ — PyTorch → .bin converters
wasm/ — browser demo (demo_mesh.html, encrypt tool)
tools/encrypt_models.py — AES-256-GCM encrypt all .onnx
docs/demo/ — GitHub Pages live demo + encrypted weights
@@ -475,9 +480,6 @@ go/facex/ — Go binding (subprocess protocol)
python/facex/ — Python binding (ctypes)
```
-The nn2 inference engine (1.5–2× ONNX, used in commercial deployments)
-is closed-source. Contact for licensing.
-
---
## FAQ
diff --git a/nn2/LICENSE b/nn2/LICENSE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/nn2/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/nn2/Makefile b/nn2/Makefile
new file mode 100644
index 0000000..1aa8f3a
--- /dev/null
+++ b/nn2/Makefile
@@ -0,0 +1,78 @@
+CC = /c/mingw64/bin/gcc
+CFLAGS = -O3 -march=native -funroll-loops -ffast-math -fomit-frame-pointer \
+ -fno-plt -fvisibility=hidden -DNDEBUG \
+ -Wno-unused-function -Wno-unused-variable -Iinclude -Isrc
+LDFLAGS = -lm -lsynchronization
+LTO = -flto
+
+# PGO targets (10-18% free speedup)
+PGO_DIR = pgo_data
+
+CORE_SRC = src/gemm.c src/gemm_res.c src/conv.c src/conv_implicit.c src/conv_fused.c \
+ src/conv_tiled.c src/winograd.c \
+ src/ops.c src/decode.c src/pool.c src/net.c src/nn2.c
+CORE_OBJ = $(CORE_SRC:.c=.o)
+
+INT8_SRC = src/gemm_int8.c
+INT8_OBJ = $(INT8_SRC:.c=.o)
+
+NVR_SRC = src/nvr.c
+NVR_OBJ = $(NVR_SRC:.c=.o)
+
+ND_SRC = src/nanodet.c
+ND_OBJ = $(ND_SRC:.c=.o)
+
+ALL_OBJ = $(CORE_OBJ) $(INT8_OBJ)
+
+all: nn2 nn2_img nn2_nvr nanodet
+
+nn2: $(ALL_OBJ) src/main.o
+ $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
+
+nn2_img: $(ALL_OBJ) src/main_img.o
+ $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
+
+nn2_nvr: $(ALL_OBJ) $(NVR_OBJ) src/main_nvr.o
+ $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
+
+nanodet: $(ALL_OBJ) $(ND_OBJ) src/main_nanodet.o
+ $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
+
+%.o: %.c
+ $(CC) $(CFLAGS) -c $< -o $@
+
+clean:
+ rm -f src/*.o nn2 nn2.exe nn2_img nn2_img.exe nn2_nvr nn2_nvr.exe nanodet nanodet.exe
+
+# Export weights (requires Python + ultralytics)
+export-320:
+ python tools/export_yolov8n.py --size 320 --output weights/yolov8n_320.bin
+
+export-640:
+ python tools/export_yolov8n.py --size 640 --output weights/yolov8n.bin
+
+export-nanodet:
+ python tools/export_nanodet.py
+
+bench: nn2
+ ./nn2 weights/yolov8n_320.bin test_image.raw 640 480 6
+
+# LTO build (cross-module inline, dead code elimination)
+lto: CFLAGS += $(LTO)
+lto: LDFLAGS += $(LTO)
+lto: all
+
+# PGO Step 1: generate profile
+pgo-gen: CFLAGS += -fprofile-generate=$(PGO_DIR)
+pgo-gen: LDFLAGS += -fprofile-generate=$(PGO_DIR)
+pgo-gen: clean all
+ @echo "Run: ./nn2_img weights/yolov8n_320.bin test_image.jpg 6"
+ @echo "Then: make pgo-use"
+
+# PGO Step 2: use profile (combine with LTO for max effect)
+pgo-use: CFLAGS += -fprofile-use=$(PGO_DIR) $(LTO) -fprofile-correction
+pgo-use: LDFLAGS += -fprofile-use=$(PGO_DIR) $(LTO)
+pgo-use: clean all
+ @echo "Built with PGO+LTO — expected 10-18% faster"
+
+.PHONY: all clean export-320 export-640 export-nanodet bench lto pgo-gen pgo-use
diff --git a/nn2/README.md b/nn2/README.md
new file mode 100644
index 0000000..da2cdec
--- /dev/null
+++ b/nn2/README.md
@@ -0,0 +1,263 @@
+# nn2 — Pure C YOLO Inference Engine
+
+**1.50x faster than ONNX Runtime. Zero dependencies. 520KB binary. 70 cameras on one CPU.**
+
+Built from scratch in pure C with hand-tuned AVX-512 SIMD. No frameworks, no libraries, no GPU required.
+
+## Performance
+
+### Single-frame inference (i5-11500, 6 cores / 12 threads)
+
+| Input | nn2 | ONNX Runtime 1.23 | Speedup |
+|-------|-----|-------------------|---------|
+| 320x320 | **8.5ms (117 FPS)** | 12.7ms (78 FPS) | **1.50x** |
+| 256x256 | **6.5ms (154 FPS)** | 8.4ms (119 FPS) | **1.30x** |
+| 224x224 | **5.7ms (177 FPS)** | — | — |
+| 192x192 | **4.8ms (208 FPS)** | — | — |
+
+### Smart NVR pipeline (motion gate + Kalman tracking)
+
+| Metric | Value |
+|--------|-------|
+| Average per frame | **0.56ms** |
+| Effective throughput | **1,746 FPS** |
+| Camera capacity (25fps) | **~70 cameras** |
+| vs naive inference | **14.8x faster** |
+
+Detection accuracy: 4/4 on bus.jpg (person 86%, bus 80%, person 72%, person 71%) — matches PyTorch reference.
+
+## Quick Start
+
+```bash
+# Build everything
+bash build.sh
+
+# Single image detection
+./nn2_img.exe weights/yolov8n_320.bin photo.jpg
+
+# Production NVR server with web dashboard
+./nn2_nvr_prod.exe -w weights/yolov8n_320.bin -p 8080
+# Open http://localhost:8080 in browser
+```
+
+## Production NVR Server
+
+Single binary with embedded web dashboard, REST API, smart pipeline:
+
+```bash
+./nn2_nvr_prod.exe -w weights/yolov8n_320.bin -p 8080
+```
+
+**Web Dashboard** at `http://localhost:8080` — live camera status, detection events, auto-refresh.
+
+**REST API:**
+
+```bash
+# Health check
+curl http://localhost:8080/api/health
+
+# Add camera
+curl -X POST http://localhost:8080/api/camera/add \
+ -d '{"name":"Front Door","url":"rtsp://..."}'
+
+# Detect objects in image
+curl -X POST http://localhost:8080/api/detect --data-binary @photo.jpg
+
+# Camera status + stats
+curl http://localhost:8080/api/status
+
+# Recent detection events
+curl http://localhost:8080/api/events
+
+# Simulate frame push (for testing)
+curl -X POST http://localhost:8080/api/camera/sim
+```
+
+**Features:**
+- Dynamic camera add/remove via API
+- Motion-gated inference (skip static frames, ~0.05ms)
+- Kalman tracking between detections (~0.01ms)
+- SORT tracker with persistent object IDs
+- Line-crossing people counting
+- Zone intrusion detection (polygon, dwell time, class filter)
+- JSON event logging
+- Thread-safe shared model
+
+## Export Weights
+
+```bash
+pip install ultralytics
+python tools/export_yolov8n.py --size 320 --output weights/yolov8n_320.bin
+python tools/export_yolov8n.py --size 256 --output weights/yolov8n_256.bin
+```
+
+## C API
+
+```c
+#include "nn2.h"
+
+// Init (auto-detect threads)
+NN2* ctx = nn2_init("weights/yolov8n_320.bin", 0);
+
+// Detect objects
+NN2Det dets[300];
+int n = nn2_detect(ctx, rgb_hwc_uint8, width, height, dets, 300);
+
+for (int i = 0; i < n; i++)
+ printf("cls=%d score=%.0f%% box=(%.0f,%.0f,%.0f,%.0f)\n",
+ dets[i].cls, dets[i].score * 100,
+ dets[i].x1, dets[i].y1, dets[i].x2, dets[i].y2);
+
+nn2_free(ctx);
+```
+
+### NVR API
+
+```c
+#include "nn2_nvr.h"
+
+void on_detect(const NN2NVREvent* e, void* ud) {
+ printf("CAM %d: %d objects (%.1fms)\n",
+ e->cam_id, e->det_count, e->inference_ms);
+}
+
+NN2NVR* nvr = nn2_nvr_create("weights/yolov8n_320.bin", 0);
+nn2_nvr_add_camera(nvr, 0, "entrance");
+nn2_nvr_set_callback(nvr, on_detect, NULL);
+nn2_nvr_set_skip_frames(nvr, 5);
+
+// Per frame:
+nn2_nvr_push_frame(nvr, cam_id, frame_rgb, 640, 480);
+
+nn2_nvr_free(nvr);
+```
+
+### Tracking + Counting + Zones
+
+```c
+#include "nn2_track.h"
+#include "nn2_count.h"
+#include "nn2_zone.h"
+
+// Tracker: persistent IDs across frames
+NN2Tracker* tr = nn2_tracker_create(30, 2);
+NN2Track tracks[100];
+int nt = nn2_tracker_update(tr, dets, n_dets, tracks, 100);
+
+// Line counter: count crossings
+NN2Counter* cnt = nn2_counter_create(0, 240, 640, 240);
+nn2_counter_update(cnt, tracks, nt);
+printf("In: %d, Out: %d\n", cnt->count_in, cnt->count_out);
+
+// Zone intrusion: polygon + dwell time + class filter
+float poly[] = {100,100, 400,100, 400,400, 100,400};
+NN2Zone* z = nn2_zone_create("Restricted", 4, poly);
+nn2_zone_set_classes(z, 1, (int[]){0}); // person only
+nn2_zone_set_dwell(z, 3); // alert after 3 frames
+NN2ZoneEvent events[10];
+int ne = nn2_zone_check(z, tracks, nt, events, 10);
+```
+
+## Architecture
+
+```
+nn2/
+├── include/
+│ ├── nn2.h Public detection API
+│ ├── nn2_track.h SORT tracker (Kalman + IoU)
+│ ├── nn2_count.h Line-crossing counter
+│ ├── nn2_zone.h Zone intrusion detection
+│ ├── nn2_nvr.h Multi-camera NVR pipeline
+│ └── nn2_json.h JSON event serialization
+├── src/
+│ ├── gemm.c AVX-512 GEMM 6x32, KC-blocking, fused bias+SiLU
+│ ├── gemm_res.c Fused GEMM + residual (separate icache)
+│ ├── conv.c Conv dispatcher, parallel im2col
+│ ├── conv_implicit.c Zero-buffer 3x3 conv (no im2col)
+│ ├── ops.c AVX-512 maxpool, upsample, DW conv, concat
+│ ├── decode.c DFL decode + greedy NMS
+│ ├── pool.c Lock-free thread pool (WaitOnAddress)
+│ ├── net.c YOLOv8n forward pass (zero-copy C2f)
+│ ├── nn2.c Public API + preprocessing
+│ ├── nvr_prod.c Production NVR server + web dashboard
+│ ├── track.c SORT tracker implementation
+│ ├── motion_gate.c Motion detection (frame diff)
+│ ├── smart_pipeline.c Smart NVR pipeline (gate+track+skip)
+│ ├── int8_nhwc/ INT8 VNNI pipeline (experimental)
+│ └── specialized/ Compile-time specialized forward
+├── tools/
+│ ├── export_yolov8n.py PyTorch → nn2 weight converter
+│ ├── bench_compare.py nn2 vs ONNX Runtime benchmark
+│ └── prune_channels.py Channel pruning tool
+├── weights/
+│ ├── yolov8n_320.bin YOLOv8n @ 320 (12.6MB)
+│ ├── yolov8n_256.bin YOLOv8n @ 256 (12.6MB)
+│ └── yolov8n_int8.bin INT8 quantized (3.1MB)
+└── build.sh Build script
+```
+
+## Binaries
+
+| Binary | Size | Purpose |
+|--------|------|---------|
+| `nn2.exe` | 260KB | CLI benchmark |
+| `nn2_img.exe` | 488KB | Image detection (JPEG/PNG) |
+| `nn2_nvr_prod.exe` | 520KB | Production NVR server |
+| `nn2_nvr.exe` | 268KB | NVR simulation |
+| `nanodet.exe` | 220KB | NanoDet-Plus-m |
+
+## Key Optimizations
+
+| Optimization | Effect |
+|---|---|
+| AVX-512 GEMM 6x32 with KC-blocking | Baseline, L1 cache fit |
+| Fused GEMM + bias + SiLU | One memory pass (saves full C read+write) |
+| A-packing (BLIS-style) | Sequential weight access, no stride |
+| Implicit im2col | Eliminates 3.7MB buffer for large 3x3 convs |
+| Parallel im2col | Multi-threaded im2col for 3x3 convs |
+| AVX-512 maxpool + threading | SPPF 6x faster |
+| AVX-512 upsample (permutexvar) | 16 pixels to 32 in one instruction |
+| K-unroll x4 + prefetch | Better ILP and memory latency hiding |
+| 2D tiling (M x N) | All cores busy even with few N-tiles |
+| Fused residual (separate .c) | Saves memory pass without icache pollution |
+| Cephes vectorized exp | Float-accurate SiLU (max error 4.8e-7) |
+| Zero-copy C2f concat | Write bottleneck output directly to concat position |
+| Lock-free thread pool | <500ns dispatch, spin-wait + WaitOnAddress |
+| Motion gate | Skip static frames (~0.05ms instead of 8.5ms) |
+| Kalman temporal skip | Track between detections (~0.01ms) |
+
+## Requirements
+
+- x86-64 CPU with AVX2+FMA (AVX-512 recommended)
+- GCC 10+ or MinGW-w64
+- ~64MB RAM for 320x320
+- No other dependencies
+
+## Optimization Journey
+
+```
+Naive C loop: 917.0 ms
++ AVX2 GEMM: 120.0 ms (7.6x)
++ AVX-512 6x32: 44.0 ms (2.7x)
++ Fused bias+SiLU: 26.0 ms (1.7x)
++ Parallel im2col: 16.0 ms (1.6x)
++ A-packing: 13.0 ms (1.2x)
++ Implicit im2col: 12.6 ms (1.03x)
++ AVX-512 maxpool: 8.9 ms (1.4x)
++ KC-blocking + 2D tiling: 8.5 ms (1.05x)
++ Fused residual: 8.1 ms (1.05x)
+─────────────────────────────────────────────
+Total: 917ms → 8.1ms = 113x speedup
+vs ONNX RT: 8.5ms vs 12.7ms = 1.50x faster
+Smart pipeline: 0.56ms avg = 1,638x from start
+```
+
+## License
+
+Apache 2.0. Free for commercial use, attribution required (see LICENSE).
+
+Copyright (c) 2026 Baurzhan Atinov.
+
+If you ship `nn2` in a product, an attribution line in your README or
+About page is appreciated, not required by the license. Contributions
+via PR welcome.
diff --git a/nn2/TODO.md b/nn2/TODO.md
new file mode 100644
index 0000000..fd72f69
--- /dev/null
+++ b/nn2/TODO.md
@@ -0,0 +1,34 @@
+# nn2 NanoDet-Plus-m TODO
+
+## Status
+- Backbone ShuffleNetV2: WORKS (all 3 stages + stride/regular blocks)
+- Neck Ghost-PAN: CRASHES after backbone (memory corruption in workspace)
+- Head GFL: Code written, not tested
+- Export: DONE (110 layers, 4.5MB)
+
+## Root Cause
+Workspace-based memory management causes corruption. The ping-pong buffers (A/B)
+and scratch buffer (tmp) overlap or are too small for stage3 intermediates.
+
+## Fix Plan
+1. Replace ALL workspace pointer arithmetic with per-tensor malloc/free
+ - Backbone: malloc for each conv output, free when no longer needed
+ - Neck: already partially done with malloc (r1/r2/r3)
+ - This sacrifices some speed (malloc overhead) but guarantees correctness
+2. Once forward pass works end-to-end, optimize memory:
+ - Profile memory usage to determine actual peak
+ - Allocate one big arena with verified offsets
+ - Pre-compute all tensor sizes at init time
+
+## Performance Projections (from operator benchmarks)
+- DW k=3 convs: ~0.04ms each (AVX-512 + threaded)
+- DW k=5 convs: ~0.5ms each (needs AVX-512 optimization)
+- PW 1x1 convs: ~0.07ms each (GEMM)
+- Estimated NanoDet total: ~5-8ms (need k=5 DW optimization)
+- Target: ~1-3ms (with k=5 DW AVX-512 + optimized memory)
+
+## Key Files
+- src/nanodet.c: Forward pass + weight loading + detect
+- src/ops.c: DW conv (AVX-512 for k=3), channel shuffle
+- tools/export_nanodet.py: ONNX → NN2N format
+- weights/nanodet_plus_m_320.bin: Exported weights
diff --git a/nn2/build.sh b/nn2/build.sh
new file mode 100644
index 0000000..187741a
--- /dev/null
+++ b/nn2/build.sh
@@ -0,0 +1,62 @@
+#!/bin/bash
+# nn2 build script
+CC=${CC:-/c/mingw64/bin/gcc}
+FL="-O3 -march=native -funroll-loops -Wno-unused-function -Wno-unused-variable -Iinclude -Isrc"
+LD="-lm -lsynchronization"
+
+echo "Building nn2 — Pure C YOLO Inference Engine"
+echo " Verified: 4/4 detections on bus.jpg (person 86%, bus 80%)"
+echo " Performance: 8.1ms@320 (124 FPS) — 1.50× faster than ONNX Runtime"
+echo ""
+
+# Core objects
+for f in src/gemm.c src/gemm_res.c src/conv.c src/conv_implicit.c src/conv_fused.c src/conv_tiled.c \
+ src/winograd.c src/ops.c src/decode.c src/pool.c src/net.c src/nn2.c src/gemm_int8.c; do
+ echo " CC $f"
+ $CC $FL -c $f -o ${f%.c}.o || exit 1
+done
+
+# nn2 CLI
+echo " CC src/main.c"
+$CC $FL -c src/main.c -o src/main.o
+$CC $FL -o nn2.exe src/gemm.o src/gemm_res.o src/gemm_int8.o src/conv.o src/conv_tiled.o src/conv_fused.o src/conv_implicit.o \
+ src/winograd.o src/ops.o src/decode.o src/pool.o src/net.o src/nn2.o src/main.o $LD
+echo " → nn2.exe ($(du -k nn2.exe | cut -f1)KB)"
+
+# nn2_img (with stb_image)
+echo " CC src/main_img.c"
+$CC $FL -c src/main_img.c -o src/main_img.o
+$CC $FL -o nn2_img.exe src/gemm.o src/gemm_res.o src/gemm_int8.o src/conv.o src/conv_tiled.o src/conv_fused.o src/conv_implicit.o \
+ src/winograd.o src/ops.o src/decode.o src/pool.o src/net.o src/nn2.o src/main_img.o $LD
+echo " → nn2_img.exe ($(du -k nn2_img.exe | cut -f1)KB)"
+
+# nn2_nvr (multi-camera)
+echo " CC src/nvr.c src/main_nvr.c"
+$CC $FL -c src/nvr.c -o src/nvr.o
+$CC $FL -c src/main_nvr.c -o src/main_nvr.o
+$CC $FL -o nn2_nvr.exe src/gemm.o src/gemm_res.o src/gemm_int8.o src/conv.o src/conv_tiled.o src/conv_fused.o src/conv_implicit.o \
+ src/winograd.o src/ops.o src/decode.o src/pool.o src/net.o src/nn2.o src/nvr.o src/main_nvr.o $LD
+echo " → nn2_nvr.exe ($(du -k nn2_nvr.exe | cut -f1)KB)"
+
+# nanodet
+echo " CC src/nanodet.c src/main_nanodet.c"
+$CC $FL -c src/nanodet.c -o src/nanodet.o
+$CC $FL -c src/main_nanodet.c -o src/main_nanodet.o
+$CC $FL -o nanodet.exe src/main_nanodet.o src/nanodet.o src/gemm.o src/gemm_int8.o \
+ src/conv.o src/conv_fused.o src/conv_implicit.o src/winograd.o src/ops.o src/decode.o src/pool.o $LD
+echo " → nanodet.exe ($(du -k nanodet.exe | cut -f1)KB)"
+
+# NVR Production Server
+echo " CC src/nvr_prod.c src/track.c src/motion_gate.c src/smart_pipeline.c"
+$CC $FL -c src/nvr_prod.c -o src/nvr_prod.o
+$CC $FL -c src/track.c -o src/track.o
+OBJ="src/gemm.o src/gemm_res.o src/gemm_int8.o src/conv.o src/conv_fused.o src/conv_implicit.o src/conv_tiled.o src/winograd.o src/ops.o src/decode.o src/pool.o src/net.o src/nn2.o"
+$CC $FL -o nn2_nvr_prod.exe src/nvr_prod.o src/track.o $OBJ $LD -lws2_32
+echo " → nn2_nvr_prod.exe ($(du -k nn2_nvr_prod.exe | cut -f1)KB)"
+
+echo ""
+echo "Build complete!"
+echo ""
+echo "Production NVR:"
+echo " ./nn2_nvr_prod.exe -w weights/yolov8n_320.bin -p 8080"
+echo " Open http://localhost:8080 for dashboard"
diff --git a/nn2/build_antispoof.sh b/nn2/build_antispoof.sh
new file mode 100644
index 0000000..d5ef77c
--- /dev/null
+++ b/nn2/build_antispoof.sh
@@ -0,0 +1,31 @@
+#!/bin/bash
+# Build the MiniFASNet anti-spoof port that lives alongside YOLO in nn2.
+set -e
+CC=${CC:-/c/mingw64/bin/gcc}
+FL="-O3 -march=native -funroll-loops -Wno-unused-function -Wno-unused-variable -Iinclude -Isrc"
+LD="-lm -lsynchronization"
+
+echo "Building nn2 anti-spoof (MiniFASNet port)"
+
+# Core objects reused from YOLO build (compile if missing)
+NEED="src/gemm.o src/gemm_res.o src/gemm_int8.o src/conv.o src/conv_implicit.o src/conv_fused.o src/conv_tiled.o src/winograd.o src/ops.o src/pool.o"
+for o in $NEED; do
+ if [ ! -f "$o" ]; then
+ src=${o%.o}.c
+ echo " CC $src"
+ $CC $FL -c "$src" -o "$o" || exit 1
+ fi
+done
+
+# New objects
+for f in src/antispoof_ops.c src/minifasnet.c src/main_antispoof.c; do
+ echo " CC $f"
+ $CC $FL -c "$f" -o "${f%.c}.o" || exit 1
+done
+
+echo " LD nn2_antispoof.exe"
+$CC $FL -o nn2_antispoof.exe \
+ src/antispoof_ops.o src/minifasnet.o src/main_antispoof.o \
+ $NEED $LD || exit 1
+
+echo " → nn2_antispoof.exe ($(du -k nn2_antispoof.exe | cut -f1)KB)"
diff --git a/nn2/build_int8.sh b/nn2/build_int8.sh
new file mode 100644
index 0000000..e293beb
--- /dev/null
+++ b/nn2/build_int8.sh
@@ -0,0 +1,35 @@
+#!/bin/bash
+# Build INT8 NHWC pipeline (separate from main build)
+CC=${CC:-/c/mingw64/bin/gcc}
+FL="-O3 -march=native -funroll-loops -mavx512vnni -Wno-unused-function -Wno-unused-variable -Iinclude -Isrc"
+LD="-lm -lsynchronization"
+
+echo "Building INT8 NHWC Pipeline"
+echo ""
+
+# Core objects from main build (reuse)
+echo " Using existing core objects..."
+
+CORE="src/gemm.o src/gemm_res.o src/gemm_int8.o src/conv.o src/conv_fused.o src/conv_implicit.o src/conv_tiled.o \
+ src/winograd.o src/ops.o src/decode.o src/pool.o src/net.o src/nn2.o"
+I8="src/int8_nhwc/gemm_vnni.o src/int8_nhwc/conv_int8.o src/int8_nhwc/ops_int8.o src/int8_nhwc/c2f_int8.o"
+
+# INT8 NHWC objects
+for f in src/int8_nhwc/gemm_vnni.c src/int8_nhwc/conv_int8.c src/int8_nhwc/ops_int8.c \
+ src/int8_nhwc/c2f_int8.c src/int8_nhwc/net_int8.c src/int8_nhwc/forward_hybrid.c; do
+ echo " CC $f"
+ $CC $FL -c $f -o ${f%.c}.o || exit 1
+done
+
+# Link per-layer benchmark
+echo " Linking nn2_int8_bench..."
+$CC $FL -o nn2_int8_bench.exe $I8 src/int8_nhwc/net_int8.o $CORE $LD || exit 1
+
+# Link hybrid pipeline benchmark
+echo " Linking nn2_hybrid..."
+$CC $FL -o nn2_hybrid.exe $I8 src/int8_nhwc/forward_hybrid.o $CORE $LD || exit 1
+
+echo " → nn2_int8_bench.exe (per-layer INT8 benchmark)"
+echo " → nn2_hybrid.exe (full hybrid pipeline benchmark)"
+echo ""
+echo "Run: ./nn2_hybrid.exe [weights/yolov8n_320.bin]"
diff --git a/nn2/docs/nexuscodec_presentation.html b/nn2/docs/nexuscodec_presentation.html
new file mode 100644
index 0000000..80081cc
--- /dev/null
+++ b/nn2/docs/nexuscodec_presentation.html
@@ -0,0 +1,962 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8">
+<meta name="viewport" content="width=device-width, initial-scale=1.0">
+<title>NexusCodec — Full H.265 Video Stack</title>
+<link rel="preconnect" href="https://fonts.googleapis.com">
+<link href="https://fonts.googleapis.com/css2?family=DM+Serif+Display&family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
+<style>
+ :root {
+ --blue: #1a56db;
+ --blue-light: #e8effc;
+ --blue-mid: #3b7ddd;
+ --dark: #111827;
+ --gray-800: #1f2937;
+ --gray-600: #4b5563;
+ --gray-400: #9ca3af;
+ --gray-200: #e5e7eb;
+ --gray-100: #f3f4f6;
+ --red: #dc2626;
+ --red-bg: #fef2f2;
+ --green: #059669;
+ --green-bg: #ecfdf5;
+ --amber: #d97706;
+ --amber-bg: #fffbeb;
+ }
+
+ * { margin: 0; padding: 0; box-sizing: border-box; }
+
+ @page {
+ size: A4;
+ margin: 0;
+ }
+
+ body {
+ font-family: 'DM Sans', sans-serif;
+ color: var(--dark);
+ background: #fff;
+ font-size: 11pt;
+ line-height: 1.55;
+ -webkit-print-color-adjust: exact;
+ print-color-adjust: exact;
+ }
+
+ .page {
+ width: 210mm;
+ min-height: 297mm;
+ padding: 28mm 24mm 20mm;
+ margin: 0 auto;
+ page-break-after: always;
+ position: relative;
+ overflow: hidden;
+ }
+
+ .page:last-child { page-break-after: avoid; }
+
+ @media screen {
+ .page {
+ margin: 20px auto;
+ box-shadow: 0 2px 20px rgba(0,0,0,0.08);
+ border: 1px solid var(--gray-200);
+ }
+ }
+
+ /* Page footer */
+ .page::after {
+ content: attr(data-footer);
+ position: absolute;
+ bottom: 12mm;
+ left: 24mm;
+ right: 24mm;
+ font-size: 7.5pt;
+ color: var(--gray-400);
+ border-top: 1px solid var(--gray-200);
+ padding-top: 6px;
+ display: flex;
+ justify-content: space-between;
+ }
+
+ .page-num {
+ position: absolute;
+ bottom: 12mm;
+ right: 24mm;
+ font-size: 7.5pt;
+ color: var(--gray-400);
+ }
+
+ /* Typography */
+ h1 {
+ font-family: 'DM Serif Display', serif;
+ font-size: 32pt;
+ font-weight: 400;
+ line-height: 1.15;
+ color: var(--dark);
+ letter-spacing: -0.5px;
+ }
+
+ h2 {
+ font-family: 'DM Serif Display', serif;
+ font-size: 18pt;
+ font-weight: 400;
+ color: var(--dark);
+ margin-bottom: 16px;
+ padding-bottom: 8px;
+ border-bottom: 2px solid var(--blue);
+ display: inline-block;
+ }
+
+ h3 {
+ font-size: 11pt;
+ font-weight: 700;
+ color: var(--gray-800);
+ margin-bottom: 6px;
+ text-transform: uppercase;
+ letter-spacing: 0.8px;
+ font-size: 8.5pt;
+ }
+
+ p { margin-bottom: 10px; color: var(--gray-600); }
+ strong { color: var(--dark); font-weight: 600; }
+
+ /* Cover page */
+ .cover {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ padding: 40mm 28mm;
+ }
+
+ .cover-badge {
+ display: inline-block;
+ background: var(--blue);
+ color: #fff;
+ font-size: 8pt;
+ font-weight: 700;
+ letter-spacing: 2px;
+ text-transform: uppercase;
+ padding: 6px 16px;
+ border-radius: 2px;
+ margin-bottom: 24px;
+ width: fit-content;
+ }
+
+ .cover h1 {
+ font-size: 42pt;
+ margin-bottom: 12px;
+ }
+
+ .cover h1 span { color: var(--blue); }
+
+ .cover-subtitle {
+ font-size: 16pt;
+ color: var(--gray-600);
+ font-weight: 400;
+ margin-bottom: 48px;
+ max-width: 380px;
+ }
+
+ .cover-meta {
+ display: grid;
+ grid-template-columns: 1fr 1fr 1fr;
+ gap: 20px;
+ border-top: 1px solid var(--gray-200);
+ padding-top: 24px;
+ margin-top: auto;
+ }
+
+ .cover-meta-item {
+ font-size: 8.5pt;
+ color: var(--gray-400);
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ }
+
+ .cover-meta-item span {
+ display: block;
+ font-size: 11pt;
+ color: var(--dark);
+ font-weight: 600;
+ margin-top: 4px;
+ text-transform: none;
+ letter-spacing: 0;
+ }
+
+ .cover-line {
+ width: 64px;
+ height: 4px;
+ background: var(--blue);
+ margin-bottom: 28px;
+ }
+
+ /* Content elements */
+ .section-label {
+ font-size: 8pt;
+ font-weight: 700;
+ color: var(--blue);
+ text-transform: uppercase;
+ letter-spacing: 2px;
+ margin-bottom: 8px;
+ }
+
+ /* Cards */
+ .card-grid {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 14px;
+ margin: 16px 0;
+ }
+
+ .card {
+ background: var(--gray-100);
+ border-radius: 6px;
+ padding: 18px 20px;
+ border-left: 3px solid var(--blue);
+ }
+
+ .card.red { background: var(--red-bg); border-left-color: var(--red); }
+ .card.green { background: var(--green-bg); border-left-color: var(--green); }
+ .card.amber { background: var(--amber-bg); border-left-color: var(--amber); }
+
+ .card h4 {
+ font-size: 10pt;
+ font-weight: 700;
+ margin-bottom: 6px;
+ color: var(--dark);
+ }
+
+ .card p {
+ font-size: 9.5pt;
+ margin-bottom: 0;
+ line-height: 1.45;
+ }
+
+ /* Big number callouts */
+ .stat-row {
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: 16px;
+ margin: 20px 0;
+ }
+
+ .stat-box {
+ text-align: center;
+ padding: 20px 12px;
+ background: var(--gray-100);
+ border-radius: 6px;
+ }
+
+ .stat-box .number {
+ font-family: 'DM Serif Display', serif;
+ font-size: 28pt;
+ color: var(--blue);
+ line-height: 1;
+ margin-bottom: 4px;
+ }
+
+ .stat-box .label {
+ font-size: 8.5pt;
+ color: var(--gray-600);
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ }
+
+ /* Tables */
+ table {
+ width: 100%;
+ border-collapse: collapse;
+ margin: 14px 0;
+ font-size: 9.5pt;
+ }
+
+ thead th {
+ background: var(--dark);
+ color: #fff;
+ padding: 10px 14px;
+ text-align: left;
+ font-weight: 600;
+ font-size: 8.5pt;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ }
+
+ thead th:first-child { border-radius: 4px 0 0 0; }
+ thead th:last-child { border-radius: 0 4px 0 0; }
+
+ tbody td {
+ padding: 10px 14px;
+ border-bottom: 1px solid var(--gray-200);
+ color: var(--gray-600);
+ }
+
+ tbody tr:last-child td { border-bottom: none; }
+
+ tbody tr:nth-child(even) { background: var(--gray-100); }
+
+ .badge {
+ display: inline-block;
+ padding: 2px 10px;
+ border-radius: 12px;
+ font-size: 8pt;
+ font-weight: 700;
+ }
+
+ .badge-red { background: #fee2e2; color: var(--red); }
+ .badge-green { background: #d1fae5; color: var(--green); }
+ .badge-amber { background: #fef3c7; color: var(--amber); }
+ .badge-blue { background: var(--blue-light); color: var(--blue); }
+
+ /* Pipeline diagram */
+ .pipeline {
+ display: flex;
+ align-items: center;
+ gap: 0;
+ margin: 20px 0;
+ justify-content: center;
+ }
+
+ .pipeline-step {
+ background: var(--blue-light);
+ border: 2px solid var(--blue);
+ border-radius: 8px;
+ padding: 12px 16px;
+ text-align: center;
+ min-width: 100px;
+ }
+
+ .pipeline-step.highlight {
+ background: var(--blue);
+ color: #fff;
+ }
+
+ .pipeline-step .step-title {
+ font-weight: 700;
+ font-size: 9pt;
+ }
+
+ .pipeline-step .step-sub {
+ font-size: 7.5pt;
+ opacity: 0.75;
+ margin-top: 2px;
+ }
+
+ .pipeline-step.highlight .step-sub { color: rgba(255,255,255,0.8); }
+
+ .pipeline-arrow {
+ font-size: 16pt;
+ color: var(--blue);
+ padding: 0 6px;
+ font-weight: 700;
+ }
+
+ /* Revenue cards */
+ .revenue-grid {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 14px;
+ margin: 16px 0;
+ }
+
+ .revenue-card {
+ border: 2px solid var(--gray-200);
+ border-radius: 8px;
+ padding: 18px;
+ position: relative;
+ }
+
+ .revenue-card .revenue-amount {
+ font-family: 'DM Serif Display', serif;
+ font-size: 20pt;
+ color: var(--blue);
+ margin-bottom: 4px;
+ }
+
+ .revenue-card .revenue-source {
+ font-weight: 700;
+ font-size: 10pt;
+ color: var(--dark);
+ margin-bottom: 6px;
+ }
+
+ .revenue-card p {
+ font-size: 9pt;
+ margin: 0;
+ }
+
+ /* Timeline */
+ .timeline {
+ display: flex;
+ gap: 0;
+ margin: 20px 0;
+ position: relative;
+ }
+
+ .timeline::before {
+ content: '';
+ position: absolute;
+ top: 20px;
+ left: 0;
+ right: 0;
+ height: 3px;
+ background: var(--gray-200);
+ }
+
+ .timeline-item {
+ flex: 1;
+ text-align: center;
+ position: relative;
+ padding-top: 36px;
+ }
+
+ .timeline-item::before {
+ content: '';
+ position: absolute;
+ top: 14px;
+ left: 50%;
+ transform: translateX(-50%);
+ width: 14px;
+ height: 14px;
+ border-radius: 50%;
+ background: var(--gray-400);
+ border: 3px solid #fff;
+ z-index: 1;
+ }
+
+ .timeline-item.done::before { background: var(--green); }
+ .timeline-item.active::before { background: var(--blue); box-shadow: 0 0 0 4px var(--blue-light); }
+ .timeline-item.future::before { background: var(--gray-300); }
+
+ .timeline-item .tl-label {
+ font-weight: 700;
+ font-size: 9.5pt;
+ color: var(--dark);
+ margin-bottom: 4px;
+ }
+
+ .timeline-item .tl-desc {
+ font-size: 8.5pt;
+ color: var(--gray-600);
+ }
+
+ /* Utility */
+ .mt-12 { margin-top: 12px; }
+ .mt-20 { margin-top: 20px; }
+ .mt-28 { margin-top: 28px; }
+ .mb-8 { margin-bottom: 8px; }
+ .text-small { font-size: 9pt; }
+ .text-center { text-align: center; }
+
+ .highlight-box {
+ background: var(--blue);
+ color: #fff;
+ border-radius: 8px;
+ padding: 20px 24px;
+ margin: 16px 0;
+ }
+
+ .highlight-box h3 { color: rgba(255,255,255,0.7); }
+ .highlight-box p { color: rgba(255,255,255,0.9); }
+ .highlight-box strong { color: #fff; }
+
+ .two-col {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 24px;
+ }
+
+ .icon-num {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 28px;
+ height: 28px;
+ border-radius: 50%;
+ background: var(--blue);
+ color: #fff;
+ font-weight: 700;
+ font-size: 11pt;
+ margin-right: 10px;
+ flex-shrink: 0;
+ }
+
+ .step-item {
+ display: flex;
+ align-items: flex-start;
+ margin-bottom: 14px;
+ }
+
+ .step-item-content h4 {
+ font-size: 10.5pt;
+ font-weight: 700;
+ color: var(--dark);
+ margin-bottom: 2px;
+ }
+
+ .step-item-content p {
+ font-size: 9pt;
+ margin: 0;
+ }
+
+ .check-list {
+ list-style: none;
+ padding: 0;
+ }
+
+ .check-list li {
+ padding: 6px 0;
+ padding-left: 24px;
+ position: relative;
+ font-size: 10pt;
+ color: var(--gray-600);
+ }
+
+ .check-list li::before {
+ content: "\2713";
+ position: absolute;
+ left: 0;
+ color: var(--green);
+ font-weight: 700;
+ }
+
+ .cross-list li::before {
+ content: "\2717";
+ color: var(--red);
+ }
+
+ /* Print */
+ @media print {
+ body { background: #fff; }
+ .page {
+ box-shadow: none;
+ border: none;
+ margin: 0;
+ }
+ }
+</style>
+</head>
+<body>
+
+<!-- ===== PAGE 1: COVER ===== -->
+<div class="page cover" data-footer="">
+ <div class="cover-badge">Confidential</div>
+ <h1>NexusCodec</h1>
+ <h1 style="margin-top:-4px"><span>Full H.265 Video Stack</span></h1>
+ <div class="cover-line"></div>
+ <div class="cover-subtitle">
+ What owning a complete video codec means for the business
+ </div>
+ <div class="cover-meta">
+ <div class="cover-meta-item">
+ Status
+ <span>Decoder Complete, Encoder Planned</span>
+ </div>
+ <div class="cover-meta-item">
+ Technology
+ <span>Pure C, Zero Dependencies</span>
+ </div>
+ <div class="cover-meta-item">
+ Market
+ <span>$60B Video Surveillance</span>
+ </div>
+ </div>
+</div>
+
+<!-- ===== PAGE 2: THE PROBLEM ===== -->
+<div class="page" data-footer="NexusCodec — Business Overview">
+ <div class="section-label">The Problem</div>
+ <h2>Every NVR Company Has a Codec Problem</h2>
+
+ <p style="font-size:11pt; color:var(--dark); max-width:500px; margin-bottom:20px;">
+ Video surveillance systems need to <strong>decode</strong> video from cameras and <strong>encode</strong> video for storage. Every company in this market relies on third-party codec software &mdash; and every option is painful.
+ </p>
+
+ <div class="card-grid">
+ <div class="card red">
+ <h4>FFmpeg &mdash; Open Source Trap</h4>
+ <p>Most used video library in the world. Licensed under <strong>GPL</strong> &mdash; meaning any product using it must also be open-sourced. Companies using FFmpeg commercially carry <strong>permanent legal risk</strong>.</p>
+ </div>
+ <div class="card red">
+ <h4>Commercial Licenses &mdash; Expensive</h4>
+ <p>MainConcept, Intel Media SDK, and others charge <strong>$50,000&ndash;100,000/year</strong> for codec licenses. Small/medium NVR companies can't afford this.</p>
+ </div>
+ <div class="card amber">
+ <h4>H.265 Patent Royalties &mdash; Triple Tax</h4>
+ <p>H.265 has <strong>three separate patent pools</strong> (MPEG LA, HEVC Advance, Access Advance). Up to <strong>$1.50 per device</strong>. Three contracts, three legal processes.</p>
+ </div>
+ <div class="card amber">
+ <h4>Hardware Lock-in</h4>
+ <p>Intel Quick Sync, NVIDIA NVDEC &mdash; tied to specific chips. Can't run on ARM, AMD, or low-cost hardware. <strong>No portability.</strong></p>
+ </div>
+ </div>
+
+ <div class="highlight-box">
+ <h3>THE BOTTOM LINE</h3>
+ <p>
+ Thousands of NVR companies worldwide are stuck: use FFmpeg and <strong>risk a lawsuit</strong>, pay $50K+/year for a license, or spend 2&ndash;3 years and $500K+ building their own. <strong>There is no good option.</strong>
+ </p>
+ </div>
+ <span class="page-num">2</span>
+</div>
+
+<!-- ===== PAGE 3: OUR SOLUTION ===== -->
+<div class="page" data-footer="NexusCodec — Business Overview">
+ <div class="section-label">Our Solution</div>
+ <h2>We Built Our Own. From Scratch.</h2>
+
+ <p style="font-size:11pt; color:var(--dark); max-width:520px; margin-bottom:20px;">
+ <strong>NexusCodec</strong> is a complete H.265 video stack written in pure C with zero external dependencies. We own every line of code. No GPL. No license fees. No hardware lock-in.
+ </p>
+
+ <div class="two-col mt-20">
+ <div>
+ <div class="card green" style="min-height:170px">
+ <h4>NexusDecode &mdash; Decoder <span class="badge badge-green">DONE</span></h4>
+ <p style="margin-top:8px">Converts compressed H.265/H.264 video from cameras into viewable images.</p>
+ <ul class="check-list" style="margin-top:10px">
+ <li>184 KB binary (vs 30+ MB for FFmpeg)</li>
+ <li>46x faster than FFmpeg on CPU</li>
+ <li>6,300 frames/sec at 640x480</li>
+ <li>Pixel-perfect quality (verified)</li>
+ <li>Runs on Intel, AMD, and ARM</li>
+ </ul>
+ </div>
+ </div>
+ <div>
+ <div class="card" style="border-left-color:var(--blue); min-height:170px">
+ <h4>NexusEncode &mdash; Encoder <span class="badge badge-blue">PLANNED</span></h4>
+ <p style="margin-top:8px">Compresses video for storage, export, re-streaming, and analytics overlay.</p>
+ <ul class="check-list" style="margin-top:10px">
+ <li>Record camera streams to disk</li>
+ <li>Export evidence clips (MP4)</li>
+ <li>Add detection overlay (bounding boxes)</li>
+ <li>Re-stream at lower quality for mobile</li>
+ <li>Estimated: 3&ndash;5 months development</li>
+ </ul>
+ </div>
+ </div>
+ </div>
+
+ <div class="stat-row mt-20">
+ <div class="stat-box">
+ <div class="number">184<span style="font-size:14pt">KB</span></div>
+ <div class="label">Binary Size</div>
+ </div>
+ <div class="stat-box">
+ <div class="number">46<span style="font-size:14pt">x</span></div>
+ <div class="label">Faster than FFmpeg</div>
+ </div>
+ <div class="stat-box">
+ <div class="number">0</div>
+ <div class="label">Dependencies</div>
+ </div>
+ </div>
+ <span class="page-num">3</span>
+</div>
+
+<!-- ===== PAGE 4: WHAT DECODER AND ENCODER DO ===== -->
+<div class="page" data-footer="NexusCodec — Business Overview">
+ <div class="section-label">In Simple Terms</div>
+ <h2>What the Decoder and Encoder Do</h2>
+
+ <div class="two-col mt-20">
+ <div>
+ <h3 style="color:var(--green);">Decoder = Camera to Screen</h3>
+ <p style="font-size:10.5pt; margin-bottom:14px;">
+ IP cameras send video as compressed data (H.265). The <strong>decoder</strong> converts this back into viewable images in real time.
+ </p>
+ <div class="card green" style="padding:14px 18px">
+ <p style="font-size:9.5pt; margin:0; line-height:1.6;">
+ <strong>Without a decoder:</strong> the NVR receives data from cameras but can't show anything on screen. It's like receiving a letter in a foreign language with no translator.<br><br>
+ <strong>Every NVR system needs a decoder.</strong> It is not optional.
+ </p>
+ </div>
+ </div>
+ <div>
+ <h3 style="color:var(--blue);">Encoder = Screen to Storage</h3>
+ <p style="font-size:10.5pt; margin-bottom:14px;">
+ The <strong>encoder</strong> takes video and compresses it for storage on disk or transmission over network.
+ </p>
+ <div class="card" style="border-left-color:var(--blue); padding:14px 18px">
+ <p style="font-size:9.5pt; margin:0; line-height:1.6;">
+ <strong>Without an encoder, you cannot:</strong><br>
+ &bull;&ensp;Record video to disk<br>
+ &bull;&ensp;Export clips for police/court evidence<br>
+ &bull;&ensp;Add analytics overlay (bounding boxes)<br>
+ &bull;&ensp;Re-stream to mobile at lower quality<br><br>
+ <strong>An encoder completes the pipeline.</strong>
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <div class="mt-28">
+ <h3>The Complete Pipeline</h3>
+ <div class="pipeline">
+ <div class="pipeline-step">
+ <div class="step-title">IP Camera</div>
+ <div class="step-sub">H.265 stream</div>
+ </div>
+ <div class="pipeline-arrow">&rarr;</div>
+ <div class="pipeline-step highlight">
+ <div class="step-title">DECODE</div>
+ <div class="step-sub">NexusDecode</div>
+ </div>
+ <div class="pipeline-arrow">&rarr;</div>
+ <div class="pipeline-step highlight" style="background:var(--blue-mid)">
+ <div class="step-title">ANALYTICS</div>
+ <div class="step-sub">nn2 AI Engine</div>
+ </div>
+ <div class="pipeline-arrow">&rarr;</div>
+ <div class="pipeline-step highlight">
+ <div class="step-title">ENCODE</div>
+ <div class="step-sub">NexusEncode</div>
+ </div>
+ <div class="pipeline-arrow">&rarr;</div>
+ <div class="pipeline-step">
+ <div class="step-title">Storage</div>
+ <div class="step-sub">Record / Export</div>
+ </div>
+ </div>
+ <p class="text-center text-small" style="color:var(--gray-400); margin-top:8px;">
+ Every blue box is our proprietary technology. No third-party code anywhere in the pipeline.
+ </p>
+ </div>
+ <span class="page-num">4</span>
+</div>
+
+<!-- ===== PAGE 5: WHY BOTH TOGETHER ===== -->
+<div class="page" data-footer="NexusCodec — Business Overview">
+ <div class="section-label">Strategic Value</div>
+ <h2>Why Decoder + Encoder Together Changes Everything</h2>
+
+ <div class="mt-12">
+ <div class="step-item">
+ <span class="icon-num">1</span>
+ <div class="step-item-content">
+ <h4>Complete Independence from FFmpeg</h4>
+ <p>No GPL code anywhere in the product. No legal risk. No forced open-sourcing. Full freedom to license commercially.</p>
+ </div>
+ </div>
+ <div class="step-item">
+ <span class="icon-num">2</span>
+ <div class="step-item-content">
+ <h4>Zero License Fees</h4>
+ <p>No $50&ndash;100K/year to MainConcept or Intel. Code is ours, costs are ours to control. Every sale is pure margin.</p>
+ </div>
+ </div>
+ <div class="step-item">
+ <span class="icon-num">3</span>
+ <div class="step-item-content">
+ <h4>Runs on Any Hardware</h4>
+ <p>Pure C with SIMD optimization. Works on Intel, AMD, ARM (Raspberry Pi, Rockchip). Not locked to any chip vendor.</p>
+ </div>
+ </div>
+ <div class="step-item">
+ <span class="icon-num">4</span>
+ <div class="step-item-content">
+ <h4>Bundled with AI Analytics</h4>
+ <p>Our nn2 YOLO engine (1.5x faster than ONNX Runtime) plugs directly into the codec pipeline. <strong>Decode &rarr; Detect &rarr; Encode in one binary.</strong> No competitor offers this.</p>
+ </div>
+ </div>
+ <div class="step-item">
+ <span class="icon-num">5</span>
+ <div class="step-item-content">
+ <h4>We Can Sell It to Others</h4>
+ <p>Thousands of NVR companies need exactly this. We can license NexusCodec as an SDK and generate recurring revenue.</p>
+ </div>
+ </div>
+ </div>
+
+ <div class="highlight-box mt-20">
+ <h3>KEY INSIGHT</h3>
+ <p>
+ A decoder alone is useful. An encoder alone is useful. <strong>Both together with AI analytics is a platform</strong> &mdash; the foundation for an entire NVR product line and a licensing business targeting every surveillance company in the world.
+ </p>
+ </div>
+ <span class="page-num">5</span>
+</div>
+
+<!-- ===== PAGE 6: COMPETITIVE COMPARISON ===== -->
+<div class="page" data-footer="NexusCodec — Business Overview">
+ <div class="section-label">Competition</div>
+ <h2>Competitive Landscape</h2>
+
+ <table class="mt-12">
+ <thead>
+ <tr>
+ <th style="width:18%">Solution</th>
+ <th style="width:16%">License</th>
+ <th style="width:14%">Cost</th>
+ <th style="width:14%">Hardware</th>
+ <th style="width:14%">AI Analytics</th>
+ <th style="width:24%">Risk</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td><strong>FFmpeg</strong></td>
+ <td><span class="badge badge-red">GPL</span></td>
+ <td>Free</td>
+ <td>Any CPU</td>
+ <td>None</td>
+ <td>Must open-source your product or face lawsuit</td>
+ </tr>
+ <tr>
+ <td><strong>MainConcept</strong></td>
+ <td>Commercial</td>
+ <td><strong>$50&ndash;100K/yr</strong></td>
+ <td>x86 only</td>
+ <td>None</td>
+ <td>Expensive, vendor dependency</td>
+ </tr>
+ <tr>
+ <td><strong>Intel Media SDK</strong></td>
+ <td>Free</td>
+ <td>Free</td>
+ <td><span class="badge badge-amber">Intel only</span></td>
+ <td>None</td>
+ <td>Locked to Intel CPUs</td>
+ </tr>
+ <tr>
+ <td><strong>NVIDIA NVDEC</strong></td>
+ <td>Free</td>
+ <td>GPU cost</td>
+ <td><span class="badge badge-amber">GPU only</span></td>
+ <td>Separate</td>
+ <td>$500+ GPU required per server</td>
+ </tr>
+ <tr style="background:var(--blue-light) !important">
+ <td><strong style="color:var(--blue)">NexusCodec</strong></td>
+ <td><span class="badge badge-green">Proprietary</span></td>
+ <td><strong>Ours</strong></td>
+ <td><span class="badge badge-green">Any CPU</span></td>
+ <td><span class="badge badge-green">Built-in</span></td>
+ <td style="color:var(--green); font-weight:600;">Zero legal risk, zero dependencies</td>
+ </tr>
+ </tbody>
+ </table>
+
+ <div class="mt-28">
+ <h3>Our Unique Advantages</h3>
+ <div class="card-grid" style="grid-template-columns: 1fr 1fr 1fr; gap:12px;">
+ <div class="card green" style="text-align:center; padding:20px 12px;">
+ <div style="font-family:'DM Serif Display',serif; font-size:22pt; color:var(--green);">418 KB</div>
+ <p style="font-size:8.5pt; margin:4px 0 0;">Total binary size<br>(H.264 + H.265)</p>
+ </div>
+ <div class="card green" style="text-align:center; padding:20px 12px;">
+ <div style="font-family:'DM Serif Display',serif; font-size:22pt; color:var(--green);">$0</div>
+ <p style="font-size:8.5pt; margin:4px 0 0;">Third-party<br>license costs</p>
+ </div>
+ <div class="card green" style="text-align:center; padding:20px 12px;">
+ <div style="font-family:'DM Serif Display',serif; font-size:22pt; color:var(--green);">3</div>
+ <p style="font-size:8.5pt; margin:4px 0 0;">Products in one stack<br>(Decode + AI + Encode)</p>
+ </div>
+ </div>
+ </div>
+ <span class="page-num">6</span>
+</div>
+
+<!-- ===== PAGE 7: REVENUE ===== -->
+<div class="page" data-footer="NexusCodec — Business Overview">
+ <div class="section-label">Revenue Model</div>
+ <h2>How We Make Money</h2>
+
+ <div class="revenue-grid mt-20">
+ <div class="revenue-card">
+ <div class="revenue-amount">$15&ndash;50K</div>
+ <div class="revenue-source">SDK License (per customer/year)</div>
+ <p>License NexusCodec to NVR software companies. They integrate our decoder/encoder into their product. Recurring annual fee.</p>
+ <p class="mt-12"><strong>Target:</strong> 10&ndash;20 customers = $150K&ndash;$1M/year</p>
+ </div>
+ <div class="revenue-card">
+ <div class="revenue-amount">$100&ndash;500K</div>
+ <div class="revenue-source">OEM Chip Deals</div>
+ <p>License to chip manufacturers (Ambarella, Rockchip, Novatek) as reference software decoder for their camera/NVR SoCs.</p>
+ <p class="mt-12"><strong>Target:</strong> 2&ndash;3 deals = $200K&ndash;$1.5M</p>
+ </div>
+ <div class="revenue-card">
+ <div class="revenue-amount">$5&ndash;10</div>
+ <div class="revenue-source">SaaS per Camera/Month</div>
+ <p>Our own NVR product: cloud-managed, edge-deployed. Full stack: decode + AI analytics + recording + web dashboard.</p>
+ <p class="mt-12"><strong>Target:</strong> 500 cameras = $30&ndash;60K MRR</p>
+ </div>
+ <div class="revenue-card">
+ <div class="revenue-amount">$30&ndash;80K</div>
+ <div class="revenue-source">Analytics Add-on</div>
+ <p>Sell nn2 AI engine separately: person detection, counting, zone intrusion. Works on CPU, no GPU needed.</p>
+ <p class="mt-12"><strong>Target:</strong> Bundle with codec SDK</p>
+ </div>
+ </div>
+
+ <div class="highlight-box mt-12">
+ <h3>YEAR 1 REVENUE PROJECTION</h3>
+ <p>
+ Conservative estimate with SDK licensing focus:<br>
+ <strong>5 SDK customers &times; $25K avg = $125K</strong> + 1 OEM deal $150K = <strong>$275K first year</strong><br>
+ Growing to <strong>$500K&ndash;$1M</strong> in year 2 as encoder completes and customer base expands.
+ </p>
+ </div>
+ <span class="page-num">7</span>
+</div>
+
+<!-- ===== PAGE 8: MARKET + TIMELINE ===== -->
+<div class="page" data-footer="NexusCodec — Business Overview">
+ <div class="section-label">Market &amp; Timeline</div>
+ <h2>Market Opportunity</h2>
+
+ <div class="stat-row">
+ <div class="stat-box">
+ <div class="number">$60<span style="font-size:14pt">B</span></div>
+ <div class="label">Video Surveillance Market</div>
+ </div>
+ <div class="stat-box">
+ <div class="number">$2<span style="font-size:14pt">B</span></div>
+ <div class="label">Codec Licensing Segment</div>
+ </div>
+ <div class="stat-box">
+ <div class="number">1000<span style="font-size:14pt">+</span></div>
+ <div class="label">NVR Companies Worldwide</div>
+ </div>
+ </div>
+
+ <p class="mt-12" style="font-size:10.5pt;">
+ Every company building NVR software, smart cameras, or video analytics is a potential customer. Key geographies: <strong>China, Taiwan, South Korea, Turkey, Brazil, India, Europe</strong> &mdash; where hundreds of small/medium NVR vendors are stuck with FFmpeg GPL or expensive licenses.
+ </p>
+
+ <div class="mt-28">
+ <h2>Development Timeline</h2>
+ <div class="timeline mt-20">
+ <div class="timeline-item done">
+ <div class="tl-label">H.265 Decoder</div>
+ <div class="tl-desc">Complete. 13,500 LOC.<br>Verified pixel-perfect.</div>
+ </div>
+ <div class="timeline-item done">
+ <div class="tl-label">AI Analytics</div>
+ <div class="tl-desc">Complete. nn2 YOLO engine.<br>1.5x faster than ONNX RT.</div>
+ </div>
+ <div class="timeline-item active">
+ <div class="tl-label">SDK Packaging</div>
+ <div class="tl-desc">In progress. API docs,<br>benchmarks, examples.</div>
+ </div>
+ <div class="timeline-item future">
+ <div class="tl-label">H.265 Encoder</div>
+ <div class="tl-desc">3&ndash;5 months.<br>Completes the pipeline.</div>
+ </div>
+ <div class="timeline-item future">
+ <div class="tl-label">Market Entry</div>
+ <div class="tl-desc">First SDK customers.<br>OEM outreach.</div>
+ </div>
+ </div>
+ </div>
+
+ <div class="highlight-box mt-28">
+ <h3>SUMMARY</h3>
+ <p>
+ We have built technology that <strong>thousands of companies need</strong> but almost no one has: a complete, independent video codec + AI analytics stack with zero dependencies and zero legal risk. The decoder is done and proven. The encoder will complete the picture. Together, they form the foundation of a scalable licensing business in a <strong>$60B market</strong>.
+ </p>
+ </div>
+ <span class="page-num">8</span>
+</div>
+
+</body>
+</html>
diff --git a/nn2/docs/nexuscodec_presentation_ru.html b/nn2/docs/nexuscodec_presentation_ru.html
new file mode 100644
index 0000000..a6f8c69
--- /dev/null
+++ b/nn2/docs/nexuscodec_presentation_ru.html
@@ -0,0 +1,938 @@
+<!DOCTYPE html>
+<html lang="ru">
+<head>
+<meta charset="UTF-8">
+<meta name="viewport" content="width=device-width, initial-scale=1.0">
+<title>NexusCodec — Полный видеостек H.265</title>
+<link rel="preconnect" href="https://fonts.googleapis.com">
+<link href="https://fonts.googleapis.com/css2?family=DM+Serif+Display&family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
+<style>
+ :root {
+ --blue: #1a56db;
+ --blue-light: #e8effc;
+ --blue-mid: #3b7ddd;
+ --dark: #111827;
+ --gray-800: #1f2937;
+ --gray-600: #4b5563;
+ --gray-400: #9ca3af;
+ --gray-200: #e5e7eb;
+ --gray-100: #f3f4f6;
+ --red: #dc2626;
+ --red-bg: #fef2f2;
+ --green: #059669;
+ --green-bg: #ecfdf5;
+ --amber: #d97706;
+ --amber-bg: #fffbeb;
+ }
+
+ * { margin: 0; padding: 0; box-sizing: border-box; }
+
+ @page {
+ size: A4;
+ margin: 0;
+ }
+
+ body {
+ font-family: 'DM Sans', sans-serif;
+ color: var(--dark);
+ background: #fff;
+ font-size: 11pt;
+ line-height: 1.55;
+ -webkit-print-color-adjust: exact;
+ print-color-adjust: exact;
+ }
+
+ .page {
+ width: 210mm;
+ min-height: 297mm;
+ padding: 28mm 24mm 20mm;
+ margin: 0 auto;
+ page-break-after: always;
+ position: relative;
+ overflow: hidden;
+ }
+
+ .page:last-child { page-break-after: avoid; }
+
+ @media screen {
+ .page {
+ margin: 20px auto;
+ box-shadow: 0 2px 20px rgba(0,0,0,0.08);
+ border: 1px solid var(--gray-200);
+ }
+ }
+
+ .page-num {
+ position: absolute;
+ bottom: 12mm;
+ right: 24mm;
+ font-size: 7.5pt;
+ color: var(--gray-400);
+ }
+
+ .page-footer {
+ position: absolute;
+ bottom: 12mm;
+ left: 24mm;
+ right: 60mm;
+ font-size: 7.5pt;
+ color: var(--gray-400);
+ border-top: 1px solid var(--gray-200);
+ padding-top: 6px;
+ }
+
+ h1 {
+ font-family: 'DM Serif Display', serif;
+ font-size: 32pt;
+ font-weight: 400;
+ line-height: 1.15;
+ color: var(--dark);
+ letter-spacing: -0.5px;
+ }
+
+ h2 {
+ font-family: 'DM Serif Display', serif;
+ font-size: 18pt;
+ font-weight: 400;
+ color: var(--dark);
+ margin-bottom: 16px;
+ padding-bottom: 8px;
+ border-bottom: 2px solid var(--blue);
+ display: inline-block;
+ }
+
+ h3 {
+ font-weight: 700;
+ color: var(--gray-800);
+ margin-bottom: 6px;
+ text-transform: uppercase;
+ letter-spacing: 0.8px;
+ font-size: 8.5pt;
+ }
+
+ p { margin-bottom: 10px; color: var(--gray-600); }
+ strong { color: var(--dark); font-weight: 600; }
+
+ /* Cover */
+ .cover {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ padding: 40mm 28mm;
+ }
+
+ .cover-badge {
+ display: inline-block;
+ background: var(--blue);
+ color: #fff;
+ font-size: 8pt;
+ font-weight: 700;
+ letter-spacing: 2px;
+ text-transform: uppercase;
+ padding: 6px 16px;
+ border-radius: 2px;
+ margin-bottom: 24px;
+ width: fit-content;
+ }
+
+ .cover h1 { font-size: 42pt; margin-bottom: 12px; }
+ .cover h1 span { color: var(--blue); }
+
+ .cover-subtitle {
+ font-size: 15pt;
+ color: var(--gray-600);
+ font-weight: 400;
+ margin-bottom: 48px;
+ max-width: 420px;
+ }
+
+ .cover-line {
+ width: 64px;
+ height: 4px;
+ background: var(--blue);
+ margin-bottom: 28px;
+ }
+
+ .cover-meta {
+ display: grid;
+ grid-template-columns: 1fr 1fr 1fr;
+ gap: 20px;
+ border-top: 1px solid var(--gray-200);
+ padding-top: 24px;
+ margin-top: auto;
+ }
+
+ .cover-meta-item {
+ font-size: 8.5pt;
+ color: var(--gray-400);
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ }
+
+ .cover-meta-item span {
+ display: block;
+ font-size: 11pt;
+ color: var(--dark);
+ font-weight: 600;
+ margin-top: 4px;
+ text-transform: none;
+ letter-spacing: 0;
+ }
+
+ .section-label {
+ font-size: 8pt;
+ font-weight: 700;
+ color: var(--blue);
+ text-transform: uppercase;
+ letter-spacing: 2px;
+ margin-bottom: 8px;
+ }
+
+ /* Cards */
+ .card-grid {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 14px;
+ margin: 16px 0;
+ }
+
+ .card {
+ background: var(--gray-100);
+ border-radius: 6px;
+ padding: 18px 20px;
+ border-left: 3px solid var(--blue);
+ }
+
+ .card.red { background: var(--red-bg); border-left-color: var(--red); }
+ .card.green { background: var(--green-bg); border-left-color: var(--green); }
+ .card.amber { background: var(--amber-bg); border-left-color: var(--amber); }
+
+ .card h4 {
+ font-size: 10pt;
+ font-weight: 700;
+ margin-bottom: 6px;
+ color: var(--dark);
+ }
+
+ .card p {
+ font-size: 9.5pt;
+ margin-bottom: 0;
+ line-height: 1.45;
+ }
+
+ /* Stats */
+ .stat-row {
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: 16px;
+ margin: 20px 0;
+ }
+
+ .stat-box {
+ text-align: center;
+ padding: 20px 12px;
+ background: var(--gray-100);
+ border-radius: 6px;
+ }
+
+ .stat-box .number {
+ font-family: 'DM Serif Display', serif;
+ font-size: 28pt;
+ color: var(--blue);
+ line-height: 1;
+ margin-bottom: 4px;
+ }
+
+ .stat-box .label {
+ font-size: 8.5pt;
+ color: var(--gray-600);
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ }
+
+ /* Tables */
+ table {
+ width: 100%;
+ border-collapse: collapse;
+ margin: 14px 0;
+ font-size: 9.5pt;
+ }
+
+ thead th {
+ background: var(--dark);
+ color: #fff;
+ padding: 10px 14px;
+ text-align: left;
+ font-weight: 600;
+ font-size: 8.5pt;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ }
+
+ thead th:first-child { border-radius: 4px 0 0 0; }
+ thead th:last-child { border-radius: 0 4px 0 0; }
+
+ tbody td {
+ padding: 10px 14px;
+ border-bottom: 1px solid var(--gray-200);
+ color: var(--gray-600);
+ }
+
+ tbody tr:last-child td { border-bottom: none; }
+ tbody tr:nth-child(even) { background: var(--gray-100); }
+
+ .badge {
+ display: inline-block;
+ padding: 2px 10px;
+ border-radius: 12px;
+ font-size: 8pt;
+ font-weight: 700;
+ }
+
+ .badge-red { background: #fee2e2; color: var(--red); }
+ .badge-green { background: #d1fae5; color: var(--green); }
+ .badge-amber { background: #fef3c7; color: var(--amber); }
+ .badge-blue { background: var(--blue-light); color: var(--blue); }
+
+ /* Pipeline */
+ .pipeline {
+ display: flex;
+ align-items: center;
+ gap: 0;
+ margin: 20px 0;
+ justify-content: center;
+ }
+
+ .pipeline-step {
+ background: var(--blue-light);
+ border: 2px solid var(--blue);
+ border-radius: 8px;
+ padding: 12px 14px;
+ text-align: center;
+ min-width: 95px;
+ }
+
+ .pipeline-step.highlight {
+ background: var(--blue);
+ color: #fff;
+ }
+
+ .pipeline-step .step-title {
+ font-weight: 700;
+ font-size: 9pt;
+ }
+
+ .pipeline-step .step-sub {
+ font-size: 7.5pt;
+ opacity: 0.75;
+ margin-top: 2px;
+ }
+
+ .pipeline-step.highlight .step-sub { color: rgba(255,255,255,0.8); }
+
+ .pipeline-arrow {
+ font-size: 16pt;
+ color: var(--blue);
+ padding: 0 5px;
+ font-weight: 700;
+ }
+
+ /* Revenue */
+ .revenue-grid {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 14px;
+ margin: 16px 0;
+ }
+
+ .revenue-card {
+ border: 2px solid var(--gray-200);
+ border-radius: 8px;
+ padding: 18px;
+ }
+
+ .revenue-card .revenue-amount {
+ font-family: 'DM Serif Display', serif;
+ font-size: 20pt;
+ color: var(--blue);
+ margin-bottom: 4px;
+ }
+
+ .revenue-card .revenue-source {
+ font-weight: 700;
+ font-size: 10pt;
+ color: var(--dark);
+ margin-bottom: 6px;
+ }
+
+ .revenue-card p { font-size: 9pt; margin: 0; }
+
+ /* Timeline */
+ .timeline {
+ display: flex;
+ gap: 0;
+ margin: 20px 0;
+ position: relative;
+ }
+
+ .timeline::before {
+ content: '';
+ position: absolute;
+ top: 20px;
+ left: 0;
+ right: 0;
+ height: 3px;
+ background: var(--gray-200);
+ }
+
+ .timeline-item {
+ flex: 1;
+ text-align: center;
+ position: relative;
+ padding-top: 36px;
+ }
+
+ .timeline-item::before {
+ content: '';
+ position: absolute;
+ top: 14px;
+ left: 50%;
+ transform: translateX(-50%);
+ width: 14px;
+ height: 14px;
+ border-radius: 50%;
+ background: var(--gray-400);
+ border: 3px solid #fff;
+ z-index: 1;
+ }
+
+ .timeline-item.done::before { background: var(--green); }
+ .timeline-item.active::before { background: var(--blue); box-shadow: 0 0 0 4px var(--blue-light); }
+
+ .timeline-item .tl-label {
+ font-weight: 700;
+ font-size: 9.5pt;
+ color: var(--dark);
+ margin-bottom: 4px;
+ }
+
+ .timeline-item .tl-desc {
+ font-size: 8.5pt;
+ color: var(--gray-600);
+ }
+
+ /* Utility */
+ .mt-12 { margin-top: 12px; }
+ .mt-20 { margin-top: 20px; }
+ .mt-28 { margin-top: 28px; }
+ .text-center { text-align: center; }
+ .text-small { font-size: 9pt; }
+
+ .highlight-box {
+ background: var(--blue);
+ color: #fff;
+ border-radius: 8px;
+ padding: 20px 24px;
+ margin: 16px 0;
+ }
+
+ .highlight-box h3 { color: rgba(255,255,255,0.7); }
+ .highlight-box p { color: rgba(255,255,255,0.9); }
+ .highlight-box strong { color: #fff; }
+
+ .two-col {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 24px;
+ }
+
+ .icon-num {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 28px;
+ height: 28px;
+ border-radius: 50%;
+ background: var(--blue);
+ color: #fff;
+ font-weight: 700;
+ font-size: 11pt;
+ margin-right: 10px;
+ flex-shrink: 0;
+ }
+
+ .step-item {
+ display: flex;
+ align-items: flex-start;
+ margin-bottom: 14px;
+ }
+
+ .step-item-content h4 {
+ font-size: 10.5pt;
+ font-weight: 700;
+ color: var(--dark);
+ margin-bottom: 2px;
+ }
+
+ .step-item-content p { font-size: 9pt; margin: 0; }
+
+ .check-list {
+ list-style: none;
+ padding: 0;
+ }
+
+ .check-list li {
+ padding: 6px 0;
+ padding-left: 24px;
+ position: relative;
+ font-size: 10pt;
+ color: var(--gray-600);
+ }
+
+ .check-list li::before {
+ content: "\2713";
+ position: absolute;
+ left: 0;
+ color: var(--green);
+ font-weight: 700;
+ }
+
+ @media print {
+ body { background: #fff; }
+ .page { box-shadow: none; border: none; margin: 0; }
+ }
+</style>
+</head>
+<body>
+
+<!-- ===== СТРАНИЦА 1: ОБЛОЖКА ===== -->
+<div class="page cover">
+ <div class="cover-badge">Конфиденциально</div>
+ <h1>NexusCodec</h1>
+ <h1 style="margin-top:-4px"><span>Полный видеостек H.265</span></h1>
+ <div class="cover-line"></div>
+ <div class="cover-subtitle">
+ Что даёт бизнесу собственный видеокодек и почему это важно
+ </div>
+ <div class="cover-meta">
+ <div class="cover-meta-item">
+ Статус
+ <span>Декодер готов, Энкодер в плане</span>
+ </div>
+ <div class="cover-meta-item">
+ Технология
+ <span>Чистый C, ноль зависимостей</span>
+ </div>
+ <div class="cover-meta-item">
+ Рынок
+ <span>$60 млрд видеонаблюдение</span>
+ </div>
+ </div>
+</div>
+
+<!-- ===== СТРАНИЦА 2: ПРОБЛЕМА ===== -->
+<div class="page">
+ <div class="section-label">Проблема</div>
+ <h2>У каждой NVR-компании есть проблема с кодеками</h2>
+
+ <p style="font-size:11pt; color:var(--dark); max-width:520px; margin-bottom:20px;">
+ Системам видеонаблюдения нужно <strong>декодировать</strong> видео с камер и <strong>кодировать</strong> его для записи. Каждая компания на рынке зависит от чужого ПО для кодеков &mdash; и все варианты болезненные.
+ </p>
+
+ <div class="card-grid">
+ <div class="card red">
+ <h4>FFmpeg &mdash; ловушка открытого кода</h4>
+ <p>Самая популярная видеобиблиотека в мире. Лицензия <strong>GPL</strong> &mdash; если используешь в продукте, обязан открыть <strong>весь свой код</strong>. Постоянный юридический риск.</p>
+ </div>
+ <div class="card red">
+ <h4>Коммерческие лицензии &mdash; дорого</h4>
+ <p>MainConcept, Intel Media SDK и другие берут <strong>$50 000&ndash;100 000 в год</strong> за лицензию на кодек. Малый и средний бизнес не может себе это позволить.</p>
+ </div>
+ <div class="card amber">
+ <h4>Патенты H.265 &mdash; тройной налог</h4>
+ <p>У H.265 <strong>три отдельных патентных пула</strong> (MPEG LA, HEVC Advance, Access Advance). До <strong>$1,50 за устройство</strong>. Три договора, три юридических процесса.</p>
+ </div>
+ <div class="card amber">
+ <h4>Привязка к железу</h4>
+ <p>Intel Quick Sync, NVIDIA NVDEC &mdash; привязаны к конкретным чипам. Не работают на ARM, AMD или бюджетном оборудовании. <strong>Никакой портативности.</strong></p>
+ </div>
+ </div>
+
+ <div class="highlight-box">
+ <h3>Итог</h3>
+ <p>
+ Тысячи NVR-компаний по всему миру в тупике: используй FFmpeg и <strong>рискуй судебным иском</strong>, плати $50K+ в год за лицензию, или трать 2&ndash;3 года и $500K+ на свою разработку. <strong>Хорошего варианта нет.</strong>
+ </p>
+ </div>
+ <div class="page-footer">NexusCodec &mdash; Бизнес-презентация</div>
+ <span class="page-num">2</span>
+</div>
+
+<!-- ===== СТРАНИЦА 3: НАШЕ РЕШЕНИЕ ===== -->
+<div class="page">
+ <div class="section-label">Наше решение</div>
+ <h2>Мы написали своё. С нуля.</h2>
+
+ <p style="font-size:11pt; color:var(--dark); max-width:520px; margin-bottom:20px;">
+ <strong>NexusCodec</strong> &mdash; это полный видеостек H.265, написанный на чистом C без единой внешней зависимости. Мы владеем каждой строчкой кода. Без GPL. Без лицензионных платежей. Без привязки к оборудованию.
+ </p>
+
+ <div class="two-col mt-20">
+ <div>
+ <div class="card green" style="min-height:180px">
+ <h4>NexusDecode &mdash; Декодер <span class="badge badge-green">ГОТОВ</span></h4>
+ <p style="margin-top:8px">Преобразует сжатое H.265/H.264 видео с камер в картинку на экране.</p>
+ <ul class="check-list" style="margin-top:10px">
+ <li>184 КБ бинарник (FFmpeg: 30+ МБ)</li>
+ <li>В 46 раз быстрее FFmpeg на CPU</li>
+ <li>6 300 кадров/сек при 640x480</li>
+ <li>Попиксельно точный (проверено)</li>
+ <li>Работает на Intel, AMD и ARM</li>
+ </ul>
+ </div>
+ </div>
+ <div>
+ <div class="card" style="border-left-color:var(--blue); min-height:180px">
+ <h4>NexusEncode &mdash; Энкодер <span class="badge badge-blue">В ПЛАНЕ</span></h4>
+ <p style="margin-top:8px">Сжимает видео для записи, экспорта, ретрансляции и наложения аналитики.</p>
+ <ul class="check-list" style="margin-top:10px">
+ <li>Запись потока с камер на диск</li>
+ <li>Экспорт клипов-улик (MP4)</li>
+ <li>Наложение рамок детекции на видео</li>
+ <li>Ретрансляция в пониженном качестве</li>
+ <li>Срок разработки: 3&ndash;5 месяцев</li>
+ </ul>
+ </div>
+ </div>
+ </div>
+
+ <div class="stat-row mt-20">
+ <div class="stat-box">
+ <div class="number">184<span style="font-size:14pt">КБ</span></div>
+ <div class="label">Размер бинарника</div>
+ </div>
+ <div class="stat-box">
+ <div class="number">46<span style="font-size:14pt">x</span></div>
+ <div class="label">Быстрее FFmpeg</div>
+ </div>
+ <div class="stat-box">
+ <div class="number">0</div>
+ <div class="label">Зависимостей</div>
+ </div>
+ </div>
+ <div class="page-footer">NexusCodec &mdash; Бизнес-презентация</div>
+ <span class="page-num">3</span>
+</div>
+
+<!-- ===== СТРАНИЦА 4: ПРОСТЫМ ЯЗЫКОМ ===== -->
+<div class="page">
+ <div class="section-label">Простым языком</div>
+ <h2>Что делают декодер и энкодер</h2>
+
+ <div class="two-col mt-20">
+ <div>
+ <h3 style="color:var(--green);">Декодер = Камера &rarr; Экран</h3>
+ <p style="font-size:10.5pt; margin-bottom:14px;">
+ IP-камеры отправляют видео в сжатом виде (H.265). <strong>Декодер</strong> превращает эти данные обратно в картинку, которую можно увидеть на экране.
+ </p>
+ <div class="card green" style="padding:14px 18px">
+ <p style="font-size:9.5pt; margin:0; line-height:1.6;">
+ <strong>Без декодера:</strong> NVR получает данные с камер, но не может ничего показать. Это как получить письмо на иностранном языке без переводчика.<br><br>
+ <strong>Каждая система видеонаблюдения обязана иметь декодер.</strong> Это не опция.
+ </p>
+ </div>
+ </div>
+ <div>
+ <h3 style="color:var(--blue);">Энкодер = Экран &rarr; Запись</h3>
+ <p style="font-size:10.5pt; margin-bottom:14px;">
+ <strong>Энкодер</strong> берёт видео и сжимает его для хранения на диске или передачи по сети.
+ </p>
+ <div class="card" style="border-left-color:var(--blue); padding:14px 18px">
+ <p style="font-size:9.5pt; margin:0; line-height:1.6;">
+ <strong>Без энкодера невозможно:</strong><br>
+ &bull;&ensp;Записывать видео на диск<br>
+ &bull;&ensp;Экспортировать клипы для полиции/суда<br>
+ &bull;&ensp;Накладывать аналитику (рамки объектов)<br>
+ &bull;&ensp;Ретранслировать на мобильные устройства<br><br>
+ <strong>Энкодер замыкает весь цикл обработки видео.</strong>
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <div class="mt-28">
+ <h3>Полный цикл обработки</h3>
+ <div class="pipeline">
+ <div class="pipeline-step">
+ <div class="step-title">IP-камера</div>
+ <div class="step-sub">Поток H.265</div>
+ </div>
+ <div class="pipeline-arrow">&rarr;</div>
+ <div class="pipeline-step highlight">
+ <div class="step-title">ДЕКОДЕР</div>
+ <div class="step-sub">NexusDecode</div>
+ </div>
+ <div class="pipeline-arrow">&rarr;</div>
+ <div class="pipeline-step highlight" style="background:var(--blue-mid)">
+ <div class="step-title">АНАЛИТИКА</div>
+ <div class="step-sub">nn2 AI-движок</div>
+ </div>
+ <div class="pipeline-arrow">&rarr;</div>
+ <div class="pipeline-step highlight">
+ <div class="step-title">ЭНКОДЕР</div>
+ <div class="step-sub">NexusEncode</div>
+ </div>
+ <div class="pipeline-arrow">&rarr;</div>
+ <div class="pipeline-step">
+ <div class="step-title">Хранилище</div>
+ <div class="step-sub">Запись / Экспорт</div>
+ </div>
+ </div>
+ <p class="text-center text-small" style="color:var(--gray-400); margin-top:8px;">
+ Все синие блоки &mdash; наша собственная технология. Нигде нет чужого кода.
+ </p>
+ </div>
+ <div class="page-footer">NexusCodec &mdash; Бизнес-презентация</div>
+ <span class="page-num">4</span>
+</div>
+
+<!-- ===== СТРАНИЦА 5: ПОЧЕМУ ОБА ВМЕСТЕ ===== -->
+<div class="page">
+ <div class="section-label">Стратегическая ценность</div>
+ <h2>Почему декодер + энкодер вместе меняют всё</h2>
+
+ <div class="mt-12">
+ <div class="step-item">
+ <span class="icon-num">1</span>
+ <div class="step-item-content">
+ <h4>Полная независимость от FFmpeg</h4>
+ <p>Нигде в продукте нет GPL-кода. Нет юридического риска. Не нужно открывать исходники. Полная свобода коммерческого лицензирования.</p>
+ </div>
+ </div>
+ <div class="step-item">
+ <span class="icon-num">2</span>
+ <div class="step-item-content">
+ <h4>Ноль лицензионных платежей</h4>
+ <p>Не платим $50&ndash;100K в год MainConcept или Intel. Код наш &mdash; расходы под нашим контролем. Каждая продажа &mdash; чистая маржа.</p>
+ </div>
+ </div>
+ <div class="step-item">
+ <span class="icon-num">3</span>
+ <div class="step-item-content">
+ <h4>Работает на любом оборудовании</h4>
+ <p>Чистый C с SIMD-оптимизацией. Работает на Intel, AMD, ARM (Raspberry Pi, Rockchip). Не привязан ни к одному производителю чипов.</p>
+ </div>
+ </div>
+ <div class="step-item">
+ <span class="icon-num">4</span>
+ <div class="step-item-content">
+ <h4>Встроенная AI-аналитика</h4>
+ <p>Наш движок nn2 (в 1,5 раза быстрее ONNX Runtime) встраивается прямо в кодек-pipeline. <strong>Декодирование &rarr; Детекция &rarr; Кодирование в одном бинарнике.</strong> Ни один конкурент такого не предлагает.</p>
+ </div>
+ </div>
+ <div class="step-item">
+ <span class="icon-num">5</span>
+ <div class="step-item-content">
+ <h4>Можем продавать другим компаниям</h4>
+ <p>Тысячам NVR-компаний нужно именно это. Мы можем лицензировать NexusCodec как SDK и получать регулярный доход.</p>
+ </div>
+ </div>
+ </div>
+
+ <div class="highlight-box mt-20">
+ <h3>Ключевой вывод</h3>
+ <p>
+ Декодер отдельно &mdash; полезен. Энкодер отдельно &mdash; полезен. <strong>Оба вместе с AI-аналитикой &mdash; это платформа:</strong> фундамент для собственной линейки NVR-продуктов и лицензионного бизнеса, нацеленного на каждую компанию видеонаблюдения в мире.
+ </p>
+ </div>
+ <div class="page-footer">NexusCodec &mdash; Бизнес-презентация</div>
+ <span class="page-num">5</span>
+</div>
+
+<!-- ===== СТРАНИЦА 6: КОНКУРЕНТЫ ===== -->
+<div class="page">
+ <div class="section-label">Конкурентный анализ</div>
+ <h2>Сравнение с рынком</h2>
+
+ <table class="mt-12">
+ <thead>
+ <tr>
+ <th style="width:17%">Решение</th>
+ <th style="width:15%">Лицензия</th>
+ <th style="width:14%">Стоимость</th>
+ <th style="width:14%">Железо</th>
+ <th style="width:14%">AI-аналитика</th>
+ <th style="width:26%">Риск</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td><strong>FFmpeg</strong></td>
+ <td><span class="badge badge-red">GPL</span></td>
+ <td>Бесплатно</td>
+ <td>Любой CPU</td>
+ <td>Нет</td>
+ <td>Обязаны открыть код или суд</td>
+ </tr>
+ <tr>
+ <td><strong>MainConcept</strong></td>
+ <td>Коммерческая</td>
+ <td><strong>$50&ndash;100K/год</strong></td>
+ <td>Только x86</td>
+ <td>Нет</td>
+ <td>Дорого, зависимость от вендора</td>
+ </tr>
+ <tr>
+ <td><strong>Intel Media SDK</strong></td>
+ <td>Бесплатная</td>
+ <td>Бесплатно</td>
+ <td><span class="badge badge-amber">Только Intel</span></td>
+ <td>Нет</td>
+ <td>Привязка к чипам Intel</td>
+ </tr>
+ <tr>
+ <td><strong>NVIDIA NVDEC</strong></td>
+ <td>Бесплатная</td>
+ <td>Цена GPU</td>
+ <td><span class="badge badge-amber">Только GPU</span></td>
+ <td>Отдельно</td>
+ <td>GPU за $500+ на каждый сервер</td>
+ </tr>
+ <tr style="background:var(--blue-light) !important">
+ <td><strong style="color:var(--blue)">NexusCodec</strong></td>
+ <td><span class="badge badge-green">Собственная</span></td>
+ <td><strong>Наш код</strong></td>
+ <td><span class="badge badge-green">Любой CPU</span></td>
+ <td><span class="badge badge-green">Встроена</span></td>
+ <td style="color:var(--green); font-weight:600;">Ноль рисков, ноль зависимостей</td>
+ </tr>
+ </tbody>
+ </table>
+
+ <div class="mt-28">
+ <h3>Наши уникальные преимущества</h3>
+ <div class="card-grid" style="grid-template-columns: 1fr 1fr 1fr; gap:12px;">
+ <div class="card green" style="text-align:center; padding:20px 12px;">
+ <div style="font-family:'DM Serif Display',serif; font-size:22pt; color:var(--green);">418 КБ</div>
+ <p style="font-size:8.5pt; margin:4px 0 0;">Весь бинарник<br>(H.264 + H.265)</p>
+ </div>
+ <div class="card green" style="text-align:center; padding:20px 12px;">
+ <div style="font-family:'DM Serif Display',serif; font-size:22pt; color:var(--green);">$0</div>
+ <p style="font-size:8.5pt; margin:4px 0 0;">Лицензионных<br>платежей третьим лицам</p>
+ </div>
+ <div class="card green" style="text-align:center; padding:20px 12px;">
+ <div style="font-family:'DM Serif Display',serif; font-size:22pt; color:var(--green);">3</div>
+ <p style="font-size:8.5pt; margin:4px 0 0;">Продукта в одном стеке<br>(Декодер + AI + Энкодер)</p>
+ </div>
+ </div>
+ </div>
+ <div class="page-footer">NexusCodec &mdash; Бизнес-презентация</div>
+ <span class="page-num">6</span>
+</div>
+
+<!-- ===== СТРАНИЦА 7: ДОХОД ===== -->
+<div class="page">
+ <div class="section-label">Модель дохода</div>
+ <h2>Как мы зарабатываем</h2>
+
+ <div class="revenue-grid mt-20">
+ <div class="revenue-card">
+ <div class="revenue-amount">$15&ndash;50K</div>
+ <div class="revenue-source">SDK-лицензия (клиент/год)</div>
+ <p>Лицензируем NexusCodec NVR-компаниям. Они встраивают наш декодер/энкодер в свой продукт. Ежегодная плата.</p>
+ <p class="mt-12"><strong>Цель:</strong> 10&ndash;20 клиентов = $150K&ndash;$1M/год</p>
+ </div>
+ <div class="revenue-card">
+ <div class="revenue-amount">$100&ndash;500K</div>
+ <div class="revenue-source">OEM-сделки с чипмейкерами</div>
+ <p>Лицензия производителям чипов (Ambarella, Rockchip, Novatek) как референсный программный декодер для их SoC.</p>
+ <p class="mt-12"><strong>Цель:</strong> 2&ndash;3 сделки = $200K&ndash;$1,5M</p>
+ </div>
+ <div class="revenue-card">
+ <div class="revenue-amount">$5&ndash;10</div>
+ <div class="revenue-source">SaaS за камеру/месяц</div>
+ <p>Собственный NVR-продукт: облачное управление, edge-установка. Полный стек: декодирование + AI-аналитика + запись + веб-панель.</p>
+ <p class="mt-12"><strong>Цель:</strong> 500 камер = $30&ndash;60K в месяц</p>
+ </div>
+ <div class="revenue-card">
+ <div class="revenue-amount">$30&ndash;80K</div>
+ <div class="revenue-source">Модуль аналитики</div>
+ <p>Продаём AI-движок nn2 отдельно: детекция людей, подсчёт, контроль зон. Работает на CPU, GPU не нужен.</p>
+ <p class="mt-12"><strong>Цель:</strong> В составе SDK-пакета</p>
+ </div>
+ </div>
+
+ <div class="highlight-box mt-12">
+ <h3>Прогноз выручки на первый год</h3>
+ <p>
+ Консервативная оценка с фокусом на SDK-лицензировании:<br>
+ <strong>5 SDK-клиентов &times; $25K средний чек = $125K</strong> + 1 OEM-сделка $150K = <strong>$275K в первый год</strong><br>
+ Рост до <strong>$500K&ndash;$1M</strong> на второй год по мере готовности энкодера и расширения клиентской базы.
+ </p>
+ </div>
+ <div class="page-footer">NexusCodec &mdash; Бизнес-презентация</div>
+ <span class="page-num">7</span>
+</div>
+
+<!-- ===== СТРАНИЦА 8: РЫНОК + ПЛАН ===== -->
+<div class="page">
+ <div class="section-label">Рынок и план</div>
+ <h2>Рыночная возможность</h2>
+
+ <div class="stat-row">
+ <div class="stat-box">
+ <div class="number">$60<span style="font-size:14pt"> млрд</span></div>
+ <div class="label">Рынок видеонаблюдения</div>
+ </div>
+ <div class="stat-box">
+ <div class="number">$2<span style="font-size:14pt"> млрд</span></div>
+ <div class="label">Сегмент кодек-лицензий</div>
+ </div>
+ <div class="stat-box">
+ <div class="number">1000<span style="font-size:14pt">+</span></div>
+ <div class="label">NVR-компаний в мире</div>
+ </div>
+ </div>
+
+ <p class="mt-12" style="font-size:10.5pt;">
+ Каждая компания, разрабатывающая NVR-софт, умные камеры или видеоаналитику, &mdash; потенциальный клиент. Ключевые рынки: <strong>Китай, Тайвань, Южная Корея, Турция, Бразилия, Индия, Европа</strong> &mdash; где сотни малых и средних NVR-вендоров используют FFmpeg GPL или дорогие лицензии.
+ </p>
+
+ <div class="mt-28">
+ <h2>Дорожная карта</h2>
+ <div class="timeline mt-20">
+ <div class="timeline-item done">
+ <div class="tl-label">Декодер H.265</div>
+ <div class="tl-desc">Готов. 13 500 строк C.<br>Проверена попиксельная точность.</div>
+ </div>
+ <div class="timeline-item done">
+ <div class="tl-label">AI-аналитика</div>
+ <div class="tl-desc">Готов. Движок nn2 YOLO.<br>В 1,5 раза быстрее ONNX RT.</div>
+ </div>
+ <div class="timeline-item active">
+ <div class="tl-label">Упаковка SDK</div>
+ <div class="tl-desc">В процессе. API-документация,<br>бенчмарки, примеры.</div>
+ </div>
+ <div class="timeline-item future">
+ <div class="tl-label">Энкодер H.265</div>
+ <div class="tl-desc">3&ndash;5 месяцев.<br>Замыкает pipeline.</div>
+ </div>
+ <div class="timeline-item future">
+ <div class="tl-label">Выход на рынок</div>
+ <div class="tl-desc">Первые SDK-клиенты.<br>OEM-переговоры.</div>
+ </div>
+ </div>
+ </div>
+
+ <div class="highlight-box mt-28">
+ <h3>Резюме</h3>
+ <p>
+ Мы создали технологию, которая <strong>нужна тысячам компаний</strong>, но которой почти ни у кого нет: полностью независимый видеокодек + AI-аналитика без единой зависимости и без юридических рисков. Декодер готов и проверен. Энкодер завершит картину. Вместе они создают фундамент масштабируемого лицензионного бизнеса на <strong>рынке в $60 млрд</strong>.
+ </p>
+ </div>
+ <div class="page-footer">NexusCodec &mdash; Бизнес-презентация</div>
+ <span class="page-num">8</span>
+</div>
+
+</body>
+</html>
diff --git a/nn2/include/nn2.h b/nn2/include/nn2.h
new file mode 100644
index 0000000..915b166
--- /dev/null
+++ b/nn2/include/nn2.h
@@ -0,0 +1,50 @@
+/*
+ * nn2 — YOLO inference engine. Pure C, zero dependencies.
+ * AVX2/AVX-512 SIMD, lock-free threading, fused Conv+BN+SiLU.
+ *
+ * Usage:
+ * NN2* ctx = nn2_init("yolov8n.bin", 0);
+ * NN2Det dets[300];
+ * int n = nn2_detect(ctx, rgb, w, h, dets, 300);
+ * nn2_free(ctx);
+ */
+
+#ifndef NN2_H
+#define NN2_H
+
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct NN2 NN2;
+
+typedef struct {
+ float x1, y1, x2, y2; /* bbox in input pixel coords */
+ float score; /* confidence */
+ int cls; /* class index */
+} NN2Det;
+
+/* Init engine. n_threads=0 → auto-detect. */
+NN2* nn2_init(const char* weights_path, int n_threads);
+
+/* Detect objects. rgb_hwc: width*height*3 uint8, HWC, BGR or RGB.
+ * Returns number of detections (0..max_det). */
+int nn2_detect(NN2* ctx, const uint8_t* rgb_hwc, int width, int height,
+ NN2Det* out, int max_det);
+
+void nn2_free(NN2* ctx);
+
+/* Config */
+void nn2_set_conf_threshold(NN2* ctx, float threshold); /* default 0.25 */
+void nn2_set_nms_threshold(NN2* ctx, float threshold); /* default 0.45 */
+void nn2_set_input_size(NN2* ctx, int size); /* 320 or 640, default from weights */
+
+const char* nn2_version(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* NN2_H */
diff --git a/nn2/include/nn2_antispoof.h b/nn2/include/nn2_antispoof.h
new file mode 100644
index 0000000..9830d0b
--- /dev/null
+++ b/nn2/include/nn2_antispoof.h
@@ -0,0 +1,58 @@
+/*
+ * nn2_antispoof.h — Public API for the MiniFASNet anti-spoof port.
+ *
+ * Provides a 2-model ensemble (MiniFASNetV2 @ scale 2.7 + MiniFASNetV1SE @ scale 4.0)
+ * that mirrors Silent-Face-Anti-Spoofing's predictor. Input is an RGB face crop
+ * of arbitrary size; the API crops with the given face bbox + scale to 80×80
+ * BGR [0,255] internally (matching ToTensor() that has /255 commented out in
+ * the original repo).
+ *
+ * Class output (3-way softmax):
+ * prob[0] = P(spoof_type_a)
+ * prob[1] = P(LIVE)
+ * prob[2] = P(spoof_type_b)
+ */
+
+#ifndef NN2_ANTISPOOF_H
+#define NN2_ANTISPOOF_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct AntiSpoofModel AntiSpoofModel;
+
+/* Model variants we support. */
+typedef enum {
+ NN2_AS_V2 = 0, /* MiniFASNetV2 — no SE, 3-class */
+ NN2_AS_V1SE = 1, /* MiniFASNetV1SE — SE blocks, 3-class */
+} AntiSpoofVariant;
+
+/* Load weights from .bin (produced by tools/export_minifasnet.py).
+ * Returns NULL on failure. n_threads<=0 → auto. */
+AntiSpoofModel* nn2_antispoof_load(const char* path, AntiSpoofVariant variant, int n_threads);
+
+void nn2_antispoof_free(AntiSpoofModel* m);
+
+/* Run inference on an already-prepared 80×80 BGR uint8 image (HWC),
+ * in [0,255] range. Writes 3 probabilities (sum=1) to prob_out[3].
+ * Returns 0 on success.
+ *
+ * Note: caller is responsible for the crop matching MiniFASNet's expected
+ * framing — bbox center, dimensions = (bbox_w * scale, bbox_h * scale)
+ * clamped to image bounds, then bilinear resize to 80×80. */
+int nn2_antispoof_predict(AntiSpoofModel* m, const unsigned char* bgr_80x80,
+ float prob_out[3]);
+
+/* Convenience: take RGB HWC uint8 image of arbitrary size + bbox [x,y,w,h],
+ * crop with model's expected scale, then predict. */
+int nn2_antispoof_predict_rgb(AntiSpoofModel* m, const unsigned char* rgb,
+ int src_w, int src_h,
+ int bbox_x, int bbox_y, int bbox_w, int bbox_h,
+ float scale, float prob_out[3]);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* NN2_ANTISPOOF_H */
diff --git a/nn2/include/nn2_count.h b/nn2/include/nn2_count.h
new file mode 100644
index 0000000..a02f2c2
--- /dev/null
+++ b/nn2/include/nn2_count.h
@@ -0,0 +1,74 @@
+/*
+ * nn2_count.h — Line-crossing people counter.
+ *
+ * Counts objects crossing a virtual line. Tracks centroid of each
+ * tracked object and increments in/out counters when it crosses.
+ *
+ * Usage:
+ * NN2Counter* cnt = nn2_counter_create(320, 240, 0, 240, 640, 240);
+ * // horizontal line at y=240 from x=0 to x=640
+ * nn2_counter_update(cnt, tracks, n_tracks);
+ * printf("In: %d, Out: %d\n", cnt->count_in, cnt->count_out);
+ */
+
+#ifndef NN2_COUNT_H
+#define NN2_COUNT_H
+
+#include "nn2_track.h"
+#include <stdlib.h>
+
+#define NN2_COUNT_MAX_IDS 1024
+
+typedef struct {
+ /* Line definition: (x1,y1) to (x2,y2) */
+ float lx1, ly1, lx2, ly2;
+
+ /* Counters */
+ int count_in; /* crossed from positive → negative side */
+ int count_out; /* crossed from negative → positive side */
+
+ /* Track state: last side for each track ID */
+ int8_t last_side[NN2_COUNT_MAX_IDS]; /* 0=unknown, 1=positive, -1=negative */
+} NN2Counter;
+
+static inline NN2Counter* nn2_counter_create(float x1, float y1, float x2, float y2)
+{
+ NN2Counter* c = (NN2Counter*)calloc(1, sizeof(NN2Counter));
+ c->lx1 = x1; c->ly1 = y1; c->lx2 = x2; c->ly2 = y2;
+ return c;
+}
+
+/* Determine which side of the line a point is on.
+ * Returns +1 or -1 based on cross product sign. */
+static inline int nn2_counter_side(const NN2Counter* c, float px, float py)
+{
+ float cross = (c->lx2 - c->lx1) * (py - c->ly1)
+ - (c->ly2 - c->ly1) * (px - c->lx1);
+ return (cross > 0) ? 1 : -1;
+}
+
+/* Update counter with tracked objects */
+static inline void nn2_counter_update(NN2Counter* c, const NN2Track* tracks, int n)
+{
+ for (int i = 0; i < n; i++) {
+ int id = tracks[i].id;
+ if (id <= 0 || id >= NN2_COUNT_MAX_IDS) continue;
+
+ /* Centroid */
+ float cx = (tracks[i].x1 + tracks[i].x2) * 0.5f;
+ float cy = (tracks[i].y1 + tracks[i].y2) * 0.5f;
+ int side = nn2_counter_side(c, cx, cy);
+
+ int8_t prev = c->last_side[id];
+ if (prev != 0 && prev != side) {
+ /* Crossed! */
+ if (prev == 1 && side == -1) c->count_in++;
+ else if (prev == -1 && side == 1) c->count_out++;
+ }
+ c->last_side[id] = (int8_t)side;
+ }
+}
+
+static inline void nn2_counter_free(NN2Counter* c) { free(c); }
+
+#endif /* NN2_COUNT_H */
diff --git a/nn2/include/nn2_json.h b/nn2/include/nn2_json.h
new file mode 100644
index 0000000..3c820f3
--- /dev/null
+++ b/nn2/include/nn2_json.h
@@ -0,0 +1,54 @@
+/*
+ * nn2_json.h — Minimal JSON serialization for detection events.
+ * No dependencies. Writes to a buffer or FILE*.
+ */
+
+#ifndef NN2_JSON_H
+#define NN2_JSON_H
+
+#include "nn2.h"
+#include "nn2_nvr.h"
+#include <stdio.h>
+
+static const char* nn2_coco_names[] = {
+ "person","bicycle","car","motorcycle","airplane","bus","train","truck","boat",
+ "traffic light","fire hydrant","stop sign","parking meter","bench","bird","cat",
+ "dog","horse","sheep","cow","elephant","bear","zebra","giraffe","backpack",
+ "umbrella","handbag","tie","suitcase","frisbee","skis","snowboard","sports ball",
+ "kite","baseball bat","baseball glove","skateboard","surfboard","tennis racket",
+ "bottle","wine glass","cup","fork","knife","spoon","bowl","banana","apple",
+ "sandwich","orange","broccoli","carrot","hot dog","pizza","donut","cake","chair",
+ "couch","potted plant","bed","dining table","toilet","tv","laptop","mouse",
+ "remote","keyboard","cell phone","microwave","oven","toaster","sink",
+ "refrigerator","book","clock","vase","scissors","teddy bear","hair drier","toothbrush"
+};
+
+/* Write detection event as JSON to buffer. Returns bytes written. */
+static inline int nn2_event_to_json(const NN2NVREvent* e, char* buf, int bufsize)
+{
+ int n = snprintf(buf, bufsize,
+ "{\"camera\":%d,\"timestamp\":%.1f,\"inference_ms\":%.1f,\"detections\":[",
+ e->cam_id, e->timestamp_ms, e->inference_ms);
+ for (int i = 0; i < e->det_count && n < bufsize - 100; i++) {
+ const char* name = (e->dets[i].cls >= 0 && e->dets[i].cls < 80)
+ ? nn2_coco_names[e->dets[i].cls] : "unknown";
+ n += snprintf(buf + n, bufsize - n,
+ "%s{\"class\":\"%s\",\"class_id\":%d,\"confidence\":%.3f,"
+ "\"bbox\":[%.1f,%.1f,%.1f,%.1f]}",
+ i > 0 ? "," : "", name, e->dets[i].cls, e->dets[i].score,
+ e->dets[i].x1, e->dets[i].y1, e->dets[i].x2, e->dets[i].y2);
+ }
+ n += snprintf(buf + n, bufsize - n, "]}");
+ return n;
+}
+
+/* Write detections as JSON to FILE* */
+static inline void nn2_event_to_file(const NN2NVREvent* e, FILE* f)
+{
+ char buf[4096];
+ nn2_event_to_json(e, buf, sizeof(buf));
+ fprintf(f, "%s\n", buf);
+ fflush(f);
+}
+
+#endif /* NN2_JSON_H */
diff --git a/nn2/include/nn2_nvr.h b/nn2/include/nn2_nvr.h
new file mode 100644
index 0000000..353566e
--- /dev/null
+++ b/nn2/include/nn2_nvr.h
@@ -0,0 +1,68 @@
+/*
+ * nn2_nvr.h — Multi-camera NVR pipeline.
+ *
+ * Manages N camera feeds, motion-gated detection, event callbacks.
+ * Single nn2 model shared across all cameras.
+ *
+ * Usage:
+ * NN2NVR* nvr = nn2_nvr_create("weights/yolov8n_320.bin", 6);
+ * nn2_nvr_add_camera(nvr, 0, "Camera-1");
+ * nn2_nvr_add_camera(nvr, 1, "Camera-2");
+ * nn2_nvr_set_callback(nvr, on_detection);
+ * // In frame loop:
+ * nn2_nvr_push_frame(nvr, cam_id, rgb, w, h);
+ * nn2_nvr_free(nvr);
+ */
+
+#ifndef NN2_NVR_H
+#define NN2_NVR_H
+
+#include "nn2.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define NN2_NVR_MAX_CAMERAS 64
+
+typedef struct {
+ int cam_id;
+ int det_count;
+ NN2Det dets[50];
+ double timestamp_ms;
+ double inference_ms;
+} NN2NVREvent;
+
+typedef void (*nn2_nvr_callback)(const NN2NVREvent* event, void* userdata);
+
+typedef struct NN2NVR NN2NVR;
+
+/* Create NVR pipeline with shared model */
+NN2NVR* nn2_nvr_create(const char* weights_path, int n_threads);
+
+/* Add a camera feed */
+int nn2_nvr_add_camera(NN2NVR* nvr, int cam_id, const char* name);
+
+/* Set detection callback */
+void nn2_nvr_set_callback(NN2NVR* nvr, nn2_nvr_callback cb, void* userdata);
+
+/* Configure */
+void nn2_nvr_set_skip_frames(NN2NVR* nvr, int skip); /* default 5 */
+void nn2_nvr_set_motion_threshold(NN2NVR* nvr, float thresh); /* 0=disabled */
+void nn2_nvr_set_conf_threshold(NN2NVR* nvr, float thresh);
+
+/* Push a frame from camera. Returns 1 if detection was run, 0 if skipped. */
+int nn2_nvr_push_frame(NN2NVR* nvr, int cam_id,
+ const uint8_t* rgb_hwc, int width, int height);
+
+/* Get stats */
+void nn2_nvr_stats(const NN2NVR* nvr, int* total_frames, int* total_detections,
+ double* avg_inference_ms);
+
+void nn2_nvr_free(NN2NVR* nvr);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* NN2_NVR_H */
diff --git a/nn2/include/nn2_track.h b/nn2/include/nn2_track.h
new file mode 100644
index 0000000..cfe4b5b
--- /dev/null
+++ b/nn2/include/nn2_track.h
@@ -0,0 +1,56 @@
+/*
+ * nn2_track.h — Simple object tracker (SORT algorithm).
+ *
+ * Kalman filter for motion prediction + IoU matching via Hungarian algorithm.
+ * Assigns persistent IDs to detections across frames.
+ *
+ * Usage:
+ * NN2Tracker* tr = nn2_tracker_create(30, 3); // max_age=30, min_hits=3
+ * // Each frame:
+ * NN2Track tracks[100];
+ * int n = nn2_tracker_update(tr, dets, n_dets, tracks, 100);
+ * for (int i = 0; i < n; i++)
+ * printf("ID %d: %s at (%.0f,%.0f)\n", tracks[i].id, ...);
+ * nn2_tracker_free(tr);
+ */
+
+#ifndef NN2_TRACK_H
+#define NN2_TRACK_H
+
+#include "nn2.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct {
+ int id; /* persistent track ID */
+ int cls; /* class from last detection */
+ float score; /* confidence from last detection */
+ float x1, y1, x2, y2; /* predicted bbox */
+ int age; /* frames since creation */
+ int hits; /* total matched detections */
+ int time_since_update; /* frames since last matched */
+} NN2Track;
+
+typedef struct NN2Tracker NN2Tracker;
+
+/* Create tracker.
+ * max_age: delete track after this many frames without match.
+ * min_hits: only output tracks with >= this many hits. */
+NN2Tracker* nn2_tracker_create(int max_age, int min_hits);
+
+/* Update tracker with new detections. Returns active tracks. */
+int nn2_tracker_update(NN2Tracker* tr, const NN2Det* dets, int n_dets,
+ NN2Track* out_tracks, int max_tracks);
+
+/* Get total unique IDs assigned so far */
+int nn2_tracker_total_ids(const NN2Tracker* tr);
+
+void nn2_tracker_free(NN2Tracker* tr);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* NN2_TRACK_H */
diff --git a/nn2/include/nn2_zone.h b/nn2/include/nn2_zone.h
new file mode 100644
index 0000000..baacf41
--- /dev/null
+++ b/nn2/include/nn2_zone.h
@@ -0,0 +1,160 @@
+/*
+ * nn2_zone.h — Zone intrusion detection.
+ *
+ * Define polygonal zones on camera view. When a tracked object's
+ * centroid enters a zone, trigger an alert. Supports:
+ * - Multiple zones per camera
+ * - Per-zone class filters (e.g., only "person" triggers)
+ * - Dwell time (alert only after N frames inside zone)
+ * - Entry/exit events
+ *
+ * Usage:
+ * NN2Zone* z = nn2_zone_create("Restricted Area", 4,
+ * (float[]){100,100, 400,100, 400,400, 100,400});
+ * nn2_zone_set_classes(z, 1, (int[]){0}); // only person (class 0)
+ * nn2_zone_set_dwell(z, 3); // alert after 3 frames inside
+ * // Per frame:
+ * NN2ZoneEvent events[10];
+ * int n = nn2_zone_check(z, tracks, n_tracks, events, 10);
+ */
+
+#ifndef NN2_ZONE_H
+#define NN2_ZONE_H
+
+#include "nn2_track.h"
+#include <stdlib.h>
+#include <string.h>
+
+#define NN2_ZONE_MAX_POINTS 16
+#define NN2_ZONE_MAX_IDS 512
+
+typedef enum {
+ NN2_ZONE_ENTER = 1,
+ NN2_ZONE_INSIDE = 2,
+ NN2_ZONE_EXIT = 3
+} NN2ZoneEventType;
+
+typedef struct {
+ int track_id;
+ int cls;
+ NN2ZoneEventType type;
+ int dwell_frames; /* how many frames inside */
+ float cx, cy; /* centroid position */
+} NN2ZoneEvent;
+
+typedef struct {
+ char name[64];
+ float poly[NN2_ZONE_MAX_POINTS * 2]; /* x,y pairs */
+ int n_points;
+ int filter_classes[80]; /* 1 = trigger on this class */
+ int n_filter_classes; /* 0 = all classes trigger */
+ int dwell_threshold; /* frames before alert (0 = immediate) */
+
+ /* Track state */
+ int8_t inside[NN2_ZONE_MAX_IDS]; /* 0=outside, 1=inside */
+ int16_t dwell_count[NN2_ZONE_MAX_IDS]; /* frames inside */
+ int total_intrusions;
+} NN2Zone;
+
+/* Point-in-polygon test (ray casting algorithm) */
+static inline int nn2_point_in_poly(float px, float py,
+ const float* poly, int n_points)
+{
+ int inside = 0;
+ for (int i = 0, j = n_points - 1; i < n_points; j = i++) {
+ float xi = poly[i*2], yi = poly[i*2+1];
+ float xj = poly[j*2], yj = poly[j*2+1];
+ if (((yi > py) != (yj > py)) &&
+ (px < (xj - xi) * (py - yi) / (yj - yi) + xi))
+ inside = !inside;
+ }
+ return inside;
+}
+
+static inline NN2Zone* nn2_zone_create(const char* name, int n_points, const float* poly)
+{
+ NN2Zone* z = (NN2Zone*)calloc(1, sizeof(NN2Zone));
+ strncpy(z->name, name ? name : "zone", sizeof(z->name) - 1);
+ z->n_points = (n_points > NN2_ZONE_MAX_POINTS) ? NN2_ZONE_MAX_POINTS : n_points;
+ memcpy(z->poly, poly, z->n_points * 2 * sizeof(float));
+ return z;
+}
+
+static inline void nn2_zone_set_classes(NN2Zone* z, int n, const int* classes)
+{
+ z->n_filter_classes = n;
+ for (int i = 0; i < n && i < 80; i++)
+ z->filter_classes[classes[i]] = 1;
+}
+
+static inline void nn2_zone_set_dwell(NN2Zone* z, int frames) { z->dwell_threshold = frames; }
+
+/* Check tracked objects against zone. Returns events. */
+static inline int nn2_zone_check(NN2Zone* z, const NN2Track* tracks, int n_tracks,
+ NN2ZoneEvent* events, int max_events)
+{
+ int n_events = 0;
+
+ /* Mark all current tracks */
+ int8_t seen[NN2_ZONE_MAX_IDS] = {0};
+
+ for (int i = 0; i < n_tracks && n_events < max_events; i++) {
+ int id = tracks[i].id;
+ if (id <= 0 || id >= NN2_ZONE_MAX_IDS) continue;
+ seen[id] = 1;
+
+ /* Class filter */
+ if (z->n_filter_classes > 0 && !z->filter_classes[tracks[i].cls])
+ continue;
+
+ /* Centroid */
+ float cx = (tracks[i].x1 + tracks[i].x2) * 0.5f;
+ float cy = (tracks[i].y1 + tracks[i].y2) * 0.5f;
+ int in_zone = nn2_point_in_poly(cx, cy, z->poly, z->n_points);
+
+ int was_inside = z->inside[id];
+
+ if (in_zone && !was_inside) {
+ /* ENTER */
+ z->inside[id] = 1;
+ z->dwell_count[id] = 1;
+ if (z->dwell_threshold <= 1) {
+ events[n_events++] = (NN2ZoneEvent){id, tracks[i].cls,
+ NN2_ZONE_ENTER, 1, cx, cy};
+ z->total_intrusions++;
+ }
+ } else if (in_zone && was_inside) {
+ /* STILL INSIDE */
+ z->dwell_count[id]++;
+ if (z->dwell_count[id] == z->dwell_threshold) {
+ /* Dwell threshold reached — first alert */
+ events[n_events++] = (NN2ZoneEvent){id, tracks[i].cls,
+ NN2_ZONE_ENTER, z->dwell_count[id], cx, cy};
+ z->total_intrusions++;
+ } else if (z->dwell_count[id] > z->dwell_threshold) {
+ events[n_events++] = (NN2ZoneEvent){id, tracks[i].cls,
+ NN2_ZONE_INSIDE, z->dwell_count[id], cx, cy};
+ }
+ } else if (!in_zone && was_inside) {
+ /* EXIT */
+ z->inside[id] = 0;
+ events[n_events++] = (NN2ZoneEvent){id, tracks[i].cls,
+ NN2_ZONE_EXIT, z->dwell_count[id], cx, cy};
+ z->dwell_count[id] = 0;
+ }
+ }
+
+ /* Check for tracks that disappeared while inside */
+ for (int id = 1; id < NN2_ZONE_MAX_IDS; id++) {
+ if (z->inside[id] && !seen[id]) {
+ z->inside[id] = 0;
+ z->dwell_count[id] = 0;
+ }
+ }
+
+ return n_events;
+}
+
+static inline void nn2_zone_free(NN2Zone* z) { free(z); }
+
+#endif /* NN2_ZONE_H */
diff --git a/nn2/nvr_events.jsonl b/nn2/nvr_events.jsonl
new file mode 100644
index 0000000..e69de29
diff --git a/nn2/pipeline_events.jsonl b/nn2/pipeline_events.jsonl
new file mode 100644
index 0000000..e69de29
diff --git a/nn2/pt_conv0.npy b/nn2/pt_conv0.npy
new file mode 100644
index 0000000..1c2f689
Binary files /dev/null and b/nn2/pt_conv0.npy differ
diff --git a/nn2/ref_conv0.npy b/nn2/ref_conv0.npy
new file mode 100644
index 0000000..95787aa
Binary files /dev/null and b/nn2/ref_conv0.npy differ
diff --git a/nn2/ref_conv1.npy b/nn2/ref_conv1.npy
new file mode 100644
index 0000000..6e4b341
Binary files /dev/null and b/nn2/ref_conv1.npy differ
diff --git a/nn2/src/antispoof_ops.c b/nn2/src/antispoof_ops.c
new file mode 100644
index 0000000..24b8b82
--- /dev/null
+++ b/nn2/src/antispoof_ops.c
@@ -0,0 +1,165 @@
+/*
+ * antispoof_ops.c — Additional ops needed for MiniFASNet that don't exist in
+ * the YOLOv8-tuned nn2 core: PReLU (per-channel), global avg pool, SE block,
+ * channel multiply, generic Linear (matmul + bias).
+ *
+ * All AVX-512 paths fall back gracefully to scalar.
+ */
+
+#include "nn2_internal.h"
+#include "nn2_antispoof_ops.h"
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+
+#ifdef __AVX512F__
+#include <immintrin.h>
+#endif
+
+
+/* ===== PReLU: per-channel parametric ReLU =====
+ * f(x) = x if x > 0
+ * alpha[c]*x if x <= 0
+ * Tensor layout: CHW row-major.
+ */
+typedef struct { float* x; const float* alpha; int C, HW; } PreluCtx;
+
+static void prelu_worker(void* arg, int start, int end)
+{
+ PreluCtx* p = (PreluCtx*)arg;
+ int HW = p->HW;
+ for (int c = start; c < end; c++) {
+ float a = p->alpha[c];
+ float* row = p->x + c * HW;
+ int i = 0;
+#ifdef __AVX512F__
+ __m512 va = _mm512_set1_ps(a);
+ __m512 vzero = _mm512_setzero_ps();
+ for (; i + 16 <= HW; i += 16) {
+ __m512 v = _mm512_loadu_ps(row + i);
+ __mmask16 neg = _mm512_cmplt_ps_mask(v, vzero);
+ __m512 out = _mm512_mask_mul_ps(v, neg, v, va);
+ _mm512_storeu_ps(row + i, out);
+ }
+#endif
+ for (; i < HW; i++) {
+ float v = row[i];
+ row[i] = v > 0.0f ? v : v * a;
+ }
+ }
+}
+
+void nn2_prelu(float* x, const float* alpha, int C, int HW)
+{
+ PreluCtx ctx = { x, alpha, C, HW };
+ if (C >= 8) nn2_tp_parallel_for(prelu_worker, &ctx, C, 4);
+ else prelu_worker(&ctx, 0, C);
+}
+
+/* 1D PReLU after Linear: simple in-place, no spatial dim. */
+void nn2_prelu_1d(float* x, const float* alpha, int N)
+{
+ int i = 0;
+#ifdef __AVX512F__
+ __m512 vzero = _mm512_setzero_ps();
+ for (; i + 16 <= N; i += 16) {
+ __m512 v = _mm512_loadu_ps(x + i);
+ __m512 a = _mm512_loadu_ps(alpha + i);
+ __mmask16 neg = _mm512_cmplt_ps_mask(v, vzero);
+ __m512 out = _mm512_mask_mul_ps(v, neg, v, a);
+ _mm512_storeu_ps(x + i, out);
+ }
+#endif
+ for (; i < N; i++) {
+ float v = x[i];
+ x[i] = v > 0.0f ? v : v * alpha[i];
+ }
+}
+
+/* ===== Global Average Pool (CHW → C) ===== */
+void nn2_global_avg_pool(const float* x, int C, int HW, float* out)
+{
+ float inv = 1.0f / (float)HW;
+ for (int c = 0; c < C; c++) {
+ const float* row = x + c * HW;
+ int i = 0;
+ float sum = 0.0f;
+#ifdef __AVX512F__
+ __m512 acc = _mm512_setzero_ps();
+ for (; i + 16 <= HW; i += 16) {
+ acc = _mm512_add_ps(acc, _mm512_loadu_ps(row + i));
+ }
+ sum = _mm512_reduce_add_ps(acc);
+#endif
+ for (; i < HW; i++) sum += row[i];
+ out[c] = sum * inv;
+ }
+}
+
+/* ===== Channel multiply: out[c, hw] = x[c, hw] * scale[c] (in-place) ===== */
+void nn2_channel_mul(float* x, const float* scale, int C, int HW)
+{
+ for (int c = 0; c < C; c++) {
+ float s = scale[c];
+ float* row = x + c * HW;
+ int i = 0;
+#ifdef __AVX512F__
+ __m512 vs = _mm512_set1_ps(s);
+ for (; i + 16 <= HW; i += 16) {
+ __m512 v = _mm512_loadu_ps(row + i);
+ _mm512_storeu_ps(row + i, _mm512_mul_ps(v, vs));
+ }
+#endif
+ for (; i < HW; i++) row[i] *= s;
+ }
+}
+
+/* ===== Add (in-place out += in) ===== */
+void nn2_add_inplace(float* out, const float* in, int N)
+{
+ int i = 0;
+#ifdef __AVX512F__
+ for (; i + 16 <= N; i += 16) {
+ __m512 a = _mm512_loadu_ps(out + i);
+ __m512 b = _mm512_loadu_ps(in + i);
+ _mm512_storeu_ps(out + i, _mm512_add_ps(a, b));
+ }
+#endif
+ for (; i < N; i++) out[i] += in[i];
+}
+
+/* ===== Linear (FC): y = W * x + b, where W is [out, in] row-major ===== */
+void nn2_linear(const float* x, const float* W, const float* b,
+ int in_f, int out_f, float* y)
+{
+ for (int o = 0; o < out_f; o++) {
+ float s = b ? b[o] : 0.0f;
+ const float* row = W + o * in_f;
+ int i = 0;
+#ifdef __AVX512F__
+ __m512 acc = _mm512_setzero_ps();
+ for (; i + 16 <= in_f; i += 16) {
+ __m512 vw = _mm512_loadu_ps(row + i);
+ __m512 vx = _mm512_loadu_ps(x + i);
+ acc = _mm512_fmadd_ps(vw, vx, acc);
+ }
+ s += _mm512_reduce_add_ps(acc);
+#endif
+ for (; i < in_f; i++) s += row[i] * x[i];
+ y[o] = s;
+ }
+}
+
+/* ===== Softmax over a small N (3 for antispoof) ===== */
+void nn2_softmax(const float* x, int N, float* y)
+{
+ float m = x[0];
+ for (int i = 1; i < N; i++) if (x[i] > m) m = x[i];
+ float sum = 0.0f;
+ for (int i = 0; i < N; i++) {
+ y[i] = expf(x[i] - m);
+ sum += y[i];
+ }
+ float inv = 1.0f / sum;
+ for (int i = 0; i < N; i++) y[i] *= inv;
+}
diff --git a/nn2/src/bench2.c b/nn2/src/bench2.c
new file mode 100644
index 0000000..0706f2e
--- /dev/null
+++ b/nn2/src/bench2.c
@@ -0,0 +1,45 @@
+#include "nn2_internal.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef _WIN32
+#include <windows.h>
+static double now(void){LARGE_INTEGER f,c;QueryPerformanceFrequency(&f);QueryPerformanceCounter(&c);return(double)c.QuadPart/f.QuadPart*1000.0;}
+#endif
+int nn2_load_weights(NN2* ctx, const char* path);
+int main(void){
+ NN2 c;memset(&c,0,sizeof(c));nn2_tp_init(6);
+ if(nn2_load_weights(&c,"weights/yolov8n.bin"))return 1;
+ int S=c.input_size;
+ float*in=(float*)calloc(256*S*S,4);
+ float*out=(float*)malloc(256*S*S*4);
+ size_t colsz=(size_t)256*9*S*S/4;
+ float*col=(float*)malloc(colsz*4);
+ if(!in||!out||!col){printf("alloc fail\n");return 1;}
+ int R=20;double t0,ms;
+ printf("=== Breakdown (input=%d, 6 threads) ===\n\n",S);
+
+ /* im2col benchmarks */
+ t0=now();for(int r=0;r<R;r++)nn2_im2col(in,3,S,S,3,3,2,1,col);ms=(now()-t0)/R;
+ printf("im2col 3ch 640 s=2: %5.2f ms\n",ms);
+ t0=now();for(int r=0;r<R;r++)nn2_im2col(in,16,S/2,S/2,3,3,2,1,col);ms=(now()-t0)/R;
+ printf("im2col 16ch 320 s=2: %5.2f ms\n",ms);
+ t0=now();for(int r=0;r<R;r++)nn2_im2col(in,16,S/4,S/4,3,3,1,1,col);ms=(now()-t0)/R;
+ printf("im2col 16ch 160 s=1: %5.2f ms\n",ms);
+ t0=now();for(int r=0;r<R;r++)nn2_im2col(in,32,S/8,S/8,3,3,1,1,col);ms=(now()-t0)/R;
+ printf("im2col 32ch 80 s=1: %5.2f ms\n",ms);
+
+ /* GEMM benchmarks */
+ t0=now();for(int r=0;r<R;r++)nn2_sgemm(16,27,102400,in,27,col,102400,out,102400);ms=(now()-t0)/R;
+ printf("GEMM 16x27x102400: %5.2f ms %.0f GFLOPS\n",ms,2.0*16*27*102400/(ms*1e6));
+ t0=now();for(int r=0;r<R;r++)nn2_sgemm(32,144,25600,in,144,col,25600,out,25600);ms=(now()-t0)/R;
+ printf("GEMM 32x144x25600: %5.2f ms %.0f GFLOPS\n",ms,2.0*32*144*25600/(ms*1e6));
+
+ /* Full conv */
+ t0=now();for(int r=0;r<R;r++)nn2_conv2d(&c.bb_conv[0],in,S,S,out,col);ms=(now()-t0)/R;
+ printf("conv0 full (3->16 s=2): %5.2f ms\n",ms);
+ t0=now();for(int r=0;r<R;r++)nn2_conv2d(&c.bb_conv[1],in,S/2,S/2,out,col);ms=(now()-t0)/R;
+ printf("conv1 full(16->32 s=2): %5.2f ms\n",ms);
+
+ free(in);free(out);free(col);nn2_tp_destroy();return 0;
+}
diff --git a/nn2/src/bench_320.c b/nn2/src/bench_320.c
new file mode 100644
index 0000000..150aa43
--- /dev/null
+++ b/nn2/src/bench_320.c
@@ -0,0 +1,49 @@
+#include "nn2_internal.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef _WIN32
+#include <windows.h>
+static double now(void){LARGE_INTEGER f,c;QueryPerformanceFrequency(&f);QueryPerformanceCounter(&c);return(double)c.QuadPart/f.QuadPart*1000.0;}
+#endif
+int nn2_load_weights(NN2* ctx, const char* path);
+int main(void){
+ NN2 c;memset(&c,0,sizeof(c));nn2_tp_init(6);
+ if(nn2_load_weights(&c,"weights/yolov8n_320.bin"))return 1;
+ int S=c.input_size;
+ float*in=(float*)calloc(256*S*S,4);
+ float*out=(float*)malloc(256*S*S*4);
+ float*col=(float*)malloc(4*1024*1024*4);
+ int R=30;double t0,ms;
+ printf("=== 320x320 Layer Profile (6 threads) ===\n\n");
+ /* Backbone convs */
+ int hs[]={320,160,80,40,20}; int chs[]={16,32,64,128,256};
+ for(int i=0;i<5;i++){
+ t0=now();for(int r=0;r<R;r++)nn2_conv2d(&c.bb_conv[i],in,hs[i],hs[i],out,col);
+ printf("bb_conv%d %3d->%3d s2 @%3d: %5.2f ms\n",i,i==0?3:chs[i-1],chs[i],hs[i],( now()-t0)/R);
+ }
+ /* C2f cv1 (pointwise) */
+ for(int i=0;i<4;i++){
+ int h=hs[i+1];
+ t0=now();for(int r=0;r<R;r++)nn2_conv2d(&c.bb_c2f[i].cv1,in,h,h,out,col);
+ printf("c2f%d.cv1 1x1 @%3d: %5.2f ms\n",i,h,(now()-t0)/R);
+ }
+ /* C2f bottleneck 3x3 */
+ for(int i=0;i<4;i++){
+ if(c.bb_c2f[i].n==0)continue;
+ int h=hs[i+1];
+ t0=now();for(int r=0;r<R;r++)nn2_conv2d(&c.bb_c2f[i].m[0].cv1,in,h,h,out,col);
+ printf("c2f%d.bn 3x3 @%3d: %5.2f ms\n",i,h,(now()-t0)/R);
+ }
+ /* SPPF maxpool */
+ t0=now();for(int r=0;r<R;r++)nn2_maxpool2d(in,128,10,10,5,1,2,out);
+ printf("sppf maxpool @10: %5.2f ms\n",(now()-t0)/R);
+ /* Upsample */
+ t0=now();for(int r=0;r<R;r++)nn2_upsample_2x(in,256,10,10,out);
+ printf("upsample 256ch 10->20: %5.2f ms\n",(now()-t0)/R);
+ t0=now();for(int r=0;r<R;r++)nn2_upsample_2x(in,128,20,20,out);
+ printf("upsample 128ch 20->40: %5.2f ms\n",(now()-t0)/R);
+ /* Decode/NMS overhead */
+ printf("\n");
+ free(in);free(out);free(col);nn2_tp_destroy();return 0;
+}
diff --git a/nn2/src/bench_asm.c b/nn2/src/bench_asm.c
new file mode 100644
index 0000000..0d17d9d
--- /dev/null
+++ b/nn2/src/bench_asm.c
@@ -0,0 +1,174 @@
+/*
+ * bench_asm.c — Compare assembly GEMM kernel vs GCC intrinsics.
+ * Uses rdtsc for cycle-accurate measurement, volatile sink to prevent DCE.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <immintrin.h>
+#include <stdint.h>
+
+#ifdef _WIN32
+#include <windows.h>
+#endif
+
+/* ---- rdtsc ---- */
+static inline uint64_t rdtsc(void) {
+ unsigned hi, lo;
+ __asm__ __volatile__("rdtsc" : "=a"(lo), "=d"(hi));
+ return ((uint64_t)hi << 32) | lo;
+}
+
+/* ---- Intrinsics 6x32 microkernel (same as gemm.c) ---- */
+static void ukernel_6x32_intrinsics(
+ int K,
+ const float* a0, const float* a1, const float* a2,
+ const float* a3, const float* a4, const float* a5,
+ const float* B, int ldb,
+ float* C, int ldc)
+{
+ __m512 c00=_mm512_setzero_ps(),c01=_mm512_setzero_ps();
+ __m512 c10=_mm512_setzero_ps(),c11=_mm512_setzero_ps();
+ __m512 c20=_mm512_setzero_ps(),c21=_mm512_setzero_ps();
+ __m512 c30=_mm512_setzero_ps(),c31=_mm512_setzero_ps();
+ __m512 c40=_mm512_setzero_ps(),c41=_mm512_setzero_ps();
+ __m512 c50=_mm512_setzero_ps(),c51=_mm512_setzero_ps();
+
+ for (int k = 0; k < K; k++) {
+ const float* bp = B + k * ldb;
+ __m512 b0 = _mm512_loadu_ps(bp);
+ __m512 b1 = _mm512_loadu_ps(bp + 16);
+ __m512 va;
+ va=_mm512_set1_ps(a0[k]);c00=_mm512_fmadd_ps(va,b0,c00);c01=_mm512_fmadd_ps(va,b1,c01);
+ va=_mm512_set1_ps(a1[k]);c10=_mm512_fmadd_ps(va,b0,c10);c11=_mm512_fmadd_ps(va,b1,c11);
+ va=_mm512_set1_ps(a2[k]);c20=_mm512_fmadd_ps(va,b0,c20);c21=_mm512_fmadd_ps(va,b1,c21);
+ va=_mm512_set1_ps(a3[k]);c30=_mm512_fmadd_ps(va,b0,c30);c31=_mm512_fmadd_ps(va,b1,c31);
+ va=_mm512_set1_ps(a4[k]);c40=_mm512_fmadd_ps(va,b0,c40);c41=_mm512_fmadd_ps(va,b1,c41);
+ va=_mm512_set1_ps(a5[k]);c50=_mm512_fmadd_ps(va,b0,c50);c51=_mm512_fmadd_ps(va,b1,c51);
+ }
+ _mm512_storeu_ps(C+0*ldc,c00);_mm512_storeu_ps(C+0*ldc+16,c01);
+ _mm512_storeu_ps(C+1*ldc,c10);_mm512_storeu_ps(C+1*ldc+16,c11);
+ _mm512_storeu_ps(C+2*ldc,c20);_mm512_storeu_ps(C+2*ldc+16,c21);
+ _mm512_storeu_ps(C+3*ldc,c30);_mm512_storeu_ps(C+3*ldc+16,c31);
+ _mm512_storeu_ps(C+4*ldc,c40);_mm512_storeu_ps(C+4*ldc+16,c41);
+ _mm512_storeu_ps(C+5*ldc,c50);_mm512_storeu_ps(C+5*ldc+16,c51);
+}
+
+/* ---- Assembly kernel (from gemm_avx512.S) ---- */
+typedef struct {
+ int K;
+ int _pad;
+ const float* a[6];
+ const float* B;
+ int ldb_bytes;
+ int _pad2;
+ float* C;
+ int ldc_bytes;
+} GemmKernArgs;
+
+extern void gemm_6x32_kern(const GemmKernArgs* args);
+
+/* Volatile sink to prevent dead code elimination */
+static volatile float g_sink;
+
+int main(void)
+{
+ /* Test sizes representative of YOLO layers */
+ int test_K[] = {16, 32, 48, 64, 128, 256};
+ int ntests = sizeof(test_K) / sizeof(test_K[0]);
+
+ printf("=== Assembly vs Intrinsics GEMM 6x32 Benchmark ===\n");
+ printf("%-8s %12s %12s %8s\n", "K", "Intrinsics", "Assembly", "Ratio");
+ printf("%-8s %12s %12s %8s\n", "", "(cycles)", "(cycles)", "(asm/int)");
+ printf("-----------------------------------------------\n");
+
+ for (int ti = 0; ti < ntests; ti++) {
+ int K = test_K[ti];
+ int ldb = 32; /* NR=32 */
+ int ldc = 32;
+
+ /* Allocate aligned buffers */
+ float* A = (float*)_mm_malloc(6 * K * sizeof(float), 64);
+ float* B = (float*)_mm_malloc(K * 32 * sizeof(float), 64);
+ float* C1 = (float*)_mm_malloc(6 * 32 * sizeof(float), 64);
+ float* C2 = (float*)_mm_malloc(6 * 32 * sizeof(float), 64);
+
+ /* Fill with small values */
+ for (int i = 0; i < 6 * K; i++) A[i] = 0.01f * (i % 17);
+ for (int i = 0; i < K * 32; i++) B[i] = 0.01f * (i % 13);
+
+ int ITERS = 10000;
+ uint64_t best_intr = UINT64_MAX;
+ uint64_t best_asm = UINT64_MAX;
+
+ /* Warmup */
+ for (int i = 0; i < 100; i++) {
+ memset(C1, 0, 6 * 32 * sizeof(float));
+ ukernel_6x32_intrinsics(K,
+ A, A+K, A+2*K, A+3*K, A+4*K, A+5*K,
+ B, ldb, C1, ldc);
+ g_sink = C1[0];
+ }
+
+ /* Benchmark intrinsics */
+ for (int i = 0; i < ITERS; i++) {
+ memset(C1, 0, 6 * 32 * sizeof(float));
+ _mm_mfence();
+ uint64_t t0 = rdtsc();
+ ukernel_6x32_intrinsics(K,
+ A, A+K, A+2*K, A+3*K, A+4*K, A+5*K,
+ B, ldb, C1, ldc);
+ uint64_t t1 = rdtsc();
+ g_sink = C1[0] + C1[95] + C1[191]; /* use result */
+ uint64_t dt = t1 - t0;
+ if (dt < best_intr) best_intr = dt;
+ }
+
+ /* Warmup assembly */
+ GemmKernArgs args;
+ args.K = K;
+ args.a[0] = A; args.a[1] = A+K; args.a[2] = A+2*K;
+ args.a[3] = A+3*K; args.a[4] = A+4*K; args.a[5] = A+5*K;
+ args.B = B;
+ args.ldb_bytes = ldb * 4;
+ args.C = C2;
+ args.ldc_bytes = ldc * 4;
+
+ for (int i = 0; i < 100; i++) {
+ memset(C2, 0, 6 * 32 * sizeof(float));
+ gemm_6x32_kern(&args);
+ g_sink = C2[0];
+ }
+
+ /* Benchmark assembly */
+ for (int i = 0; i < ITERS; i++) {
+ memset(C2, 0, 6 * 32 * sizeof(float));
+ _mm_mfence();
+ uint64_t t0 = rdtsc();
+ gemm_6x32_kern(&args);
+ uint64_t t1 = rdtsc();
+ g_sink = C2[0] + C2[95] + C2[191]; /* use result */
+ uint64_t dt = t1 - t0;
+ if (dt < best_asm) best_asm = dt;
+ }
+
+ /* Verify correctness */
+ float max_err = 0;
+ for (int i = 0; i < 6 * 32; i++) {
+ float err = fabsf(C1[i] - C2[i]);
+ if (err > max_err) max_err = err;
+ }
+
+ double ratio = (double)best_asm / (double)best_intr;
+ double flops = 2.0 * 6 * 32 * K;
+ printf("K=%-5d %10llu %10llu %.3f (err=%.2e, %.0f FLOPs)\n",
+ K, (unsigned long long)best_intr, (unsigned long long)best_asm,
+ ratio, max_err, flops);
+
+ _mm_free(A); _mm_free(B); _mm_free(C1); _mm_free(C2);
+ }
+
+ printf("\nRatio < 1.0 = assembly is faster\n");
+ return 0;
+}
diff --git a/nn2/src/bench_int8.c b/nn2/src/bench_int8.c
new file mode 100644
index 0000000..52a4432
--- /dev/null
+++ b/nn2/src/bench_int8.c
@@ -0,0 +1,46 @@
+#include "nn2_internal.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef _WIN32
+#include <windows.h>
+static double now(void){LARGE_INTEGER f,c;QueryPerformanceFrequency(&f);QueryPerformanceCounter(&c);return(double)c.QuadPart/f.QuadPart*1000.0;}
+#endif
+int main(void){
+ nn2_tp_init(6);
+ printf("=== INT8 VNNI GEMM vs FP32 (6 threads) ===\n\n");
+ /* Conv GEMM: C^T[spatial,Cout] = Input^T[spatial,Cin] x Weight_packed[Cin,Cout]
+ * INT8 GEMM: C[M,N] = A[M,K] x B_packed[K,N] where M=spatial, K=Cin, N=Cout */
+ struct { const char* name; int spatial,cin,cout; } tests[] = {
+ {"1x1 32->32 @160x160", 25600, 32, 32},
+ {"1x1 64->64 @80x80", 6400, 64, 64},
+ {"1x1 128->128 @40x40", 1600, 128,128},
+ {"1x1 128->64 @80x80", 6400, 128, 64},
+ {"1x1 256->256 @20x20", 400, 256,256},
+ };
+ int R=20;
+ for(int t=0;t<5;t++){
+ int M=tests[t].spatial, K=tests[t].cin, N=tests[t].cout;
+ double ops=2.0*M*K*N;
+ /* FP32: C[Cout,spatial] = W[Cout,Cin] x Input[Cin,spatial] */
+ float*fw=(float*)calloc(N*K,4);float*fi=(float*)calloc(K*M,4);float*fo=(float*)malloc(N*M*4);
+ double t0=now();
+ for(int r=0;r<R;r++) nn2_sgemm(N,K,M,fw,K,fi,M,fo,M);
+ double fp32_ms=(now()-t0)/R;
+ /* INT8: C^T[spatial,Cout] = Input^T[spatial,Cin] x W_packed */
+ int8_t*iw=(int8_t*)calloc(N*K,1); /* weights [Cout,Cin] */
+ int psz=nn2_int8_packed_size(K,N);
+ void*ipk=malloc(psz);int32_t*cs=(int32_t*)calloc(N,4);
+ float*ws=(float*)malloc(N*4);float*bi=(float*)calloc(N,4);
+ for(int i=0;i<N;i++)ws[i]=0.01f;
+ nn2_int8_pack_weights(iw,K,N,ipk,cs);
+ int8_t*ia=(int8_t*)calloc(M*K,1); /* Input^T[spatial,Cin] */
+ t0=now();
+ for(int r=0;r<R;r++)nn2_int8_gemm_fused(ia,M,K,N,ipk,cs,ws,bi,0.05f,0.05f,0,fo);
+ double int8_ms=(now()-t0)/R;
+ printf("%-28s FP32:%5.1fms(%3.0fG) INT8:%5.1fms(%3.0fG) %.1fx\n",
+ tests[t].name,fp32_ms,ops/(fp32_ms*1e6),int8_ms,ops/(int8_ms*1e6),fp32_ms/int8_ms);
+ free(fw);free(fi);free(fo);free(iw);free(ipk);free(cs);free(ws);free(bi);free(ia);
+ }
+ nn2_tp_destroy();return 0;
+}
diff --git a/nn2/src/bench_layers.c b/nn2/src/bench_layers.c
new file mode 100644
index 0000000..1bf442e
--- /dev/null
+++ b/nn2/src/bench_layers.c
@@ -0,0 +1,52 @@
+#include "nn2_internal.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef _WIN32
+#include <windows.h>
+static double now_ms(void) { LARGE_INTEGER f,c; QueryPerformanceFrequency(&f); QueryPerformanceCounter(&c); return (double)c.QuadPart/f.QuadPart*1000.0; }
+#endif
+int nn2_load_weights(NN2* ctx, const char* path);
+
+static void bench_conv(const char* name, ConvLayer* L, int H, int W) {
+ int Ho=(H+2*L->pad-L->k)/L->stride+1, Wo=(W+2*L->pad-L->k)/L->stride+1;
+ float* in=(float*)calloc(L->cin*H*W,4);
+ float* out=(float*)malloc(L->cout*Ho*Wo*4);
+ float* col=(float*)malloc((size_t)L->cin*L->k*L->k*Ho*Wo*4);
+ double t0=now_ms(); int R=10;
+ for(int r=0;r<R;r++) nn2_conv2d(L,in,H,W,out,col);
+ printf(" %-30s %6.2f ms\n",name,(now_ms()-t0)/R);
+ free(in);free(out);free(col);
+}
+static void bench_gemm(const char* name, int m, int k, int n) {
+ float* a=(float*)calloc(m*k,4); float* b=(float*)calloc(k*n,4); float* c=(float*)malloc(m*n*4);
+ double t0=now_ms(); int R=10;
+ for(int r=0;r<R;r++) nn2_sgemm(m,k,n,a,k,b,n,c,n);
+ double ms=(now_ms()-t0)/R;
+ printf(" %-30s %6.2f ms %.1f GFLOPS\n",name,ms,2.0*m*k*n/(ms*1e6));
+ free(a);free(b);free(c);
+}
+int main(void) {
+ NN2 c; memset(&c,0,sizeof(c)); nn2_tp_init(4);
+ if(nn2_load_weights(&c,"weights/yolov8n.bin")) return 1;
+ int S=c.input_size;
+ printf("=== nn2 profiling (input=%d, 4 threads) ===\n\nConv layers:\n",S);
+ bench_conv("conv0: 3->16 s=2",&c.bb_conv[0],S,S);
+ bench_conv("conv1: 16->32 s=2",&c.bb_conv[1],S/2,S/2);
+ bench_conv("conv2: 32->64 s=2",&c.bb_conv[2],S/4,S/4);
+ bench_conv("conv3: 64->128 s=2",&c.bb_conv[3],S/8,S/8);
+ bench_conv("conv4: 128->256 s=2",&c.bb_conv[4],S/16,S/16);
+ printf("\n1x1 conv (C2f cv1):\n");
+ bench_conv("c2f0.cv1: 32->32 1x1",&c.bb_c2f[0].cv1,S/4,S/4);
+ bench_conv("c2f1.cv1: 64->64 1x1",&c.bb_c2f[1].cv1,S/8,S/8);
+ printf("\n3x3 conv (C2f bottleneck):\n");
+ bench_conv("c2f0.bn: 16->16 3x3",&c.bb_c2f[0].m[0].cv1,S/4,S/4);
+ bench_conv("c2f1.bn: 32->32 3x3",&c.bb_c2f[1].m[0].cv1,S/8,S/8);
+ printf("\nGEMM:\n");
+ bench_gemm("16x27x102400",16,27,102400);
+ bench_gemm("32x144x25600",32,144,25600);
+ bench_gemm("64x288x6400",64,288,6400);
+ bench_gemm("128x576x1600",128,576,1600);
+ bench_gemm("32x32x25600",32,32,25600);
+ nn2_tp_destroy(); return 0;
+}
diff --git a/nn2/src/bench_nanodet.c b/nn2/src/bench_nanodet.c
new file mode 100644
index 0000000..ccfaf48
--- /dev/null
+++ b/nn2/src/bench_nanodet.c
@@ -0,0 +1,73 @@
+#include "nn2_internal.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef _WIN32
+#include <windows.h>
+static double now(void){LARGE_INTEGER f,c;QueryPerformanceFrequency(&f);QueryPerformanceCounter(&c);return(double)c.QuadPart/f.QuadPart*1000.0;}
+#endif
+int main(void){
+ nn2_tp_init(6);
+ printf("=== NanoDet-Plus-m Operator Benchmarks (6 threads) ===\n\n");
+ int R=100; double t0,ms;
+
+ /* DW conv benchmarks (the most common op in NanoDet) */
+ printf("Depthwise Conv (per-channel, no GEMM):\n");
+ struct{const char*n;int c,h,k,s;} dw_tests[]={
+ {"DW 58ch k=3 s=1 @80", 58, 80, 3, 1},
+ {"DW 116ch k=3 s=1 @40", 116, 40, 3, 1},
+ {"DW 232ch k=3 s=1 @20", 232, 20, 3, 1},
+ {"DW 96ch k=5 s=1 @40", 96, 40, 5, 1},
+ {"DW 96ch k=5 s=1 @20", 96, 20, 5, 1},
+ {"DW 192ch k=5 s=1 @40", 192, 40, 5, 1},
+ {"DW 96ch k=5 s=2 @40", 96, 40, 5, 2},
+ };
+ for(int t=0;t<7;t++){
+ int c=dw_tests[t].c, h=dw_tests[t].h, k=dw_tests[t].k, s=dw_tests[t].s;
+ int ho=(h+2*(k/2)-k)/s+1;
+ float*in=(float*)calloc(c*h*h,4);
+ float*w=(float*)calloc(c*k*k,4);
+ float*b=(float*)calloc(c,4);
+ float*out=(float*)malloc(c*ho*ho*4);
+ t0=now();
+ for(int r=0;r<R;r++)nn2_dwconv2d(in,w,b,c,h,h,k,s,k/2,3,out);
+ ms=(now()-t0)/R;
+ printf(" %-28s %.3f ms\n",dw_tests[t].n,ms);
+ free(in);free(w);free(b);free(out);
+ }
+
+ /* PW (1x1) conv benchmarks */
+ printf("\nPointwise Conv (pure GEMM):\n");
+ struct{const char*n;int co,ci,h;} pw_tests[]={
+ {"PW 58->58 @80", 58, 58, 80},
+ {"PW 116->116 @40",116,116, 40},
+ {"PW 232->232 @20",232,232, 20},
+ {"PW 96->96 @40", 96, 96, 40},
+ {"PW 96->112 @40", 112, 96, 40},
+ {"PW 116->96 @40", 96,116, 40},
+ {"PW 232->96 @20", 96,232, 20},
+ };
+ for(int t=0;t<7;t++){
+ int co=pw_tests[t].co, ci=pw_tests[t].ci, h=pw_tests[t].h;
+ int sp=h*h;
+ float*w=(float*)calloc(co*ci,4);
+ float*in=(float*)calloc(ci*sp,4);
+ float*out=(float*)malloc(co*sp*4);
+ t0=now();
+ for(int r=0;r<R;r++)nn2_sgemm(co,ci,sp,w,ci,in,sp,out,sp);
+ ms=(now()-t0)/R;
+ printf(" %-28s %.3f ms\n",pw_tests[t].n,ms);
+ free(w);free(in);free(out);
+ }
+
+ /* Sum up estimated total */
+ printf("\n--- Estimated NanoDet total ---\n");
+ printf(" ~43 DW convs: ~43 * 0.03ms avg = ~1.3ms\n");
+ printf(" ~66 PW convs: ~66 * 0.02ms avg = ~1.3ms\n");
+ printf(" 1 regular conv + overhead: ~0.4ms\n");
+ printf(" Estimated total: ~3.0ms\n");
+ printf(" vs ONNX RT NanoDet: 10.7ms\n");
+ printf(" vs ONNX RT YOLOv8n: 13.6ms\n");
+
+ nn2_tp_destroy();return 0;
+}
diff --git a/nn2/src/bench_profile.c b/nn2/src/bench_profile.c
new file mode 100644
index 0000000..fa5e7f0
--- /dev/null
+++ b/nn2/src/bench_profile.c
@@ -0,0 +1,276 @@
+/*
+ * bench_profile.c — Per-layer profiling of YOLOv8n forward pass.
+ * Identifies which layers consume the most time.
+ */
+
+#include "nn2_internal.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef _WIN32
+#include <windows.h>
+static double now(void) {
+ static LARGE_INTEGER freq;
+ static int init = 0;
+ if (!init) { QueryPerformanceFrequency(&freq); init = 1; }
+ LARGE_INTEGER t;
+ QueryPerformanceCounter(&t);
+ return (double)t.QuadPart / (double)freq.QuadPart;
+}
+#else
+#include <time.h>
+static double now(void) {
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return ts.tv_sec + ts.tv_nsec * 1e-9;
+}
+#endif
+
+/* Global profiling counters */
+#define MAX_PROF 200
+static struct {
+ const char* name;
+ double total_ms;
+ int calls;
+} g_prof[MAX_PROF];
+static int g_nprof = 0;
+
+static int prof_slot(const char* name) {
+ for (int i = 0; i < g_nprof; i++)
+ if (strcmp(g_prof[i].name, name) == 0) return i;
+ int s = g_nprof++;
+ g_prof[s].name = _strdup(name);
+ g_prof[s].total_ms = 0;
+ g_prof[s].calls = 0;
+ return s;
+}
+
+static void prof_add(const char* name, double ms) {
+ int s = prof_slot(name);
+ g_prof[s].total_ms += ms;
+ g_prof[s].calls++;
+}
+
+/* Profiled conv */
+static void prof_conv(const char* name, const ConvLayer* L, const float* in,
+ int H, int W, float* out, float* im2col) {
+ double t0 = now();
+ nn2_conv2d(L, in, H, W, out, im2col);
+ double t1 = now();
+ prof_add(name, (t1 - t0) * 1000.0);
+}
+
+/* Profiled C2f */
+static void prof_c2f(const char* name, const C2fBlock* blk, const float* in,
+ int H, int W, float* out, float* im2col, float* tmp) {
+ int spatial = H * W;
+ int c = blk->c;
+ int total_ch = (2 + blk->n) * c;
+ float* cat = tmp;
+ float* scratch = tmp + total_ch * spatial;
+ char buf[64];
+
+ double t0 = now();
+ sprintf(buf, "%s.cv1", name);
+ prof_conv(buf, &blk->cv1, in, H, W, cat, im2col);
+
+ float* bn_in = cat + c * spatial;
+ for (int i = 0; i < blk->n; i++) {
+ sprintf(buf, "%s.bn%d.cv1", name, i);
+ prof_conv(buf, &blk->m[i].cv1, bn_in, H, W, scratch, im2col);
+
+ float* bn_out = cat + (2 + i) * c * spatial;
+ sprintf(buf, "%s.bn%d.cv2", name, i);
+ prof_conv(buf, &blk->m[i].cv2, scratch, H, W, bn_out, im2col);
+
+ if (blk->shortcut)
+ for (int j = 0; j < c * spatial; j++) bn_out[j] += bn_in[j];
+ bn_in = bn_out;
+ }
+
+ sprintf(buf, "%s.cv2", name);
+ prof_conv(buf, &blk->cv2, cat, H, W, out, im2col);
+
+ double t1 = now();
+ prof_add(name, (t1 - t0) * 1000.0);
+}
+
+int main(int argc, char** argv)
+{
+ const char* wpath = "weights/yolov8n_320.bin";
+ if (argc > 1) wpath = argv[1];
+
+ NN2* ctx = nn2_init(wpath, 0);
+ if (!ctx) { fprintf(stderr, "Failed to init\n"); return 1; }
+
+ int S = ctx->input_size;
+ float* input = (float*)calloc(3 * S * S, sizeof(float));
+ for (int i = 0; i < 3 * S * S; i++) input[i] = 0.5f;
+
+ /* Warmup — run forward pass directly with float input */
+ int total_anchors = 0;
+ {
+ int bbox_ch = 4 * NN2_REG_MAX;
+ int nc = ctx->num_classes;
+ int ta = (S/8)*(S/8) + (S/16)*(S/16) + (S/32)*(S/32);
+ float* bbox = (float*)malloc(bbox_ch * ta * sizeof(float));
+ float* cls = (float*)malloc(nc * ta * sizeof(float));
+ for (int i = 0; i < 3; i++)
+ total_anchors = nn2_forward(ctx, input, bbox, cls);
+ free(bbox); free(cls);
+ }
+
+ /* Profile: run forward pass manually with timing */
+ int RUNS = 20;
+
+ for (int run = 0; run < RUNS; run++) {
+ float* ws = ctx->workspace;
+ float* im2col = ws; ws += 4*1024*1024;
+ float* buf0 = ws; ws += 4*1024*1024;
+ float* buf1 = ws; ws += 4*1024*1024;
+ float* save_p3 = ws; ws += 64*(S/8)*(S/8);
+ float* save_p4 = ws; ws += 128*(S/16)*(S/16);
+ float* save_p5 = ws; ws += 256*(S/32)*(S/32);
+ float* save_n3 = ws; ws += 128*(S/16)*(S/16);
+ float* c2f_tmp = ws;
+
+ float *cur = buf0, *nxt = buf1;
+ #define SWAP() { float* t = cur; cur = nxt; nxt = t; }
+ int h = S, w = S;
+ int h0=S/2,w0=S/2, h1=S/4,w1=S/4, h2=S/8,w2=S/8, h3=S/16,w3=S/16, h4=S/32,w4=S/32;
+
+ prof_conv("bb_conv0", &ctx->bb_conv[0], input, h, w, cur, im2col);
+ prof_conv("bb_conv1", &ctx->bb_conv[1], cur, h0, w0, nxt, im2col); SWAP();
+ prof_c2f("bb_c2f0", &ctx->bb_c2f[0], cur, h1, w1, nxt, im2col, c2f_tmp); SWAP();
+ prof_conv("bb_conv2", &ctx->bb_conv[2], cur, h1, w1, nxt, im2col); SWAP();
+ prof_c2f("bb_c2f1", &ctx->bb_c2f[1], cur, h2, w2, nxt, im2col, c2f_tmp); SWAP();
+ memcpy(save_p3, cur, 64*h2*w2*sizeof(float));
+ prof_conv("bb_conv3", &ctx->bb_conv[3], cur, h2, w2, nxt, im2col); SWAP();
+ prof_c2f("bb_c2f2", &ctx->bb_c2f[2], cur, h3, w3, nxt, im2col, c2f_tmp); SWAP();
+ memcpy(save_p4, cur, 128*h3*w3*sizeof(float));
+ prof_conv("bb_conv4", &ctx->bb_conv[4], cur, h3, w3, nxt, im2col); SWAP();
+ prof_c2f("bb_c2f3", &ctx->bb_c2f[3], cur, h4, w4, nxt, im2col, c2f_tmp); SWAP();
+
+ prof_conv("sppf_cv1", &ctx->sppf_cv1, cur, h4, w4, nxt, im2col); SWAP();
+ {
+ int sp = h4*w4;
+ float* cat = c2f_tmp;
+ float* mp1 = cat + 512*sp, *mp2 = mp1+128*sp, *mp3 = mp2+128*sp;
+ double t0 = now();
+ nn2_maxpool2d(cur, 128, h4, w4, 5, 1, 2, mp1);
+ nn2_maxpool2d(mp1, 128, h4, w4, 5, 1, 2, mp2);
+ nn2_maxpool2d(mp2, 128, h4, w4, 5, 1, 2, mp3);
+ memcpy(cat, cur, 128*sp*sizeof(float));
+ memcpy(cat+128*sp, mp1, 128*sp*sizeof(float));
+ memcpy(cat+256*sp, mp2, 128*sp*sizeof(float));
+ memcpy(cat+384*sp, mp3, 128*sp*sizeof(float));
+ prof_add("sppf_pool", (now()-t0)*1000.0);
+ prof_conv("sppf_cv2", &ctx->sppf_cv2, cat, h4, w4, nxt, im2col); SWAP();
+ }
+ memcpy(save_p5, cur, 256*h4*w4*sizeof(float));
+
+ /* Neck */
+ {
+ float* up = c2f_tmp;
+ double t0 = now();
+ nn2_upsample_2x(cur, 256, h4, w4, up);
+ nn2_concat(up, 256, save_p4, 128, h3, w3, nxt);
+ prof_add("upsample1", (now()-t0)*1000.0);
+ SWAP();
+ }
+ prof_c2f("nk_c2f0", &ctx->nk_c2f[0], cur, h3, w3, nxt, im2col, c2f_tmp); SWAP();
+ memcpy(save_n3, cur, 128*h3*w3*sizeof(float));
+
+ {
+ float* up = c2f_tmp;
+ double t0 = now();
+ nn2_upsample_2x(cur, 128, h3, w3, up);
+ nn2_concat(up, 128, save_p3, 64, h2, w2, nxt);
+ prof_add("upsample2", (now()-t0)*1000.0);
+ SWAP();
+ }
+
+ float* feat_n2 = save_p3;
+ prof_c2f("nk_c2f1", &ctx->nk_c2f[1], cur, h2, w2, feat_n2, im2col, c2f_tmp);
+
+ prof_conv("nk_conv0", &ctx->nk_conv[0], feat_n2, h2, w2, cur, im2col);
+ {
+ double t0 = now();
+ nn2_concat(cur, 64, save_n3, 128, h3, w3, nxt);
+ prof_add("concat3", (now()-t0)*1000.0);
+ SWAP();
+ }
+
+ float* feat_n4 = save_p4;
+ prof_c2f("nk_c2f2", &ctx->nk_c2f[2], cur, h3, w3, feat_n4, im2col, c2f_tmp);
+
+ prof_conv("nk_conv1", &ctx->nk_conv[1], feat_n4, h3, w3, cur, im2col);
+ {
+ double t0 = now();
+ nn2_concat(cur, 128, save_p5, 256, h4, w4, nxt);
+ prof_add("concat4", (now()-t0)*1000.0);
+ SWAP();
+ }
+
+ float* feat_n5 = save_p5;
+ prof_c2f("nk_c2f3", &ctx->nk_c2f[3], cur, h4, w4, feat_n5, im2col, c2f_tmp);
+
+ /* Head */
+ float* feats[3] = {feat_n2, feat_n4, feat_n5};
+ int feat_h[] = {h2, h3, h4};
+ int feat_w[] = {w2, w3, w4};
+ for (int s = 0; s < 3; s++) {
+ char name[32];
+ float* tmp = c2f_tmp;
+ int fh = feat_h[s], fw = feat_w[s], sp = fh*fw;
+
+ sprintf(name, "head%d_bbox0", s);
+ prof_conv(name, &ctx->head[s].bbox[0], feats[s], fh, fw, tmp, im2col);
+ sprintf(name, "head%d_bbox1", s);
+ prof_conv(name, &ctx->head[s].bbox[1], tmp, fh, fw, tmp+ctx->head[s].bbox[0].cout*sp, im2col);
+ sprintf(name, "head%d_bbox2", s);
+ prof_conv(name, &ctx->head[s].bbox[2], tmp+ctx->head[s].bbox[0].cout*sp, fh, fw,
+ tmp+ctx->head[s].bbox[0].cout*sp+ctx->head[s].bbox[1].cout*sp, im2col);
+
+ float* cx = tmp + ctx->head[s].bbox[0].cout*sp + ctx->head[s].bbox[1].cout*sp + 64*sp;
+ sprintf(name, "head%d_cls0", s);
+ prof_conv(name, &ctx->head[s].cls[0], feats[s], fh, fw, cx, im2col);
+ sprintf(name, "head%d_cls1", s);
+ prof_conv(name, &ctx->head[s].cls[1], cx, fh, fw, cx + ctx->head[s].cls[0].cout*sp, im2col);
+ sprintf(name, "head%d_cls2", s);
+ prof_conv(name, &ctx->head[s].cls[2], cx + ctx->head[s].cls[0].cout*sp, fh, fw,
+ cx + ctx->head[s].cls[0].cout*sp + ctx->head[s].cls[1].cout*sp, im2col);
+ }
+ #undef SWAP
+ }
+
+ /* Print results sorted by time */
+ printf("=== YOLOv8n@%d Per-Layer Profile (%d runs) ===\n\n", S, RUNS);
+ printf("%-30s %8s %8s %6s\n", "Layer", "Total ms", "Avg ms", "%%");
+
+ double total = 0;
+ for (int i = 0; i < g_nprof; i++) total += g_prof[i].total_ms;
+
+ /* Bubble sort by total_ms desc */
+ for (int i = 0; i < g_nprof - 1; i++)
+ for (int j = i + 1; j < g_nprof; j++)
+ if (g_prof[j].total_ms > g_prof[i].total_ms) {
+ typeof(g_prof[0]) tmp = g_prof[i];
+ g_prof[i] = g_prof[j]; g_prof[j] = tmp;
+ }
+
+ for (int i = 0; i < g_nprof; i++) {
+ double avg = g_prof[i].total_ms / g_prof[i].calls;
+ double pct = 100.0 * g_prof[i].total_ms / total;
+ if (pct < 0.5) continue; /* skip tiny layers */
+ printf("%-30s %8.2f %8.3f %5.1f%%\n",
+ g_prof[i].name, g_prof[i].total_ms, avg, pct);
+ }
+ printf("%-30s %8.2f\n", "TOTAL", total);
+ printf("\nPer-inference: %.2f ms\n", total / RUNS);
+
+ free(input);
+ nn2_free(ctx);
+ return 0;
+}
diff --git a/nn2/src/bench_sparse.c b/nn2/src/bench_sparse.c
new file mode 100644
index 0000000..f2ec569
--- /dev/null
+++ b/nn2/src/bench_sparse.c
@@ -0,0 +1,73 @@
+#include "nn2_internal.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#ifdef _WIN32
+#include <windows.h>
+static double now(void){LARGE_INTEGER f,c;QueryPerformanceFrequency(&f);QueryPerformanceCounter(&c);return(double)c.QuadPart/f.QuadPart*1000.0;}
+#endif
+
+/* Forward declarations from gemm_sparse_int8.c */
+typedef struct SparseINT8Weights SparseINT8Weights;
+SparseINT8Weights* nn2_sparse_int8_pack(const int8_t* w, int K, int N, int32_t* cs);
+void nn2_sparse_int8_free(SparseINT8Weights* sw);
+#ifdef __AVX512VNNI__
+void nn2_sparse_int8_gemm(const int8_t* A, int M, int K,
+ const SparseINT8Weights* sw, const int32_t* cs,
+ const float* ws, const float* bias, float as, int act, float* out);
+#endif
+
+int main(void){
+ srand(42);
+ nn2_tp_init(6);
+ printf("=== Sparse INT8 VNNI vs Dense FP32 (6 threads) ===\n\n");
+
+ /* Test: 1x1 conv equivalent M=spatial, K=Cin, N=Cout */
+ struct{const char*name;int M,K,N;} tests[]={
+ {"C2f 1x1 @160x160 (32->32)", 25600, 32, 32},
+ {"C2f 1x1 @80x80 (64->64)", 6400, 64, 64},
+ {"Head 1x1 @40x40 (128->80)", 1600,128, 80},
+ };
+
+ for(float sparsity=0.0f; sparsity<=0.9f; sparsity+=0.25f){
+ printf("--- Sparsity: %.0f%% ---\n", sparsity*100);
+ for(int t=0;t<3;t++){
+ int M=tests[t].M, K=tests[t].K, N=tests[t].N;
+ double ops=2.0*M*K*N;
+
+ /* Dense FP32 */
+ float*fw=(float*)calloc(N*K,4);float*fi=(float*)calloc(K*M,4);
+ float*fo=(float*)malloc(N*M*4);
+ double t0=now();int R=30;
+ for(int r=0;r<R;r++)nn2_sgemm(N,K,M,fw,K,fi,M,fo,M);
+ double fp32=( now()-t0)/R;
+
+ /* Sparse INT8 */
+ int8_t*iw=(int8_t*)malloc(N*K);
+ for(int i=0;i<N*K;i++)
+ iw[i]=(rand()%100<(int)(sparsity*100))?0:(int8_t)(rand()%20-10);
+ int32_t*cs=(int32_t*)calloc(N,4);
+ SparseINT8Weights*sw=nn2_sparse_int8_pack(iw,K,N,cs);
+ float*ws=(float*)malloc(N*4);float*bi=(float*)calloc(N,4);
+ for(int i=0;i<N;i++)ws[i]=0.01f;
+ int8_t*ia=(int8_t*)calloc(M*K,1);
+
+#ifdef __AVX512VNNI__
+ /* Warmup */
+ nn2_sparse_int8_gemm(ia,M,K,sw,cs,ws,bi,0.05f,0,fo);
+ t0=now();
+ for(int r=0;r<R;r++)
+ nn2_sparse_int8_gemm(ia,M,K,sw,cs,ws,bi,0.05f,0,fo);
+ double sint8=(now()-t0)/R;
+ printf(" %-30s FP32:%5.2fms SparseINT8:%5.2fms = %.1fx\n",
+ tests[t].name,fp32,sint8,fp32/sint8);
+#else
+ printf(" %-30s FP32:%5.2fms (no VNNI)\n",tests[t].name,fp32);
+#endif
+ free(fw);free(fi);free(fo);free(iw);free(cs);free(ws);free(bi);free(ia);
+ nn2_sparse_int8_free(sw);
+ }
+ }
+ nn2_tp_destroy();return 0;
+}
diff --git a/nn2/src/bench_tc.c b/nn2/src/bench_tc.c
new file mode 100644
index 0000000..2ea7df3
--- /dev/null
+++ b/nn2/src/bench_tc.c
@@ -0,0 +1,8 @@
+#include "nn2_internal.h"
+#include <stdio.h>
+void nn2_tc_print_info(int input_size);
+int main(void) {
+ nn2_tc_print_info(320);
+ nn2_tc_print_info(640);
+ return 0;
+}
diff --git a/nn2/src/bench_tune.c b/nn2/src/bench_tune.c
new file mode 100644
index 0000000..abd46d1
--- /dev/null
+++ b/nn2/src/bench_tune.c
@@ -0,0 +1,31 @@
+#include "nn2_internal.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef _WIN32
+#include <windows.h>
+static double now(void){LARGE_INTEGER f,c;QueryPerformanceFrequency(&f);QueryPerformanceCounter(&c);return(double)c.QuadPart/f.QuadPart*1000.0;}
+#endif
+int main(void){
+ /* Test the bottleneck: conv 16->16, 3x3 s=1 @80x80 (at 320 input) */
+ float*in=(float*)calloc(16*80*80,4);
+ float*out=(float*)malloc(16*80*80*4);
+ float*col=(float*)malloc(144*6400*4);
+ float*w=(float*)calloc(16*144,4);
+ float bias[16]={0};
+ ConvLayer L={w,bias,NULL,NULL,NULL,NULL,0,0, 16,16,3,1,1,1};
+
+ for(int t=1;t<=6;t++){
+ nn2_tp_init(t);
+ double t0=now();int R=100;
+ for(int r=0;r<R;r++) nn2_conv2d(&L,in,80,80,out,col);
+ double ms=(now()-t0)/R;
+ printf("conv 16->16 3x3 @80x80: %dt = %.2f ms\n",t,ms);
+ nn2_tp_destroy();
+ }
+
+ /* Also test full forward at 320 */
+ printf("\n");
+ free(in);free(out);free(col);
+ return 0;
+}
diff --git a/nn2/src/conv.c b/nn2/src/conv.c
new file mode 100644
index 0000000..36f4d45
--- /dev/null
+++ b/nn2/src/conv.c
@@ -0,0 +1,531 @@
+/*
+ * conv.c — Convolution operators.
+ *
+ * im2col + GEMM for 3x3 conv. Direct GEMM for 1x1 conv.
+ * Fused bias + SiLU with AVX2 fast sigmoid approximation.
+ */
+
+#include "nn2_internal.h"
+#include <string.h>
+#include <math.h>
+
+#ifdef __AVX2__
+#include <immintrin.h>
+#endif
+
+/* ============ Parallel im2col helpers ============ */
+
+typedef struct { const float* in; float* col; int C,H,W,Hout,Wout,spatial; } Im2colS2Ctx;
+
+static void im2col_s2_worker(void* arg, int start, int end) {
+ Im2colS2Ctx* x = (Im2colS2Ctx*)arg;
+ for (int row = start; row < end; row++) {
+ int c = row / 9, rem = row % 9;
+ int kh = rem / 3, kw = rem % 3;
+ const float* src = x->in + c * x->H * x->W;
+ float* dst = x->col + row * x->spatial;
+ int iw_off = kw - 1;
+ for (int oh = 0; oh < x->Hout; oh++) {
+ int ih = oh * 2 - 1 + kh;
+ float* drow = dst + oh * x->Wout;
+ if (ih < 0 || ih >= x->H) {
+ memset(drow, 0, x->Wout * sizeof(float));
+ continue;
+ }
+ const float* srow = src + ih * x->W;
+ int ow_start = 0, ow_end = x->Wout;
+ if (iw_off == -1) { drow[0] = 0.0f; ow_start = 1; }
+ int last_iw = (ow_end - 1) * 2 + iw_off;
+ if (last_iw >= x->W) { drow[ow_end - 1] = 0.0f; ow_end--; }
+ int ow = ow_start;
+#ifdef __AVX2__
+ __m256i vidx = _mm256_setr_epi32(0,2,4,6,8,10,12,14);
+ for (; ow + 8 <= ow_end; ow += 8) {
+ __m256 g = _mm256_i32gather_ps(srow + ow*2 + iw_off, vidx, 4);
+ _mm256_storeu_ps(drow + ow, g);
+ }
+#endif
+ for (; ow < ow_end; ow++)
+ drow[ow] = srow[ow * 2 + iw_off];
+ }
+ }
+}
+
+typedef struct { const float* in; float* col; int C,H,W; } Im2colS1Ctx;
+
+static void im2col_s1_worker(void* arg, int start, int end) {
+ Im2colS1Ctx* x = (Im2colS1Ctx*)arg;
+ int H = x->H, W = x->W;
+ int spatial = H * W;
+ for (int row = start; row < end; row++) {
+ int c = row / 9, rem = row % 9;
+ int kh = rem / 3, kw = rem % 3;
+ const float* src = x->in + c * H * W;
+ float* dst = x->col + row * spatial;
+ int ih_base = kh - 1;
+ for (int oh = 0; oh < H; oh++) {
+ int ih = oh + ih_base;
+ if (ih < 0 || ih >= H) {
+ memset(dst + oh * W, 0, W * sizeof(float));
+ continue;
+ }
+ const float* srow = src + ih * W;
+ float* drow = dst + oh * W;
+ if (kw == 0) {
+ drow[0] = 0.0f;
+ memcpy(drow + 1, srow, (W - 1) * sizeof(float));
+ } else if (kw == 1) {
+ memcpy(drow, srow, W * sizeof(float));
+ } else {
+ memcpy(drow, srow + 1, (W - 1) * sizeof(float));
+ drow[W - 1] = 0.0f;
+ }
+ }
+ }
+}
+
+/* ============ im2col ============ */
+
+void nn2_im2col(const float* in, int C, int H, int W,
+ int kH, int kW, int stride, int pad,
+ float* col)
+{
+ int Hout = (H + 2 * pad - kH) / stride + 1;
+ int Wout = (W + 2 * pad - kW) / stride + 1;
+ int spatial = Hout * Wout;
+
+ /* Fast path: 3x3, stride 1, pad 1 — parallel across im2col rows */
+ if (kH == 3 && kW == 3 && stride == 1 && pad == 1) {
+ Im2colS1Ctx ctx = {in, col, C, H, W};
+ int total_rows = C * 9;
+ if (total_rows >= 36 && spatial >= 400) /* parallel only for large enough */
+ nn2_tp_parallel_for(im2col_s1_worker, &ctx, total_rows, 9);
+ else
+ im2col_s1_worker(&ctx, 0, total_rows);
+ return;
+ }
+
+ /* Fast path: 3x3, stride 2, pad 1 — parallel across im2col rows */
+ if (kH == 3 && kW == 3 && stride == 2 && pad == 1) {
+ Im2colS2Ctx ctx = {in, col, C, H, W, Hout, Wout, spatial};
+ int total_rows = C * 9;
+ if (total_rows >= 36 && spatial >= 200) /* parallel only for large enough */
+ nn2_tp_parallel_for(im2col_s2_worker, &ctx, total_rows, 9);
+ else
+ im2col_s2_worker(&ctx, 0, total_rows);
+ return;
+ }
+
+ /* Generic fallback */
+ for (int c = 0; c < C; c++) {
+ for (int kh = 0; kh < kH; kh++) {
+ for (int kw = 0; kw < kW; kw++) {
+ int col_row = (c * kH + kh) * kW + kw;
+ float* dst = col + col_row * spatial;
+ for (int oh = 0; oh < Hout; oh++) {
+ int ih = oh * stride - pad + kh;
+ for (int ow = 0; ow < Wout; ow++) {
+ int iw = ow * stride - pad + kw;
+ *dst++ = (ih >= 0 && ih < H && iw >= 0 && iw < W)
+ ? in[c * H * W + ih * W + iw] : 0.0f;
+ }
+ }
+ }
+ }
+ }
+}
+
+/* ============ Fused bias + activation ============ */
+
+#ifdef __AVX512F__
+#include "fast_exp.h"
+static inline __m512 fast_silu_avx512(__m512 x) { return _mm512_silu_fast(x); }
+static inline __m512 fast_sigmoid_avx512(__m512 x) { return _mm512_sigmoid_fast(x); }
+#endif
+
+#ifdef __AVX2__
+static inline __m256 fast_sigmoid_avx2(__m256 x)
+{
+ __m256 half = _mm256_set1_ps(0.5f);
+ __m256 z = _mm256_mul_ps(x, half);
+ __m256 z2 = _mm256_mul_ps(z, z);
+ __m256 v27 = _mm256_set1_ps(27.0f);
+ __m256 num = _mm256_mul_ps(z, _mm256_add_ps(v27, z2));
+ __m256 den = _mm256_add_ps(v27, _mm256_mul_ps(_mm256_set1_ps(9.0f), z2));
+ __m256 t = _mm256_div_ps(num, den);
+ return _mm256_fmadd_ps(half, t, half);
+}
+static inline __m256 fast_silu_avx2(__m256 x)
+{
+ return _mm256_mul_ps(x, fast_sigmoid_avx2(x));
+}
+
+#endif /* __AVX2__ */
+
+static void apply_bias_act(float* out, const float* bias, int cout, int spatial,
+ int act)
+{
+ for (int co = 0; co < cout; co++) {
+ float b = bias[co];
+ float* row = out + co * spatial;
+ int i = 0;
+
+#ifdef __AVX512F__
+ __m512 vb512 = _mm512_set1_ps(b);
+ if (act == 1) {
+ for (; i + 16 <= spatial; i += 16) {
+ __m512 vx = _mm512_add_ps(_mm512_loadu_ps(row + i), vb512);
+ _mm512_storeu_ps(row + i, fast_silu_avx512(vx));
+ }
+ } else if (act == 2) {
+ for (; i + 16 <= spatial; i += 16) {
+ __m512 vx = _mm512_add_ps(_mm512_loadu_ps(row + i), vb512);
+ _mm512_storeu_ps(row + i, fast_sigmoid_avx512(vx));
+ }
+ } else {
+ for (; i + 16 <= spatial; i += 16)
+ _mm512_storeu_ps(row + i, _mm512_add_ps(_mm512_loadu_ps(row + i), vb512));
+ }
+#endif
+#ifdef __AVX2__
+ __m256 vb = _mm256_set1_ps(b);
+ if (act == 1) {
+ for (; i + 8 <= spatial; i += 8) {
+ __m256 vx = _mm256_add_ps(_mm256_loadu_ps(row + i), vb);
+ _mm256_storeu_ps(row + i, fast_silu_avx2(vx));
+ }
+ } else if (act == 2) {
+ for (; i + 8 <= spatial; i += 8) {
+ __m256 vx = _mm256_add_ps(_mm256_loadu_ps(row + i), vb);
+ _mm256_storeu_ps(row + i, fast_sigmoid_avx2(vx));
+ }
+ } else {
+ for (; i + 8 <= spatial; i += 8)
+ _mm256_storeu_ps(row + i, _mm256_add_ps(_mm256_loadu_ps(row + i), vb));
+ }
+#endif
+ for (; i < spatial; i++) {
+ float x = row[i] + b;
+ if (act == 1) {
+ float s = 1.0f / (1.0f + expf(-x));
+ x = x * s;
+ } else if (act == 2) {
+ x = 1.0f / (1.0f + expf(-x));
+ }
+ row[i] = x;
+ }
+ }
+}
+
+/* ============ Direct conv for small Cin (avoids im2col overhead) ============ */
+
+#ifdef __AVX2__
+static void direct_conv3x3_s2(const ConvLayer* L, const float* in, int H, int W,
+ float* out)
+{
+ int Hout = (H + 1) / 2; /* (H + 2*1 - 3)/2 + 1 = H/2 */
+ int Wout = (W + 1) / 2;
+ int spatial = Hout * Wout;
+
+ /* For each output channel, accumulate over cin×3×3 */
+ for (int co = 0; co < L->cout; co++) {
+ float* dst = out + co * spatial;
+ const float* wt = L->w + co * L->cin * 9; /* [cin*9] */
+
+ /* Initialize with bias */
+ float b = L->b[co];
+ int i = 0;
+ __m256 vb = _mm256_set1_ps(b);
+ for (; i + 8 <= spatial; i += 8)
+ _mm256_storeu_ps(dst + i, vb);
+ for (; i < spatial; i++)
+ dst[i] = b;
+
+ for (int ci = 0; ci < L->cin; ci++) {
+ const float* src = in + ci * H * W;
+ const float* w = wt + ci * 9;
+
+ for (int kh = 0; kh < 3; kh++) {
+ for (int kw = 0; kw < 3; kw++) {
+ float wv = w[kh * 3 + kw];
+ if (wv == 0.0f) continue;
+ __m256 vw = _mm256_set1_ps(wv);
+
+ for (int oh = 0; oh < Hout; oh++) {
+ int ih = oh * 2 - 1 + kh;
+ if (ih < 0 || ih >= H) continue;
+ const float* srow = src + ih * W;
+ float* drow = dst + oh * Wout;
+ int iw_off = kw - 1;
+
+ int ow = 0;
+ /* Handle left boundary */
+ if (iw_off < 0) { ow = 1; } /* skip ow=0 (padding) */
+ /* Handle right boundary */
+ int ow_end = Wout;
+ if ((ow_end - 1) * 2 + iw_off >= W) ow_end--;
+
+ /* AVX2 gather path */
+ __m256i vidx = _mm256_setr_epi32(0,2,4,6,8,10,12,14);
+ for (; ow + 8 <= ow_end; ow += 8) {
+ int biw = ow * 2 + iw_off;
+ __m256 sv = _mm256_i32gather_ps(srow + biw, vidx, 4);
+ __m256 dv = _mm256_loadu_ps(drow + ow);
+ _mm256_storeu_ps(drow + ow, _mm256_fmadd_ps(vw, sv, dv));
+ }
+ for (; ow < ow_end; ow++) {
+ drow[ow] += wv * srow[ow * 2 + iw_off];
+ }
+ }
+ }
+ }
+ }
+
+ /* Apply activation (SiLU) */
+ if (L->act == 1) {
+ i = 0;
+ for (; i + 8 <= spatial; i += 8) {
+ __m256 vx = _mm256_loadu_ps(dst + i);
+ _mm256_storeu_ps(dst + i, fast_silu_avx2(vx));
+ }
+ for (; i < spatial; i++) {
+ float x = dst[i];
+ dst[i] = x / (1.0f + expf(-x));
+ }
+ }
+ }
+}
+#endif
+
+/* ============ Winograd F(2,3) for 3x3 stride-1 conv ============
+ *
+ * Reduces multiplications by 2.25x: 9→4 per output element.
+ * Input transform: V = B^T × d × B (4×4 tile → 16 values)
+ * Filter transform: U = G × g × G^T (3×3 → 16 values, pre-computed)
+ * Output transform: y = A^T × m × A (4×4 → 2×2 output)
+ * Core: 16 independent GEMMs of [Cout,Cin] × [Cin,tiles]
+ */
+
+/* Pre-transform filter weights for Winograd */
+void nn2_prepare_winograd(ConvLayer* L)
+{
+ if (L->k != 3 || L->stride != 1 || L->pad != 1) return;
+ /* U[16][cout][cin] */
+ int co = L->cout, ci = L->cin;
+ L->w_wino = (float*)malloc(16 * co * ci * sizeof(float));
+ if (!L->w_wino) return;
+
+ for (int oc = 0; oc < co; oc++) {
+ for (int ic = 0; ic < ci; ic++) {
+ const float* g = L->w + oc * ci * 9 + ic * 9; /* 3×3 filter */
+ /* G × g (4×3) */
+ float t[4][3];
+ t[0][0] = g[0]; t[0][1] = g[1]; t[0][2] = g[2];
+ t[1][0] = (g[0]+g[3]+g[6])*0.5f; t[1][1] = (g[1]+g[4]+g[7])*0.5f; t[1][2] = (g[2]+g[5]+g[8])*0.5f;
+ t[2][0] = (g[0]-g[3]+g[6])*0.5f; t[2][1] = (g[1]-g[4]+g[7])*0.5f; t[2][2] = (g[2]-g[5]+g[8])*0.5f;
+ t[3][0] = g[6]; t[3][1] = g[7]; t[3][2] = g[8];
+ /* × G^T → U[4][4] */
+ float U[16];
+ for (int i = 0; i < 4; i++) {
+ U[i*4+0] = t[i][0];
+ U[i*4+1] = (t[i][0]+t[i][1]+t[i][2])*0.5f;
+ U[i*4+2] = (t[i][0]-t[i][1]+t[i][2])*0.5f;
+ U[i*4+3] = t[i][2];
+ }
+ /* Store as [16][co][ci]: component-major for GEMM batching */
+ for (int a = 0; a < 16; a++)
+ L->w_wino[a * co * ci + oc * ci + ic] = U[a];
+ }
+ }
+}
+
+static void winograd_conv3x3(const ConvLayer* L, const float* in, int H, int W,
+ float* out, float* work)
+{
+ int Hout = H, Wout = W; /* stride=1, pad=1 */
+ int h_tiles = (Hout + 1) / 2;
+ int w_tiles = (Wout + 1) / 2;
+ int n_tiles = h_tiles * w_tiles;
+ int ci = L->cin, co = L->cout;
+
+ /* work layout: V[16][ci][tiles] + M[16][co][tiles] */
+ float* V = work;
+ float* M = V + 16 * ci * n_tiles;
+
+ /* 1. Input transform: for each channel, extract tiles and transform */
+ for (int c = 0; c < ci; c++) {
+ const float* src = in + c * H * W;
+ for (int th = 0; th < h_tiles; th++) {
+ for (int tw = 0; tw < w_tiles; tw++) {
+ int tile_idx = th * w_tiles + tw;
+ int oh = th * 2, ow = tw * 2;
+
+ /* Extract 4×4 tile with padding */
+ float d[4][4];
+ for (int i = 0; i < 4; i++) {
+ int ih = oh - 1 + i; /* pad=1 */
+ for (int j = 0; j < 4; j++) {
+ int iw = ow - 1 + j;
+ d[i][j] = (ih >= 0 && ih < H && iw >= 0 && iw < W)
+ ? src[ih * W + iw] : 0.0f;
+ }
+ }
+
+ /* B^T × d (rows) */
+ float t[4][4];
+ for (int j = 0; j < 4; j++) {
+ t[0][j] = d[0][j] - d[2][j];
+ t[1][j] = d[1][j] + d[2][j];
+ t[2][j] = -d[1][j] + d[2][j];
+ t[3][j] = d[1][j] - d[3][j];
+ }
+ /* × B (cols) → V components */
+ for (int i = 0; i < 4; i++) {
+ float v0 = t[i][0] - t[i][2];
+ float v1 = t[i][1] + t[i][2];
+ float v2 = -t[i][1] + t[i][2];
+ float v3 = t[i][1] - t[i][3];
+ V[(i*4+0) * ci * n_tiles + c * n_tiles + tile_idx] = v0;
+ V[(i*4+1) * ci * n_tiles + c * n_tiles + tile_idx] = v1;
+ V[(i*4+2) * ci * n_tiles + c * n_tiles + tile_idx] = v2;
+ V[(i*4+3) * ci * n_tiles + c * n_tiles + tile_idx] = v3;
+ }
+ }
+ }
+ }
+
+ /* 2. Batched GEMM: M_a = U_a × V_a for each of 16 components */
+ for (int a = 0; a < 16; a++) {
+ const float* Ua = L->w_wino + a * co * ci; /* [co, ci] */
+ const float* Va = V + a * ci * n_tiles; /* [ci, tiles] */
+ float* Ma = M + a * co * n_tiles; /* [co, tiles] */
+ nn2_sgemm(co, ci, n_tiles, Ua, ci, Va, n_tiles, Ma, n_tiles);
+ }
+
+ /* 3. Output transform + bias + activation */
+ for (int oc = 0; oc < co; oc++) {
+ float bias = L->b[oc];
+ for (int th = 0; th < h_tiles; th++) {
+ for (int tw = 0; tw < w_tiles; tw++) {
+ int tile_idx = th * w_tiles + tw;
+ int oh = th * 2, ow = tw * 2;
+
+ /* Gather M[4][4] for this tile */
+ float m[4][4];
+ for (int i = 0; i < 4; i++)
+ for (int j = 0; j < 4; j++)
+ m[i][j] = M[(i*4+j) * co * n_tiles + oc * n_tiles + tile_idx];
+
+ /* A^T × m (rows) */
+ float t[2][4];
+ for (int j = 0; j < 4; j++) {
+ t[0][j] = m[0][j] + m[1][j] + m[2][j];
+ t[1][j] = m[1][j] - m[2][j] - m[3][j];
+ }
+ /* × A (cols) → 2×2 output */
+ float y00 = t[0][0] + t[0][1] + t[0][2] + bias;
+ float y01 = t[0][1] - t[0][2] - t[0][3] + bias;
+ float y10 = t[1][0] + t[1][1] + t[1][2] + bias;
+ float y11 = t[1][1] - t[1][2] - t[1][3] + bias;
+
+ /* Activation */
+ if (L->act == 1) { /* SiLU */
+ #define SILU(x) ((x) / (1.0f + expf(-(x))))
+ y00 = SILU(y00); y01 = SILU(y01);
+ y10 = SILU(y10); y11 = SILU(y11);
+ #undef SILU
+ }
+
+ /* Write to output (handle boundary for odd H/W) */
+ float* dst = out + oc * Hout * Wout;
+ if (oh < Hout && ow < Wout) dst[oh * Wout + ow] = y00;
+ if (oh < Hout && ow+1 < Wout) dst[oh * Wout + ow + 1] = y01;
+ if (oh+1 < Hout && ow < Wout) dst[(oh+1) * Wout + ow] = y10;
+ if (oh+1 < Hout && ow+1 < Wout) dst[(oh+1) * Wout + ow + 1] = y11;
+ }
+ }
+ }
+}
+
+/* ============ Conv2d ============ */
+
+void nn2_conv2d(const ConvLayer* L, const float* in, int H, int W,
+ float* out, float* col_buf)
+{
+ int Hout = (H + 2 * L->pad - L->k) / L->stride + 1;
+ int Wout = (W + 2 * L->pad - L->k) / L->stride + 1;
+ int spatial = Hout * Wout;
+
+ if (L->k == 1 && L->stride == 1 && L->pad == 0) {
+ /* INT8 path for pointwise conv (if quantized weights available) */
+ if (L->w_int8_packed) {
+ /* Quantize input FP32 → INT8 */
+ int n_in = L->cin * spatial;
+ int8_t* a_int8 = (int8_t*)col_buf; /* borrow col_buf for quantized input */
+ float inv_scale = 1.0f / L->act_in_scale;
+ for (int i = 0; i < n_in; i++) {
+ int v = (int)(in[i] * inv_scale + 0.5f);
+ a_int8[i] = (int8_t)(v < -128 ? -128 : v > 127 ? 127 : v);
+ }
+ nn2_int8_gemm_fused(a_int8, L->cout, L->cin, spatial,
+ L->w_int8_packed, L->col_sums,
+ L->w_scales, L->b,
+ L->act_in_scale, L->act_out_scale,
+ L->act, out);
+ return;
+ }
+ /* Fused GEMM+bias+activation — use packed weights if available */
+ if (L->w_packed) {
+ nn2_sgemm_bias_act_packed(L->cout, L->cin, spatial,
+ L->w_packed, in,
+ out, spatial, L->b, L->act);
+ } else {
+ nn2_sgemm_bias_act(L->cout, L->cin, spatial,
+ L->w, L->cin, in, spatial,
+ out, spatial, L->b, L->act);
+ }
+ return;
+ }
+
+ int K_gemm = L->cin * L->k * L->k;
+
+ /* Winograd F(2,3) for 3x3 stride-1 — 2.25x fewer multiplications.
+ * Wins on single-thread (fewer FLOPs). Loses on multi-thread (16 small GEMMs
+ * can't parallelize as well as one large GEMM). */
+#ifdef __AVX512F__
+ /* Implicit im2col: skip the im2col buffer entirely.
+ * Load input on-the-fly during GEMM. Saves 2× memory traffic. */
+ /* Implicit im2col: best for small Cin (K=Cin*9 small → few iterations per tile).
+ * For large Cin (K>200), regular im2col+GEMM wins due to tighter inner loop. */
+ if (L->k == 3 && L->stride == 1 && L->pad == 1
+ && L->w_packed && spatial >= 2500) {
+ /* Implicit im2col: no buffer, loads input on-the-fly.
+ * Wins when im2col buffer (K×spatial×4B) would thrash L2.
+ * Threshold 2500 = ~50×50 minimum (avoids edge-case issues at very small sizes). */
+ nn2_conv3x3_s1_implicit(in, L->w, L->b, L->cin, L->cout, H, W, L->act, out, L->w_packed);
+ return;
+ }
+#endif
+ if (L->w_wino && L->k == 3 && L->stride == 1 && L->pad == 1
+ && nn2_tp_num_threads() <= 2) {
+ /* workspace: 16*(Cin+Cout)*tiles floats. Use col_buf. */
+ int tiles = ((Hout+1)/2) * ((Wout+1)/2);
+ /* Check col_buf is large enough: need 16*(cin+cout)*tiles */
+ nn2_winograd_conv3x3(in, L->cin, H, W, L->w_wino, L->b, L->cout, L->act,
+ out, col_buf);
+ return;
+ }
+
+ /* Standard im2col + fused GEMM (with packed weights if available) */
+ nn2_im2col(in, L->cin, H, W, L->k, L->k, L->stride, L->pad, col_buf);
+ if (L->w_packed) {
+ nn2_sgemm_bias_act_packed(L->cout, K_gemm, spatial,
+ L->w_packed, col_buf,
+ out, spatial, L->b, L->act);
+ } else {
+ nn2_sgemm_bias_act(L->cout, K_gemm, spatial,
+ L->w, K_gemm, col_buf, spatial,
+ out, spatial, L->b, L->act);
+ }
+}
+
diff --git a/nn2/src/conv_fused.c b/nn2/src/conv_fused.c
new file mode 100644
index 0000000..482debe
--- /dev/null
+++ b/nn2/src/conv_fused.c
@@ -0,0 +1,225 @@
+/*
+ * conv_fused.c — Fused im2col+GEMM for 3x3 convolutions.
+ *
+ * Instead of materializing the full im2col matrix (15+ MB for early layers),
+ * load input elements directly during GEMM computation.
+ *
+ * For stride-1: consecutive output positions → contiguous input loads.
+ * For stride-2: consecutive output positions → stride-2 input loads (gather).
+ *
+ * Processes MR=6 output channels × 16 output positions per microkernel.
+ */
+
+#include "nn2_internal.h"
+#include <string.h>
+#include <math.h>
+
+#ifdef __AVX2__
+#include <immintrin.h>
+
+/* Fast SiLU from conv.c */
+static inline __m256 _fast_sigmoid(__m256 x)
+{
+ __m256 half = _mm256_set1_ps(0.5f);
+ __m256 one = _mm256_set1_ps(1.0f);
+ __m256 ax = _mm256_andnot_ps(_mm256_set1_ps(-0.0f), x);
+ return _mm256_fmadd_ps(half, _mm256_div_ps(x, _mm256_add_ps(one, ax)), half);
+}
+static inline __m256 _fast_silu(__m256 x)
+{
+ return _mm256_mul_ps(x, _fast_sigmoid(x));
+}
+
+/* ============ Fused 3x3 stride-1 pad-1 ============ */
+
+void nn2_conv3x3_s1_fused(const ConvLayer* L, const float* in, int H, int W,
+ float* out)
+{
+ int co = L->cout, ci = L->cin;
+ /* Process MR=6 output channels at a time */
+ for (int oc0 = 0; oc0 < co; oc0 += NN2_MR) {
+ int mr = (oc0 + NN2_MR <= co) ? NN2_MR : co - oc0;
+
+ for (int oh = 0; oh < H; oh++) {
+ for (int ow = 0; ow < W; ow += 16) {
+ int nr = (ow + 16 <= W) ? 16 : W - ow;
+
+ /* Accumulators: mr × 2 YMM (16 output cols) */
+ __m256 c0_lo = _mm256_setzero_ps(), c0_hi = _mm256_setzero_ps();
+ __m256 c1_lo = _mm256_setzero_ps(), c1_hi = _mm256_setzero_ps();
+ __m256 c2_lo = _mm256_setzero_ps(), c2_hi = _mm256_setzero_ps();
+ __m256 c3_lo = _mm256_setzero_ps(), c3_hi = _mm256_setzero_ps();
+ __m256 c4_lo = _mm256_setzero_ps(), c4_hi = _mm256_setzero_ps();
+ __m256 c5_lo = _mm256_setzero_ps(), c5_hi = _mm256_setzero_ps();
+
+ /* Accumulate over input channels and kernel positions */
+ for (int ic = 0; ic < ci; ic++) {
+ const float* src = in + ic * H * W;
+
+ for (int kh = 0; kh < 3; kh++) {
+ int ih = oh - 1 + kh;
+ if (ih < 0 || ih >= H) continue;
+ const float* srow = src + ih * W;
+
+ for (int kw = 0; kw < 3; kw++) {
+ int iw = ow - 1 + kw;
+
+ /* Load 16 input values.
+ * For interior positions (1 ≤ ow ≤ W-17, kw=1):
+ * just load contiguous. Handle edges with scalar. */
+ __m256 v_lo, v_hi;
+
+ if (iw >= 0 && iw + 16 <= W && nr == 16) {
+ /* Fast path: all 16 values in bounds */
+ v_lo = _mm256_loadu_ps(srow + iw);
+ v_hi = _mm256_loadu_ps(srow + iw + 8);
+ } else {
+ /* Edge: load with bounds checking */
+ float tmp[16] = {0};
+ for (int j = 0; j < nr; j++) {
+ int iw_j = iw + j;
+ if (iw_j >= 0 && iw_j < W)
+ tmp[j] = srow[iw_j];
+ }
+ v_lo = _mm256_loadu_ps(tmp);
+ v_hi = _mm256_loadu_ps(tmp + 8);
+ }
+
+ /* Multiply-accumulate for each output channel */
+ int woff = ic * 9 + kh * 3 + kw;
+ #define FMA_OC(i, lo, hi) if (i < mr) { \
+ __m256 vw = _mm256_broadcast_ss(&L->w[(oc0+(i))*ci*9 + woff]); \
+ lo = _mm256_fmadd_ps(vw, v_lo, lo); \
+ hi = _mm256_fmadd_ps(vw, v_hi, hi); \
+ }
+ FMA_OC(0, c0_lo, c0_hi);
+ FMA_OC(1, c1_lo, c1_hi);
+ FMA_OC(2, c2_lo, c2_hi);
+ FMA_OC(3, c3_lo, c3_hi);
+ FMA_OC(4, c4_lo, c4_hi);
+ FMA_OC(5, c5_lo, c5_hi);
+ #undef FMA_OC
+ }
+ }
+ }
+
+ /* Add bias + activation + store */
+ #define FINISH_OC(i, lo, hi) if (i < mr) { \
+ __m256 vb = _mm256_broadcast_ss(&L->b[oc0+(i)]); \
+ lo = _mm256_add_ps(lo, vb); \
+ hi = _mm256_add_ps(hi, vb); \
+ if (L->act == 1) { lo = _fast_silu(lo); hi = _fast_silu(hi); } \
+ float* dst = out + (oc0+(i)) * H * W + oh * W + ow; \
+ if (nr >= 16) { \
+ _mm256_storeu_ps(dst, lo); \
+ _mm256_storeu_ps(dst + 8, hi); \
+ } else { \
+ float tmp[16]; \
+ _mm256_storeu_ps(tmp, lo); _mm256_storeu_ps(tmp + 8, hi); \
+ memcpy(dst, tmp, nr * sizeof(float)); \
+ } \
+ }
+ FINISH_OC(0, c0_lo, c0_hi);
+ FINISH_OC(1, c1_lo, c1_hi);
+ FINISH_OC(2, c2_lo, c2_hi);
+ FINISH_OC(3, c3_lo, c3_hi);
+ FINISH_OC(4, c4_lo, c4_hi);
+ FINISH_OC(5, c5_lo, c5_hi);
+ #undef FINISH_OC
+ }
+ }
+ }
+}
+
+/* ============ Fused 3x3 stride-2 pad-1 ============ */
+
+void nn2_conv3x3_s2_fused(const ConvLayer* L, const float* in, int H, int W,
+ float* out)
+{
+ int Hout = (H + 1) / 2, Wout = (W + 1) / 2;
+ int co = L->cout, ci = L->cin;
+ __m256i vidx = _mm256_setr_epi32(0, 2, 4, 6, 8, 10, 12, 14);
+
+ for (int oc0 = 0; oc0 < co; oc0 += NN2_MR) {
+ int mr = (oc0 + NN2_MR <= co) ? NN2_MR : co - oc0;
+
+ for (int oh = 0; oh < Hout; oh++) {
+ for (int ow = 0; ow < Wout; ow += 16) {
+ int nr = (ow + 16 <= Wout) ? 16 : Wout - ow;
+
+ __m256 c0_lo = _mm256_setzero_ps(), c0_hi = _mm256_setzero_ps();
+ __m256 c1_lo = _mm256_setzero_ps(), c1_hi = _mm256_setzero_ps();
+ __m256 c2_lo = _mm256_setzero_ps(), c2_hi = _mm256_setzero_ps();
+ __m256 c3_lo = _mm256_setzero_ps(), c3_hi = _mm256_setzero_ps();
+ __m256 c4_lo = _mm256_setzero_ps(), c4_hi = _mm256_setzero_ps();
+ __m256 c5_lo = _mm256_setzero_ps(), c5_hi = _mm256_setzero_ps();
+
+ for (int ic = 0; ic < ci; ic++) {
+ const float* src = in + ic * H * W;
+
+ for (int kh = 0; kh < 3; kh++) {
+ int ih = oh * 2 - 1 + kh;
+ if (ih < 0 || ih >= H) continue;
+ const float* srow = src + ih * W;
+
+ for (int kw = 0; kw < 3; kw++) {
+ int iw_base = ow * 2 - 1 + kw;
+ __m256 v_lo, v_hi;
+
+ /* Gather stride-2 values using AVX2 gather */
+ if (iw_base >= 0 && iw_base + 30 < W && nr == 16) {
+ v_lo = _mm256_i32gather_ps(srow + iw_base, vidx, 4);
+ v_hi = _mm256_i32gather_ps(srow + iw_base + 16, vidx, 4);
+ } else {
+ float tmp[16] = {0};
+ for (int j = 0; j < nr; j++) {
+ int iw = iw_base + j * 2;
+ if (iw >= 0 && iw < W) tmp[j] = srow[iw];
+ }
+ v_lo = _mm256_loadu_ps(tmp);
+ v_hi = _mm256_loadu_ps(tmp + 8);
+ }
+
+ int woff = ic * 9 + kh * 3 + kw;
+ #define FMA_OC2(i, lo, hi) if (i < mr) { \
+ __m256 vw = _mm256_broadcast_ss(&L->w[(oc0+(i))*ci*9 + woff]); \
+ lo = _mm256_fmadd_ps(vw, v_lo, lo); \
+ hi = _mm256_fmadd_ps(vw, v_hi, hi); \
+ }
+ FMA_OC2(0, c0_lo, c0_hi);
+ FMA_OC2(1, c1_lo, c1_hi);
+ FMA_OC2(2, c2_lo, c2_hi);
+ FMA_OC2(3, c3_lo, c3_hi);
+ FMA_OC2(4, c4_lo, c4_hi);
+ FMA_OC2(5, c5_lo, c5_hi);
+ #undef FMA_OC2
+ }
+ }
+ }
+
+ #define FINISH_OC2(i, lo, hi) if (i < mr) { \
+ __m256 vb = _mm256_broadcast_ss(&L->b[oc0+(i)]); \
+ lo = _mm256_add_ps(lo, vb); hi = _mm256_add_ps(hi, vb); \
+ if (L->act == 1) { lo = _fast_silu(lo); hi = _fast_silu(hi); } \
+ float* dst = out + (oc0+(i)) * Hout * Wout + oh * Wout + ow; \
+ if (nr >= 16) { \
+ _mm256_storeu_ps(dst, lo); _mm256_storeu_ps(dst + 8, hi); \
+ } else { \
+ float tmp[16]; \
+ _mm256_storeu_ps(tmp, lo); _mm256_storeu_ps(tmp + 8, hi); \
+ memcpy(dst, tmp, nr * sizeof(float)); \
+ } \
+ }
+ FINISH_OC2(0, c0_lo, c0_hi);
+ FINISH_OC2(1, c1_lo, c1_hi);
+ FINISH_OC2(2, c2_lo, c2_hi);
+ FINISH_OC2(3, c3_lo, c3_hi);
+ FINISH_OC2(4, c4_lo, c4_hi);
+ FINISH_OC2(5, c5_lo, c5_hi);
+ #undef FINISH_OC2
+ }
+ }
+ }
+}
+
+#endif /* __AVX2__ */
diff --git a/nn2/src/conv_implicit.c b/nn2/src/conv_implicit.c
new file mode 100644
index 0000000..dcf9b33
--- /dev/null
+++ b/nn2/src/conv_implicit.c
@@ -0,0 +1,242 @@
+/*
+ * conv_implicit.c — 3x3 stride-1 conv WITHOUT im2col buffer.
+ *
+ * Replaces im2col+GEMM with a single pass that loads input on-the-fly.
+ * Saves 2×15MB memory traffic for the biggest bottleneck layers.
+ *
+ * For each N-tile of 32 output pixels (same row, consecutive columns):
+ * For each k = (c, kh, kw):
+ * Load 32 input values from input[c][oh+kh-1][ow_start+kw-1 .. ow_start+kw+30]
+ * This is a contiguous load (shifted by kw-1) — perfect for AVX-512!
+ * Multiply-accumulate with weight A[m][k]
+ * Store with fused bias+SiLU
+ *
+ * Threading: parallel across N-tiles (same as regular GEMM).
+ */
+
+#include "nn2_internal.h"
+#include <string.h>
+#include <math.h>
+#include <immintrin.h>
+
+#ifdef __AVX512F__
+
+typedef struct {
+ const float* input; /* [Cin, H, W] */
+ const float* weight; /* [Cout, Cin*9] original */
+ const float* w_packed; /* packed A or NULL */
+ const float* bias; /* [Cout] */
+ float* output; /* [Cout, H, W] */
+ int Cin, Cout, H, W;
+ int act;
+} ImplicitConvCtx;
+
+#include "fast_exp.h"
+static inline __m512 _isilu(__m512 x) { return _mm512_silu_fast(x); }
+
+/* Worker: process output tiles [start, end) where each tile = 32 consecutive output columns */
+static void implicit_conv_worker(void* arg, int start, int end)
+{
+ ImplicitConvCtx* g = (ImplicitConvCtx*)arg;
+ int H = g->H, W = g->W;
+ int Cin = g->Cin, Cout = g->Cout;
+ int spatial = H * W;
+
+ for (int ti = start; ti < end; ti++) {
+ /* Tile → (oh, ow_start): tile = oh * tiles_per_row + ow_block */
+ int tiles_per_row = (W + 31) / 32;
+ int oh = ti / tiles_per_row;
+ int ow_block = ti % tiles_per_row;
+ int ow_start = ow_block * 32;
+ int nr = 32;
+ if (ow_start + nr > W) nr = W - ow_start;
+
+ /* Process MR=6 output channels at a time */
+ for (int oc = 0; oc < Cout; oc += NN2_MR) {
+ int mr = (oc + NN2_MR <= Cout) ? NN2_MR : Cout - oc;
+
+ __m512 c00 = _mm512_setzero_ps(), c01 = _mm512_setzero_ps();
+ __m512 c10 = _mm512_setzero_ps(), c11 = _mm512_setzero_ps();
+ __m512 c20 = _mm512_setzero_ps(), c21 = _mm512_setzero_ps();
+ __m512 c30 = _mm512_setzero_ps(), c31 = _mm512_setzero_ps();
+ __m512 c40 = _mm512_setzero_ps(), c41 = _mm512_setzero_ps();
+ __m512 c50 = _mm512_setzero_ps(), c51 = _mm512_setzero_ps();
+
+ int K = Cin * 9;
+ int panel = oc / NN2_MR;
+ const float* Ap = g->w_packed ? g->w_packed + panel * K * NN2_MR : NULL;
+
+ for (int ci = 0; ci < Cin; ci++) {
+ const float* src = g->input + ci * H * W;
+
+ for (int kh = 0; kh < 3; kh++) {
+ int ih = oh - 1 + kh;
+ if (ih < 0 || ih >= H) continue;
+ const float* srow = src + ih * W;
+
+ for (int kw = 0; kw < 3; kw++) {
+ int iw = ow_start - 1 + kw;
+
+ /* Load 32 input values: srow[iw .. iw+31] */
+ __m512 b0, b1;
+ if (iw >= 0 && iw + 32 <= W && nr == 32) {
+ b0 = _mm512_loadu_ps(srow + iw);
+ b1 = _mm512_loadu_ps(srow + iw + 16);
+ } else {
+ /* Edge case: partial load with bounds check */
+ float tmp[32] = {0};
+ for (int j = 0; j < nr; j++) {
+ int iw_j = iw + j;
+ if (iw_j >= 0 && iw_j < W) tmp[j] = srow[iw_j];
+ }
+ b0 = _mm512_loadu_ps(tmp);
+ b1 = _mm512_loadu_ps(tmp + 16);
+ }
+
+ int k = ci * 9 + kh * 3 + kw;
+ const float* a = Ap + k * NN2_MR; /* packed: 6 consecutive */
+ __m512 va;
+ va=_mm512_set1_ps(a[0]); c00=_mm512_fmadd_ps(va,b0,c00); c01=_mm512_fmadd_ps(va,b1,c01);
+ if(mr>1){va=_mm512_set1_ps(a[1]); c10=_mm512_fmadd_ps(va,b0,c10); c11=_mm512_fmadd_ps(va,b1,c11);}
+ if(mr>2){va=_mm512_set1_ps(a[2]); c20=_mm512_fmadd_ps(va,b0,c20); c21=_mm512_fmadd_ps(va,b1,c21);}
+ if(mr>3){va=_mm512_set1_ps(a[3]); c30=_mm512_fmadd_ps(va,b0,c30); c31=_mm512_fmadd_ps(va,b1,c31);}
+ if(mr>4){va=_mm512_set1_ps(a[4]); c40=_mm512_fmadd_ps(va,b0,c40); c41=_mm512_fmadd_ps(va,b1,c41);}
+ if(mr>5){va=_mm512_set1_ps(a[5]); c50=_mm512_fmadd_ps(va,b0,c50); c51=_mm512_fmadd_ps(va,b1,c51);}
+ }
+ }
+ }
+
+ /* Fused bias + SiLU + store */
+ #define ISTORE(i, lo, hi) if(i<mr) { \
+ __m512 vb = _mm512_set1_ps(g->bias[oc+(i)]); \
+ lo = _mm512_add_ps(lo, vb); hi = _mm512_add_ps(hi, vb); \
+ if (g->act == 1) { lo = _isilu(lo); hi = _isilu(hi); } \
+ _mm512_storeu_ps(g->output + (oc+(i))*spatial + oh*W + ow_start, lo); \
+ if (nr > 16) _mm512_storeu_ps(g->output + (oc+(i))*spatial + oh*W + ow_start + 16, hi); \
+ }
+ ISTORE(0,c00,c01); ISTORE(1,c10,c11); ISTORE(2,c20,c21);
+ ISTORE(3,c30,c31); ISTORE(4,c40,c41); ISTORE(5,c50,c51);
+ #undef ISTORE
+ }
+ }
+}
+
+void nn2_conv3x3_s1_implicit(const float* input, const float* weight, const float* bias,
+ int Cin, int Cout, int H, int W, int act, float* output,
+ const float* w_packed)
+{
+ ImplicitConvCtx ctx = {input, weight, w_packed, bias, output, Cin, Cout, H, W, act};
+ /* Tiles: each tile = one (oh, ow_block). ow_block = 32 columns per row.
+ * Total = H * tiles_per_row. Tile index → (oh, ow_start) via divmod. */
+ int tiles_per_row = (W + 31) / 32;
+ int total_tiles = H * tiles_per_row;
+
+ int grain = (total_tiles > 128) ? total_tiles / (nn2_tp_num_threads() * 4) : 1;
+ if (grain < 1) grain = 1;
+ nn2_tp_parallel_for(implicit_conv_worker, &ctx, total_tiles, grain);
+}
+
+/* ============ Implicit 3x3 stride-2 conv ============ */
+
+typedef struct {
+ const float* input;
+ const float* weight;
+ const float* bias;
+ float* output;
+ int Cin, Cout, H, W, Hout, Wout;
+ int act;
+} ImplicitConvS2Ctx;
+
+static void implicit_conv_s2_worker(void* arg, int start, int end)
+{
+ ImplicitConvS2Ctx* g = (ImplicitConvS2Ctx*)arg;
+ int H = g->H, W = g->W, Wout = g->Wout;
+ int Cin = g->Cin, Cout = g->Cout;
+ int out_spatial = g->Hout * g->Wout;
+
+ __m256i vidx = _mm256_setr_epi32(0,2,4,6,8,10,12,14); /* stride-2 gather */
+
+ for (int ti = start; ti < end; ti++) {
+ int n_start = ti * 16; /* 16 output pixels per tile (AVX-512 half) */
+ int oh = n_start / Wout;
+ int ow_start = n_start % Wout;
+ int nr = 16;
+ if (ow_start + nr > Wout) nr = Wout - ow_start;
+
+ for (int oc = 0; oc < Cout; oc += NN2_MR) {
+ int mr = (oc + NN2_MR <= Cout) ? NN2_MR : Cout - oc;
+
+ __m512 c0=_mm512_setzero_ps();
+ __m512 c1=_mm512_setzero_ps();
+ __m512 c2=_mm512_setzero_ps();
+ __m512 c3=_mm512_setzero_ps();
+ __m512 c4=_mm512_setzero_ps();
+ __m512 c5=_mm512_setzero_ps();
+
+ const float* Wp[6];
+ Wp[0] = g->weight + oc*Cin*9;
+ for (int i=1;i<6;i++) Wp[i] = (i<mr) ? Wp[0]+i*Cin*9 : Wp[0];
+
+ for (int ci = 0; ci < Cin; ci++) {
+ const float* src = g->input + ci*H*W;
+ int woff = ci*9;
+ for (int kh = 0; kh < 3; kh++) {
+ int ih = oh*2 - 1 + kh;
+ if (ih < 0 || ih >= H) continue;
+ const float* srow = src + ih*W;
+ for (int kw = 0; kw < 3; kw++) {
+ int iw_base = ow_start*2 - 1 + kw;
+ __m512 b;
+ /* Stride-2 gather: load srow[iw_base], srow[iw_base+2], ... */
+ if (iw_base >= 0 && iw_base + nr*2 <= W && nr == 16) {
+ /* Use two AVX2 gathers → combine into ZMM */
+ __m256 lo = _mm256_i32gather_ps(srow+iw_base, vidx, 4);
+ __m256 hi = _mm256_i32gather_ps(srow+iw_base+16, vidx, 4);
+ b = _mm512_insertf32x8(_mm512_castps256_ps512(lo), hi, 1);
+ } else {
+ float tmp[16] = {0};
+ for (int j = 0; j < nr; j++) {
+ int iw = iw_base + j*2;
+ if (iw >= 0 && iw < W) tmp[j] = srow[iw];
+ }
+ b = _mm512_loadu_ps(tmp);
+ }
+ int k = woff + kh*3 + kw;
+ __m512 va;
+ va=_mm512_set1_ps(Wp[0][k]); c0=_mm512_fmadd_ps(va,b,c0);
+ if(mr>1){va=_mm512_set1_ps(Wp[1][k]); c1=_mm512_fmadd_ps(va,b,c1);}
+ if(mr>2){va=_mm512_set1_ps(Wp[2][k]); c2=_mm512_fmadd_ps(va,b,c2);}
+ if(mr>3){va=_mm512_set1_ps(Wp[3][k]); c3=_mm512_fmadd_ps(va,b,c3);}
+ if(mr>4){va=_mm512_set1_ps(Wp[4][k]); c4=_mm512_fmadd_ps(va,b,c4);}
+ if(mr>5){va=_mm512_set1_ps(Wp[5][k]); c5=_mm512_fmadd_ps(va,b,c5);}
+ }
+ }
+ }
+
+ #define IS2(i, acc) if(i<mr) { \
+ __m512 vb = _mm512_set1_ps(g->bias[oc+(i)]); \
+ acc = _mm512_add_ps(acc, vb); \
+ if (g->act==1) acc = _isilu(acc); \
+ if (nr>=16) _mm512_storeu_ps(g->output+(oc+(i))*out_spatial+oh*Wout+ow_start, acc); \
+ else { __mmask16 mask = ((__mmask16)1<<nr)-1; \
+ _mm512_mask_storeu_ps(g->output+(oc+(i))*out_spatial+oh*Wout+ow_start, mask, acc); } \
+ }
+ IS2(0,c0);IS2(1,c1);IS2(2,c2);IS2(3,c3);IS2(4,c4);IS2(5,c5);
+ #undef IS2
+ }
+ }
+}
+
+void nn2_conv3x3_s2_implicit(const float* input, const float* weight, const float* bias,
+ int Cin, int Cout, int H, int W, int act, float* output)
+{
+ int Hout = (H+1)/2, Wout = (W+1)/2;
+ ImplicitConvS2Ctx ctx = {input, weight, bias, output, Cin, Cout, H, W, Hout, Wout, act};
+ int tiles_per_row = (Wout + 15) / 16;
+ int total_tiles = Hout * tiles_per_row;
+ int grain = (total_tiles > 64) ? total_tiles / (nn2_tp_num_threads()*4) : 1;
+ if (grain < 1) grain = 1;
+ nn2_tp_parallel_for(implicit_conv_s2_worker, &ctx, total_tiles, grain);
+}
+
+#endif /* __AVX512F__ */
diff --git a/nn2/src/conv_int8.c b/nn2/src/conv_int8.c
new file mode 100644
index 0000000..cc31755
--- /dev/null
+++ b/nn2/src/conv_int8.c
@@ -0,0 +1,259 @@
+/*
+ * conv_int8.c — INT8 quantized convolution using AVX-512 VNNI.
+ *
+ * Pipeline per conv layer:
+ * 1. Quantize FP32 input to INT8 (per-tensor scale)
+ * 2. INT8 GEMM with VNNI: VPDPBUSD (4×u8×s8→s32)
+ * 3. Dequantize INT32 accumulators to FP32
+ * 4. Add bias + apply SiLU activation
+ * 5. Output FP32 for next layer
+ *
+ * Throughput: 4× over FP32 for compute-bound layers.
+ * Memory: 4× less weight data → better cache utilization.
+ */
+
+#include "nn2_internal.h"
+#include <string.h>
+#include <stdlib.h>
+#include <math.h>
+#include <immintrin.h>
+#include "fast_exp.h"
+
+#ifdef __AVX512VNNI__
+
+/* Quantize FP32 tensor to INT8 with per-tensor scale */
+static void quantize_f32_to_s8(const float* in, int n, float scale, int8_t* out)
+{
+ __m512 vscale = _mm512_set1_ps(scale);
+ int i = 0;
+ for (; i + 16 <= n; i += 16) {
+ __m512 v = _mm512_mul_ps(_mm512_loadu_ps(in + i), vscale);
+ __m512i vi = _mm512_cvtps_epi32(v);
+ /* Clamp to [-127, 127] and pack to int8 */
+ vi = _mm512_max_epi32(vi, _mm512_set1_epi32(-127));
+ vi = _mm512_min_epi32(vi, _mm512_set1_epi32(127));
+ /* Pack 16 int32 → 16 int8 (lower bytes) */
+ __m128i packed = _mm512_cvtsepi32_epi8(vi);
+ _mm_storeu_si128((__m128i*)(out + i), packed);
+ }
+ for (; i < n; i++) {
+ int v = (int)roundf(in[i] * scale);
+ out[i] = (int8_t)(v < -127 ? -127 : v > 127 ? 127 : v);
+ }
+}
+
+/* INT8 GEMM: C_s32[M,N] = A_u8[M,K] × B_s8_packed[K,N]
+ * A is converted from s8 to u8 via +128 offset (XOR trick).
+ * B is pre-packed in VNNI format: [N/16 groups][K/4 blocks][16×4 bytes].
+ * Compensation: col_sums[n] = 128 * sum(B[:,n]) per output channel. */
+static void int8_gemm_16x16(
+ const int8_t* A, int M, int K, int N,
+ const int8_t* B_packed, /* [N/16][K/4][64 bytes] */
+ int32_t* C)
+{
+ int K4 = (K + 3) & ~3;
+ const uint32_t xor32 = 0x80808080u;
+
+ for (int m = 0; m < M; m++) {
+ const int8_t* a_row = A + m * K;
+ const uint8_t* bp = (const uint8_t*)B_packed;
+
+ for (int n = 0; n < N; n += 16) {
+ __m512i acc = _mm512_setzero_si512();
+
+ for (int k = 0; k < K4; k += 4) {
+ /* Load 4 A bytes, convert s8→u8, broadcast to all lanes */
+ uint32_t a_val;
+ if (k + 4 <= K)
+ memcpy(&a_val, a_row + k, 4);
+ else {
+ a_val = 0;
+ memcpy(&a_val, a_row + k, K - k);
+ }
+ a_val ^= xor32;
+ __m512i va = _mm512_set1_epi32(a_val);
+
+ /* Load B panel: 16 channels × 4 k-values = 64 bytes */
+ __m512i vb = _mm512_loadu_si512((const __m512i*)bp);
+ bp += 64;
+
+ /* VPDPBUSD: acc += u8(A) dot s8(B) per 32-bit lane */
+ acc = _mm512_dpbusd_epi32(acc, va, vb);
+ }
+
+ _mm512_storeu_si512((__m512i*)(C + m * N + n), acc);
+ }
+ }
+}
+
+/* Dequantize INT32 accumulators to FP32 and apply bias + activation.
+ * result = (acc - compensation) * (input_scale * weight_scale) + bias
+ * then apply SiLU or LeakyReLU. */
+static void dequant_bias_act(
+ const int32_t* acc, int M, int N,
+ const int32_t* col_sums, /* [N] */
+ float input_scale, /* 1/act_scale (to convert back) */
+ const float* w_scales, /* [N] per-channel */
+ const float* bias, /* [N] */
+ int act,
+ float* output)
+{
+ float inv_input = 1.0f / (input_scale + 1e-10f);
+ for (int m = 0; m < M; m++) {
+ int i = 0;
+#ifdef __AVX512F__
+ for (; i + 16 <= N; i += 16) {
+ __m512i vacc = _mm512_loadu_si512((const __m512i*)(acc + m*N + i));
+ __m512i vcomp = _mm512_loadu_si512((const __m512i*)(col_sums + i));
+ __m512 vfacc = _mm512_cvtepi32_ps(_mm512_sub_epi32(vacc, vcomp));
+ __m512 vws = _mm512_loadu_ps(w_scales + i);
+ __m512 vb = _mm512_loadu_ps(bias + i);
+ /* result = acc * inv_input * w_scale + bias */
+ __m512 result = _mm512_fmadd_ps(
+ _mm512_mul_ps(vfacc, _mm512_set1_ps(inv_input)), vws, vb);
+ if (act == 1) result = _mm512_silu_fast(result);
+ _mm512_storeu_ps(output + m*N + i, result);
+ }
+#endif
+ for (; i < N; i++) {
+ float val = (float)(acc[m*N+i] - col_sums[i]) * inv_input * w_scales[i] + bias[i];
+ if (act == 1) { float s = 1.0f/(1.0f+expf(-val)); val *= s; }
+ else if (act == 3 && val < 0) val *= 0.1f;
+ output[m*N+i] = val;
+ }
+ }
+}
+
+/* Pack INT8 weights into VNNI format: [N/16][K/4][64 bytes]
+ * Also compute col_sums for unsigned offset compensation. */
+void nn2_int8_pack_vnni(const int8_t* weights, int N, int K,
+ int8_t* packed, int32_t* col_sums)
+{
+ int K4 = (K + 3) & ~3;
+ for (int n = 0; n < N; n += 16) {
+ int nr = (n + 16 <= N) ? 16 : N - n;
+ /* Col sums */
+ for (int j = 0; j < nr; j++) {
+ int32_t sum = 0;
+ for (int k = 0; k < K; k++)
+ sum += (int32_t)weights[(n+j)*K + k];
+ col_sums[n+j] = 128 * sum;
+ }
+ /* Pack: [K4/4 blocks][16 × 4 bytes] */
+ for (int k = 0; k < K4; k += 4) {
+ for (int j = 0; j < 16; j++) {
+ for (int kk = 0; kk < 4; kk++) {
+ int idx = (n/16) * (K4/4) * 64 + (k/4) * 64 + j * 4 + kk;
+ if (j < nr && (k+kk) < K)
+ packed[idx] = weights[(n+j)*K + (k+kk)];
+ else
+ packed[idx] = 0;
+ }
+ }
+ }
+ }
+}
+
+/* Full INT8 conv: quantize input → INT8 GEMM → dequant+bias+act → FP32 output */
+void nn2_conv2d_int8(
+ const float* input, int Cin, int H, int W,
+ const int8_t* w_packed, /* VNNI-packed INT8 weights */
+ const int32_t* col_sums,
+ const float* w_scales, /* per-channel weight scales */
+ const float* bias,
+ int Cout, int k, int stride, int pad, int act,
+ float act_scale, /* per-tensor activation scale */
+ float* output,
+ float* col_buf, /* im2col scratch */
+ int8_t* quant_buf) /* quantized activation scratch */
+{
+ int Hout = (H + 2*pad - k) / stride + 1;
+ int Wout = (W + 2*pad - k) / stride + 1;
+ int spatial = Hout * Wout;
+ int K = Cin * k * k;
+ int K4 = (K + 3) & ~3;
+
+ /* Step 1: im2col (still FP32) */
+ if (k > 1)
+ nn2_im2col(input, Cin, H, W, k, k, stride, pad, col_buf);
+ else
+ col_buf = (float*)input; /* 1x1: no im2col */
+
+ /* Step 2: Quantize activations to INT8 */
+ int act_size = K * spatial;
+ quantize_f32_to_s8(col_buf, act_size, act_scale, quant_buf);
+
+ /* Step 3: INT8 GEMM with VNNI */
+ /* Note: GEMM expects A[M,K] × B_packed → C[M,N]
+ * For conv: M=spatial, K=Cin*k*k, N=Cout */
+ /* But our B_packed is [Cout, K] packed per-Cout-group.
+ * We need transposed: C^T[spatial,Cout] = A^T[spatial,K] × B_packed
+ * Actually: output[Cout,spatial] = Weight[Cout,K] × im2col[K,spatial]
+ * INT8 GEMM: iterate output channels in groups of 16 */
+ int32_t* acc = (int32_t*)malloc(Cout * spatial * sizeof(int32_t));
+
+ /* Simple INT8 GEMM: for each spatial position, accumulate across K */
+ int N16 = (Cout + 15) & ~15;
+ memset(acc, 0, N16 * spatial * sizeof(int32_t));
+
+ /* Transpose approach: process per-spatial-position */
+ for (int s = 0; s < spatial; s++) {
+ const int8_t* a = quant_buf + s; /* stride = spatial (column of im2col) */
+ /* Need contiguous A for VNNI: copy column to contiguous buffer */
+ int8_t a_col[2048]; /* max K */
+ for (int kk = 0; kk < K; kk++)
+ a_col[kk] = quant_buf[kk * spatial + s];
+ /* Zero-pad to K4 */
+ for (int kk = K; kk < K4; kk++) a_col[kk] = 0;
+
+ /* VNNI: accumulate for all Cout channels */
+ const uint8_t* bp = (const uint8_t*)w_packed;
+ uint32_t xor32 = 0x80808080u;
+
+ for (int co = 0; co < Cout; co += 16) {
+ __m512i vacc = _mm512_setzero_si512();
+ for (int kk = 0; kk < K4; kk += 4) {
+ uint32_t a_val;
+ memcpy(&a_val, a_col + kk, 4);
+ a_val ^= xor32;
+ __m512i va = _mm512_set1_epi32(a_val);
+ __m512i vb = _mm512_loadu_si512((const __m512i*)bp);
+ bp += 64;
+ vacc = _mm512_dpbusd_epi32(vacc, va, vb);
+ }
+ /* Store accumulator */
+ for (int j = 0; j < 16 && (co+j) < Cout; j++)
+ acc[(co+j) * spatial + s] = ((int32_t*)&vacc)[j];
+ }
+ }
+
+ /* Step 4: Dequantize + bias + activation */
+ for (int co = 0; co < Cout; co++) {
+ float ws = w_scales[co];
+ float b = bias[co];
+ float inv_as = 1.0f / (act_scale + 1e-10f);
+ int i = 0;
+#ifdef __AVX512F__
+ __m512 v_inv = _mm512_set1_ps(inv_as * ws);
+ __m512 v_b = _mm512_set1_ps(b);
+ __m512i v_comp = _mm512_set1_epi32(col_sums[co]);
+ for (; i + 16 <= spatial; i += 16) {
+ __m512i vacc = _mm512_loadu_si512((const __m512i*)(acc + co*spatial + i));
+ __m512 vf = _mm512_cvtepi32_ps(_mm512_sub_epi32(vacc, v_comp));
+ __m512 result = _mm512_fmadd_ps(vf, v_inv, v_b);
+ if (act == 1) result = _mm512_silu_fast(result);
+ _mm512_storeu_ps(output + co*spatial + i, result);
+ }
+#endif
+ for (; i < spatial; i++) {
+ float val = (float)(acc[co*spatial+i] - col_sums[co]) * inv_as * ws + b;
+ if (act == 1) { float s = 1.0f/(1.0f+expf(-val)); val *= s; }
+ else if (act == 3 && val < 0) val *= 0.1f;
+ output[co*spatial+i] = val;
+ }
+ }
+
+ free(acc);
+}
+
+#endif /* __AVX512VNNI__ */
diff --git a/nn2/src/conv_int8_fast.c b/nn2/src/conv_int8_fast.c
new file mode 100644
index 0000000..aec4394
--- /dev/null
+++ b/nn2/src/conv_int8_fast.c
@@ -0,0 +1,113 @@
+/*
+ * conv_int8_fast.c — Fast INT8 conv with VNNI, transposed GEMM layout.
+ *
+ * Instead of Weight[Cout,K] × im2col[K,spatial] (FP32 layout),
+ * transpose to: im2col^T[spatial,K] × Weight_packed[K,Cout] (INT8 layout).
+ *
+ * This gives contiguous A-rows for VNNI: each spatial position
+ * has K consecutive INT8 values = perfect for VPDPBUSD.
+ *
+ * 2.6× proven speedup over FP32 GEMM.
+ */
+
+#include "nn2_internal.h"
+#include <string.h>
+#include <stdlib.h>
+#include <math.h>
+#include <immintrin.h>
+#include "fast_exp.h"
+
+#ifdef __AVX512VNNI__
+
+/* Transpose [K, spatial] → [spatial, K] and quantize to INT8 */
+static void transpose_quantize(const float* src, int K, int spatial,
+ float scale, int8_t* dst, int K4)
+{
+ for (int s = 0; s < spatial; s++) {
+ int k = 0;
+ for (; k < K; k++) {
+ int v = (int)roundf(src[k * spatial + s] * scale);
+ dst[s * K4 + k] = (int8_t)(v < -127 ? -127 : v > 127 ? 127 : v);
+ }
+ for (; k < K4; k++) dst[s * K4 + k] = 0;
+ }
+}
+
+/* Transpose [spatial, Cout] → [Cout, spatial] */
+static void transpose_output(const float* src, int spatial, int Cout, float* dst)
+{
+ for (int co = 0; co < Cout; co++)
+ for (int s = 0; s < spatial; s++)
+ dst[co * spatial + s] = src[s * Cout + co];
+}
+
+/* INT8 VNNI conv: full pipeline with transposed GEMM.
+ * Input: FP32 [Cin, H, W] (or im2col [K, spatial])
+ * Output: FP32 [Cout, Hout, Wout]
+ * Weights: pre-packed VNNI format */
+void nn2_conv2d_int8_fast(
+ const float* input, /* [Cin, H, W] for 1x1, or im2col [K, spatial] for 3x3 */
+ int K, int spatial, /* K=Cin*k*k, spatial=Hout*Wout */
+ const int8_t* w_packed, /* VNNI-packed [Cout/16][K4/4][64] */
+ const int32_t* col_sums, /* [Cout] compensation */
+ const float* w_scales, /* [Cout] per-channel */
+ const float* bias, /* [Cout] */
+ int Cout, int act,
+ float act_scale,
+ float* output, /* [Cout, spatial] */
+ int8_t* quant_buf) /* workspace: [spatial, K4] */
+{
+ int K4 = (K + 3) & ~3;
+ uint32_t xor32 = 0x80808080u;
+
+ /* Step 1: Transpose [K, spatial] → [spatial, K] and quantize to INT8 */
+ transpose_quantize(input, K, spatial, act_scale, quant_buf, K4);
+
+ /* Step 2: INT8 VNNI GEMM: C[spatial, Cout] = A[spatial, K4] × B_packed[K4, Cout]
+ * Process MR=4 spatial rows at a time for register reuse */
+ float* out_t = (float*)malloc(spatial * Cout * sizeof(float));
+
+ for (int s = 0; s < spatial; s++) {
+ const int8_t* a = quant_buf + s * K4;
+ const uint8_t* bp = (const uint8_t*)w_packed;
+
+ for (int co = 0; co < Cout; co += 16) {
+ __m512i vacc = _mm512_setzero_si512();
+
+ for (int k = 0; k < K4; k += 4) {
+ uint32_t av;
+ memcpy(&av, a + k, 4);
+ av ^= xor32;
+ __m512i va = _mm512_set1_epi32(av);
+ __m512i vb = _mm512_load_si512((const __m512i*)bp);
+ bp += 64;
+ vacc = _mm512_dpbusd_epi32(vacc, va, vb);
+ }
+
+ /* Dequantize + bias + SiLU inline */
+ __m512i vcomp = _mm512_loadu_si512((const __m512i*)(col_sums + co));
+ __m512 vf = _mm512_cvtepi32_ps(_mm512_sub_epi32(vacc, vcomp));
+ __m512 vws = _mm512_loadu_ps(w_scales + co);
+ __m512 vb = _mm512_loadu_ps(bias + co);
+ float inv_scale = 1.0f / (act_scale + 1e-10f);
+ __m512 result = _mm512_fmadd_ps(
+ _mm512_mul_ps(vf, _mm512_set1_ps(inv_scale)), vws, vb);
+ if (act == 1) result = _mm512_silu_fast(result);
+
+ /* Store to transposed output [spatial, Cout] */
+ int nr = (co + 16 <= Cout) ? 16 : Cout - co;
+ if (nr >= 16)
+ _mm512_storeu_ps(out_t + s * Cout + co, result);
+ else {
+ __mmask16 mask = ((__mmask16)1 << nr) - 1;
+ _mm512_mask_storeu_ps(out_t + s * Cout + co, mask, result);
+ }
+ }
+ }
+
+ /* Step 3: Transpose [spatial, Cout] → [Cout, spatial] */
+ transpose_output(out_t, spatial, Cout, output);
+ free(out_t);
+}
+
+#endif /* __AVX512VNNI__ */
diff --git a/nn2/src/conv_tiled.c b/nn2/src/conv_tiled.c
new file mode 100644
index 0000000..bd2b6fd
--- /dev/null
+++ b/nn2/src/conv_tiled.c
@@ -0,0 +1,210 @@
+/*
+ * conv_tiled.c — Cross-layer fused 3x3→3x3 bottleneck.
+ *
+ * Instead of: cv1(full H×W) → scratch[c×H×W] → cv2(full H×W)
+ * We do: cv1(3 rows at a time) → line_buf[c×3×W] → cv2(1 row) → output
+ *
+ * The line buffer (3×c×W floats) stays in L1 cache.
+ * Eliminates writing/reading the full intermediate feature map.
+ *
+ * For cv1: 3x3 s=1 p=1, Cin→c
+ * For cv2: 3x3 s=1 p=1, c→c
+ * With optional residual add on cv2 output.
+ */
+
+#include "nn2_internal.h"
+#include <string.h>
+#include <immintrin.h>
+
+#ifdef __AVX512F__
+#include "fast_exp.h"
+
+/* Compute one output row of a 3x3 s=1 p=1 conv with packed weights.
+ * Reads 3 input rows (ih-1, ih, ih+1) or zero-pads if out of bounds.
+ * Output: out[cout × W] for row oh. */
+static void conv3x3_one_row(
+ const float* input, int Cin, int H, int W, int oh,
+ const float* w_packed, const float* bias, int Cout, int act,
+ float* out_row)
+{
+ int K = Cin * 9;
+ int panels = (Cout + NN2_MR - 1) / NN2_MR;
+
+ /* Process NR=32 output columns at a time */
+ int tiles_w = (W + 31) / 32;
+ for (int tw = 0; tw < tiles_w; tw++) {
+ int ow_start = tw * 32;
+ int nr = (ow_start + 32 <= W) ? 32 : W - ow_start;
+
+ for (int p = 0; p < panels; p++) {
+ int oc = p * NN2_MR;
+ int mr = (oc + NN2_MR <= Cout) ? NN2_MR : Cout - oc;
+
+ __m512 c00=_mm512_setzero_ps(),c01=_mm512_setzero_ps();
+ __m512 c10=_mm512_setzero_ps(),c11=_mm512_setzero_ps();
+ __m512 c20=_mm512_setzero_ps(),c21=_mm512_setzero_ps();
+ __m512 c30=_mm512_setzero_ps(),c31=_mm512_setzero_ps();
+ __m512 c40=_mm512_setzero_ps(),c41=_mm512_setzero_ps();
+ __m512 c50=_mm512_setzero_ps(),c51=_mm512_setzero_ps();
+
+ const float* Ap = w_packed + p * K * NN2_MR;
+
+ for (int ci = 0; ci < Cin; ci++) {
+ const float* src = input + ci * H * W;
+ for (int kh = 0; kh < 3; kh++) {
+ int ih = oh - 1 + kh;
+ if (ih < 0 || ih >= H) continue;
+ const float* srow = src + ih * W;
+ for (int kw = 0; kw < 3; kw++) {
+ int iw = ow_start - 1 + kw;
+ __m512 b0, b1;
+ if (iw >= 0 && iw + 32 <= W && nr == 32) {
+ b0 = _mm512_loadu_ps(srow + iw);
+ b1 = _mm512_loadu_ps(srow + iw + 16);
+ } else {
+ float tmp[32] = {0};
+ for (int j = 0; j < nr; j++)
+ if (iw+j >= 0 && iw+j < W) tmp[j] = srow[iw+j];
+ b0 = _mm512_loadu_ps(tmp);
+ b1 = _mm512_loadu_ps(tmp + 16);
+ }
+ int k = (ci * 9 + kh * 3 + kw);
+ const float* a = Ap + k * NN2_MR;
+ __m512 va;
+ va=_mm512_set1_ps(a[0]);c00=_mm512_fmadd_ps(va,b0,c00);c01=_mm512_fmadd_ps(va,b1,c01);
+ if(mr>1){va=_mm512_set1_ps(a[1]);c10=_mm512_fmadd_ps(va,b0,c10);c11=_mm512_fmadd_ps(va,b1,c11);}
+ if(mr>2){va=_mm512_set1_ps(a[2]);c20=_mm512_fmadd_ps(va,b0,c20);c21=_mm512_fmadd_ps(va,b1,c21);}
+ if(mr>3){va=_mm512_set1_ps(a[3]);c30=_mm512_fmadd_ps(va,b0,c30);c31=_mm512_fmadd_ps(va,b1,c31);}
+ if(mr>4){va=_mm512_set1_ps(a[4]);c40=_mm512_fmadd_ps(va,b0,c40);c41=_mm512_fmadd_ps(va,b1,c41);}
+ if(mr>5){va=_mm512_set1_ps(a[5]);c50=_mm512_fmadd_ps(va,b0,c50);c51=_mm512_fmadd_ps(va,b1,c51);}
+ }
+ }
+ }
+
+ #define ST(i,lo,hi) if(i<mr){ \
+ __m512 vb=_mm512_set1_ps(bias[oc+(i)]); \
+ lo=_mm512_add_ps(lo,vb);hi=_mm512_add_ps(hi,vb); \
+ if(act==1){lo=_mm512_silu_fast(lo);hi=_mm512_silu_fast(hi);} \
+ _mm512_storeu_ps(out_row+(oc+(i))*W+ow_start,lo); \
+ if(nr>16) _mm512_storeu_ps(out_row+(oc+(i))*W+ow_start+16,hi); \
+ }
+ ST(0,c00,c01);ST(1,c10,c11);ST(2,c20,c21);
+ ST(3,c30,c31);ST(4,c40,c41);ST(5,c50,c51);
+ #undef ST
+ }
+ }
+}
+
+/* Fused bottleneck: cv1(3x3) → cv2(3x3) with line-buffer streaming.
+ * cv2 reads from a 3-row circular buffer of cv1 output.
+ * Optional residual add from 'residual' pointer. */
+void nn2_bottleneck_fused(
+ const float* input, int Cin, int H, int W,
+ const ConvLayer* cv1, const ConvLayer* cv2,
+ const float* residual, /* NULL or [c×H×W] for shortcut */
+ float* output, /* [c×H×W] */
+ float* line_buf) /* workspace: [3×c×W] */
+{
+ int c = cv1->cout; /* cv1 output channels = cv2 input channels */
+
+ /* line_buf holds 3 rows of cv1 output in circular fashion */
+ /* Row mapping: line_buf[(row % 3) * c * W ... ] */
+
+ /* Pre-compute cv1 rows 0 and 1 into line buffer */
+ conv3x3_one_row(input, Cin, H, W, 0, cv1->w_packed, cv1->b, c, cv1->act,
+ line_buf + 0 * c * W);
+ if (H > 1)
+ conv3x3_one_row(input, Cin, H, W, 1, cv1->w_packed, cv1->b, c, cv1->act,
+ line_buf + 1 * c * W);
+
+ /* Stream: for each output row of cv2, compute cv1's next row then cv2 */
+ for (int oh = 0; oh < H; oh++) {
+ /* Compute cv1 row oh+1 (if valid) into circular buffer */
+ int next_row = oh + 1;
+ if (next_row < H) {
+ int slot = next_row % 3;
+ conv3x3_one_row(input, Cin, H, W, next_row, cv1->w_packed, cv1->b, c, cv1->act,
+ line_buf + slot * c * W);
+ }
+
+ /* Now cv2 for row oh: reads cv1 rows (oh-1, oh, oh+1) from line buffer.
+ * We build a virtual 3-row "input" for cv2's row computation. */
+
+ /* cv2 processes: for each output pixel at (oh, ow), accumulate over
+ * c channels × 3 kh × 3 kw, reading from line_buf rows. */
+ int K2 = c * 9;
+ int panels2 = (cv2->cout + NN2_MR - 1) / NN2_MR;
+ int tiles_w = (W + 31) / 32;
+
+ for (int tw = 0; tw < tiles_w; tw++) {
+ int ow_start = tw * 32;
+ int nr = (ow_start + 32 <= W) ? 32 : W - ow_start;
+
+ for (int p2 = 0; p2 < panels2; p2++) {
+ int oc = p2 * NN2_MR;
+ int mr = (oc + NN2_MR <= cv2->cout) ? NN2_MR : cv2->cout - oc;
+
+ __m512 c00=_mm512_setzero_ps(),c01=_mm512_setzero_ps();
+ __m512 c10=_mm512_setzero_ps(),c11=_mm512_setzero_ps();
+ __m512 c20=_mm512_setzero_ps(),c21=_mm512_setzero_ps();
+ __m512 c30=_mm512_setzero_ps(),c31=_mm512_setzero_ps();
+ __m512 c40=_mm512_setzero_ps(),c41=_mm512_setzero_ps();
+ __m512 c50=_mm512_setzero_ps(),c51=_mm512_setzero_ps();
+
+ const float* Ap2 = cv2->w_packed + p2 * K2 * NN2_MR;
+
+ for (int ci = 0; ci < c; ci++) {
+ for (int kh = 0; kh < 3; kh++) {
+ int ih = oh - 1 + kh;
+ if (ih < 0 || ih >= H) continue;
+ /* Read from circular line buffer */
+ int slot = ih % 3;
+ const float* srow = line_buf + slot * c * W + ci * W;
+ for (int kw = 0; kw < 3; kw++) {
+ int iw = ow_start - 1 + kw;
+ __m512 b0, b1;
+ if (iw >= 0 && iw + 32 <= W && nr == 32) {
+ b0 = _mm512_loadu_ps(srow + iw);
+ b1 = _mm512_loadu_ps(srow + iw + 16);
+ } else {
+ float tmp[32] = {0};
+ for (int j = 0; j < nr; j++)
+ if (iw+j >= 0 && iw+j < W) tmp[j] = srow[iw+j];
+ b0 = _mm512_loadu_ps(tmp);
+ b1 = _mm512_loadu_ps(tmp + 16);
+ }
+ int k = ci * 9 + kh * 3 + kw;
+ const float* a = Ap2 + k * NN2_MR;
+ __m512 va;
+ va=_mm512_set1_ps(a[0]);c00=_mm512_fmadd_ps(va,b0,c00);c01=_mm512_fmadd_ps(va,b1,c01);
+ if(mr>1){va=_mm512_set1_ps(a[1]);c10=_mm512_fmadd_ps(va,b0,c10);c11=_mm512_fmadd_ps(va,b1,c11);}
+ if(mr>2){va=_mm512_set1_ps(a[2]);c20=_mm512_fmadd_ps(va,b0,c20);c21=_mm512_fmadd_ps(va,b1,c21);}
+ if(mr>3){va=_mm512_set1_ps(a[3]);c30=_mm512_fmadd_ps(va,b0,c30);c31=_mm512_fmadd_ps(va,b1,c31);}
+ if(mr>4){va=_mm512_set1_ps(a[4]);c40=_mm512_fmadd_ps(va,b0,c40);c41=_mm512_fmadd_ps(va,b1,c41);}
+ if(mr>5){va=_mm512_set1_ps(a[5]);c50=_mm512_fmadd_ps(va,b0,c50);c51=_mm512_fmadd_ps(va,b1,c51);}
+ }
+ }
+ }
+
+ /* Store cv2 output + optional residual */
+ int out_spatial = H * W;
+ #define ST2(i,lo,hi) if(i<mr){ \
+ __m512 vb=_mm512_set1_ps(cv2->b[oc+(i)]); \
+ lo=_mm512_add_ps(lo,vb);hi=_mm512_add_ps(hi,vb); \
+ if(cv2->act==1){lo=_mm512_silu_fast(lo);hi=_mm512_silu_fast(hi);} \
+ if(residual){ \
+ lo=_mm512_add_ps(lo,_mm512_loadu_ps(residual+(oc+(i))*out_spatial+oh*W+ow_start)); \
+ if(nr>16)hi=_mm512_add_ps(hi,_mm512_loadu_ps(residual+(oc+(i))*out_spatial+oh*W+ow_start+16)); \
+ } \
+ _mm512_storeu_ps(output+(oc+(i))*out_spatial+oh*W+ow_start,lo); \
+ if(nr>16) _mm512_storeu_ps(output+(oc+(i))*out_spatial+oh*W+ow_start+16,hi); \
+ }
+ ST2(0,c00,c01);ST2(1,c10,c11);ST2(2,c20,c21);
+ ST2(3,c30,c31);ST2(4,c40,c41);ST2(5,c50,c51);
+ #undef ST2
+ }
+ }
+ }
+}
+
+#endif /* __AVX512F__ */
diff --git a/nn2/src/decode.c b/nn2/src/decode.c
new file mode 100644
index 0000000..e8564fe
--- /dev/null
+++ b/nn2/src/decode.c
@@ -0,0 +1,194 @@
+/*
+ * decode.c — YOLO detection head decoding + NMS.
+ * Optimized: early threshold on raw logits, precomputed total_anchors,
+ * fast DFL with AVX-512.
+ */
+
+#include "nn2_internal.h"
+#include <math.h>
+#include <string.h>
+#include <stdlib.h>
+#include <immintrin.h>
+
+/* DFL: softmax over reg_max=16 bins → weighted sum.
+ * AVX-512: process all 16 bins in one pass (1 register). */
+#include "fast_exp.h"
+
+static inline float dfl_one(const float* logits, int reg_max, const float* w)
+{
+#ifdef __AVX512F__
+ if (reg_max == 16) {
+ __m512 v = _mm512_loadu_ps(logits);
+ float maxv = _mm512_reduce_max_ps(v);
+ __m512 shifted = _mm512_sub_ps(v, _mm512_set1_ps(maxv));
+ __m512 e = _mm512_exp_fast(shifted);
+ float sum = _mm512_reduce_add_ps(e);
+ __m512 wv = _mm512_loadu_ps(w);
+ float val = _mm512_reduce_add_ps(_mm512_mul_ps(e, wv));
+ return val / sum;
+ }
+#endif
+ /* Scalar fallback */
+ float maxv = logits[0];
+ for (int i = 1; i < reg_max; i++)
+ if (logits[i] > maxv) maxv = logits[i];
+
+ float sum = 0.0f, val = 0.0f;
+ for (int i = 0; i < reg_max; i++) {
+ float e = expf(logits[i] - maxv);
+ sum += e;
+ val += e * w[i];
+ }
+ return val / sum;
+}
+
+/* ============ Decode all scales ============ */
+
+int nn2_decode(const float* bbox_feat,
+ const float* cls_feat,
+ int num_classes, int input_size, float conf_thresh,
+ const float* dfl_w, NN2Det* dets, int max_det)
+{
+ static const int strides[] = {8, 16, 32};
+ int grid_sizes[3];
+ for (int i = 0; i < 3; i++)
+ grid_sizes[i] = input_size / strides[i];
+
+ int total_anchors = 0;
+ for (int i = 0; i < 3; i++)
+ total_anchors += grid_sizes[i] * grid_sizes[i];
+
+ /* Pre-compute sigmoid threshold: sigmoid(x) > thresh ⟺ x > ln(thresh/(1-thresh)) */
+ float raw_thresh = logf(conf_thresh / (1.0f - conf_thresh));
+
+ int n_det = 0;
+ int anchor_offset = 0;
+
+ for (int si = 0; si < 3; si++) {
+ int gs = grid_sizes[si];
+ int stride = strides[si];
+ int n_anchors = gs * gs;
+
+ for (int a = 0; a < n_anchors && n_det < max_det; a++) {
+ int idx = anchor_offset + a;
+
+ /* Find best class — threshold on raw logits (no expf needed) */
+ const float* cls_ptr = cls_feat + idx;
+ float best_raw = -1e9f;
+ int best_cls = 0;
+#ifdef __AVX512F__
+ /* Gather 16 class scores at a time (stride = total_anchors) */
+ if (num_classes >= 16) {
+ __m512 vmax = _mm512_set1_ps(-1e9f);
+ __m512i vidx = _mm512_setzero_epi32();
+ int c = 0;
+ for (; c + 16 <= num_classes; c += 16) {
+ /* Gather 16 scores with stride = total_anchors * sizeof(float) */
+ __m512i offsets = _mm512_setr_epi32(
+ (c+0)*total_anchors, (c+1)*total_anchors, (c+2)*total_anchors, (c+3)*total_anchors,
+ (c+4)*total_anchors, (c+5)*total_anchors, (c+6)*total_anchors, (c+7)*total_anchors,
+ (c+8)*total_anchors, (c+9)*total_anchors, (c+10)*total_anchors, (c+11)*total_anchors,
+ (c+12)*total_anchors, (c+13)*total_anchors, (c+14)*total_anchors, (c+15)*total_anchors);
+ __m512 scores = _mm512_i32gather_ps(offsets, cls_ptr, 4);
+ __mmask16 gt = _mm512_cmp_ps_mask(scores, vmax, _CMP_GT_OQ);
+ if (gt) {
+ vmax = _mm512_mask_blend_ps(gt, vmax, scores);
+ vidx = _mm512_mask_blend_epi32(gt, vidx, _mm512_add_epi32(_mm512_set1_epi32(c),
+ _mm512_setr_epi32(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)));
+ }
+ }
+ /* Horizontal reduction: find max across 16 lanes */
+ float vals[16]; int idxs[16];
+ _mm512_storeu_ps(vals, vmax);
+ _mm512_storeu_epi32(idxs, vidx);
+ for (int k = 0; k < 16; k++) {
+ if (vals[k] > best_raw) { best_raw = vals[k]; best_cls = idxs[k]; }
+ }
+ /* Remaining classes */
+ for (; c < num_classes; c++) {
+ float s = cls_ptr[c * total_anchors];
+ if (s > best_raw) { best_raw = s; best_cls = c; }
+ }
+ } else
+#endif
+ {
+ for (int c = 0; c < num_classes; c++) {
+ float s = cls_ptr[c * total_anchors];
+ if (s > best_raw) { best_raw = s; best_cls = c; }
+ }
+ }
+
+ /* Early reject on raw logit — saves expf for 95%+ of anchors */
+ if (best_raw < raw_thresh) continue;
+
+ float best_score = 1.0f / (1.0f + expf(-best_raw));
+
+ /* DFL decode bbox */
+ const float* bbox_ptr = bbox_feat + idx;
+ float ltrb[4];
+ for (int d = 0; d < 4; d++) {
+ float logits[16];
+ for (int r = 0; r < NN2_REG_MAX; r++)
+ logits[r] = bbox_ptr[(d * NN2_REG_MAX + r) * total_anchors];
+ ltrb[d] = dfl_one(logits, NN2_REG_MAX, dfl_w);
+ }
+
+ int ay = a / gs, ax = a % gs;
+ float cx = (ax + 0.5f) * stride;
+ float cy = (ay + 0.5f) * stride;
+
+ NN2Det* d = &dets[n_det++];
+ d->x1 = cx - ltrb[0] * stride;
+ d->y1 = cy - ltrb[1] * stride;
+ d->x2 = cx + ltrb[2] * stride;
+ d->y2 = cy + ltrb[3] * stride;
+ d->score = best_score;
+ d->cls = best_cls;
+ }
+ anchor_offset += n_anchors;
+ }
+ return n_det;
+}
+
+/* ============ NMS ============ */
+
+static float iou(const NN2Det* a, const NN2Det* b)
+{
+ float x1 = a->x1 > b->x1 ? a->x1 : b->x1;
+ float y1 = a->y1 > b->y1 ? a->y1 : b->y1;
+ float x2 = a->x2 < b->x2 ? a->x2 : b->x2;
+ float y2 = a->y2 < b->y2 ? a->y2 : b->y2;
+ float inter = (x2-x1>0?x2-x1:0) * (y2-y1>0?y2-y1:0);
+ float area_a = (a->x2-a->x1) * (a->y2-a->y1);
+ float area_b = (b->x2-b->x1) * (b->y2-b->y1);
+ return inter / (area_a + area_b - inter + 1e-6f);
+}
+
+static int cmp_score_desc(const void* a, const void* b)
+{
+ float sa = ((const NN2Det*)a)->score;
+ float sb = ((const NN2Det*)b)->score;
+ return (sb > sa) - (sb < sa);
+}
+
+int nn2_nms(NN2Det* dets, int n, float iou_thresh)
+{
+ if (n <= 1) return n;
+ qsort(dets, n, sizeof(NN2Det), cmp_score_desc);
+
+ /* Stack-based suppress array — no malloc in NMS hot path */
+ uint8_t suppress[1024]; /* max 1024 detections */
+ if (n > 1024) n = 1024;
+ memset(suppress, 0, n);
+ int out_n = 0;
+ for (int i = 0; i < n; i++) {
+ if (suppress[i]) continue;
+ dets[out_n++] = dets[i];
+ for (int j = i + 1; j < n; j++) {
+ if (!suppress[j] && dets[i].cls == dets[j].cls
+ && iou(&dets[i], &dets[j]) > iou_thresh)
+ suppress[j] = 1;
+ }
+ }
+ return out_n;
+}
diff --git a/nn2/src/draw.h b/nn2/src/draw.h
new file mode 100644
index 0000000..3055980
--- /dev/null
+++ b/nn2/src/draw.h
@@ -0,0 +1,92 @@
+/*
+ * draw.h — Draw bounding boxes and labels on RGB images.
+ * Minimal implementation, no fonts — uses simple block characters.
+ */
+
+#ifndef NN2_DRAW_H
+#define NN2_DRAW_H
+
+#include "nn2.h"
+#include <string.h>
+
+/* Colors for different classes (RGB) */
+static const uint8_t nn2_colors[][3] = {
+ {255,0,0},{0,255,0},{0,0,255},{255,255,0},{255,0,255},{0,255,255},
+ {255,128,0},{128,0,255},{0,128,255},{255,0,128},{128,255,0},{0,255,128},
+ {200,100,100},{100,200,100},{100,100,200},{200,200,100},{200,100,200},{100,200,200},
+};
+
+/* Draw a single pixel (bounds checked) */
+static inline void draw_pixel(uint8_t* img, int w, int h, int x, int y,
+ uint8_t r, uint8_t g, uint8_t b)
+{
+ if (x >= 0 && x < w && y >= 0 && y < h) {
+ uint8_t* p = img + (y * w + x) * 3;
+ p[0] = r; p[1] = g; p[2] = b;
+ }
+}
+
+/* Draw thick horizontal line */
+static inline void draw_hline(uint8_t* img, int w, int h,
+ int x1, int x2, int y, int thick,
+ uint8_t r, uint8_t g, uint8_t b)
+{
+ for (int t = 0; t < thick; t++)
+ for (int x = x1; x <= x2; x++)
+ draw_pixel(img, w, h, x, y + t, r, g, b);
+}
+
+/* Draw thick vertical line */
+static inline void draw_vline(uint8_t* img, int w, int h,
+ int x, int y1, int y2, int thick,
+ uint8_t r, uint8_t g, uint8_t b)
+{
+ for (int t = 0; t < thick; t++)
+ for (int y = y1; y <= y2; y++)
+ draw_pixel(img, w, h, x + t, y, r, g, b);
+}
+
+/* Draw rectangle */
+static inline void draw_rect(uint8_t* img, int w, int h,
+ int x1, int y1, int x2, int y2, int thick,
+ uint8_t r, uint8_t g, uint8_t b)
+{
+ draw_hline(img, w, h, x1, x2, y1, thick, r, g, b);
+ draw_hline(img, w, h, x1, x2, y2 - thick + 1, thick, r, g, b);
+ draw_vline(img, w, h, x1, y1, y2, thick, r, g, b);
+ draw_vline(img, w, h, x2 - thick + 1, y1, y2, thick, r, g, b);
+}
+
+/* Draw filled rectangle (for label background) */
+static inline void draw_filled_rect(uint8_t* img, int w, int h,
+ int x1, int y1, int x2, int y2,
+ uint8_t r, uint8_t g, uint8_t b)
+{
+ for (int y = y1; y <= y2; y++)
+ for (int x = x1; x <= x2; x++)
+ draw_pixel(img, w, h, x, y, r, g, b);
+}
+
+/* Draw all detections on image */
+static inline void nn2_draw_detections(uint8_t* img, int w, int h,
+ const NN2Det* dets, int n)
+{
+ for (int i = 0; i < n; i++) {
+ int x1 = (int)dets[i].x1, y1 = (int)dets[i].y1;
+ int x2 = (int)dets[i].x2, y2 = (int)dets[i].y2;
+ if (x1 < 0) x1 = 0; if (y1 < 0) y1 = 0;
+ if (x2 >= w) x2 = w-1; if (y2 >= h) y2 = h-1;
+
+ int ci = dets[i].cls % 18;
+ uint8_t r = nn2_colors[ci][0], g = nn2_colors[ci][1], b = nn2_colors[ci][2];
+
+ /* Draw box (2px thick) */
+ draw_rect(img, w, h, x1, y1, x2, y2, 2, r, g, b);
+
+ /* Draw label background */
+ int lh = 14; /* label height */
+ draw_filled_rect(img, w, h, x1, y1 - lh - 2, x1 + 80, y1 - 2, r, g, b);
+ }
+}
+
+#endif /* NN2_DRAW_H */
diff --git a/nn2/src/fast_exp.h b/nn2/src/fast_exp.h
new file mode 100644
index 0000000..0443662
--- /dev/null
+++ b/nn2/src/fast_exp.h
@@ -0,0 +1,82 @@
+/*
+ * fast_exp.h — Vectorized expf() for AVX-512, accurate to float precision.
+ *
+ * Based on Cephes approach: exp(x) = 2^n * P(f) where n=round(x/ln2), f=x-n*ln2.
+ * P(f) is a degree-6 minimax polynomial on [-ln2/2, ln2/2].
+ * Accuracy: max relative error < 2^-23 (same as hardware expf).
+ *
+ * ~15 SIMD instructions per call. 3-4x faster than scalar expf loop.
+ */
+
+#ifndef FAST_EXP_H
+#define FAST_EXP_H
+
+#include <immintrin.h>
+
+#ifdef __AVX512F__
+
+static inline __m512 _mm512_exp_fast(__m512 x)
+{
+ /* Constants */
+ const __m512 log2e = _mm512_set1_ps(1.44269504088896341f); /* 1/ln(2) */
+ const __m512 ln2_hi = _mm512_set1_ps(0.693145751953125f);
+ const __m512 ln2_lo = _mm512_set1_ps(1.42860682030941723212e-6f);
+ const __m512 half = _mm512_set1_ps(0.5f);
+
+ /* Polynomial coefficients (Cephes) */
+ const __m512 c1 = _mm512_set1_ps(1.0f);
+ const __m512 c2 = _mm512_set1_ps(0.5f);
+ const __m512 c3 = _mm512_set1_ps(0.166666666666666019037f);
+ const __m512 c4 = _mm512_set1_ps(0.0416666666665065678e0f);
+ const __m512 c5 = _mm512_set1_ps(0.00833333333371142972e0f);
+ const __m512 c6 = _mm512_set1_ps(0.00138888889039885e0f);
+
+ /* Clamp to prevent overflow/underflow */
+ x = _mm512_max_ps(x, _mm512_set1_ps(-87.3f));
+ x = _mm512_min_ps(x, _mm512_set1_ps(88.7f));
+
+ /* n = round(x / ln2) */
+ __m512 n = _mm512_roundscale_ps(_mm512_mul_ps(x, log2e), 0);
+
+ /* f = x - n * ln2 (exact via two-part subtraction) */
+ __m512 f = _mm512_fnmadd_ps(n, ln2_hi, x);
+ f = _mm512_fnmadd_ps(n, ln2_lo, f);
+
+ /* P(f) = 1 + f + f²/2 + f³/6 + ... (Horner's method) */
+ __m512 f2 = _mm512_mul_ps(f, f);
+ __m512 p = c6;
+ p = _mm512_fmadd_ps(p, f, c5);
+ p = _mm512_fmadd_ps(p, f, c4);
+ p = _mm512_fmadd_ps(p, f, c3);
+ p = _mm512_fmadd_ps(p, f, c2);
+ p = _mm512_fmadd_ps(p, f, c1);
+ p = _mm512_fmadd_ps(p, f, c1);
+
+ /* result = 2^n * P(f). Construct 2^n via integer exponent manipulation. */
+ __m512i ni = _mm512_cvtps_epi32(n);
+ ni = _mm512_add_epi32(ni, _mm512_set1_epi32(127)); /* add float bias */
+ ni = _mm512_slli_epi32(ni, 23); /* shift to exponent position */
+ __m512 pow2n = _mm512_castsi512_ps(ni);
+
+ return _mm512_mul_ps(p, pow2n);
+}
+
+/* Vectorized sigmoid: 1 / (1 + exp(-x)), using rcp14 instead of div */
+static inline __m512 _mm512_sigmoid_fast(__m512 x)
+{
+ __m512 one = _mm512_set1_ps(1.0f);
+ __m512 neg_x = _mm512_sub_ps(_mm512_setzero_ps(), x);
+ __m512 denom = _mm512_add_ps(one, _mm512_exp_fast(neg_x));
+ /* Use div for accuracy — sigmoid needs full precision */
+ return _mm512_div_ps(_mm512_set1_ps(1.0f), denom);
+}
+
+/* Vectorized SiLU: x * sigmoid(x), float-accurate */
+static inline __m512 _mm512_silu_fast(__m512 x)
+{
+ return _mm512_mul_ps(x, _mm512_sigmoid_fast(x));
+}
+
+#endif /* __AVX512F__ */
+
+#endif /* FAST_EXP_H */
diff --git a/nn2/src/gemm.c b/nn2/src/gemm.c
new file mode 100644
index 0000000..6d0ca34
--- /dev/null
+++ b/nn2/src/gemm.c
@@ -0,0 +1,535 @@
+/*
+ * gemm.c — FP32 GEMM: AVX-512 → AVX2 → scalar fallback.
+ *
+ * C[M,N] = A[M,K] * B[K,N] (row-major)
+ * AVX-512: MR=6 × NR=32 (ZMM, 16 float/reg), 12 acc + 2 B + 1 A = 15/32 regs.
+ * AVX2: MR=6 × NR=16 (YMM, 8 float/reg), 12 acc + 2 B + 1 A = 15/16 regs.
+ * Output-stationary, parallel across N-tiles.
+ */
+
+#include "nn2_internal.h"
+#include <string.h>
+#include <stdlib.h>
+#include <immintrin.h>
+
+/* ============================================================
+ * AVX-512 path: MR=6, NR=32
+ * ============================================================ */
+
+#ifdef __AVX512F__
+
+#define NR512 32
+
+static inline void ukernel_6x32_avx512(
+ int K,
+ const float* restrict A, int lda,
+ const float* restrict B, int ldb,
+ float* restrict C, int ldc,
+ int mr, int nr)
+{
+ __m512 c00=_mm512_setzero_ps(),c01=_mm512_setzero_ps();
+ __m512 c10=_mm512_setzero_ps(),c11=_mm512_setzero_ps();
+ __m512 c20=_mm512_setzero_ps(),c21=_mm512_setzero_ps();
+ __m512 c30=_mm512_setzero_ps(),c31=_mm512_setzero_ps();
+ __m512 c40=_mm512_setzero_ps(),c41=_mm512_setzero_ps();
+ __m512 c50=_mm512_setzero_ps(),c51=_mm512_setzero_ps();
+ const float*a0=A,*a1=A,*a2=A,*a3=A,*a4=A,*a5=A;
+ if(mr>1)a1=A+lda;if(mr>2)a2=A+2*lda;if(mr>3)a3=A+3*lda;
+ if(mr>4)a4=A+4*lda;if(mr>5)a5=A+5*lda;
+ for(int k=0;k<K;k++){
+ const float*bp=B+k*ldb;
+ if(k+2<K)_mm_prefetch((const char*)(B+(k+2)*ldb),_MM_HINT_T0);
+ __m512 b0=_mm512_loadu_ps(bp),b1=_mm512_loadu_ps(bp+16);
+ __m512 va;
+ va=_mm512_set1_ps(a0[k]);c00=_mm512_fmadd_ps(va,b0,c00);c01=_mm512_fmadd_ps(va,b1,c01);
+ va=_mm512_set1_ps(a1[k]);c10=_mm512_fmadd_ps(va,b0,c10);c11=_mm512_fmadd_ps(va,b1,c11);
+ va=_mm512_set1_ps(a2[k]);c20=_mm512_fmadd_ps(va,b0,c20);c21=_mm512_fmadd_ps(va,b1,c21);
+ va=_mm512_set1_ps(a3[k]);c30=_mm512_fmadd_ps(va,b0,c30);c31=_mm512_fmadd_ps(va,b1,c31);
+ va=_mm512_set1_ps(a4[k]);c40=_mm512_fmadd_ps(va,b0,c40);c41=_mm512_fmadd_ps(va,b1,c41);
+ va=_mm512_set1_ps(a5[k]);c50=_mm512_fmadd_ps(va,b0,c50);c51=_mm512_fmadd_ps(va,b1,c51);
+ }
+ if(nr>=32){
+ #define W512(i,lo,hi) if(i<mr){_mm512_storeu_ps(C+i*ldc,lo);_mm512_storeu_ps(C+i*ldc+16,hi);}
+ W512(0,c00,c01);W512(1,c10,c11);W512(2,c20,c21);
+ W512(3,c30,c31);W512(4,c40,c41);W512(5,c50,c51);
+ #undef W512
+ } else {
+ __mmask16 ml=(nr>=16)?0xFFFF:((__mmask16)1<<nr)-1;
+ __mmask16 mh=(nr<=16)?0:(nr>=32)?0xFFFF:((__mmask16)1<<(nr-16))-1;
+ #define WM(i,lo,hi) if(i<mr){_mm512_mask_storeu_ps(C+i*ldc,ml,lo);if(mh)_mm512_mask_storeu_ps(C+i*ldc+16,mh,hi);}
+ WM(0,c00,c01);WM(1,c10,c11);WM(2,c20,c21);WM(3,c30,c31);WM(4,c40,c41);WM(5,c50,c51);
+ #undef WM
+ }
+}
+
+#endif /* __AVX512F__ */
+
+typedef struct {
+ int M, K, N;
+ const float* A; int lda;
+ const float* B;
+ float* C; int ldc;
+} GemmCtx;
+
+#ifdef __AVX512F__
+static void gemm_avx512_worker(void* arg, int start, int end)
+{
+ GemmCtx* g = (GemmCtx*)arg;
+ for (int ni = start; ni < end; ni++) {
+ int n = ni * NR512;
+ int nr = (n + NR512 <= g->N) ? NR512 : g->N - n;
+ for (int m = 0; m < g->M; m += NN2_MR) {
+ int mr = (m + NN2_MR <= g->M) ? NN2_MR : g->M - m;
+ ukernel_6x32_avx512(g->K, g->A + m*g->lda, g->lda,
+ g->B + n, g->N,
+ g->C + m*g->ldc + n, g->ldc, mr, nr);
+ }
+ }
+}
+
+#endif /* __AVX512F__ */
+
+/* ============================================================
+ * AVX2 path: MR=6, NR=16 (direct, no B packing)
+ * ============================================================ */
+
+#ifdef __AVX2__
+
+static inline void ukernel_6x16_avx2(
+ int K,
+ const float* restrict A, int lda,
+ const float* restrict B, int ldb,
+ float* restrict C, int ldc,
+ int mr, int nr)
+{
+ __m256 c00=_mm256_setzero_ps(), c01=_mm256_setzero_ps();
+ __m256 c10=_mm256_setzero_ps(), c11=_mm256_setzero_ps();
+ __m256 c20=_mm256_setzero_ps(), c21=_mm256_setzero_ps();
+ __m256 c30=_mm256_setzero_ps(), c31=_mm256_setzero_ps();
+ __m256 c40=_mm256_setzero_ps(), c41=_mm256_setzero_ps();
+ __m256 c50=_mm256_setzero_ps(), c51=_mm256_setzero_ps();
+
+ const float *a0=A, *a1=A, *a2=A, *a3=A, *a4=A, *a5=A;
+ if (mr>1) a1=A+lda; if (mr>2) a2=A+2*lda; if (mr>3) a3=A+3*lda;
+ if (mr>4) a4=A+4*lda; if (mr>5) a5=A+5*lda;
+
+ int k=0;
+ for (; k+3<K; k+=4) {
+ #define I256(off) { \
+ const float*bp=B+(k+(off))*ldb; \
+ if ((off)==0 && k+4<K) _mm_prefetch((const char*)(B+(k+4)*ldb), _MM_HINT_T0); \
+ __m256 b0=_mm256_loadu_ps(bp), b1=_mm256_loadu_ps(bp+8); \
+ __m256 va; \
+ va=_mm256_broadcast_ss(a0+k+(off));c00=_mm256_fmadd_ps(va,b0,c00);c01=_mm256_fmadd_ps(va,b1,c01); \
+ va=_mm256_broadcast_ss(a1+k+(off));c10=_mm256_fmadd_ps(va,b0,c10);c11=_mm256_fmadd_ps(va,b1,c11); \
+ va=_mm256_broadcast_ss(a2+k+(off));c20=_mm256_fmadd_ps(va,b0,c20);c21=_mm256_fmadd_ps(va,b1,c21); \
+ va=_mm256_broadcast_ss(a3+k+(off));c30=_mm256_fmadd_ps(va,b0,c30);c31=_mm256_fmadd_ps(va,b1,c31); \
+ va=_mm256_broadcast_ss(a4+k+(off));c40=_mm256_fmadd_ps(va,b0,c40);c41=_mm256_fmadd_ps(va,b1,c41); \
+ va=_mm256_broadcast_ss(a5+k+(off));c50=_mm256_fmadd_ps(va,b0,c50);c51=_mm256_fmadd_ps(va,b1,c51); \
+ }
+ I256(0);I256(1);I256(2);I256(3);
+ #undef I256
+ }
+ for (; k<K; k++) {
+ const float*bp=B+k*ldb;
+ __m256 b0=_mm256_loadu_ps(bp), b1=_mm256_loadu_ps(bp+8);
+ __m256 va;
+ va=_mm256_broadcast_ss(a0+k);c00=_mm256_fmadd_ps(va,b0,c00);c01=_mm256_fmadd_ps(va,b1,c01);
+ va=_mm256_broadcast_ss(a1+k);c10=_mm256_fmadd_ps(va,b0,c10);c11=_mm256_fmadd_ps(va,b1,c11);
+ va=_mm256_broadcast_ss(a2+k);c20=_mm256_fmadd_ps(va,b0,c20);c21=_mm256_fmadd_ps(va,b1,c21);
+ va=_mm256_broadcast_ss(a3+k);c30=_mm256_fmadd_ps(va,b0,c30);c31=_mm256_fmadd_ps(va,b1,c31);
+ va=_mm256_broadcast_ss(a4+k);c40=_mm256_fmadd_ps(va,b0,c40);c41=_mm256_fmadd_ps(va,b1,c41);
+ va=_mm256_broadcast_ss(a5+k);c50=_mm256_fmadd_ps(va,b0,c50);c51=_mm256_fmadd_ps(va,b1,c51);
+ }
+
+ if (nr >= 16) {
+ #define W256(i,lo,hi) if(i<mr){_mm256_storeu_ps(C+(i)*ldc,lo);_mm256_storeu_ps(C+(i)*ldc+8,hi);}
+ W256(0,c00,c01);W256(1,c10,c11);W256(2,c20,c21);
+ W256(3,c30,c31);W256(4,c40,c41);W256(5,c50,c51);
+ #undef W256
+ } else {
+ float tmp[6*16] __attribute__((aligned(32)));
+ _mm256_store_ps(tmp,c00);_mm256_store_ps(tmp+8,c01);
+ _mm256_store_ps(tmp+16,c10);_mm256_store_ps(tmp+24,c11);
+ _mm256_store_ps(tmp+32,c20);_mm256_store_ps(tmp+40,c21);
+ _mm256_store_ps(tmp+48,c30);_mm256_store_ps(tmp+56,c31);
+ _mm256_store_ps(tmp+64,c40);_mm256_store_ps(tmp+72,c41);
+ _mm256_store_ps(tmp+80,c50);_mm256_store_ps(tmp+88,c51);
+ for (int i=0;i<mr;i++) for (int j=0;j<nr;j++) C[i*ldc+j]=tmp[i*16+j];
+ }
+}
+
+static void gemm_avx2_worker(void* arg, int start, int end)
+{
+ GemmCtx* g = (GemmCtx*)arg;
+ for (int ni = start; ni < end; ni++) {
+ int n = ni * NN2_NR;
+ int nr = (n + NN2_NR <= g->N) ? NN2_NR : g->N - n;
+ for (int m = 0; m < g->M; m += NN2_MR) {
+ int mr = (m + NN2_MR <= g->M) ? NN2_MR : g->M - m;
+ ukernel_6x16_avx2(g->K, g->A + m*g->lda, g->lda,
+ g->B + n, g->N,
+ g->C + m*g->ldc + n, g->ldc, mr, nr);
+ }
+ }
+}
+
+#endif /* __AVX2__ */
+
+/* ============ A-packing ============ */
+
+float* nn2_pack_weight_a(const float* A, int M, int K)
+{
+ int panels = (M + NN2_MR - 1) / NN2_MR;
+ float* Ap = (float*)_aligned_malloc((size_t)panels * K * NN2_MR * sizeof(float), 64);
+ if (!Ap) return NULL;
+ for (int p = 0; p < panels; p++) {
+ for (int k = 0; k < K; k++) {
+ for (int i = 0; i < NN2_MR; i++) {
+ int row = p * NN2_MR + i;
+ Ap[(p * K + k) * NN2_MR + i] = (row < M) ? A[row * K + k] : 0.0f;
+ }
+ }
+ }
+ return Ap;
+}
+
+/* ============ Scalar fallback ============ */
+
+/* ============================================================
+ * Fused GEMM: C = A×B + bias[row] + activation
+ * Eliminates separate bias+activation pass (saves one full C read+write)
+ * ============================================================ */
+
+typedef struct {
+ int M, K, N;
+ const float* A; int lda;
+ const float* B;
+ float* C; int ldc;
+ const float* bias;
+ int act;
+} GemmFusedCtx;
+
+#ifdef __AVX512F__
+
+#include "fast_exp.h"
+#include "gemm_asm.h"
+
+static inline __m512 _fused_silu512(__m512 x) {
+ return _mm512_silu_fast(x);
+}
+
+/* KC block size: keeps B panel (KC×NR×4 bytes) in L1 cache */
+#define KC_BLOCK 256
+
+static void gemm_fused_avx512_worker(void* arg, int start, int end)
+{
+ GemmFusedCtx* g = (GemmFusedCtx*)arg;
+ for (int ni = start; ni < end; ni++) {
+ int n = ni * NR512;
+ int nr = (n + NR512 <= g->N) ? NR512 : g->N - n;
+ for (int m = 0; m < g->M; m += NN2_MR) {
+ int mr = (m + NN2_MR <= g->M) ? NN2_MR : g->M - m;
+
+ __m512 c00=_mm512_setzero_ps(),c01=_mm512_setzero_ps();
+ __m512 c10=_mm512_setzero_ps(),c11=_mm512_setzero_ps();
+ __m512 c20=_mm512_setzero_ps(),c21=_mm512_setzero_ps();
+ __m512 c30=_mm512_setzero_ps(),c31=_mm512_setzero_ps();
+ __m512 c40=_mm512_setzero_ps(),c41=_mm512_setzero_ps();
+ __m512 c50=_mm512_setzero_ps(),c51=_mm512_setzero_ps();
+
+ const float*A=g->A+m*g->lda;
+ const float*a0=A,*a1=A,*a2=A,*a3=A,*a4=A,*a5=A;
+ if(mr>1)a1=A+g->lda;if(mr>2)a2=A+2*g->lda;if(mr>3)a3=A+3*g->lda;
+ if(mr>4)a4=A+4*g->lda;if(mr>5)a5=A+5*g->lda;
+
+ /* KC-blocked K-loop with unroll by 4 */
+ for (int kc = 0; kc < g->K; kc += KC_BLOCK) {
+ int kb = (kc + KC_BLOCK <= g->K) ? KC_BLOCK : g->K - kc;
+ int k = kc;
+ int kend4 = kc + (kb & ~3);
+ #define FK(off) { \
+ const float*bp=g->B+(k+(off))*g->N+n; \
+ __m512 b0=_mm512_loadu_ps(bp),b1=_mm512_loadu_ps(bp+16); __m512 va; \
+ va=_mm512_set1_ps(a0[k+(off)]);c00=_mm512_fmadd_ps(va,b0,c00);c01=_mm512_fmadd_ps(va,b1,c01); \
+ va=_mm512_set1_ps(a1[k+(off)]);c10=_mm512_fmadd_ps(va,b0,c10);c11=_mm512_fmadd_ps(va,b1,c11); \
+ va=_mm512_set1_ps(a2[k+(off)]);c20=_mm512_fmadd_ps(va,b0,c20);c21=_mm512_fmadd_ps(va,b1,c21); \
+ va=_mm512_set1_ps(a3[k+(off)]);c30=_mm512_fmadd_ps(va,b0,c30);c31=_mm512_fmadd_ps(va,b1,c31); \
+ va=_mm512_set1_ps(a4[k+(off)]);c40=_mm512_fmadd_ps(va,b0,c40);c41=_mm512_fmadd_ps(va,b1,c41); \
+ va=_mm512_set1_ps(a5[k+(off)]);c50=_mm512_fmadd_ps(va,b0,c50);c51=_mm512_fmadd_ps(va,b1,c51); }
+ for(;k<kend4;k+=4) { FK(0);FK(1);FK(2);FK(3); }
+ for(;k<kc+kb;k++) { FK(0); }
+ #undef FK
+ }
+
+ float*C=g->C+m*g->ldc+n;
+ #define FS(i,lo,hi) if(i<mr){ \
+ __m512 vb=_mm512_set1_ps(g->bias[m+(i)]); \
+ lo=_mm512_add_ps(lo,vb);hi=_mm512_add_ps(hi,vb); \
+ if(g->act==1){lo=_fused_silu512(lo);hi=_fused_silu512(hi);} \
+ else if(g->act==3){__m512 vl=_mm512_set1_ps(0.1f),vz=_mm512_setzero_ps(); \
+ lo=_mm512_mask_mul_ps(lo,_mm512_cmplt_ps_mask(lo,vz),lo,vl); \
+ hi=_mm512_mask_mul_ps(hi,_mm512_cmplt_ps_mask(hi,vz),hi,vl);} \
+ if(nr>=32){_mm512_storeu_ps(C+i*g->ldc,lo);_mm512_storeu_ps(C+i*g->ldc+16,hi);} \
+ else{__mmask16 ml=(nr>=16)?0xFFFF:((__mmask16)1<<nr)-1,mh=(nr<=16)?0:((__mmask16)1<<(nr-16))-1; \
+ _mm512_mask_storeu_ps(C+i*g->ldc,ml,lo);if(mh)_mm512_mask_storeu_ps(C+i*g->ldc+16,mh,hi);} \
+ }
+ FS(0,c00,c01);FS(1,c10,c11);FS(2,c20,c21);FS(3,c30,c31);FS(4,c40,c41);FS(5,c50,c51);
+ #undef FS
+ }
+ }
+}
+#endif /* __AVX512F__ */
+
+#ifdef __AVX512F__
+typedef struct { int M,K,N; const float*Ap; const float*B; float*C; int ldc; const float*bias; int act; } PackedCtx;
+
+/* KC-blocked packed fused worker.
+ * Split K into KC-sized chunks so B panel (KC×NR=KC×32 floats = KC×128 bytes)
+ * stays in L1 cache (~48KB). KC=256 → 32KB B panel per tile. */
+static void packed_fused_worker(void* arg, int start, int end) {
+ PackedCtx* g = (PackedCtx*)arg;
+ for (int ni = start; ni < end; ni++) {
+ int n = ni * NR512;
+ int nr = (n + NR512 <= g->N) ? NR512 : g->N - n;
+ int panels = (g->M + NN2_MR - 1) / NN2_MR;
+ for (int p = 0; p < panels; p++) {
+ int mr = ((p+1)*NN2_MR <= g->M) ? NN2_MR : g->M - p*NN2_MR;
+ __m512 c00=_mm512_setzero_ps(),c01=_mm512_setzero_ps();
+ __m512 c10=_mm512_setzero_ps(),c11=_mm512_setzero_ps();
+ __m512 c20=_mm512_setzero_ps(),c21=_mm512_setzero_ps();
+ __m512 c30=_mm512_setzero_ps(),c31=_mm512_setzero_ps();
+ __m512 c40=_mm512_setzero_ps(),c41=_mm512_setzero_ps();
+ __m512 c50=_mm512_setzero_ps(),c51=_mm512_setzero_ps();
+ const float* ap_base = g->Ap + p * g->K * NN2_MR;
+
+ /* KC-blocked K loop */
+ for (int kc = 0; kc < g->K; kc += KC_BLOCK) {
+ int kb = (kc + KC_BLOCK <= g->K) ? KC_BLOCK : g->K - kc;
+ const float* ap = ap_base + kc * NN2_MR;
+ const float* bp_base = g->B + kc * g->N + n;
+ int k = 0;
+ /* Unroll by 4 within KC block, prefetch B+2 rows ahead */
+ for (; k + 3 < kb; k += 4) {
+ if (k + 6 < kb) _mm_prefetch((const char*)(bp_base + (k+6) * g->N), _MM_HINT_T0);
+ #define KCF(off) { \
+ const float* bp = bp_base + (k+(off)) * g->N; \
+ const float* a = ap + (k+(off)) * NN2_MR; \
+ __m512 b0=_mm512_loadu_ps(bp), b1=_mm512_loadu_ps(bp+16); __m512 va; \
+ va=_mm512_set1_ps(a[0]);c00=_mm512_fmadd_ps(va,b0,c00);c01=_mm512_fmadd_ps(va,b1,c01); \
+ va=_mm512_set1_ps(a[1]);c10=_mm512_fmadd_ps(va,b0,c10);c11=_mm512_fmadd_ps(va,b1,c11); \
+ va=_mm512_set1_ps(a[2]);c20=_mm512_fmadd_ps(va,b0,c20);c21=_mm512_fmadd_ps(va,b1,c21); \
+ va=_mm512_set1_ps(a[3]);c30=_mm512_fmadd_ps(va,b0,c30);c31=_mm512_fmadd_ps(va,b1,c31); \
+ va=_mm512_set1_ps(a[4]);c40=_mm512_fmadd_ps(va,b0,c40);c41=_mm512_fmadd_ps(va,b1,c41); \
+ va=_mm512_set1_ps(a[5]);c50=_mm512_fmadd_ps(va,b0,c50);c51=_mm512_fmadd_ps(va,b1,c51); }
+ KCF(0);KCF(1);KCF(2);KCF(3);
+ #undef KCF
+ }
+ for (; k < kb; k++) {
+ const float* bp = bp_base + k * g->N;
+ const float* a = ap + k * NN2_MR;
+ __m512 b0=_mm512_loadu_ps(bp), b1=_mm512_loadu_ps(bp+16);
+ __m512 va;
+ va=_mm512_set1_ps(a[0]);c00=_mm512_fmadd_ps(va,b0,c00);c01=_mm512_fmadd_ps(va,b1,c01);
+ va=_mm512_set1_ps(a[1]);c10=_mm512_fmadd_ps(va,b0,c10);c11=_mm512_fmadd_ps(va,b1,c11);
+ va=_mm512_set1_ps(a[2]);c20=_mm512_fmadd_ps(va,b0,c20);c21=_mm512_fmadd_ps(va,b1,c21);
+ va=_mm512_set1_ps(a[3]);c30=_mm512_fmadd_ps(va,b0,c30);c31=_mm512_fmadd_ps(va,b1,c31);
+ va=_mm512_set1_ps(a[4]);c40=_mm512_fmadd_ps(va,b0,c40);c41=_mm512_fmadd_ps(va,b1,c41);
+ va=_mm512_set1_ps(a[5]);c50=_mm512_fmadd_ps(va,b0,c50);c51=_mm512_fmadd_ps(va,b1,c51);
+ }
+ }
+
+ int m = p * NN2_MR;
+ float* Cp = g->C + m * g->ldc + n;
+ #define FP(i,lo,hi) if(i<mr){ \
+ __m512 vb=_mm512_set1_ps(g->bias[m+(i)]); \
+ lo=_mm512_add_ps(lo,vb);hi=_mm512_add_ps(hi,vb); \
+ if(g->act==1){lo=_fused_silu512(lo);hi=_fused_silu512(hi);} \
+ if(nr>=32){_mm512_storeu_ps(Cp+i*g->ldc,lo);_mm512_storeu_ps(Cp+i*g->ldc+16,hi);} \
+ else{__mmask16 ml=(nr>=16)?0xFFFF:((__mmask16)1<<nr)-1,mh=(nr<=16)?0:((__mmask16)1<<(nr-16))-1; \
+ _mm512_mask_storeu_ps(Cp+i*g->ldc,ml,lo);if(mh)_mm512_mask_storeu_ps(Cp+i*g->ldc+16,mh,hi);}}
+ FP(0,c00,c01);FP(1,c10,c11);FP(2,c20,c21);FP(3,c30,c31);FP(4,c40,c41);FP(5,c50,c51);
+ #undef FP
+ }
+ }
+}
+#endif /* __AVX512F__ */
+
+/* 2D-tiled packed fused worker: tile index → (m_panel, n_tile) */
+typedef struct { int M,K,N; const float*Ap; const float*B; float*C; int ldc; const float*bias; int act; int n_tiles; } Packed2DCtx;
+
+static void packed_fused_2d_worker(void* arg, int start, int end) {
+ Packed2DCtx* g = (Packed2DCtx*)arg;
+ int panels = (g->M + NN2_MR - 1) / NN2_MR;
+ for (int ti = start; ti < end; ti++) {
+ int ni = ti % g->n_tiles;
+ int p = ti / g->n_tiles;
+ int n = ni * NR512;
+ int nr = (n + NR512 <= g->N) ? NR512 : g->N - n;
+ int mr = ((p+1)*NN2_MR <= g->M) ? NN2_MR : g->M - p*NN2_MR;
+
+ __m512 c00=_mm512_setzero_ps(),c01=_mm512_setzero_ps();
+ __m512 c10=_mm512_setzero_ps(),c11=_mm512_setzero_ps();
+ __m512 c20=_mm512_setzero_ps(),c21=_mm512_setzero_ps();
+ __m512 c30=_mm512_setzero_ps(),c31=_mm512_setzero_ps();
+ __m512 c40=_mm512_setzero_ps(),c41=_mm512_setzero_ps();
+ __m512 c50=_mm512_setzero_ps(),c51=_mm512_setzero_ps();
+ const float* ap_base = g->Ap + p * g->K * NN2_MR;
+ for (int kc = 0; kc < g->K; kc += KC_BLOCK) {
+ int kb = (kc + KC_BLOCK <= g->K) ? KC_BLOCK : g->K - kc;
+ const float* ap = ap_base + kc * NN2_MR;
+ const float* bp_base = g->B + kc * g->N + n;
+ int k = 0;
+ for (; k + 3 < kb; k += 4) {
+ #define KCF2(off) { \
+ const float* bp = bp_base + (k+(off)) * g->N; \
+ const float* a = ap + (k+(off)) * NN2_MR; \
+ __m512 b0=_mm512_loadu_ps(bp), b1=_mm512_loadu_ps(bp+16); __m512 va; \
+ va=_mm512_set1_ps(a[0]);c00=_mm512_fmadd_ps(va,b0,c00);c01=_mm512_fmadd_ps(va,b1,c01); \
+ va=_mm512_set1_ps(a[1]);c10=_mm512_fmadd_ps(va,b0,c10);c11=_mm512_fmadd_ps(va,b1,c11); \
+ va=_mm512_set1_ps(a[2]);c20=_mm512_fmadd_ps(va,b0,c20);c21=_mm512_fmadd_ps(va,b1,c21); \
+ va=_mm512_set1_ps(a[3]);c30=_mm512_fmadd_ps(va,b0,c30);c31=_mm512_fmadd_ps(va,b1,c31); \
+ va=_mm512_set1_ps(a[4]);c40=_mm512_fmadd_ps(va,b0,c40);c41=_mm512_fmadd_ps(va,b1,c41); \
+ va=_mm512_set1_ps(a[5]);c50=_mm512_fmadd_ps(va,b0,c50);c51=_mm512_fmadd_ps(va,b1,c51); }
+ KCF2(0);KCF2(1);KCF2(2);KCF2(3);
+ #undef KCF2
+ }
+ for (; k < kb; k++) {
+ const float* bp = bp_base + k * g->N;
+ const float* a = ap + k * NN2_MR;
+ __m512 b0=_mm512_loadu_ps(bp), b1=_mm512_loadu_ps(bp+16); __m512 va;
+ va=_mm512_set1_ps(a[0]);c00=_mm512_fmadd_ps(va,b0,c00);c01=_mm512_fmadd_ps(va,b1,c01);
+ va=_mm512_set1_ps(a[1]);c10=_mm512_fmadd_ps(va,b0,c10);c11=_mm512_fmadd_ps(va,b1,c11);
+ va=_mm512_set1_ps(a[2]);c20=_mm512_fmadd_ps(va,b0,c20);c21=_mm512_fmadd_ps(va,b1,c21);
+ va=_mm512_set1_ps(a[3]);c30=_mm512_fmadd_ps(va,b0,c30);c31=_mm512_fmadd_ps(va,b1,c31);
+ va=_mm512_set1_ps(a[4]);c40=_mm512_fmadd_ps(va,b0,c40);c41=_mm512_fmadd_ps(va,b1,c41);
+ va=_mm512_set1_ps(a[5]);c50=_mm512_fmadd_ps(va,b0,c50);c51=_mm512_fmadd_ps(va,b1,c51);
+ }
+ }
+ int m = p * NN2_MR;
+ float* Cp = g->C + m * g->ldc + n;
+ #define FP2(i,lo,hi) if(i<mr){ \
+ __m512 vb=_mm512_set1_ps(g->bias[m+(i)]); \
+ lo=_mm512_add_ps(lo,vb);hi=_mm512_add_ps(hi,vb); \
+ if(g->act==1){lo=_fused_silu512(lo);hi=_fused_silu512(hi);} \
+ if(nr>=32){_mm512_storeu_ps(Cp+i*g->ldc,lo);_mm512_storeu_ps(Cp+i*g->ldc+16,hi);} \
+ else{__mmask16 ml=(nr>=16)?0xFFFF:((__mmask16)1<<nr)-1,mh=(nr<=16)?0:((__mmask16)1<<(nr-16))-1; \
+ _mm512_mask_storeu_ps(Cp+i*g->ldc,ml,lo);if(mh)_mm512_mask_storeu_ps(Cp+i*g->ldc+16,mh,hi);}}
+ FP2(0,c00,c01);FP2(1,c10,c11);FP2(2,c20,c21);FP2(3,c30,c31);FP2(4,c40,c41);FP2(5,c50,c51);
+ #undef FP2
+ }
+}
+
+void nn2_sgemm_bias_act_packed(int M, int K, int N,
+ const float* Ap,
+ const float* B, float* C, int ldc,
+ const float* bias, int act)
+{
+#ifdef __AVX512F__
+ int n_tiles = (N + NR512 - 1) / NR512;
+ int m_panels = (M + NN2_MR - 1) / NN2_MR;
+ int total_2d = m_panels * n_tiles;
+ /* Use 2D tiling when N-tiles alone aren't enough to fill threads */
+ if (n_tiles <= 1) {
+ PackedCtx pg = {M, K, N, Ap, B, C, ldc, bias, act};
+ packed_fused_worker(&pg, 0, n_tiles);
+ } else if (n_tiles < nn2_tp_num_threads() && total_2d >= 4) {
+ Packed2DCtx pg = {M, K, N, Ap, B, C, ldc, bias, act, n_tiles};
+ int grain = (total_2d > 64) ? total_2d / (nn2_tp_num_threads() * 4) : 1;
+ if (grain < 1) grain = 1;
+ nn2_tp_parallel_for(packed_fused_2d_worker, &pg, total_2d, grain);
+ } else {
+ PackedCtx pg = {M, K, N, Ap, B, C, ldc, bias, act};
+ int grain = (n_tiles > 128) ? n_tiles / (nn2_tp_num_threads() * 4) : 1;
+ if (grain < 1) grain = 1;
+ nn2_tp_parallel_for(packed_fused_worker, &pg, n_tiles, grain);
+ }
+#else
+ (void)Ap;(void)B;(void)C;(void)ldc;(void)bias;(void)act;(void)M;(void)K;(void)N;
+#endif
+}
+
+void nn2_sgemm_bias_act(int M, int K, int N,
+ const float* A, int lda,
+ const float* B, int ldb,
+ float* C, int ldc,
+ const float* bias, int act)
+{
+ (void)ldb;
+#ifdef __AVX512F__
+ GemmFusedCtx g = {M, K, N, A, lda, B, C, ldc, bias, act};
+ int n_tiles = (N + NR512 - 1) / NR512;
+ int grain = (n_tiles > 128) ? n_tiles / (nn2_tp_num_threads() * 4) : 1;
+ if (grain < 1) grain = 1;
+ if (n_tiles >= 2)
+ nn2_tp_parallel_for(gemm_fused_avx512_worker, &g, n_tiles, grain);
+ else
+ gemm_fused_avx512_worker(&g, 0, n_tiles);
+#else
+ /* Fallback: regular GEMM + separate bias+act */
+ nn2_sgemm(M, K, N, A, lda, B, ldb, C, ldc);
+ for (int m = 0; m < M; m++) {
+ float b = bias[m];
+ for (int n = 0; n < N; n++) {
+ float v = C[m*ldc+n] + b;
+ if (act == 1) { float s = 1.0f/(1.0f+expf(-v)); v *= s; }
+ else if (act == 3 && v < 0) v *= 0.1f;
+ C[m*ldc+n] = v;
+ }
+ }
+#endif
+}
+
+/* ============ Scalar fallback ============ */
+
+static void gemm_scalar(int M, int K, int N,
+ const float* A, int lda,
+ const float* B, float* C, int ldc)
+{
+ for (int m=0;m<M;m++)
+ for (int n=0;n<N;n++) {
+ float acc=0;
+ for (int k=0;k<K;k++) acc+=A[m*lda+k]*B[k*N+n];
+ C[m*ldc+n]=acc;
+ }
+}
+
+/* ============ Public GEMM ============ */
+
+void nn2_sgemm(int M, int K, int N,
+ const float* A, int lda,
+ const float* B, int ldb,
+ float* C, int ldc)
+{
+ (void)ldb;
+
+#ifdef __AVX512F__
+ {
+ GemmCtx g = {M, K, N, A, lda, B, C, ldc};
+ int n_tiles = (N + NR512 - 1) / NR512;
+ int grain = (n_tiles > 128) ? n_tiles / (nn2_tp_num_threads() * 4) : 1;
+ if (grain < 1) grain = 1;
+ if (n_tiles >= 2 && N >= 32)
+ nn2_tp_parallel_for(gemm_avx512_worker, &g, n_tiles, grain);
+ else
+ gemm_avx512_worker(&g, 0, n_tiles);
+ return;
+ }
+#endif
+
+#ifdef __AVX2__
+ {
+ GemmCtx g = {M, K, N, A, lda, B, C, ldc};
+ int n_tiles = (N + NN2_NR - 1) / NN2_NR;
+ int grain = (n_tiles > 256) ? n_tiles / (nn2_tp_num_threads() * 4) : 1;
+ if (grain < 1) grain = 1;
+ if (n_tiles >= 2 && N >= 32)
+ nn2_tp_parallel_for(gemm_avx2_worker, &g, n_tiles, grain);
+ else
+ gemm_avx2_worker(&g, 0, n_tiles);
+ return;
+ }
+#endif
+
+ gemm_scalar(M, K, N, A, lda, B, C, ldc);
+}
diff --git a/nn2/src/gemm_asm.h b/nn2/src/gemm_asm.h
new file mode 100644
index 0000000..ba45761
--- /dev/null
+++ b/nn2/src/gemm_asm.h
@@ -0,0 +1,145 @@
+/*
+ * gemm_asm.h — AVX-512 GEMM microkernel in GCC inline assembly.
+ *
+ * 6×32 tile: 12 ZMM accumulators, software-pipelined B loads.
+ * Register allocation:
+ * zmm0-zmm11: accumulators (c00,c01,c10,...,c51)
+ * zmm12-zmm13: B loads (current)
+ * zmm14-zmm15: B loads (prefetched next iteration)
+ * zmm30: A broadcast
+ *
+ * Software pipeline: load B[k+1] while computing with B[k].
+ * This hides the ~7 cycle load latency behind FMA computation.
+ */
+
+#ifndef GEMM_ASM_H
+#define GEMM_ASM_H
+
+#ifdef __AVX512F__
+#ifdef __GNUC__
+
+#include <immintrin.h>
+
+/* Assembly 6×32 microkernel with software-pipelined B loads.
+ * C[6][32] += A[6][K] × B[K][32]
+ * A rows accessed via a0..a5 pointers, B via bp with stride ldb. */
+static inline void gemm_6x32_asm(
+ int K,
+ const float* a0, const float* a1, const float* a2,
+ const float* a3, const float* a4, const float* a5,
+ const float* B, int ldb_bytes, /* ldb * 4 */
+ float* C, int ldc)
+{
+ /* Zero accumulators */
+ __asm__ __volatile__(
+ "vpxord %%zmm0, %%zmm0, %%zmm0\n\t"
+ "vpxord %%zmm1, %%zmm1, %%zmm1\n\t"
+ "vpxord %%zmm2, %%zmm2, %%zmm2\n\t"
+ "vpxord %%zmm3, %%zmm3, %%zmm3\n\t"
+ "vpxord %%zmm4, %%zmm4, %%zmm4\n\t"
+ "vpxord %%zmm5, %%zmm5, %%zmm5\n\t"
+ "vpxord %%zmm6, %%zmm6, %%zmm6\n\t"
+ "vpxord %%zmm7, %%zmm7, %%zmm7\n\t"
+ "vpxord %%zmm8, %%zmm8, %%zmm8\n\t"
+ "vpxord %%zmm9, %%zmm9, %%zmm9\n\t"
+ "vpxord %%zmm10, %%zmm10, %%zmm10\n\t"
+ "vpxord %%zmm11, %%zmm11, %%zmm11\n\t"
+ ::: "zmm0","zmm1","zmm2","zmm3","zmm4","zmm5",
+ "zmm6","zmm7","zmm8","zmm9","zmm10","zmm11"
+ );
+
+ /* K-loop with software-pipelined B loads */
+ const float* bp = B;
+ for (int k = 0; k < K; k++) {
+ __asm__ __volatile__(
+ /* Load B[k][0:16] and B[k][16:32] */
+ "vmovups (%[bp]), %%zmm12\n\t"
+ "vmovups 64(%[bp]), %%zmm13\n\t"
+
+ /* Prefetch next B row */
+ "prefetcht0 (%[bp],%[ldb])\n\t"
+
+ /* Row 0: broadcast a0[k], FMA with B */
+ "vbroadcastss (%[a0],%[k4]), %%zmm30\n\t"
+ "vfmadd231ps %%zmm30, %%zmm12, %%zmm0\n\t"
+ "vfmadd231ps %%zmm30, %%zmm13, %%zmm1\n\t"
+
+ /* Row 1 */
+ "vbroadcastss (%[a1],%[k4]), %%zmm30\n\t"
+ "vfmadd231ps %%zmm30, %%zmm12, %%zmm2\n\t"
+ "vfmadd231ps %%zmm30, %%zmm13, %%zmm3\n\t"
+
+ /* Row 2 */
+ "vbroadcastss (%[a2],%[k4]), %%zmm30\n\t"
+ "vfmadd231ps %%zmm30, %%zmm12, %%zmm4\n\t"
+ "vfmadd231ps %%zmm30, %%zmm13, %%zmm5\n\t"
+
+ /* Row 3 */
+ "vbroadcastss (%[a3],%[k4]), %%zmm30\n\t"
+ "vfmadd231ps %%zmm30, %%zmm12, %%zmm6\n\t"
+ "vfmadd231ps %%zmm30, %%zmm13, %%zmm7\n\t"
+
+ /* Row 4 */
+ "vbroadcastss (%[a4],%[k4]), %%zmm30\n\t"
+ "vfmadd231ps %%zmm30, %%zmm12, %%zmm8\n\t"
+ "vfmadd231ps %%zmm30, %%zmm13, %%zmm9\n\t"
+
+ /* Row 5 */
+ "vbroadcastss (%[a5],%[k4]), %%zmm30\n\t"
+ "vfmadd231ps %%zmm30, %%zmm12, %%zmm10\n\t"
+ "vfmadd231ps %%zmm30, %%zmm13, %%zmm11\n\t"
+
+ :
+ : [bp] "r" (bp), [ldb] "r" ((long long)ldb_bytes),
+ [a0] "r" (a0), [a1] "r" (a1), [a2] "r" (a2),
+ [a3] "r" (a3), [a4] "r" (a4), [a5] "r" (a5),
+ [k4] "r" ((long long)(k * 4))
+ : "zmm0","zmm1","zmm2","zmm3","zmm4","zmm5",
+ "zmm6","zmm7","zmm8","zmm9","zmm10","zmm11",
+ "zmm12","zmm13","zmm30","memory"
+ );
+ bp = (const float*)((const char*)bp + ldb_bytes);
+ }
+
+ /* Store accumulators to C */
+ float* c = C;
+ __asm__ __volatile__(
+ "vmovups %%zmm0, (%[c])\n\t"
+ "vmovups %%zmm1, 64(%[c])\n\t"
+ :: [c] "r" (c) : "memory"
+ );
+ c += ldc;
+ __asm__ __volatile__(
+ "vmovups %%zmm2, (%[c])\n\t"
+ "vmovups %%zmm3, 64(%[c])\n\t"
+ :: [c] "r" (c) : "memory"
+ );
+ c += ldc;
+ __asm__ __volatile__(
+ "vmovups %%zmm4, (%[c])\n\t"
+ "vmovups %%zmm5, 64(%[c])\n\t"
+ :: [c] "r" (c) : "memory"
+ );
+ c += ldc;
+ __asm__ __volatile__(
+ "vmovups %%zmm6, (%[c])\n\t"
+ "vmovups %%zmm7, 64(%[c])\n\t"
+ :: [c] "r" (c) : "memory"
+ );
+ c += ldc;
+ __asm__ __volatile__(
+ "vmovups %%zmm8, (%[c])\n\t"
+ "vmovups %%zmm9, 64(%[c])\n\t"
+ :: [c] "r" (c) : "memory"
+ );
+ c += ldc;
+ __asm__ __volatile__(
+ "vmovups %%zmm10, (%[c])\n\t"
+ "vmovups %%zmm11, 64(%[c])\n\t"
+ :: [c] "r" (c) : "memory"
+ );
+}
+
+#endif /* __GNUC__ */
+#endif /* __AVX512F__ */
+#endif /* GEMM_ASM_H */
diff --git a/nn2/src/gemm_avx512.S b/nn2/src/gemm_avx512.S
new file mode 100644
index 0000000..86b8e64
--- /dev/null
+++ b/nn2/src/gemm_avx512.S
@@ -0,0 +1,136 @@
+/*
+ * gemm_avx512.S — Hand-written AVX-512 6×32 microkernel.
+ *
+ * C ABI wrapper passes all args via a single struct pointer.
+ * void gemm_6x32_kern(const GemmKernArgs* args);
+ *
+ * struct GemmKernArgs {
+ * int K; // offset 0
+ * const float* a[6]; // offset 8 (8 bytes each = 48 bytes)
+ * const float* B; // offset 56
+ * int ldb_bytes; // offset 64
+ * float* C; // offset 72
+ * int ldc_bytes; // offset 80
+ * };
+ */
+
+ .text
+ .globl gemm_6x32_kern
+
+gemm_6x32_kern:
+ /* rcx = args pointer (Win64) */
+ push %rbx
+ push %rsi
+ push %rdi
+ push %r12
+ push %r13
+ push %r14
+ push %r15
+
+ mov %rcx, %rbx /* args base */
+
+ /* Load args from struct */
+ mov (%rbx), %eax /* K (int, 4 bytes, but at offset 0) */
+ /* Actually struct has int K at offset 0, then padding to 8 for pointers */
+ mov 8(%rbx), %r10 /* a[0] */
+ mov 16(%rbx), %r11 /* a[1] */
+ mov 24(%rbx), %r12 /* a[2] */
+ mov 32(%rbx), %r13 /* a[3] */
+ mov 40(%rbx), %r14 /* a[4] */
+ mov 48(%rbx), %r15 /* a[5] */
+ mov 56(%rbx), %rsi /* B */
+ mov 64(%rbx), %edi /* ldb_bytes */
+ mov 72(%rbx), %r8 /* C */
+ mov 80(%rbx), %r9d /* ldc_bytes */
+
+ /* Zero accumulators */
+ vpxord %zmm0, %zmm0, %zmm0
+ vpxord %zmm1, %zmm1, %zmm1
+ vpxord %zmm2, %zmm2, %zmm2
+ vpxord %zmm3, %zmm3, %zmm3
+ vpxord %zmm4, %zmm4, %zmm4
+ vpxord %zmm5, %zmm5, %zmm5
+ vpxord %zmm6, %zmm6, %zmm6
+ vpxord %zmm7, %zmm7, %zmm7
+ vpxord %zmm8, %zmm8, %zmm8
+ vpxord %zmm9, %zmm9, %zmm9
+ vpxord %zmm10, %zmm10, %zmm10
+ vpxord %zmm11, %zmm11, %zmm11
+
+ /* K loop — ecx = byte offset into A rows */
+ xor %ecx, %ecx
+ shl $2, %eax /* K *= 4 (byte count) */
+
+.Lloop:
+ cmp %eax, %ecx
+ jge .Ldone
+
+ /* Load B[k][0:32] */
+ vmovups (%rsi), %zmm28
+ vmovups 64(%rsi), %zmm29
+
+ /* 6 rows: broadcast A[row][k] × B[k] */
+ vbroadcastss (%r10, %rcx, 1), %zmm30
+ vfmadd231ps %zmm30, %zmm28, %zmm0
+ vfmadd231ps %zmm30, %zmm29, %zmm1
+
+ vbroadcastss (%r11, %rcx, 1), %zmm30
+ vfmadd231ps %zmm30, %zmm28, %zmm2
+ vfmadd231ps %zmm30, %zmm29, %zmm3
+
+ vbroadcastss (%r12, %rcx, 1), %zmm30
+ vfmadd231ps %zmm30, %zmm28, %zmm4
+ vfmadd231ps %zmm30, %zmm29, %zmm5
+
+ vbroadcastss (%r13, %rcx, 1), %zmm30
+ vfmadd231ps %zmm30, %zmm28, %zmm6
+ vfmadd231ps %zmm30, %zmm29, %zmm7
+
+ vbroadcastss (%r14, %rcx, 1), %zmm30
+ vfmadd231ps %zmm30, %zmm28, %zmm8
+ vfmadd231ps %zmm30, %zmm29, %zmm9
+
+ vbroadcastss (%r15, %rcx, 1), %zmm30
+ vfmadd231ps %zmm30, %zmm28, %zmm10
+ vfmadd231ps %zmm30, %zmm29, %zmm11
+
+ /* Advance */
+ movsxd %edi, %rdx
+ add %rdx, %rsi /* B += ldb_bytes */
+ add $4, %ecx /* k_offset += 4 */
+ jmp .Lloop
+
+.Ldone:
+ /* Store C */
+ vmovups %zmm0, (%r8)
+ vmovups %zmm1, 64(%r8)
+ movsxd %r9d, %rdx
+ add %rdx, %r8
+
+ vmovups %zmm2, (%r8)
+ vmovups %zmm3, 64(%r8)
+ add %rdx, %r8
+
+ vmovups %zmm4, (%r8)
+ vmovups %zmm5, 64(%r8)
+ add %rdx, %r8
+
+ vmovups %zmm6, (%r8)
+ vmovups %zmm7, 64(%r8)
+ add %rdx, %r8
+
+ vmovups %zmm8, (%r8)
+ vmovups %zmm9, 64(%r8)
+ add %rdx, %r8
+
+ vmovups %zmm10, (%r8)
+ vmovups %zmm11, 64(%r8)
+
+ pop %r15
+ pop %r14
+ pop %r13
+ pop %r12
+ pop %rdi
+ pop %rsi
+ pop %rbx
+ ret
diff --git a/nn2/src/gemm_int8.c b/nn2/src/gemm_int8.c
new file mode 100644
index 0000000..c1a6314
--- /dev/null
+++ b/nn2/src/gemm_int8.c
@@ -0,0 +1,197 @@
+/*
+ * gemm_int8.c — INT8 GEMM with AVX-512 VNNI.
+ *
+ * Uses VPDPBUSD: u8 × s8 → s32 accumulation, no saturation.
+ * Tile: MR=4, NR=16 (4 rows × 16 cols, 4 ZMM accumulators).
+ *
+ * Weight layout: packed c4 format (4 k-values per group for VNNI alignment).
+ * Activation: s8 converted to u8 via +128 offset (XOR trick).
+ * Compensation: pre-computed 128 * col_sum per output channel.
+ *
+ * Fused epilogue: acc → float → (- compensation) * w_scale → + bias → SiLU → * out_scale → clamp → s8
+ */
+
+#include "nn2_internal.h"
+#include <string.h>
+#include <stdlib.h>
+#include <math.h>
+#include <immintrin.h>
+
+/* ============ Weight packing for VNNI: [Cout_group][K_blocks][16×4 bytes] ============ */
+
+/* Pack int8 weights from [Cout, K] row-major into VNNI-friendly format.
+ * NR=16 columns per group, K padded to multiple of 4.
+ * Layout per group: [K/4 blocks of 64 bytes: 16 cols × 4 k-values] */
+void nn2_int8_pack_weights(
+ const int8_t* weights, /* [Cout, K] */
+ int K, int Cout,
+ void* packed_out, /* output buffer */
+ int32_t* col_sums) /* [Cout]: 128 * sum(w) per channel */
+{
+ int K4 = (K + 3) & ~3;
+ uint8_t* out = (uint8_t*)packed_out;
+
+ for (int co = 0; co < Cout; co += 16) {
+ int nr = (co + 16 <= Cout) ? 16 : Cout - co;
+
+ /* Compute col_sums */
+ for (int j = 0; j < nr; j++) {
+ int32_t sum = 0;
+ for (int k = 0; k < K; k++)
+ sum += (int32_t)weights[(co + j) * K + k];
+ col_sums[co + j] = 128 * sum;
+ }
+
+ /* Pack: [K4/4 blocks][16 cols × 4 k-values = 64 bytes] */
+ for (int k = 0; k < K4; k += 4) {
+ for (int j = 0; j < 16; j++) {
+ for (int kk = 0; kk < 4; kk++) {
+ if (j < nr && (k + kk) < K)
+ *out++ = (uint8_t)weights[(co + j) * K + (k + kk)];
+ else
+ *out++ = 0;
+ }
+ }
+ }
+ }
+}
+
+int nn2_int8_packed_size(int K, int Cout)
+{
+ int K4 = (K + 3) & ~3;
+ int groups = (Cout + 15) / 16;
+ return groups * K4 * 16; /* bytes */
+}
+
+/* ============ VNNI microkernel: 4 rows × 16 cols ============ */
+
+#ifdef __AVX512VNNI__
+
+static void vnni_4x16_ukernel(
+ int K, /* must be padded to multiple of 4 */
+ const int8_t* A, int a_stride, /* [mr, K] s8 activation */
+ const uint8_t* W, /* packed weights [K/4][16×4] */
+ int32_t* C, /* [mr, 16] output accumulators */
+ int mr)
+{
+ __m512i acc0 = _mm512_setzero_si512();
+ __m512i acc1 = _mm512_setzero_si512();
+ __m512i acc2 = _mm512_setzero_si512();
+ __m512i acc3 = _mm512_setzero_si512();
+
+ const int8_t* a0 = A;
+ const int8_t* a1 = (mr > 1) ? a0 + a_stride : a0;
+ const int8_t* a2 = (mr > 2) ? a0 + 2 * a_stride : a0;
+ const int8_t* a3 = (mr > 3) ? a0 + 3 * a_stride : a0;
+
+ const uint32_t xor32 = 0x80808080u;
+
+ for (int k = 0; k < K; k += 4) {
+ /* Load packed B: 16 columns × 4 k-values = 64 bytes = 1 ZMM */
+ __m512i vb = _mm512_loadu_si512((const __m512i*)W);
+ W += 64;
+
+ /* Broadcast 4 A bytes (one row), XOR to unsigned */
+ uint32_t a0_val, a1_val, a2_val, a3_val;
+ memcpy(&a0_val, a0 + k, 4); a0_val ^= xor32;
+ memcpy(&a1_val, a1 + k, 4); a1_val ^= xor32;
+ memcpy(&a2_val, a2 + k, 4); a2_val ^= xor32;
+ memcpy(&a3_val, a3 + k, 4); a3_val ^= xor32;
+
+ __m512i va0 = _mm512_set1_epi32(a0_val);
+ __m512i va1 = _mm512_set1_epi32(a1_val);
+ __m512i va2 = _mm512_set1_epi32(a2_val);
+ __m512i va3 = _mm512_set1_epi32(a3_val);
+
+ /* VPDPBUSD: acc += u8(A) · s8(B) per 32-bit lane, no saturation */
+ acc0 = _mm512_dpbusd_epi32(acc0, va0, vb);
+ acc1 = _mm512_dpbusd_epi32(acc1, va1, vb);
+ acc2 = _mm512_dpbusd_epi32(acc2, va2, vb);
+ acc3 = _mm512_dpbusd_epi32(acc3, va3, vb);
+ }
+
+ _mm512_storeu_si512((__m512i*)(C), acc0);
+ if (mr > 1) _mm512_storeu_si512((__m512i*)(C + 16), acc1);
+ if (mr > 2) _mm512_storeu_si512((__m512i*)(C + 32), acc2);
+ if (mr > 3) _mm512_storeu_si512((__m512i*)(C + 48), acc3);
+}
+
+#endif /* __AVX512VNNI__ */
+
+/* ============ Full INT8 GEMM with fused epilogue ============ */
+
+void nn2_int8_gemm_fused(
+ const int8_t* A, int M, int K, int N, /* A[M,K] s8 activations */
+ const void* B_packed, /* packed weights */
+ const int32_t* col_sums, /* [N] compensation */
+ const float* w_scales, /* [N] per-channel weight scale */
+ const float* bias, /* [N] or NULL */
+ float act_scale, /* input activation scale (per-tensor) */
+ float out_scale, /* output activation scale (per-tensor) */
+ int act_type, /* 0=none, 1=SiLU, 2=ReLU */
+ float* output) /* [M, N] float output */
+{
+ int K4 = (K + 3) & ~3;
+ /* Pad A to K4 */
+ int8_t* A_pad = NULL;
+ const int8_t* A_eff = A;
+ if (K != K4) {
+ A_pad = (int8_t*)calloc(M * K4, 1);
+ for (int m = 0; m < M; m++)
+ memcpy(A_pad + m * K4, A + m * K, K);
+ A_eff = A_pad;
+ }
+
+#ifdef __AVX512VNNI__
+ int32_t acc_buf[4 * 16];
+
+ for (int m = 0; m < M; m += 4) {
+ int mr = (m + 4 <= M) ? 4 : M - m;
+ const uint8_t* w_ptr = (const uint8_t*)B_packed;
+
+ for (int n = 0; n < N; n += 16) {
+ int nr = (n + 16 <= N) ? 16 : N - n;
+
+ memset(acc_buf, 0, sizeof(acc_buf));
+ vnni_4x16_ukernel(K4, A_eff + m * K4, K4, w_ptr, acc_buf, mr);
+
+ /* Fused epilogue: dequant + bias + activation */
+ float inv_out = (out_scale > 0) ? 1.0f / out_scale : 1.0f;
+ for (int i = 0; i < mr; i++) {
+ float* orow = output + (m + i) * N + n;
+ for (int j = 0; j < nr; j++) {
+ /* Dequantize: (acc - compensation) * act_scale * w_scale */
+ float val = (float)(acc_buf[i * 16 + j] - col_sums[n + j])
+ * act_scale * w_scales[n + j];
+ if (bias) val += bias[n + j];
+
+ /* Activation */
+ if (act_type == 1) { /* SiLU */
+ float sig = 1.0f / (1.0f + expf(-val));
+ val = val * sig;
+ } else if (act_type == 2) { /* ReLU */
+ if (val < 0) val = 0;
+ }
+
+ orow[j] = val;
+ }
+ }
+
+ w_ptr += K4 * 16;
+ }
+ }
+#else
+ /* Scalar fallback */
+ for (int m = 0; m < M; m++) {
+ for (int n = 0; n < N; n++) {
+ int32_t acc = 0;
+ for (int k = 0; k < K; k++)
+ acc += (int32_t)((uint8_t)((int)A_eff[m * K + k] + 128)) * (int32_t)((const int8_t*)B_packed)[/* ... */0];
+ /* ... simplified, real impl needs proper unpacking */
+ output[m * N + n] = (float)acc;
+ }
+ }
+#endif
+
+ free(A_pad);
+}
diff --git a/nn2/src/gemm_neon.h b/nn2/src/gemm_neon.h
new file mode 100644
index 0000000..a809354
--- /dev/null
+++ b/nn2/src/gemm_neon.h
@@ -0,0 +1,205 @@
+/*
+ * gemm_neon.h — ARM NEON FP32 GEMM + SiLU for AArch64.
+ *
+ * Microkernel: MR=8, NR=4 (8 rows × 4 cols = 8 accumulators).
+ * NEON: 128-bit, 4 floats per register, 32 registers available.
+ * 8 acc + 1 B load + 8 A broadcasts = 17 registers. Fits.
+ *
+ * For Raspberry Pi 4 (Cortex-A72): ~12 GFLOPS FP32 peak.
+ * For Rockchip RK3588 (Cortex-A76): ~50 GFLOPS FP32 peak.
+ */
+
+#ifndef GEMM_NEON_H
+#define GEMM_NEON_H
+
+#ifdef __aarch64__
+#include <arm_neon.h>
+
+#define NEON_MR 8
+#define NEON_NR 4
+
+/* ============ Cephes exp for NEON ============ */
+
+static inline float32x4_t neon_exp_fast(float32x4_t x)
+{
+ const float32x4_t log2e = vdupq_n_f32(1.44269504088896341f);
+ const float32x4_t ln2_hi = vdupq_n_f32(0.693145751953125f);
+ const float32x4_t ln2_lo = vdupq_n_f32(1.42860682030941723212e-6f);
+
+ /* Clamp */
+ x = vmaxq_f32(x, vdupq_n_f32(-87.3f));
+ x = vminq_f32(x, vdupq_n_f32(88.7f));
+
+ /* n = round(x / ln2) */
+ float32x4_t n = vrndnq_f32(vmulq_f32(x, log2e));
+
+ /* f = x - n * ln2 */
+ float32x4_t f = vfmsq_f32(x, n, ln2_hi);
+ f = vfmsq_f32(f, n, ln2_lo);
+
+ /* Polynomial: 1 + f + f²/2 + f³/6 + ... */
+ float32x4_t p = vdupq_n_f32(0.00138888889039885e0f);
+ p = vfmaq_f32(vdupq_n_f32(0.00833333333371142972e0f), p, f);
+ p = vfmaq_f32(vdupq_n_f32(0.0416666666665065678e0f), p, f);
+ p = vfmaq_f32(vdupq_n_f32(0.166666666666666019037f), p, f);
+ p = vfmaq_f32(vdupq_n_f32(0.5f), p, f);
+ p = vfmaq_f32(vdupq_n_f32(1.0f), p, f);
+ p = vfmaq_f32(vdupq_n_f32(1.0f), p, f);
+
+ /* 2^n via bit manipulation */
+ int32x4_t ni = vcvtq_s32_f32(n);
+ ni = vaddq_s32(ni, vdupq_n_s32(127));
+ ni = vshlq_n_s32(ni, 23);
+ float32x4_t pow2n = vreinterpretq_f32_s32(ni);
+
+ return vmulq_f32(p, pow2n);
+}
+
+static inline float32x4_t neon_sigmoid(float32x4_t x)
+{
+ float32x4_t one = vdupq_n_f32(1.0f);
+ float32x4_t neg_x = vnegq_f32(x);
+ return vdivq_f32(one, vaddq_f32(one, neon_exp_fast(neg_x)));
+}
+
+static inline float32x4_t neon_silu(float32x4_t x)
+{
+ return vmulq_f32(x, neon_sigmoid(x));
+}
+
+/* ============ GEMM 8×4 microkernel ============ */
+
+static inline void neon_ukernel_8x4(
+ int K,
+ const float* restrict A, int lda,
+ const float* restrict B, int ldb,
+ float* restrict C, int ldc,
+ int mr)
+{
+ float32x4_t c0 = vdupq_n_f32(0), c1 = vdupq_n_f32(0);
+ float32x4_t c2 = vdupq_n_f32(0), c3 = vdupq_n_f32(0);
+ float32x4_t c4 = vdupq_n_f32(0), c5 = vdupq_n_f32(0);
+ float32x4_t c6 = vdupq_n_f32(0), c7 = vdupq_n_f32(0);
+
+ const float *a0=A, *a1=A, *a2=A, *a3=A, *a4=A, *a5=A, *a6=A, *a7=A;
+ if(mr>1) a1=A+lda; if(mr>2) a2=A+2*lda; if(mr>3) a3=A+3*lda;
+ if(mr>4) a4=A+4*lda; if(mr>5) a5=A+5*lda;
+ if(mr>6) a6=A+6*lda; if(mr>7) a7=A+7*lda;
+
+ for (int k = 0; k < K; k++) {
+ float32x4_t b = vld1q_f32(B + k * ldb);
+ c0 = vfmaq_n_f32(c0, b, a0[k]);
+ c1 = vfmaq_n_f32(c1, b, a1[k]);
+ c2 = vfmaq_n_f32(c2, b, a2[k]);
+ c3 = vfmaq_n_f32(c3, b, a3[k]);
+ c4 = vfmaq_n_f32(c4, b, a4[k]);
+ c5 = vfmaq_n_f32(c5, b, a5[k]);
+ c6 = vfmaq_n_f32(c6, b, a6[k]);
+ c7 = vfmaq_n_f32(c7, b, a7[k]);
+ }
+
+ if(mr>0) vst1q_f32(C + 0*ldc, c0);
+ if(mr>1) vst1q_f32(C + 1*ldc, c1);
+ if(mr>2) vst1q_f32(C + 2*ldc, c2);
+ if(mr>3) vst1q_f32(C + 3*ldc, c3);
+ if(mr>4) vst1q_f32(C + 4*ldc, c4);
+ if(mr>5) vst1q_f32(C + 5*ldc, c5);
+ if(mr>6) vst1q_f32(C + 6*ldc, c6);
+ if(mr>7) vst1q_f32(C + 7*ldc, c7);
+}
+
+/* ============ Fused GEMM + bias + SiLU for NEON ============ */
+
+static inline void neon_ukernel_8x4_fused(
+ int K,
+ const float* restrict A, int lda,
+ const float* restrict B, int ldb,
+ float* restrict C, int ldc,
+ const float* bias, int m_start, int mr, int act)
+{
+ float32x4_t c0={0},c1={0},c2={0},c3={0},c4={0},c5={0},c6={0},c7={0};
+ const float *a0=A, *a1=A, *a2=A, *a3=A, *a4=A, *a5=A, *a6=A, *a7=A;
+ if(mr>1) a1=A+lda; if(mr>2) a2=A+2*lda; if(mr>3) a3=A+3*lda;
+ if(mr>4) a4=A+4*lda; if(mr>5) a5=A+5*lda;
+ if(mr>6) a6=A+6*lda; if(mr>7) a7=A+7*lda;
+
+ for (int k = 0; k < K; k++) {
+ float32x4_t b = vld1q_f32(B + k * ldb);
+ c0=vfmaq_n_f32(c0,b,a0[k]); c1=vfmaq_n_f32(c1,b,a1[k]);
+ c2=vfmaq_n_f32(c2,b,a2[k]); c3=vfmaq_n_f32(c3,b,a3[k]);
+ c4=vfmaq_n_f32(c4,b,a4[k]); c5=vfmaq_n_f32(c5,b,a5[k]);
+ c6=vfmaq_n_f32(c6,b,a6[k]); c7=vfmaq_n_f32(c7,b,a7[k]);
+ }
+
+ /* Fused: bias + activation + store */
+ #define NEON_STORE(i, acc) if(i<mr) { \
+ acc = vaddq_f32(acc, vdupq_n_f32(bias[m_start+(i)])); \
+ if (act == 1) acc = neon_silu(acc); \
+ else if (act == 3) { \
+ uint32x4_t neg = vcltq_f32(acc, vdupq_n_f32(0)); \
+ acc = vbslq_f32(neg, vmulq_n_f32(acc, 0.1f), acc); } \
+ vst1q_f32(C + (i)*ldc, acc); }
+ NEON_STORE(0,c0); NEON_STORE(1,c1); NEON_STORE(2,c2); NEON_STORE(3,c3);
+ NEON_STORE(4,c4); NEON_STORE(5,c5); NEON_STORE(6,c6); NEON_STORE(7,c7);
+ #undef NEON_STORE
+}
+
+/* ============ Depthwise conv 3×3 NEON ============ */
+
+static inline void neon_dwconv3x3(
+ const float* src, const float* wt, float bias,
+ int H, int W, int act, float* dst)
+{
+ float32x4_t vw[9];
+ for (int i = 0; i < 9; i++) vw[i] = vdupq_n_f32(wt[i]);
+ float32x4_t vb = vdupq_n_f32(bias);
+
+ for (int oh = 0; oh < H; oh++) {
+ const float* r0 = (oh > 0) ? src + (oh-1)*W : NULL;
+ const float* r1 = src + oh*W;
+ const float* r2 = (oh < H-1) ? src + (oh+1)*W : NULL;
+
+ int ow = 1; /* skip first column (padding) */
+ for (; ow + 4 <= W - 1; ow += 4) {
+ float32x4_t sum = vb;
+ if (r0) {
+ sum = vfmaq_f32(sum, vld1q_f32(r0+ow-1), vw[0]);
+ sum = vfmaq_f32(sum, vld1q_f32(r0+ow), vw[1]);
+ sum = vfmaq_f32(sum, vld1q_f32(r0+ow+1), vw[2]);
+ }
+ sum = vfmaq_f32(sum, vld1q_f32(r1+ow-1), vw[3]);
+ sum = vfmaq_f32(sum, vld1q_f32(r1+ow), vw[4]);
+ sum = vfmaq_f32(sum, vld1q_f32(r1+ow+1), vw[5]);
+ if (r2) {
+ sum = vfmaq_f32(sum, vld1q_f32(r2+ow-1), vw[6]);
+ sum = vfmaq_f32(sum, vld1q_f32(r2+ow), vw[7]);
+ sum = vfmaq_f32(sum, vld1q_f32(r2+ow+1), vw[8]);
+ }
+ if (act == 1) sum = neon_silu(sum);
+ else if (act == 3) {
+ uint32x4_t neg = vcltq_f32(sum, vdupq_n_f32(0));
+ sum = vbslq_f32(neg, vmulq_n_f32(sum, 0.1f), sum);
+ }
+ vst1q_f32(dst + oh*W + ow, sum);
+ }
+ /* Scalar edges */
+ for (int x = 0; x < W; x++) {
+ if (x >= 1 && x < W-1 && (x-1) % 4 == 0 && x+3 < W-1) continue; /* done by NEON */
+ float s = bias;
+ for (int kh = 0; kh < 3; kh++) {
+ int ih = oh-1+kh;
+ if (ih < 0 || ih >= H) continue;
+ for (int kw = 0; kw < 3; kw++) {
+ int iw = x-1+kw;
+ if (iw >= 0 && iw < W) s += src[ih*W+iw] * wt[kh*3+kw];
+ }
+ }
+ if (act == 1) { float sig = 1.0f/(1.0f+expf(-s)); s *= sig; }
+ else if (act == 3 && s < 0) s *= 0.1f;
+ dst[oh*W+x] = s;
+ }
+ }
+}
+
+#endif /* __aarch64__ */
+#endif /* GEMM_NEON_H */
diff --git a/nn2/src/gemm_res.c b/nn2/src/gemm_res.c
new file mode 100644
index 0000000..2a0078e
--- /dev/null
+++ b/nn2/src/gemm_res.c
@@ -0,0 +1,126 @@
+/*
+ * gemm_res.c — Fused GEMM + bias + activation + residual add.
+ *
+ * SEPARATE compilation unit to avoid icache pollution of the main GEMM.
+ * result[m][n] = act(A_packed×B[m][n] + bias[m]) + residual[m][n]
+ */
+
+#include "nn2_internal.h"
+#include <immintrin.h>
+
+#ifdef __AVX512F__
+
+#include "fast_exp.h"
+
+#define NR512 32
+#define KC_BLOCK 256
+
+static inline __m512 _res_silu512(__m512 x) { return _mm512_silu_fast(x); }
+
+typedef struct {
+ int M, K, N;
+ const float* Ap;
+ const float* B;
+ float* C; int ldc;
+ const float* bias;
+ int act;
+ const float* res; int ldr;
+ int n_tiles;
+} ResCtx;
+
+static void res_worker(void* arg, int start, int end) {
+ ResCtx* g = (ResCtx*)arg;
+ for (int ti = start; ti < end; ti++) {
+ int ni = ti % g->n_tiles;
+ int p = ti / g->n_tiles;
+ int n = ni * NR512;
+ int nr = (n + NR512 <= g->N) ? NR512 : g->N - n;
+ int mr = ((p+1)*NN2_MR <= g->M) ? NN2_MR : g->M - p*NN2_MR;
+
+ __m512 c00=_mm512_setzero_ps(),c01=_mm512_setzero_ps();
+ __m512 c10=_mm512_setzero_ps(),c11=_mm512_setzero_ps();
+ __m512 c20=_mm512_setzero_ps(),c21=_mm512_setzero_ps();
+ __m512 c30=_mm512_setzero_ps(),c31=_mm512_setzero_ps();
+ __m512 c40=_mm512_setzero_ps(),c41=_mm512_setzero_ps();
+ __m512 c50=_mm512_setzero_ps(),c51=_mm512_setzero_ps();
+
+ const float* ap_base = g->Ap + p * g->K * NN2_MR;
+ for (int kc = 0; kc < g->K; kc += KC_BLOCK) {
+ int kb = (kc + KC_BLOCK <= g->K) ? KC_BLOCK : g->K - kc;
+ const float* ap = ap_base + kc * NN2_MR;
+ const float* bp_base = g->B + kc * g->N + n;
+ int k = 0;
+ for (; k + 3 < kb; k += 4) {
+ #define RK(off) { \
+ const float* bp = bp_base + (k+(off)) * g->N; \
+ const float* a = ap + (k+(off)) * NN2_MR; \
+ __m512 b0=_mm512_loadu_ps(bp), b1=_mm512_loadu_ps(bp+16); __m512 va; \
+ va=_mm512_set1_ps(a[0]);c00=_mm512_fmadd_ps(va,b0,c00);c01=_mm512_fmadd_ps(va,b1,c01); \
+ va=_mm512_set1_ps(a[1]);c10=_mm512_fmadd_ps(va,b0,c10);c11=_mm512_fmadd_ps(va,b1,c11); \
+ va=_mm512_set1_ps(a[2]);c20=_mm512_fmadd_ps(va,b0,c20);c21=_mm512_fmadd_ps(va,b1,c21); \
+ va=_mm512_set1_ps(a[3]);c30=_mm512_fmadd_ps(va,b0,c30);c31=_mm512_fmadd_ps(va,b1,c31); \
+ va=_mm512_set1_ps(a[4]);c40=_mm512_fmadd_ps(va,b0,c40);c41=_mm512_fmadd_ps(va,b1,c41); \
+ va=_mm512_set1_ps(a[5]);c50=_mm512_fmadd_ps(va,b0,c50);c51=_mm512_fmadd_ps(va,b1,c51); }
+ RK(0); RK(1); RK(2); RK(3);
+ #undef RK
+ }
+ for (; k < kb; k++) {
+ const float* bp = bp_base + k * g->N;
+ const float* a = ap + k * NN2_MR;
+ __m512 b0=_mm512_loadu_ps(bp), b1=_mm512_loadu_ps(bp+16); __m512 va;
+ va=_mm512_set1_ps(a[0]);c00=_mm512_fmadd_ps(va,b0,c00);c01=_mm512_fmadd_ps(va,b1,c01);
+ va=_mm512_set1_ps(a[1]);c10=_mm512_fmadd_ps(va,b0,c10);c11=_mm512_fmadd_ps(va,b1,c11);
+ va=_mm512_set1_ps(a[2]);c20=_mm512_fmadd_ps(va,b0,c20);c21=_mm512_fmadd_ps(va,b1,c21);
+ va=_mm512_set1_ps(a[3]);c30=_mm512_fmadd_ps(va,b0,c30);c31=_mm512_fmadd_ps(va,b1,c31);
+ va=_mm512_set1_ps(a[4]);c40=_mm512_fmadd_ps(va,b0,c40);c41=_mm512_fmadd_ps(va,b1,c41);
+ va=_mm512_set1_ps(a[5]);c50=_mm512_fmadd_ps(va,b0,c50);c51=_mm512_fmadd_ps(va,b1,c51);
+ }
+ }
+
+ int m = p * NN2_MR;
+ float* Cp = g->C + m * g->ldc + n;
+ const float* Rp = g->res + m * g->ldr + n;
+ #define FR(i,lo,hi) if(i<mr){ \
+ __m512 vb=_mm512_set1_ps(g->bias[m+(i)]); \
+ lo=_mm512_add_ps(lo,vb); hi=_mm512_add_ps(hi,vb); \
+ if(g->act==1){lo=_res_silu512(lo);hi=_res_silu512(hi);} \
+ lo=_mm512_add_ps(lo,_mm512_loadu_ps(Rp+i*g->ldr)); \
+ hi=_mm512_add_ps(hi,_mm512_loadu_ps(Rp+i*g->ldr+16)); \
+ if(nr>=32){_mm512_storeu_ps(Cp+i*g->ldc,lo);_mm512_storeu_ps(Cp+i*g->ldc+16,hi);} \
+ else{__mmask16 ml=(nr>=16)?0xFFFF:((__mmask16)1<<nr)-1,mh=(nr<=16)?0:((__mmask16)1<<(nr-16))-1; \
+ _mm512_mask_storeu_ps(Cp+i*g->ldc,ml,lo);if(mh)_mm512_mask_storeu_ps(Cp+i*g->ldc+16,mh,hi);}}
+ FR(0,c00,c01);FR(1,c10,c11);FR(2,c20,c21);FR(3,c30,c31);FR(4,c40,c41);FR(5,c50,c51);
+ #undef FR
+ }
+}
+
+void nn2_sgemm_bias_act_res_packed(int M, int K, int N,
+ const float* Ap, const float* B,
+ float* C, int ldc,
+ const float* bias, int act,
+ const float* residual, int ldr)
+{
+ int n_tiles = (N + NR512 - 1) / NR512;
+ int m_panels = (M + NN2_MR - 1) / NN2_MR;
+ int total = m_panels * n_tiles;
+ ResCtx ctx = {M, K, N, Ap, B, C, ldc, bias, act, residual, ldr, n_tiles};
+ int grain = (total > 64) ? total / (nn2_tp_num_threads() * 4) : 1;
+ if (grain < 1) grain = 1;
+ nn2_tp_parallel_for(res_worker, &ctx, total, grain);
+}
+
+#else /* no AVX-512 */
+
+void nn2_sgemm_bias_act_res_packed(int M, int K, int N,
+ const float* Ap, const float* B,
+ float* C, int ldc,
+ const float* bias, int act,
+ const float* residual, int ldr)
+{
+ nn2_sgemm_bias_act_packed(M, K, N, Ap, B, C, ldc, bias, act);
+ for (int m = 0; m < M; m++)
+ for (int n = 0; n < N; n++)
+ C[m*ldc+n] += residual[m*ldr+n];
+}
+
+#endif
diff --git a/nn2/src/gemm_sparse_int8.c b/nn2/src/gemm_sparse_int8.c
new file mode 100644
index 0000000..6cee690
--- /dev/null
+++ b/nn2/src/gemm_sparse_int8.c
@@ -0,0 +1,268 @@
+/*
+ * gemm_sparse_int8.c — Sparse INT8 GEMM with AVX-512 VNNI.
+ *
+ * Block-sparse: weights stored in CSR-like format with 1×4 blocks.
+ * Zero blocks are skipped entirely → 75% sparsity = 4x fewer ops.
+ * VNNI VPDPBUSD: 4 INT8 multiplies per 32-bit lane per cycle.
+ *
+ * Combined: sparse × INT8 = up to 16x over dense FP32 GEMM.
+ *
+ * Weight format (sparse packed):
+ * For each output channel group (NR=16 channels):
+ * [uint16 nnz_blocks] - number of non-zero K/4 blocks
+ * [nnz_blocks × uint16 block_indices] - which K/4 blocks are non-zero
+ * [nnz_blocks × 64 bytes] - packed weights (16 cols × 4 k-values)
+ *
+ * Execution: iterate only over non-zero blocks per output group.
+ */
+
+#include "nn2_internal.h"
+#include <string.h>
+#include <stdlib.h>
+#include <math.h>
+#include <immintrin.h>
+
+/* ============ Sparse weight packing ============ */
+
+typedef struct {
+ void* data; /* packed sparse data */
+ size_t data_size;
+ int K, N; /* original dimensions */
+ int K4; /* K padded to 4 */
+ float sparsity; /* fraction of zero blocks */
+} SparseINT8Weights;
+
+SparseINT8Weights* nn2_sparse_int8_pack(
+ const int8_t* weights, /* [N, K] dense weights */
+ int K, int N,
+ int32_t* col_sums) /* [N] output: 128 * sum(w) per channel */
+{
+ int K4 = (K + 3) & ~3;
+ int n_blocks = K4 / 4;
+
+ /* First pass: count non-zero blocks per group to size buffer */
+ size_t total_size = 0;
+ int total_nnz = 0, total_blocks = 0;
+
+ for (int co = 0; co < N; co += 16) {
+ int nr = (co + 16 <= N) ? 16 : N - co;
+ int nnz = 0;
+ for (int b = 0; b < n_blocks; b++) {
+ /* Check if any of the 16 channels × 4 k-values is non-zero */
+ int has_nonzero = 0;
+ for (int j = 0; j < nr && !has_nonzero; j++) {
+ for (int kk = 0; kk < 4 && !has_nonzero; kk++) {
+ int k = b * 4 + kk;
+ if (k < K && weights[(co + j) * K + k] != 0)
+ has_nonzero = 1;
+ }
+ }
+ if (has_nonzero) nnz++;
+ }
+ total_size += 2 + nnz * 2 + nnz * 64; /* header + indices + data */
+ total_nnz += nnz;
+ total_blocks += n_blocks;
+ }
+
+ SparseINT8Weights* sw = (SparseINT8Weights*)malloc(sizeof(SparseINT8Weights));
+ sw->data = malloc(total_size);
+ sw->data_size = total_size;
+ sw->K = K;
+ sw->N = N;
+ sw->K4 = K4;
+ sw->sparsity = 1.0f - (float)total_nnz / total_blocks;
+
+ /* Second pass: pack */
+ uint8_t* out = (uint8_t*)sw->data;
+
+ for (int co = 0; co < N; co += 16) {
+ int nr = (co + 16 <= N) ? 16 : N - co;
+
+ /* Col sums for compensation */
+ for (int j = 0; j < nr; j++) {
+ int32_t sum = 0;
+ for (int k = 0; k < K; k++)
+ sum += (int32_t)weights[(co + j) * K + k];
+ col_sums[co + j] = 128 * sum;
+ }
+
+ /* Find non-zero blocks */
+ uint16_t nnz = 0;
+ uint16_t indices[4096]; /* max K4/4 blocks */
+ for (int b = 0; b < n_blocks; b++) {
+ int has_nz = 0;
+ for (int j = 0; j < nr && !has_nz; j++)
+ for (int kk = 0; kk < 4 && !has_nz; kk++) {
+ int k = b * 4 + kk;
+ if (k < K && weights[(co + j) * K + k] != 0) has_nz = 1;
+ }
+ if (has_nz)
+ indices[nnz++] = (uint16_t)b;
+ }
+
+ /* Write header */
+ memcpy(out, &nnz, 2); out += 2;
+ memcpy(out, indices, nnz * 2); out += nnz * 2;
+
+ /* Write non-zero block data: [16 cols × 4 k-values = 64 bytes] per block */
+ for (int bi = 0; bi < nnz; bi++) {
+ int b = indices[bi];
+ for (int j = 0; j < 16; j++) {
+ for (int kk = 0; kk < 4; kk++) {
+ int k = b * 4 + kk;
+ if (j < nr && k < K)
+ *out++ = (uint8_t)weights[(co + j) * K + k];
+ else
+ *out++ = 0;
+ }
+ }
+ }
+ }
+
+ return sw;
+}
+
+void nn2_sparse_int8_free(SparseINT8Weights* sw)
+{
+ if (sw) { free(sw->data); free(sw); }
+}
+
+/* ============ Sparse INT8 GEMM with VNNI ============ */
+
+#ifdef __AVX512VNNI__
+
+void nn2_sparse_int8_gemm(
+ const int8_t* A, int M, int K, /* A[M, K] activations (will be quantized) */
+ const SparseINT8Weights* sw,
+ const int32_t* col_sums,
+ const float* w_scales, /* [N] per-channel */
+ const float* bias, /* [N] or NULL */
+ float act_scale, /* per-tensor activation scale */
+ int act_type, /* 0=none, 1=SiLU, 2=ReLU */
+ float* output) /* [M, N] float32 output */
+{
+ int N = sw->N;
+ int K4 = sw->K4;
+
+ /* Pad A to K4 if needed */
+ const int8_t* A_eff = A;
+ int8_t* A_pad = NULL;
+ if (K != K4) {
+ A_pad = (int8_t*)calloc(M * K4, 1);
+ for (int m = 0; m < M; m++)
+ memcpy(A_pad + m * K4, A + m * K, K);
+ A_eff = A_pad;
+ }
+
+ const uint32_t xor32 = 0x80808080u;
+ const uint8_t* wptr = (const uint8_t*)sw->data;
+
+ for (int co = 0; co < N; co += 16) {
+ /* Read sparse header */
+ uint16_t nnz;
+ memcpy(&nnz, wptr, 2); wptr += 2;
+ const uint16_t* block_indices = (const uint16_t*)wptr;
+ wptr += nnz * 2;
+ const uint8_t* block_data = wptr;
+ wptr += nnz * 64;
+
+ /* Process 4 activation rows at a time */
+ for (int m = 0; m < M; m += 4) {
+ int mr = (m + 4 <= M) ? 4 : M - m;
+
+ __m512i acc0 = _mm512_setzero_si512();
+ __m512i acc1 = _mm512_setzero_si512();
+ __m512i acc2 = _mm512_setzero_si512();
+ __m512i acc3 = _mm512_setzero_si512();
+
+ const int8_t* a0 = A_eff + m * K4;
+ const int8_t* a1 = (mr > 1) ? a0 + K4 : a0;
+ const int8_t* a2 = (mr > 2) ? a0 + 2*K4 : a0;
+ const int8_t* a3 = (mr > 3) ? a0 + 3*K4 : a0;
+
+ /* Only iterate over non-zero blocks! */
+ for (int bi = 0; bi < nnz; bi++) {
+ int b = block_indices[bi];
+ int k_off = b * 4;
+
+ __m512i vb = _mm512_loadu_si512((const __m512i*)(block_data + bi * 64));
+
+ /* Load and convert 4 activation bytes per row */
+ uint32_t a0v, a1v, a2v, a3v;
+ memcpy(&a0v, a0 + k_off, 4); a0v ^= xor32;
+ memcpy(&a1v, a1 + k_off, 4); a1v ^= xor32;
+ memcpy(&a2v, a2 + k_off, 4); a2v ^= xor32;
+ memcpy(&a3v, a3 + k_off, 4); a3v ^= xor32;
+
+ acc0 = _mm512_dpbusd_epi32(acc0, _mm512_set1_epi32(a0v), vb);
+ acc1 = _mm512_dpbusd_epi32(acc1, _mm512_set1_epi32(a1v), vb);
+ acc2 = _mm512_dpbusd_epi32(acc2, _mm512_set1_epi32(a2v), vb);
+ acc3 = _mm512_dpbusd_epi32(acc3, _mm512_set1_epi32(a3v), vb);
+ }
+
+ /* Fused epilogue: dequant + bias + activation */
+ int nr = (co + 16 <= N) ? 16 : N - co;
+ int32_t acc_buf[4][16];
+ _mm512_storeu_si512(acc_buf[0], acc0);
+ _mm512_storeu_si512(acc_buf[1], acc1);
+ _mm512_storeu_si512(acc_buf[2], acc2);
+ _mm512_storeu_si512(acc_buf[3], acc3);
+
+ for (int i = 0; i < mr; i++) {
+ float* orow = output + (m + i) * N + co;
+ for (int j = 0; j < nr; j++) {
+ float val = (float)(acc_buf[i][j] - col_sums[co + j])
+ * act_scale * w_scales[co + j];
+ if (bias) val += bias[co + j];
+ if (act_type == 1) {
+ float s = 1.0f / (1.0f + expf(-val));
+ val *= s;
+ } else if (act_type == 2 && val < 0) {
+ val = 0;
+ }
+ orow[j] = val;
+ }
+ }
+ }
+ }
+
+ free(A_pad);
+}
+
+#endif /* __AVX512VNNI__ */
+
+/* ============ Benchmark helper ============ */
+
+void nn2_sparse_int8_bench(int M, int K, int N, float target_sparsity)
+{
+ /* Create weights with target sparsity */
+ int8_t* w = (int8_t*)malloc(N * K);
+ for (int i = 0; i < N * K; i++)
+ w[i] = (rand() % 100 < (int)(target_sparsity * 100)) ? 0 : (int8_t)(rand() % 20 - 10);
+
+ int32_t* csums = (int32_t*)calloc(N, sizeof(int32_t));
+ SparseINT8Weights* sw = nn2_sparse_int8_pack(w, K, N, csums);
+
+ float* wscales = (float*)malloc(N * sizeof(float));
+ float* bias = (float*)calloc(N, sizeof(float));
+ for (int i = 0; i < N; i++) wscales[i] = 0.01f;
+
+ int8_t* a = (int8_t*)calloc(M * K, 1);
+ float* out = (float*)malloc(M * N * sizeof(float));
+
+ printf(" Sparse INT8 [%d,%d,%d] sparsity=%.0f%%: packed %.1f KB (%.0f%% of dense)\n",
+ M, K, N, sw->sparsity * 100,
+ sw->data_size / 1024.0,
+ sw->data_size * 100.0 / (N * K));
+
+#ifdef __AVX512VNNI__
+ /* Warmup */
+ nn2_sparse_int8_gemm(a, M, K, sw, csums, wscales, bias, 0.05f, 0, out);
+
+ /* Bench */
+ /* (timing done externally) */
+#endif
+
+ free(w); free(csums); free(wscales); free(bias); free(a); free(out);
+ nn2_sparse_int8_free(sw);
+}
diff --git a/nn2/src/http_server.h b/nn2/src/http_server.h
new file mode 100644
index 0000000..77a3d39
--- /dev/null
+++ b/nn2/src/http_server.h
@@ -0,0 +1,159 @@
+/*
+ * http_server.h — Minimal single-threaded HTTP server for detection API.
+ * No dependencies. Uses raw Winsock2/POSIX sockets.
+ *
+ * Endpoints:
+ * POST /detect — upload image, get JSON detections
+ * GET /health — returns {"status":"ok"}
+ * GET /stats — returns inference stats
+ */
+
+#ifndef NN2_HTTP_SERVER_H
+#define NN2_HTTP_SERVER_H
+
+#ifdef _WIN32
+#define WIN32_LEAN_AND_MEAN
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#pragma comment(lib, "ws2_32.lib")
+typedef SOCKET socket_t;
+#define CLOSE_SOCKET closesocket
+#else
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <unistd.h>
+typedef int socket_t;
+#define CLOSE_SOCKET close
+#define INVALID_SOCKET -1
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define HTTP_MAX_BODY (10 * 1024 * 1024) /* 10MB max upload */
+
+typedef struct {
+ char method[8];
+ char path[256];
+ char content_type[128];
+ int content_length;
+ char* body;
+} HttpRequest;
+
+typedef void (*http_handler)(const HttpRequest* req, socket_t client, void* userdata);
+
+static int http_parse_request(socket_t client, HttpRequest* req)
+{
+ char header[4096];
+ int total = 0;
+ memset(req, 0, sizeof(*req));
+ req->body = NULL;
+
+ /* Read header */
+ while (total < (int)sizeof(header) - 1) {
+ int n = recv(client, header + total, 1, 0);
+ if (n <= 0) return -1;
+ total++;
+ if (total >= 4 && memcmp(header + total - 4, "\r\n\r\n", 4) == 0) break;
+ }
+ header[total] = 0;
+
+ /* Parse first line */
+ sscanf(header, "%7s %255s", req->method, req->path);
+
+ /* Parse Content-Length */
+ char* cl = strstr(header, "Content-Length:");
+ if (!cl) cl = strstr(header, "content-length:");
+ if (cl) req->content_length = atoi(cl + 15);
+
+ /* Parse Content-Type */
+ char* ct = strstr(header, "Content-Type:");
+ if (!ct) ct = strstr(header, "content-type:");
+ if (ct) {
+ ct += 13;
+ while (*ct == ' ') ct++;
+ int i = 0;
+ while (*ct && *ct != '\r' && *ct != '\n' && i < 127) req->content_type[i++] = *ct++;
+ req->content_type[i] = 0;
+ }
+
+ /* Read body */
+ if (req->content_length > 0 && req->content_length < HTTP_MAX_BODY) {
+ req->body = (char*)malloc(req->content_length);
+ int read = 0;
+ while (read < req->content_length) {
+ int n = recv(client, req->body + read, req->content_length - read, 0);
+ if (n <= 0) break;
+ read += n;
+ }
+ }
+ return 0;
+}
+
+static void http_send(socket_t client, int code, const char* content_type, const char* body, int body_len)
+{
+ char header[512];
+ const char* status = (code == 200) ? "OK" : (code == 404) ? "Not Found" : "Bad Request";
+ int hlen = snprintf(header, sizeof(header),
+ "HTTP/1.1 %d %s\r\n"
+ "Content-Type: %s\r\n"
+ "Content-Length: %d\r\n"
+ "Access-Control-Allow-Origin: *\r\n"
+ "Connection: close\r\n"
+ "\r\n",
+ code, status, content_type, body_len);
+ send(client, header, hlen, 0);
+ if (body && body_len > 0)
+ send(client, body, body_len, 0);
+}
+
+static void http_send_json(socket_t client, int code, const char* json)
+{
+ http_send(client, code, "application/json", json, (int)strlen(json));
+}
+
+static int http_listen(int port, http_handler handler, void* userdata)
+{
+#ifdef _WIN32
+ WSADATA wsa;
+ WSAStartup(MAKEWORD(2,2), &wsa);
+#endif
+
+ socket_t server = socket(AF_INET, SOCK_STREAM, 0);
+ if (server == INVALID_SOCKET) return -1;
+
+ int opt = 1;
+ setsockopt(server, SOL_SOCKET, SO_REUSEADDR, (char*)&opt, sizeof(opt));
+
+ struct sockaddr_in addr;
+ memset(&addr, 0, sizeof(addr));
+ addr.sin_family = AF_INET;
+ addr.sin_addr.s_addr = INADDR_ANY;
+ addr.sin_port = htons(port);
+
+ if (bind(server, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
+ CLOSE_SOCKET(server);
+ return -1;
+ }
+
+ listen(server, 8);
+ fprintf(stderr, "nn2 HTTP server listening on port %d\n", port);
+
+ while (1) {
+ socket_t client = accept(server, NULL, NULL);
+ if (client == INVALID_SOCKET) continue;
+
+ HttpRequest req;
+ if (http_parse_request(client, &req) == 0)
+ handler(&req, client, userdata);
+
+ free(req.body);
+ CLOSE_SOCKET(client);
+ }
+
+ CLOSE_SOCKET(server);
+ return 0;
+}
+
+#endif /* NN2_HTTP_SERVER_H */
diff --git a/nn2/src/int8_nhwc/c2f_int8.c b/nn2/src/int8_nhwc/c2f_int8.c
new file mode 100644
index 0000000..b319cd4
--- /dev/null
+++ b/nn2/src/int8_nhwc/c2f_int8.c
@@ -0,0 +1,149 @@
+/*
+ * c2f_int8.c — INT8 NHWC C2f block and helper ops.
+ *
+ * NHWC simplifies C2f greatly:
+ * - cv1 output [H,W,2c_pad] → chunk0=[0..c), chunk1=[c..2c) per pixel
+ * - Bottleneck: extract chunk as contiguous → cv1 → cv2 → write to cat
+ * - cv2 input is the full concat buffer [H,W,total_c_pad]
+ *
+ * Channel slice in NHWC: for each pixel, copy C bytes at offset.
+ * This is sequential access — much faster than NCHW interleave.
+ */
+
+#include "nn2_int8.h"
+#include "../nn2_internal.h"
+#include <string.h>
+#include <stdlib.h>
+
+/* Extract channel slice from NHWC: in[H,W,Cin_pad] → out[H,W,slice_pad]
+ * Copies channels [ch_start..ch_start+ch_count) per pixel.
+ * Threaded for large spatial. */
+
+typedef struct { const int8_t* in; int8_t* out; int Cin_pad, ch_start, ch_count, out_pad, W; } SliceCtx;
+static void slice_worker(void* arg, int start, int end) {
+ SliceCtx* g = (SliceCtx*)arg;
+ for (int i = start; i < end; i++) {
+ memcpy(g->out + i * g->out_pad,
+ g->in + i * g->Cin_pad + g->ch_start, g->ch_count);
+ if (g->ch_count < g->out_pad)
+ memset(g->out + i * g->out_pad + g->ch_count, 0, g->out_pad - g->ch_count);
+ }
+}
+
+static void i8_channel_slice(const int8_t* in, int Cin_pad,
+ int ch_start, int ch_count,
+ int H, int W, int8_t* out, int out_pad)
+{
+ int spatial = H * W;
+ SliceCtx ctx = {in, out, Cin_pad, ch_start, ch_count, out_pad, W};
+ if (spatial >= 256)
+ nn2_tp_parallel_for(slice_worker, &ctx, spatial, spatial / 12);
+ else
+ slice_worker(&ctx, 0, spatial);
+}
+
+typedef struct { const int8_t* src; int8_t* dst; int src_pad, dst_pad, ch_start, ch_count; } WriteCtx;
+static void write_worker(void* arg, int start, int end) {
+ WriteCtx* g = (WriteCtx*)arg;
+ for (int i = start; i < end; i++)
+ memcpy(g->dst + i * g->dst_pad + g->ch_start,
+ g->src + i * g->src_pad, g->ch_count);
+}
+
+static void i8_channel_write(const int8_t* src, int src_pad, int ch_count,
+ int H, int W, int8_t* dst, int dst_pad, int ch_start)
+{
+ int spatial = H * W;
+ WriteCtx ctx = {src, dst, src_pad, dst_pad, ch_start, ch_count};
+ if (spatial >= 256)
+ nn2_tp_parallel_for(write_worker, &ctx, spatial, spatial / 12);
+ else
+ write_worker(&ctx, 0, spatial);
+}
+
+/* INT8 shortcut add: a[spatial * c_pad] += b[spatial * c_pad], saturating */
+extern void i8_residual_add(int8_t* a, const int8_t* b, int total,
+ float sa, float sb, float so);
+
+/* Forward declare */
+extern void i8_conv(const I8Conv* L, const int8_t* input, int H, int W,
+ int8_t* output, int8_t* scratch);
+
+/* ============ C2f block ============ */
+
+void i8_c2f(const I8C2f* blk, const int8_t* input, int Cin_pad,
+ int H, int W, int8_t* output, int Cout_pad, int8_t* work)
+{
+ int spatial = H * W;
+ int c = blk->c;
+ int c_pad = C_PAD16(c);
+ int n = blk->n;
+ int total_c = (2 + n) * c;
+ int total_pad = C_PAD16(total_c);
+
+ /* Workspace layout:
+ * [cv1_out: spatial * cv1.cout_pad]
+ * [cat: spatial * total_pad] ← concat buffer
+ * [scratch: 4MB for sub-convs]
+ */
+ int cv1_out_pad = blk->cv1.cout_pad;
+ int8_t* cv1_out = work;
+ int8_t* cat = cv1_out + spatial * cv1_out_pad;
+ int8_t* scratch = cat + spatial * total_pad;
+
+ /* cv1: input → cv1_out [H,W,2c_pad] */
+ i8_conv(&blk->cv1, input, H, W, cv1_out, scratch);
+
+ /* Copy cv1 output channels to cat buffer:
+ * cat[pixel][0..2c) = cv1_out[pixel][0..2c) */
+ for (int i = 0; i < spatial; i++) {
+ memcpy(cat + i * total_pad, cv1_out + i * cv1_out_pad, 2 * c);
+ /* Zero-fill rest */
+ if (2 * c < total_pad)
+ memset(cat + i * total_pad + 2 * c, 0, total_pad - 2 * c);
+ }
+
+ /* Bottleneck iterations */
+ int bn_ch_offset = c; /* where the current bottleneck input starts in cat */
+
+ for (int bi = 0; bi < n; bi++) {
+ /* Extract bn_in: cat channels [bn_ch_offset .. bn_ch_offset+c) */
+ int8_t* bn_in = scratch;
+ i8_channel_slice(cat, total_pad, bn_ch_offset, c, H, W, bn_in, c_pad);
+
+ /* bn.cv1: c → c, 3x3 */
+ int8_t* bn_mid = scratch + spatial * c_pad;
+ i8_conv(&blk->m[bi].cv1, bn_in, H, W, bn_mid, scratch + 2 * spatial * c_pad);
+
+ /* bn.cv2: c → c, 3x3 */
+ int8_t* bn_out = scratch + 2 * spatial * c_pad;
+ i8_conv(&blk->m[bi].cv2, bn_mid, H, W, bn_out, scratch + 3 * spatial * c_pad);
+
+ /* Shortcut: bn_out += bn_in */
+ if (blk->shortcut) {
+ i8_residual_add(bn_out, bn_in, spatial * c_pad,
+ blk->m[bi].cv2.out_scale,
+ blk->m[bi].cv1.act_scale,
+ blk->m[bi].cv2.out_scale);
+ }
+
+ /* Write bn_out to cat at channel position (2+bi)*c */
+ int cat_offset = (2 + bi) * c;
+ i8_channel_write(bn_out, c_pad, c, H, W, cat, total_pad, cat_offset);
+
+ bn_ch_offset = cat_offset;
+ }
+
+ /* cv2: cat[total_c channels] → output */
+ /* Extract active channels from cat into contiguous buffer for cv2 */
+ int cv2_in_pad = C_PAD16(total_c);
+ int8_t* cv2_in = scratch;
+ if (total_pad == cv2_in_pad && total_c == total_pad) {
+ cv2_in = cat; /* no copy needed */
+ } else {
+ for (int i = 0; i < spatial; i++)
+ memcpy(cv2_in + i * cv2_in_pad, cat + i * total_pad, total_c);
+ }
+
+ i8_conv(&blk->cv2, cv2_in, H, W, output, scratch + spatial * cv2_in_pad);
+}
diff --git a/nn2/src/int8_nhwc/conv_int8.c b/nn2/src/int8_nhwc/conv_int8.c
new file mode 100644
index 0000000..c15271b
--- /dev/null
+++ b/nn2/src/int8_nhwc/conv_int8.c
@@ -0,0 +1,162 @@
+/*
+ * conv_int8.c — INT8 NHWC convolution: 1x1 and 3x3.
+ *
+ * NHWC layout: input[H][W][C_pad] — channels are contiguous.
+ * For 1x1: input IS the A matrix for GEMM (no im2col!).
+ * For 3x3: im2col gathers [spatial, K4] from NHWC — channels contiguous.
+ *
+ * This is where NHWC pays off: im2col just copies contiguous C-sized
+ * blocks from neighboring pixels. No scatter/gather.
+ */
+
+#include "nn2_int8.h"
+#include "../nn2_internal.h"
+#include <string.h>
+
+/* ============ 1x1 Conv (direct GEMM) ============ */
+
+void i8_conv1x1(const I8Conv* L, const int8_t* input, int H, int W,
+ int8_t* output)
+{
+ int spatial = H * W;
+ int cin_pad = C_PAD16(L->cin);
+ int cout_pad = L->cout_pad;
+
+ /* In NHWC: input is [spatial, cin_pad], treat as A[M=spatial, K=cin_pad]
+ * Weight is B_packed[K4, Cout] in VNNI format.
+ * Output is [spatial, cout_pad]. */
+ i8_gemm_bias_act(input, spatial, L->K4, L->cout,
+ L->w_packed, L->col_sums, L->w_scales, L->bias,
+ L->act_scale, L->out_scale, L->act,
+ output, cout_pad);
+}
+
+/* ============ 3x3 im2col in INT8 NHWC ============ */
+
+/* im2col for 3x3 s=1 p=1: NHWC input → [spatial, K4] contiguous.
+ * For each output pixel (oh,ow), gather 3×3 neighborhood × C channels.
+ * In NHWC, each pixel's channels are contiguous → memcpy per neighbor pixel. */
+static void i8_im2col_3x3_s1(const int8_t* input, int C_pad, int H, int W,
+ int8_t* col, int K4)
+{
+ int C = C_pad; /* use padded channel count for alignment */
+ int K = C * 9;
+
+ for (int oh = 0; oh < H; oh++) {
+ for (int ow = 0; ow < W; ow++) {
+ int8_t* dst = col + (oh * W + ow) * K4;
+ int k = 0;
+ for (int kh = 0; kh < 3; kh++) {
+ int ih = oh - 1 + kh;
+ for (int kw = 0; kw < 3; kw++) {
+ int iw = ow - 1 + kw;
+ if (ih >= 0 && ih < H && iw >= 0 && iw < W) {
+ /* Copy C contiguous bytes from NHWC input */
+ memcpy(dst + k, input + (ih * W + iw) * C_pad, C);
+ } else {
+ memset(dst + k, 0, C);
+ }
+ k += C;
+ }
+ }
+ /* Zero-pad K to K4 */
+ if (k < K4) memset(dst + k, 0, K4 - k);
+ }
+ }
+}
+
+/* im2col for 3x3 s=2 p=1 */
+static void i8_im2col_3x3_s2(const int8_t* input, int C_pad, int H, int W,
+ int Hout, int Wout, int8_t* col, int K4)
+{
+ int C = C_pad;
+ for (int oh = 0; oh < Hout; oh++) {
+ for (int ow = 0; ow < Wout; ow++) {
+ int8_t* dst = col + (oh * Wout + ow) * K4;
+ int k = 0;
+ for (int kh = 0; kh < 3; kh++) {
+ int ih = oh * 2 - 1 + kh;
+ for (int kw = 0; kw < 3; kw++) {
+ int iw = ow * 2 - 1 + kw;
+ if (ih >= 0 && ih < H && iw >= 0 && iw < W) {
+ memcpy(dst + k, input + (ih * W + iw) * C_pad, C);
+ } else {
+ memset(dst + k, 0, C);
+ }
+ k += C;
+ }
+ }
+ if (k < K4) memset(dst + k, 0, K4 - k);
+ }
+ }
+}
+
+/* Parallel im2col wrapper */
+typedef struct {
+ const int8_t* input; int C_pad, H, W, Hout, Wout, K4, stride;
+ int8_t* col;
+} I8Im2colCtx;
+
+static void i8_im2col_worker(void* arg, int start, int end)
+{
+ I8Im2colCtx* g = (I8Im2colCtx*)arg;
+ int C = g->C_pad;
+ int K4 = g->K4;
+ int Wout = g->Wout;
+
+ for (int idx = start; idx < end; idx++) {
+ int oh = idx / Wout;
+ int ow = idx % Wout;
+ int8_t* dst = g->col + idx * K4;
+ int k = 0;
+ for (int kh = 0; kh < 3; kh++) {
+ int ih = oh * g->stride - 1 + kh;
+ for (int kw = 0; kw < 3; kw++) {
+ int iw = ow * g->stride - 1 + kw;
+ if (ih >= 0 && ih < g->H && iw >= 0 && iw < g->W) {
+ memcpy(dst + k, g->input + (ih * g->W + iw) * C, C);
+ } else {
+ memset(dst + k, 0, C);
+ }
+ k += C;
+ }
+ }
+ if (k < K4) memset(dst + k, 0, K4 - k);
+ }
+}
+
+/* ============ 3x3 Conv ============ */
+
+void i8_conv3x3(const I8Conv* L, const int8_t* input, int H, int W,
+ int8_t* output, int8_t* im2col_buf)
+{
+ int Hout = (H + 2 * L->pad - L->k) / L->stride + 1;
+ int Wout = (W + 2 * L->pad - L->k) / L->stride + 1;
+ int spatial = Hout * Wout;
+ int cin_pad = C_PAD16(L->cin);
+ int cout_pad = L->cout_pad;
+
+ /* INT8 im2col: NHWC → [spatial, K4] with parallel dispatch */
+ I8Im2colCtx ctx = {input, cin_pad, H, W, Hout, Wout, L->K4, L->stride, im2col_buf};
+ if (spatial >= 64)
+ nn2_tp_parallel_for(i8_im2col_worker, &ctx, spatial, spatial > 256 ? spatial / 12 : 8);
+ else
+ i8_im2col_worker(&ctx, 0, spatial);
+
+ /* VNNI GEMM */
+ i8_gemm_bias_act(im2col_buf, spatial, L->K4, L->cout,
+ L->w_packed, L->col_sums, L->w_scales, L->bias,
+ L->act_scale, L->out_scale, L->act,
+ output, cout_pad);
+}
+
+/* ============ Generic conv dispatch ============ */
+
+void i8_conv(const I8Conv* L, const int8_t* input, int H, int W,
+ int8_t* output, int8_t* scratch)
+{
+ if (L->k == 1 && L->stride == 1)
+ i8_conv1x1(L, input, H, W, output);
+ else
+ i8_conv3x3(L, input, H, W, output, scratch);
+}
diff --git a/nn2/src/int8_nhwc/forward_hybrid.c b/nn2/src/int8_nhwc/forward_hybrid.c
new file mode 100644
index 0000000..3d041a6
--- /dev/null
+++ b/nn2/src/int8_nhwc/forward_hybrid.c
@@ -0,0 +1,415 @@
+/*
+ * forward_hybrid.c — Hybrid FP32/INT8 YOLOv8n forward pass.
+ *
+ * Phase 1 (FP32 NCHW): conv0 → conv1 → c2f0 (Cin < 32, FP32 faster)
+ * Transition: FP32 NCHW [32ch, 80×80] → INT8 NHWC [32ch_pad, 80×80]
+ * Phase 2 (INT8 NHWC): conv2 → c2f1 → conv3 → c2f2 → conv4 → c2f3 → SPPF → neck
+ * Transition: INT8 NHWC → FP32 NCHW for head features
+ * Phase 3 (FP32 NCHW): head convs + decode (accuracy-sensitive)
+ */
+
+#include "nn2_int8.h"
+#include "../nn2_internal.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+
+#ifdef _WIN32
+#include <windows.h>
+static double h_now(void) {
+ static LARGE_INTEGER freq; static int init=0;
+ if(!init){QueryPerformanceFrequency(&freq);init=1;}
+ LARGE_INTEGER t; QueryPerformanceCounter(&t);
+ return (double)t.QuadPart/(double)freq.QuadPart;
+}
+#endif
+
+/* Forward declares from other INT8 files */
+extern void i8_conv(const I8Conv* L, const int8_t* input, int H, int W,
+ int8_t* output, int8_t* scratch);
+extern void i8_c2f(const I8C2f* blk, const int8_t* input, int Cin_pad,
+ int H, int W, int8_t* output, int Cout_pad, int8_t* work);
+
+/* ============ Init helpers ============ */
+
+static float default_act_scale = 0.05f;
+
+static void init_i8conv_default(I8Conv* dst, const ConvLayer* src) {
+ int K = src->cin * src->k * src->k;
+ int K4 = K_PAD4(K);
+ int Cout16 = C_PAD16(src->cout);
+ dst->cin = src->cin; dst->cout = src->cout; dst->k = src->k;
+ dst->stride = src->stride; dst->pad = src->pad; dst->act = src->act;
+ dst->K4 = K4; dst->cout_pad = Cout16;
+ dst->act_scale = default_act_scale; dst->out_scale = default_act_scale;
+ size_t ps = (size_t)(Cout16/16)*(K4/4)*64;
+ dst->w_packed = (int8_t*)_aligned_malloc(ps, 64);
+ dst->col_sums = (int32_t*)calloc(Cout16, sizeof(int32_t));
+ dst->w_scales = (float*)calloc(Cout16, sizeof(float));
+ dst->bias = (float*)calloc(Cout16, sizeof(float));
+ memcpy(dst->bias, src->b, src->cout * sizeof(float));
+ i8_pack_weights(src->w, src->cout, K, dst->w_packed, dst->col_sums, dst->w_scales);
+}
+
+static void init_i8c2f(I8C2f* dst, const C2fBlock* src) {
+ dst->n = src->n; dst->c = src->c; dst->shortcut = src->shortcut;
+ init_i8conv_default(&dst->cv1, &src->cv1);
+ init_i8conv_default(&dst->cv2, &src->cv2);
+ for (int i = 0; i < src->n; i++) {
+ init_i8conv_default(&dst->m[i].cv1, &src->m[i].cv1);
+ init_i8conv_default(&dst->m[i].cv2, &src->m[i].cv2);
+ }
+}
+
+static void free_i8conv_s(I8Conv* L) {
+ _aligned_free(L->w_packed); free(L->col_sums); free(L->w_scales); free(L->bias);
+}
+static void free_i8c2f(I8C2f* b) {
+ free_i8conv_s(&b->cv1); free_i8conv_s(&b->cv2);
+ for(int i=0;i<b->n;i++){free_i8conv_s(&b->m[i].cv1);free_i8conv_s(&b->m[i].cv2);}
+}
+
+/* ============ Hybrid forward ============ */
+
+static int hybrid_forward(
+ NN2* fp32,
+ /* INT8 layers (conv2-4, c2f1-3, sppf, neck) */
+ I8Conv* i8_conv2, I8Conv* i8_conv3, I8Conv* i8_conv4,
+ I8C2f* i8_c2f1, I8C2f* i8_c2f2, I8C2f* i8_c2f3,
+ I8Conv* i8_sppf1, I8Conv* i8_sppf2,
+ I8C2f* i8_nk0, I8C2f* i8_nk1, I8C2f* i8_nk2, I8C2f* i8_nk3,
+ I8Conv* i8_nkconv0, I8Conv* i8_nkconv1,
+ /* Buffers */
+ const float* input_chw,
+ float* bbox_out, float* cls_out)
+{
+ int S = fp32->input_size;
+ float* ws = fp32->workspace;
+
+ /* FP32 workspace */
+ float* im2col = ws; ws += 4*1024*1024;
+ float* buf0 = ws; ws += 4*1024*1024;
+ float* buf1 = ws; ws += 4*1024*1024;
+ float* c2f_tmp = ws; /* rest */
+
+ /* INT8 workspace — use static to avoid malloc/free in hot path */
+ static int8_t* i8ws = NULL;
+ if (!i8ws) i8ws = (int8_t*)_aligned_malloc(16 * 1024 * 1024, 64);
+ int8_t* i8a = i8ws;
+ int8_t* i8b = i8ws + 4*1024*1024;
+ int8_t* i8scratch = i8ws + 8*1024*1024;
+
+ int h0=S/2,w0=S/2, h1=S/4,w1=S/4, h2=S/8,w2=S/8;
+ int h3=S/16,w3=S/16, h4=S/32,w4=S/32;
+
+ /* ============ Phase 1: FP32 NCHW (conv0 → conv1 → c2f0) ============ */
+ nn2_conv2d(&fp32->bb_conv[0], input_chw, S, S, buf0, im2col);
+ nn2_conv2d(&fp32->bb_conv[1], buf0, h0, w0, buf1, im2col);
+
+ /* c2f0 in FP32 */
+ {
+ C2fBlock* blk = &fp32->bb_c2f[0];
+ int spatial = h1 * w1;
+ int c = blk->c;
+ int total_ch = (2 + blk->n) * c;
+ float* cat = c2f_tmp;
+ float* scratch = cat + total_ch * spatial;
+ nn2_conv2d(&blk->cv1, buf1, h1, w1, cat, im2col);
+ float* bn_in = cat + c * spatial;
+ for (int i = 0; i < blk->n; i++) {
+ nn2_conv2d(&blk->m[i].cv1, bn_in, h1, w1, scratch, im2col);
+ float* bn_out = cat + (2+i) * c * spatial;
+ nn2_conv2d(&blk->m[i].cv2, scratch, h1, w1, bn_out, im2col);
+ if (blk->shortcut)
+ for (int j = 0; j < c*spatial; j++) bn_out[j] += bn_in[j];
+ bn_in = bn_out;
+ }
+ nn2_conv2d(&blk->cv2, cat, h1, w1, buf0, im2col);
+ }
+ /* buf0 = 32ch FP32 NCHW @ h1×w1 (80×80 for 320) */
+
+ /* ============ Transition: FP32 NCHW → INT8 NHWC ============ */
+ int c_at_transition = 32;
+ int c_trans_pad = C_PAD16(c_at_transition);
+ i8_quantize_nhwc(buf0, c_at_transition, h1, w1,
+ default_act_scale, i8a, c_trans_pad);
+
+ /* ============ Phase 2: INT8 NHWC ============ */
+
+ /* conv2: 32→64, 3x3 s=2, h1→h2 */
+ int c64_pad = C_PAD16(64);
+ i8_conv(i8_conv2, i8a, h1, w1, i8b, i8scratch);
+ /* i8b = 64ch INT8 NHWC @ h2×w2 */
+
+ /* c2f1: 64→64, n=2 */
+ i8_c2f(i8_c2f1, i8b, c64_pad, h2, w2, i8a, c64_pad, i8scratch);
+ /* i8a = 64ch @ h2×w2 — save as P3 */
+ static int8_t* save_p3 = NULL;
+ if (!save_p3) save_p3 = (int8_t*)_aligned_malloc(256*256*4, 64); /* max size */
+ memcpy(save_p3, i8a, h2 * w2 * c64_pad);
+
+ /* conv3: 64→128, 3x3 s=2 */
+ int c128_pad = C_PAD16(128);
+ i8_conv(i8_conv3, i8a, h2, w2, i8b, i8scratch);
+
+ /* c2f2: 128→128, n=2 */
+ i8_c2f(i8_c2f2, i8b, c128_pad, h3, w3, i8a, c128_pad, i8scratch);
+ static int8_t* save_p4 = NULL;
+ if (!save_p4) save_p4 = (int8_t*)_aligned_malloc(256*256*4, 64);
+ memcpy(save_p4, i8a, h3 * w3 * c128_pad);
+
+ /* conv4: 128→256, 3x3 s=2 */
+ int c256_pad = C_PAD16(256);
+ i8_conv(i8_conv4, i8a, h3, w3, i8b, i8scratch);
+
+ /* c2f3: 256→256, n=1 */
+ i8_c2f(i8_c2f3, i8b, c256_pad, h4, w4, i8a, c256_pad, i8scratch);
+
+ /* SPPF: cv1(256→128) → 3×maxpool → concat(512) → cv2(512→256) */
+ i8_conv(i8_sppf1, i8a, h4, w4, i8b, i8scratch); /* 128ch */
+ {
+ int sp = h4 * w4;
+ int8_t* mp1 = i8scratch;
+ int8_t* mp2 = mp1 + sp * c128_pad;
+ int8_t* mp3 = mp2 + sp * c128_pad;
+ i8_maxpool(i8b, c128_pad, h4, w4, 5, 1, 2, mp1);
+ i8_maxpool(mp1, c128_pad, h4, w4, 5, 1, 2, mp2);
+ i8_maxpool(mp2, c128_pad, h4, w4, 5, 1, 2, mp3);
+ /* concat: [sppf_in, mp1, mp2, mp3] = 512ch */
+ int c512_pad = C_PAD16(512);
+ int8_t* cat512 = mp3 + sp * c128_pad;
+ for (int i = 0; i < sp; i++) {
+ memcpy(cat512 + i*c512_pad + 0, i8b + i*c128_pad, 128);
+ memcpy(cat512 + i*c512_pad + 128, mp1 + i*c128_pad, 128);
+ memcpy(cat512 + i*c512_pad + 256, mp2 + i*c128_pad, 128);
+ memcpy(cat512 + i*c512_pad + 384, mp3 + i*c128_pad, 128);
+ }
+ i8_conv(i8_sppf2, cat512, h4, w4, i8a, i8scratch); /* 256ch */
+ }
+ static int8_t* save_p5 = NULL;
+ if (!save_p5) save_p5 = (int8_t*)_aligned_malloc(256*256*4, 64);
+ memcpy(save_p5, i8a, h4 * w4 * c256_pad);
+
+ /* ============ Neck ============ */
+
+ /* Upsample P5 (h4→h3) + concat P4 → 384ch */
+ i8_upsample_2x(i8a, c256_pad, h4, w4, i8b); /* 256ch @ h3 */
+ {
+ int c384_pad = C_PAD16(384);
+ int sp = h3 * w3;
+ int8_t* cat384 = i8scratch;
+ for (int i = 0; i < sp; i++) {
+ memcpy(cat384 + i*c384_pad, i8b + i*c256_pad, 256);
+ memcpy(cat384 + i*c384_pad + 256, save_p4 + i*c128_pad, 128);
+ }
+ i8_c2f(i8_nk0, cat384, c384_pad, h3, w3, i8a, c128_pad, i8scratch + sp*c384_pad);
+ }
+ /* i8a = N3 = 128ch @ h3 — save */
+ static int8_t* save_n3 = NULL;
+ if (!save_n3) save_n3 = (int8_t*)_aligned_malloc(256*256*4, 64);
+ memcpy(save_n3, i8a, h3 * w3 * c128_pad);
+
+ /* Upsample N3 (h3→h2) + concat P3 → 192ch */
+ i8_upsample_2x(i8a, c128_pad, h3, w3, i8b); /* 128ch @ h2 */
+ {
+ int c192_pad = C_PAD16(192);
+ int sp = h2 * w2;
+ int8_t* cat192 = i8scratch;
+ for (int i = 0; i < sp; i++) {
+ memcpy(cat192 + i*c192_pad, i8b + i*c128_pad, 128);
+ memcpy(cat192 + i*c192_pad + 128, save_p3 + i*c64_pad, 64);
+ }
+ i8_c2f(i8_nk1, cat192, c192_pad, h2, w2, i8a, c64_pad, i8scratch + sp*c192_pad);
+ }
+ /* i8a = N2 = 64ch @ h2 — save before overwrite */
+ static int8_t* save_n2 = NULL;
+ if (!save_n2) save_n2 = (int8_t*)_aligned_malloc(256*256*4, 64);
+ memcpy(save_n2, i8a, h2 * w2 * c64_pad);
+
+ /* Downsample N2 + concat N3 → 192ch */
+ i8_conv(i8_nkconv0, i8a, h2, w2, i8b, i8scratch); /* 64ch @ h3 */
+ {
+ int c192_pad = C_PAD16(192);
+ int sp = h3 * w3;
+ int8_t* cat192 = i8scratch;
+ for (int i = 0; i < sp; i++) {
+ memcpy(cat192 + i*c192_pad, i8b + i*c64_pad, 64);
+ memcpy(cat192 + i*c192_pad + 64, save_n3 + i*c128_pad, 128);
+ }
+ i8_c2f(i8_nk2, cat192, c192_pad, h3, w3, i8b, c128_pad, i8scratch + sp*c192_pad);
+ }
+ /* i8b = N4 = 128ch @ h3 — head scale 1 feature */
+
+ /* Downsample N4 + concat P5 → 384ch */
+ i8_conv(i8_nkconv1, i8b, h3, w3, i8a, i8scratch); /* 128ch @ h4 */
+ {
+ int c384_pad = C_PAD16(384);
+ int sp = h4 * w4;
+ int8_t* cat384 = i8scratch;
+ for (int i = 0; i < sp; i++) {
+ memcpy(cat384 + i*c384_pad, i8a + i*c128_pad, 128);
+ memcpy(cat384 + i*c384_pad + 128, save_p5 + i*c256_pad, 256);
+ }
+ i8_c2f(i8_nk3, cat384, c384_pad, h4, w4, i8a, c256_pad, i8scratch + sp*c384_pad);
+ }
+ /* i8a = N5 = 256ch @ h4 — head scale 2 feature */
+
+ /* ============ Phase 3: Dequant → FP32 head → decode ============ */
+
+ /* Dequant N2(64ch@h2), N4(128ch@h3→i8b), N5(256ch@h4→i8a) to FP32 NCHW */
+ int head_ch[] = {64, 128, 256};
+ int feat_h[] = {h2, h3, h4};
+ int feat_w[] = {w2, w3, w4};
+ int8_t* feat_i8[] = {save_n2, i8b, i8a}; /* N2, N4, N5 */
+ int feat_pad[] = {c64_pad, c128_pad, c256_pad};
+
+ /* Dequant to buf0/buf1 area (reuse FP32 workspace) */
+ float* feat_fp32[3];
+ float* fptr = buf0;
+ for (int s = 0; s < 3; s++) {
+ feat_fp32[s] = fptr;
+ i8_dequant_to_chw(feat_i8[s], head_ch[s], feat_h[s], feat_w[s],
+ feat_pad[s], default_act_scale, feat_fp32[s]);
+ fptr += head_ch[s] * feat_h[s] * feat_w[s];
+ }
+
+ /* FP32 head: bbox + cls branches for 3 scales */
+ int total_anchors = h2*w2 + h3*w3 + h4*w4;
+ int bbox_ch = 4 * 16; /* 4 * REG_MAX */
+ int cls_ch = fp32->num_classes;
+ int offset = 0;
+
+ float* head_tmp = c2f_tmp;
+ for (int s = 0; s < 3; s++) {
+ int fh = feat_h[s], fw = feat_w[s], sp = fh * fw;
+
+ /* Bbox: conv3x3 → conv3x3 → conv1x1 */
+ float* bx1 = head_tmp;
+ nn2_conv2d(&fp32->head[s].bbox[0], feat_fp32[s], fh, fw, bx1, im2col);
+ float* bx2 = bx1 + fp32->head[s].bbox[0].cout * sp;
+ nn2_conv2d(&fp32->head[s].bbox[1], bx1, fh, fw, bx2, im2col);
+ float* bx3 = bx2 + fp32->head[s].bbox[1].cout * sp;
+ nn2_conv2d(&fp32->head[s].bbox[2], bx2, fh, fw, bx3, im2col);
+
+ /* Cls: conv3x3 → conv3x3 → conv1x1 */
+ float* cx1 = bx3 + bbox_ch * sp;
+ nn2_conv2d(&fp32->head[s].cls[0], feat_fp32[s], fh, fw, cx1, im2col);
+ float* cx2 = cx1 + fp32->head[s].cls[0].cout * sp;
+ nn2_conv2d(&fp32->head[s].cls[1], cx1, fh, fw, cx2, im2col);
+ float* cx3 = cx2 + fp32->head[s].cls[1].cout * sp;
+ nn2_conv2d(&fp32->head[s].cls[2], cx2, fh, fw, cx3, im2col);
+
+ /* Copy to output arrays */
+ for (int c = 0; c < bbox_ch; c++)
+ memcpy(bbox_out + c * total_anchors + offset, bx3 + c * sp, sp * sizeof(float));
+ for (int c = 0; c < cls_ch; c++)
+ memcpy(cls_out + c * total_anchors + offset, cx3 + c * sp, sp * sizeof(float));
+ offset += sp;
+ }
+
+ /* static buffers — not freed */
+ return total_anchors;
+}
+
+/* ============ Main benchmark ============ */
+
+int main(int argc, char** argv)
+{
+ const char* wpath = "weights/yolov8n_320.bin";
+ if (argc > 1) wpath = argv[1];
+
+ NN2* fp32 = nn2_init(wpath, 0);
+ if (!fp32) { fprintf(stderr, "Failed\n"); return 1; }
+ int S = fp32->input_size;
+
+ /* Convert INT8 layers */
+ I8Conv i8_conv2, i8_conv3, i8_conv4, i8_sppf1, i8_sppf2, i8_nkconv0, i8_nkconv1;
+ init_i8conv_default(&i8_conv2, &fp32->bb_conv[2]);
+ init_i8conv_default(&i8_conv3, &fp32->bb_conv[3]);
+ init_i8conv_default(&i8_conv4, &fp32->bb_conv[4]);
+ init_i8conv_default(&i8_sppf1, &fp32->sppf_cv1);
+ init_i8conv_default(&i8_sppf2, &fp32->sppf_cv2);
+ init_i8conv_default(&i8_nkconv0, &fp32->nk_conv[0]);
+ init_i8conv_default(&i8_nkconv1, &fp32->nk_conv[1]);
+
+ I8C2f i8_c2f1, i8_c2f2, i8_c2f3, i8_nk0, i8_nk1, i8_nk2, i8_nk3;
+ init_i8c2f(&i8_c2f1, &fp32->bb_c2f[1]);
+ init_i8c2f(&i8_c2f2, &fp32->bb_c2f[2]);
+ init_i8c2f(&i8_c2f3, &fp32->bb_c2f[3]);
+ init_i8c2f(&i8_nk0, &fp32->nk_c2f[0]);
+ init_i8c2f(&i8_nk1, &fp32->nk_c2f[1]);
+ init_i8c2f(&i8_nk2, &fp32->nk_c2f[2]);
+ init_i8c2f(&i8_nk3, &fp32->nk_c2f[3]);
+
+ fprintf(stderr, "Converted all layers to INT8 VNNI\n");
+
+ /* Dummy input */
+ float* input = (float*)calloc(3 * S * S, sizeof(float));
+ for (int i = 0; i < 3*S*S; i++) input[i] = 0.5f;
+
+ int ta = (S/8)*(S/8)+(S/16)*(S/16)+(S/32)*(S/32);
+ float* bbox = (float*)calloc(64*ta, sizeof(float));
+ float* cls = (float*)calloc(80*ta, sizeof(float));
+
+ /* Warmup */
+ for (int i = 0; i < 3; i++)
+ hybrid_forward(fp32, &i8_conv2, &i8_conv3, &i8_conv4,
+ &i8_c2f1, &i8_c2f2, &i8_c2f3,
+ &i8_sppf1, &i8_sppf2,
+ &i8_nk0, &i8_nk1, &i8_nk2, &i8_nk3,
+ &i8_nkconv0, &i8_nkconv1,
+ input, bbox, cls);
+
+ /* Benchmark full hybrid (backbone + neck + head + decode) */
+ int RUNS = 50;
+
+ /* Warmup + check correctness */
+ int n_anchors = hybrid_forward(fp32, &i8_conv2, &i8_conv3, &i8_conv4,
+ &i8_c2f1, &i8_c2f2, &i8_c2f3,
+ &i8_sppf1, &i8_sppf2,
+ &i8_nk0, &i8_nk1, &i8_nk2, &i8_nk3,
+ &i8_nkconv0, &i8_nkconv1,
+ input, bbox, cls);
+
+ /* Decode to check detections */
+ float dfl_w[16]; for(int i=0;i<16;i++) dfl_w[i]=(float)i;
+ NN2Det dets[300];
+ int nd = nn2_decode(bbox, cls, fp32->num_classes, S, 0.25f, dfl_w, dets, 300);
+ nd = nn2_nms(dets, nd, 0.45f);
+ printf("=== Hybrid INT8 detections (dummy input): %d dets ===\n", nd);
+
+ /* Benchmark hybrid full pipeline */
+ double t0 = h_now();
+ for (int i = 0; i < RUNS; i++)
+ hybrid_forward(fp32, &i8_conv2, &i8_conv3, &i8_conv4,
+ &i8_c2f1, &i8_c2f2, &i8_c2f3,
+ &i8_sppf1, &i8_sppf2,
+ &i8_nk0, &i8_nk1, &i8_nk2, &i8_nk3,
+ &i8_nkconv0, &i8_nkconv1,
+ input, bbox, cls);
+ double hybrid_ms = (h_now() - t0) / RUNS * 1000.0;
+
+ /* Benchmark pure FP32 full forward */
+ t0 = h_now();
+ for (int i = 0; i < RUNS; i++)
+ nn2_forward(fp32, input, bbox, cls);
+ double fp32_ms = (h_now() - t0) / RUNS * 1000.0;
+
+ printf("\n=== Full Pipeline (backbone + neck + head + decode) ===\n");
+ printf(" Hybrid INT8+FP32: %.2f ms (%.0f FPS)\n", hybrid_ms, 1000.0/hybrid_ms);
+ printf(" Pure FP32: %.2f ms (%.0f FPS)\n", fp32_ms, 1000.0/fp32_ms);
+ printf(" Speedup: %.2fx\n", fp32_ms / hybrid_ms);
+ printf("\n ONNX RT reference: ~12.3 ms (81 FPS)\n");
+ printf(" vs ONNX RT: %.2fx faster\n", 12.3 / hybrid_ms);
+
+ /* Cleanup */
+ free_i8conv_s(&i8_conv2); free_i8conv_s(&i8_conv3); free_i8conv_s(&i8_conv4);
+ free_i8conv_s(&i8_sppf1); free_i8conv_s(&i8_sppf2);
+ free_i8conv_s(&i8_nkconv0); free_i8conv_s(&i8_nkconv1);
+ free_i8c2f(&i8_c2f1); free_i8c2f(&i8_c2f2); free_i8c2f(&i8_c2f3);
+ free_i8c2f(&i8_nk0); free_i8c2f(&i8_nk1); free_i8c2f(&i8_nk2); free_i8c2f(&i8_nk3);
+ free(input); free(bbox); free(cls);
+ nn2_free(fp32);
+ return 0;
+}
diff --git a/nn2/src/int8_nhwc/gemm_vnni.c b/nn2/src/int8_nhwc/gemm_vnni.c
new file mode 100644
index 0000000..5366411
--- /dev/null
+++ b/nn2/src/int8_nhwc/gemm_vnni.c
@@ -0,0 +1,232 @@
+/*
+ * gemm_vnni.c — INT8 VNNI GEMM for NHWC pipeline.
+ *
+ * C[M,N] = A_u8[M,K4] × B_s8_packed[K4,N] via VPDPBUSD
+ * Then: dequant + bias + act + requant → INT8 output.
+ *
+ * A is s8 input converted to u8 via XOR 0x80 (add 128).
+ * B is pre-packed VNNI: [N/16][K4/4][16×4 bytes].
+ * Compensation: col_sums[n] = 128 * sum(B[:,n]).
+ *
+ * Threading: parallel across N-tiles (16 channels per tile).
+ */
+
+#include "nn2_int8.h"
+#include "../nn2_internal.h"
+#include <string.h>
+#include <math.h>
+#include <immintrin.h>
+
+#ifdef __AVX512VNNI__
+
+#include "../fast_exp.h"
+
+/* ============ VNNI GEMM worker ============ */
+
+typedef struct {
+ const int8_t* A;
+ int M, K4, N;
+ const int8_t* B_packed;
+ const int32_t* col_sums;
+ const float* w_scales;
+ const float* bias;
+ float inv_act_scale; /* 1 / act_scale */
+ float out_inv_scale; /* 1 / out_scale (for requant) */
+ int act;
+ int8_t* output;
+ int out_stride;
+} VnniCtx;
+
+/* MR=4: process 4 spatial rows sharing same B panel loads */
+#define VNNI_MR 4
+
+static void vnni_worker(void* arg, int start, int end)
+{
+ VnniCtx* g = (VnniCtx*)arg;
+ const uint32_t xor32 = 0x80808080u;
+
+ for (int ni = start; ni < end; ni++) {
+ int n = ni * 16;
+ int nr = (n + 16 <= g->N) ? 16 : g->N - n;
+ const uint8_t* bp_base = (const uint8_t*)g->B_packed
+ + (size_t)(ni) * (g->K4 / 4) * 64;
+
+ /* Preload dequant constants (reused across all M rows) */
+ __m512i vcomp = _mm512_loadu_si512((const __m512i*)(g->col_sums + n));
+ __m512 vws = _mm512_loadu_ps(g->w_scales + n);
+ __m512 vbias = _mm512_loadu_ps(g->bias + n);
+ __m512 vinv = _mm512_set1_ps(g->inv_act_scale);
+ __m512 vout_s = _mm512_set1_ps(g->out_inv_scale);
+ __m512i vmin = _mm512_set1_epi32(-127);
+ __m512i vmax = _mm512_set1_epi32(127);
+
+ int m = 0;
+ /* Process MR=4 rows at a time — share B panel loads */
+ for (; m + VNNI_MR <= g->M; m += VNNI_MR) {
+ const int8_t* a0 = g->A + (m+0) * g->K4;
+ const int8_t* a1 = g->A + (m+1) * g->K4;
+ const int8_t* a2 = g->A + (m+2) * g->K4;
+ const int8_t* a3 = g->A + (m+3) * g->K4;
+ const uint8_t* bp = bp_base;
+
+ __m512i acc0 = _mm512_setzero_si512();
+ __m512i acc1 = _mm512_setzero_si512();
+ __m512i acc2 = _mm512_setzero_si512();
+ __m512i acc3 = _mm512_setzero_si512();
+
+ for (int k = 0; k < g->K4; k += 4) {
+ __m512i vb = _mm512_load_si512((const __m512i*)bp);
+ bp += 64;
+ uint32_t av;
+ memcpy(&av, a0+k, 4); av ^= xor32;
+ acc0 = _mm512_dpbusd_epi32(acc0, _mm512_set1_epi32(av), vb);
+ memcpy(&av, a1+k, 4); av ^= xor32;
+ acc1 = _mm512_dpbusd_epi32(acc1, _mm512_set1_epi32(av), vb);
+ memcpy(&av, a2+k, 4); av ^= xor32;
+ acc2 = _mm512_dpbusd_epi32(acc2, _mm512_set1_epi32(av), vb);
+ memcpy(&av, a3+k, 4); av ^= xor32;
+ acc3 = _mm512_dpbusd_epi32(acc3, _mm512_set1_epi32(av), vb);
+ }
+
+ /* Dequant + bias + act + requant for all 4 rows */
+ #define VNNI_STORE(i, acc_i) { \
+ __m512 vf = _mm512_cvtepi32_ps(_mm512_sub_epi32(acc_i, vcomp)); \
+ __m512 res = _mm512_fmadd_ps(_mm512_mul_ps(vf, vinv), vws, vbias); \
+ if (g->act == 1) res = _mm512_silu_fast(res); \
+ __m512i vi = _mm512_cvtps_epi32(_mm512_mul_ps(res, vout_s)); \
+ vi = _mm512_max_epi32(vi, vmin); vi = _mm512_min_epi32(vi, vmax); \
+ __m128i pk = _mm512_cvtsepi32_epi8(vi); \
+ _mm_storeu_si128((__m128i*)(g->output + (m+(i)) * g->out_stride + n), pk); \
+ }
+ VNNI_STORE(0, acc0);
+ VNNI_STORE(1, acc1);
+ VNNI_STORE(2, acc2);
+ VNNI_STORE(3, acc3);
+ #undef VNNI_STORE
+ }
+
+ /* Tail: remaining rows */
+ for (; m < g->M; m++) {
+ const int8_t* a_row = g->A + m * g->K4;
+ const uint8_t* bp = bp_base;
+ __m512i vacc = _mm512_setzero_si512();
+ for (int k = 0; k < g->K4; k += 4) {
+ uint32_t av; memcpy(&av, a_row+k, 4); av ^= xor32;
+ vacc = _mm512_dpbusd_epi32(vacc, _mm512_set1_epi32(av),
+ _mm512_load_si512((const __m512i*)bp));
+ bp += 64;
+ }
+ __m512 vf = _mm512_cvtepi32_ps(_mm512_sub_epi32(vacc, vcomp));
+ __m512 res = _mm512_fmadd_ps(_mm512_mul_ps(vf, vinv), vws, vbias);
+ if (g->act == 1) res = _mm512_silu_fast(res);
+ __m512i vi = _mm512_cvtps_epi32(_mm512_mul_ps(res, vout_s));
+ vi = _mm512_max_epi32(vi, vmin); vi = _mm512_min_epi32(vi, vmax);
+ _mm_storeu_si128((__m128i*)(g->output + m * g->out_stride + n),
+ _mm512_cvtsepi32_epi8(vi));
+ }
+ }
+}
+
+void i8_gemm_bias_act(
+ const int8_t* A, int M, int K4, int N,
+ const int8_t* B_packed,
+ const int32_t* col_sums,
+ const float* w_scales,
+ const float* bias,
+ float act_scale,
+ float out_scale,
+ int act,
+ int8_t* output,
+ int out_stride)
+{
+ float inv_act = 1.0f / (act_scale + 1e-10f);
+ float out_inv = 1.0f / (out_scale + 1e-10f);
+
+ VnniCtx ctx = {A, M, K4, N, B_packed, col_sums, w_scales, bias,
+ inv_act, out_inv, act, output, out_stride};
+
+ int n_tiles = (N + 15) / 16;
+ int grain = (n_tiles > 32) ? n_tiles / (nn2_tp_num_threads() * 2) : 1;
+ if (grain < 1) grain = 1;
+ if (n_tiles >= 2)
+ nn2_tp_parallel_for(vnni_worker, &ctx, n_tiles, grain);
+ else
+ vnni_worker(&ctx, 0, n_tiles);
+}
+
+/* ============ Weight packing ============ */
+
+void i8_pack_weights(const float* weights, int Cout, int K,
+ int8_t* packed, int32_t* col_sums,
+ float* w_scales)
+{
+ int K4 = K_PAD4(K);
+ int Cout16 = C_PAD16(Cout);
+
+ /* Step 1: Find per-channel scale (absmax) */
+ for (int co = 0; co < Cout; co++) {
+ float amax = 0;
+ for (int k = 0; k < K; k++) {
+ float v = fabsf(weights[co * K + k]);
+ if (v > amax) amax = v;
+ }
+ w_scales[co] = amax / 127.0f;
+ if (w_scales[co] < 1e-10f) w_scales[co] = 1e-10f;
+ }
+
+ /* Step 2: Quantize + pack VNNI format [Cout/16][K4/4][16×4] */
+ memset(packed, 0, (size_t)(Cout16 / 16) * (K4 / 4) * 64);
+
+ for (int n = 0; n < Cout; n += 16) {
+ int nr = (n + 16 <= Cout) ? 16 : Cout - n;
+ int block_base = (n / 16) * (K4 / 4) * 64;
+
+ /* Column sums for compensation */
+ for (int j = 0; j < nr; j++) {
+ int32_t sum = 0;
+ float inv_s = 1.0f / w_scales[n + j];
+ for (int k = 0; k < K; k++) {
+ int8_t q = (int8_t)roundf(weights[(n + j) * K + k] * inv_s);
+ if (q < -127) q = -127;
+ if (q > 127) q = 127;
+ sum += (int32_t)q;
+ }
+ col_sums[n + j] = 128 * sum;
+ }
+
+ /* Pack: [K4/4 blocks][16 channels × 4 k-values] */
+ for (int k = 0; k < K4; k += 4) {
+ for (int j = 0; j < 16; j++) {
+ for (int kk = 0; kk < 4; kk++) {
+ int idx = block_base + (k / 4) * 64 + j * 4 + kk;
+ if (j < nr && (k + kk) < K) {
+ float inv_s = 1.0f / w_scales[n + j];
+ int v = (int)roundf(weights[(n + j) * K + (k + kk)] * inv_s);
+ packed[idx] = (int8_t)(v < -127 ? -127 : v > 127 ? 127 : v);
+ }
+ }
+ }
+ }
+ }
+}
+
+#else /* no VNNI */
+
+void i8_gemm_bias_act(const int8_t* A, int M, int K4, int N,
+ const int8_t* B_packed, const int32_t* col_sums,
+ const float* w_scales, const float* bias,
+ float act_scale, float out_scale, int act,
+ int8_t* output, int out_stride)
+{
+ (void)A;(void)M;(void)K4;(void)N;(void)B_packed;(void)col_sums;
+ (void)w_scales;(void)bias;(void)act_scale;(void)out_scale;(void)act;
+ (void)output;(void)out_stride;
+}
+
+void i8_pack_weights(const float* weights, int Cout, int K,
+ int8_t* packed, int32_t* col_sums, float* w_scales)
+{
+ (void)weights;(void)Cout;(void)K;(void)packed;(void)col_sums;(void)w_scales;
+}
+
+#endif /* __AVX512VNNI__ */
diff --git a/nn2/src/int8_nhwc/net_int8.c b/nn2/src/int8_nhwc/net_int8.c
new file mode 100644
index 0000000..a98c26d
--- /dev/null
+++ b/nn2/src/int8_nhwc/net_int8.c
@@ -0,0 +1,438 @@
+/*
+ * net_int8.c — INT8 NHWC forward pass for YOLOv8n.
+ *
+ * Strategy:
+ * - Backbone + SPPF + Neck: fully INT8 NHWC
+ * - Head: dequant to FP32 CHW, use existing FP32 head
+ *
+ * Weight loading: load FP32 weights from existing .bin, quantize+pack at init.
+ * Activation scales: from calibration file or default heuristic.
+ */
+
+#include "nn2_int8.h"
+#include "../nn2_internal.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+
+/* ============ Init I8Conv from FP32 ConvLayer ============ */
+
+static void init_i8conv(I8Conv* dst, const ConvLayer* src, float act_scale, float out_scale)
+{
+ int K = src->cin * src->k * src->k;
+ int K4 = K_PAD4(K);
+ int Cout16 = C_PAD16(src->cout);
+
+ dst->cin = src->cin;
+ dst->cout = src->cout;
+ dst->k = src->k;
+ dst->stride = src->stride;
+ dst->pad = src->pad;
+ dst->act = src->act;
+ dst->K4 = K4;
+ dst->cout_pad = Cout16;
+ dst->act_scale = act_scale;
+ dst->out_scale = out_scale;
+
+ /* Pack weights */
+ size_t packed_size = (size_t)(Cout16 / 16) * (K4 / 4) * 64;
+ dst->w_packed = (int8_t*)_aligned_malloc(packed_size, 64);
+ dst->col_sums = (int32_t*)malloc(Cout16 * sizeof(int32_t));
+ dst->w_scales = (float*)malloc(Cout16 * sizeof(float));
+ dst->bias = (float*)malloc(Cout16 * sizeof(float));
+
+ memset(dst->col_sums, 0, Cout16 * sizeof(int32_t));
+ memset(dst->w_scales, 0, Cout16 * sizeof(float));
+ memset(dst->bias, 0, Cout16 * sizeof(float));
+ memcpy(dst->bias, src->b, src->cout * sizeof(float));
+
+ i8_pack_weights(src->w, src->cout, K, dst->w_packed, dst->col_sums, dst->w_scales);
+}
+
+static void free_i8conv(I8Conv* L)
+{
+ _aligned_free(L->w_packed);
+ free(L->col_sums);
+ free(L->w_scales);
+ free(L->bias);
+}
+
+/* Forward-declare conv dispatch */
+extern void i8_conv(const I8Conv* L, const int8_t* input, int H, int W,
+ int8_t* output, int8_t* scratch);
+
+/* Forward-declare residual add */
+extern void i8_residual_add(int8_t* a, const int8_t* b, int total,
+ float sa, float sb, float so);
+
+/* ============ INT8 C2f block ============ */
+
+static void i8_c2f_run(const I8C2f* blk, const int8_t* in, int H, int W,
+ int8_t* out, int8_t* scratch, int8_t* tmp)
+{
+ int spatial = H * W;
+ int c = blk->c;
+ int c_pad = C_PAD16(c);
+ int total_ch = (2 + blk->n) * c;
+ int total_pad = C_PAD16(total_ch);
+
+ /* cv1: input → cat buffer (2c channels in NHWC) */
+ int cv1_out_pad = C_PAD16(blk->cv1.cout);
+ int8_t* cat = tmp; /* [spatial, total_pad] */
+ int8_t* cv1_out = scratch;
+ i8_conv(&blk->cv1, in, H, W, cv1_out, scratch + spatial * cv1_out_pad);
+
+ /* Split cv1 output (2c channels) into cat buffer:
+ * chunk0 = channels [0,c), chunk1 = channels [c,2c)
+ * In NHWC: just the first 2c channels per pixel */
+ /* Copy cv1 output channels to beginning of cat */
+ for (int i = 0; i < spatial; i++) {
+ memcpy(cat + i * total_pad, cv1_out + i * cv1_out_pad, 2 * c);
+ }
+
+ /* Bottleneck iterations */
+ int8_t* bn_in_base = cat; /* points to chunk1 start within cat */
+ int bn_in_offset = c; /* channel offset within cat for bn_in */
+
+ for (int bi = 0; bi < blk->n; bi++) {
+ /* Extract bn_in as contiguous [spatial, c_pad] */
+ int8_t* bn_in_cont = scratch;
+ for (int i = 0; i < spatial; i++)
+ memcpy(bn_in_cont + i * c_pad, cat + i * total_pad + bn_in_offset, c);
+
+ /* bn.cv1 */
+ int8_t* bn_cv1_out = scratch + spatial * c_pad;
+ i8_conv(&blk->m[bi].cv1, bn_in_cont, H, W, bn_cv1_out,
+ scratch + 2 * spatial * c_pad);
+
+ /* bn.cv2 */
+ int8_t* bn_cv2_out = scratch + 2 * spatial * c_pad;
+ i8_conv(&blk->m[bi].cv2, bn_cv1_out, H, W, bn_cv2_out,
+ scratch + 3 * spatial * c_pad);
+
+ /* Residual add if shortcut */
+ if (blk->shortcut) {
+ i8_residual_add(bn_cv2_out, bn_in_cont, spatial * c_pad,
+ blk->m[bi].cv2.out_scale, blk->m[bi].cv1.act_scale,
+ blk->m[bi].cv2.out_scale);
+ }
+
+ /* Copy bn_cv2 output to cat at position (2+bi)*c */
+ int cat_offset = (2 + bi) * c;
+ for (int i = 0; i < spatial; i++)
+ memcpy(cat + i * total_pad + cat_offset, bn_cv2_out + i * c_pad, c);
+
+ bn_in_offset = cat_offset;
+ }
+
+ /* cv2: cat → output */
+ /* Extract cat as contiguous for cv2 input */
+ int cv2_cin_pad = C_PAD16(total_ch);
+ int8_t* cv2_in = scratch;
+ for (int i = 0; i < spatial; i++)
+ memcpy(cv2_in + i * cv2_cin_pad, cat + i * total_pad, total_ch);
+
+ i8_conv(&blk->cv2, cv2_in, H, W, out, scratch + spatial * cv2_cin_pad);
+}
+
+/* ============ Benchmark entry point ============ */
+
+/* Simple benchmark: load FP32 model, convert to INT8, run forward pass.
+ * Uses default activation scales (heuristic). */
+
+#include <float.h>
+
+#ifdef _WIN32
+#include <windows.h>
+static double i8_now(void) {
+ static LARGE_INTEGER freq; static int init=0;
+ if(!init){QueryPerformanceFrequency(&freq);init=1;}
+ LARGE_INTEGER t; QueryPerformanceCounter(&t);
+ return (double)t.QuadPart/(double)freq.QuadPart;
+}
+#endif
+
+int main(int argc, char** argv)
+{
+ const char* wpath = "weights/yolov8n_320.bin";
+ if (argc > 1) wpath = argv[1];
+
+ /* Load FP32 model first */
+ NN2* fp32 = nn2_init(wpath, 0);
+ if (!fp32) { fprintf(stderr, "Failed to load model\n"); return 1; }
+ int S = fp32->input_size;
+ fprintf(stderr, "Loaded FP32 model: %dx%d, %d classes\n", S, S, fp32->num_classes);
+
+ /* Default activation scales (should come from calibration) */
+ float default_scale = 0.05f; /* conservative default */
+
+ /* Convert backbone convs to INT8 */
+ I8Conv i8_bb_conv[5];
+ for (int i = 0; i < 5; i++)
+ init_i8conv(&i8_bb_conv[i], &fp32->bb_conv[i], default_scale, default_scale);
+
+ fprintf(stderr, "Converted %d backbone convs to INT8 VNNI\n", 5);
+
+ /* Quick GEMM benchmark: INT8 vs FP32 for backbone conv0 */
+ int H = S, W = S;
+ int h0 = S/2, w0 = S/2;
+
+ /* Create dummy INT8 NHWC input */
+ int C_in = 3, C_in_pad = C_PAD16(C_in);
+ int8_t* input_i8 = (int8_t*)calloc(H * W * C_in_pad, 1);
+ for (int i = 0; i < H * W * C_in_pad; i++) input_i8[i] = (int8_t)(i % 100 - 50);
+
+ /* Output buffer */
+ int cout0 = fp32->bb_conv[0].cout;
+ int cout0_pad = C_PAD16(cout0);
+ int8_t* output_i8 = (int8_t*)calloc(h0 * w0 * cout0_pad, 1);
+ int8_t* scratch = (int8_t*)calloc(4 * 1024 * 1024, 1); /* 4MB scratch */
+
+ /* FP32 input for comparison */
+ float* input_fp32 = (float*)calloc(3 * S * S, sizeof(float));
+ for (int i = 0; i < 3 * S * S; i++) input_fp32[i] = 0.5f;
+ float* output_fp32 = (float*)calloc(cout0 * h0 * w0, sizeof(float));
+ float* col_buf = (float*)calloc(4 * 1024 * 1024, sizeof(float));
+
+ /* Warmup */
+ for (int i = 0; i < 3; i++) {
+ i8_conv3x3(&i8_bb_conv[0], input_i8, H, W, output_i8, scratch);
+ nn2_conv2d(&fp32->bb_conv[0], input_fp32, H, W, output_fp32, col_buf);
+ }
+
+ int RUNS = 100;
+
+ /* Benchmark INT8 */
+ double t0 = i8_now();
+ for (int i = 0; i < RUNS; i++)
+ i8_conv3x3(&i8_bb_conv[0], input_i8, H, W, output_i8, scratch);
+ double t1 = i8_now();
+ double i8_ms = (t1 - t0) / RUNS * 1000.0;
+
+ /* Benchmark FP32 */
+ t0 = i8_now();
+ for (int i = 0; i < RUNS; i++)
+ nn2_conv2d(&fp32->bb_conv[0], input_fp32, H, W, output_fp32, col_buf);
+ t1 = i8_now();
+ double fp32_ms = (t1 - t0) / RUNS * 1000.0;
+
+ printf("=== Conv0 (3→16, 3x3 s=2, %dx%d → %dx%d) ===\n", S, S, h0, w0);
+ printf(" FP32 NCHW: %.3f ms\n", fp32_ms);
+ printf(" INT8 NHWC: %.3f ms\n", i8_ms);
+ printf(" Speedup: %.2fx\n", fp32_ms / i8_ms);
+
+ /* Benchmark all 5 backbone convs */
+ printf("\n=== All backbone convs ===\n");
+ int hh[] = {S, S/2, S/4, S/4, S/16};
+ int ww[] = {S, S/2, S/4, S/4, S/16};
+ int ho[] = {S/2, S/4, S/8, S/8, S/32};
+ int wo[] = {S/2, S/4, S/8, S/8, S/32};
+
+ /* Correct: use cumulative sizes */
+ hh[0]=S; ww[0]=S; ho[0]=S/2; wo[0]=S/2;
+ hh[1]=S/2; ww[1]=S/2; ho[1]=S/4; wo[1]=S/4;
+ hh[2]=S/4; ww[2]=S/4; ho[2]=S/8; wo[2]=S/8;
+ hh[3]=S/8; ww[3]=S/8; ho[3]=S/16; wo[3]=S/16;
+ hh[4]=S/16; ww[4]=S/16; ho[4]=S/32; wo[4]=S/32;
+
+ double total_i8 = 0, total_fp = 0;
+ for (int layer = 0; layer < 5; layer++) {
+ int cin = fp32->bb_conv[layer].cin;
+ int cout = fp32->bb_conv[layer].cout;
+ int cin_pad = C_PAD16(cin);
+ int cout_p = C_PAD16(cout);
+
+ int8_t* li = (int8_t*)calloc(hh[layer] * ww[layer] * cin_pad, 1);
+ int8_t* lo = (int8_t*)calloc(ho[layer] * wo[layer] * cout_p, 1);
+ float* fi = (float*)calloc(cin * hh[layer] * ww[layer], sizeof(float));
+ float* fo = (float*)calloc(cout * ho[layer] * wo[layer], sizeof(float));
+
+ for (int r = 0; r < 3; r++) {
+ i8_conv3x3(&i8_bb_conv[layer], li, hh[layer], ww[layer], lo, scratch);
+ nn2_conv2d(&fp32->bb_conv[layer], fi, hh[layer], ww[layer], fo, col_buf);
+ }
+
+ t0 = i8_now();
+ for (int r = 0; r < RUNS; r++)
+ i8_conv3x3(&i8_bb_conv[layer], li, hh[layer], ww[layer], lo, scratch);
+ t1 = i8_now();
+ double ms_i8 = (t1-t0)/RUNS*1000.0;
+
+ t0 = i8_now();
+ for (int r = 0; r < RUNS; r++)
+ nn2_conv2d(&fp32->bb_conv[layer], fi, hh[layer], ww[layer], fo, col_buf);
+ t1 = i8_now();
+ double ms_fp = (t1-t0)/RUNS*1000.0;
+
+ printf(" conv%d (%d→%d, %dx%d→%dx%d): FP32=%.3f INT8=%.3f %.2fx\n",
+ layer, cin, cout, hh[layer], ww[layer], ho[layer], wo[layer],
+ ms_fp, ms_i8, ms_fp/ms_i8);
+ total_i8 += ms_i8;
+ total_fp += ms_fp;
+
+ free(li); free(lo); free(fi); free(fo);
+ }
+ printf(" TOTAL backbone: FP32=%.3f INT8=%.3f %.2fx\n",
+ total_fp, total_i8, total_fp/total_i8);
+
+ /* ============ Hybrid pipeline benchmark ============
+ * FP32: conv0, conv1, c2f0 (Cin<32 → FP32 faster)
+ * Transition: FP32 CHW → INT8 NHWC at 64ch boundary
+ * INT8: conv2-4, c2f1-3, SPPF, neck (Cin≥32 → INT8 faster) */
+
+ printf("\n=== Hybrid Pipeline Benchmark ===\n");
+ {
+ /* Run FP32 layers: conv0 → conv1 → c2f0 → conv2 */
+ float* ws = fp32->workspace;
+ float* im = ws; ws += 4*1024*1024;
+ float* b0 = ws; ws += 4*1024*1024;
+ float* b1 = ws; ws += 4*1024*1024;
+ float* c2f_tmp = ws;
+
+ /* Dummy input */
+ float* inp = (float*)calloc(3*S*S, sizeof(float));
+ for(int i=0;i<3*S*S;i++) inp[i]=0.5f;
+
+ int HRUNS = 50;
+
+ /* Measure FP32 portion: conv0→conv1→c2f0→conv2 */
+ /* Warmup */
+ nn2_conv2d(&fp32->bb_conv[0], inp, S, S, b0, im);
+ nn2_conv2d(&fp32->bb_conv[1], b0, S/2, S/2, b1, im);
+
+ double t_fp = i8_now();
+ for (int r = 0; r < HRUNS; r++) {
+ nn2_conv2d(&fp32->bb_conv[0], inp, S, S, b0, im);
+ nn2_conv2d(&fp32->bb_conv[1], b0, S/2, S/2, b1, im);
+ /* c2f0 would go here but skip for now */
+ nn2_conv2d(&fp32->bb_conv[2], b1, S/4, S/4, b0, im);
+ }
+ double fp_early_ms = (i8_now() - t_fp) / HRUNS * 1000.0;
+
+ /* Measure INT8 portion: conv3→conv4 (heavy layers) */
+ I8Conv i8c3, i8c4;
+ init_i8conv(&i8c3, &fp32->bb_conv[3], default_scale, default_scale);
+ init_i8conv(&i8c4, &fp32->bb_conv[4], default_scale, default_scale);
+
+ int c3_cin_pad = C_PAD16(fp32->bb_conv[3].cin);
+ int c3_cout_pad = C_PAD16(fp32->bb_conv[3].cout);
+ int c4_cout_pad = C_PAD16(fp32->bb_conv[4].cout);
+
+ int8_t* i8_in3 = (int8_t*)calloc((S/8)*(S/8)*c3_cin_pad, 1);
+ int8_t* i8_out3 = (int8_t*)calloc((S/16)*(S/16)*c3_cout_pad, 1);
+ int8_t* i8_out4 = (int8_t*)calloc((S/32)*(S/32)*c4_cout_pad, 1);
+ int8_t* i8_scr = (int8_t*)calloc(4*1024*1024, 1);
+
+ /* Warmup */
+ i8_conv3x3(&i8c3, i8_in3, S/8, S/8, i8_out3, i8_scr);
+ i8_conv3x3(&i8c4, i8_out3, S/16, S/16, i8_out4, i8_scr);
+
+ double t_i8 = i8_now();
+ for (int r = 0; r < HRUNS; r++) {
+ i8_conv3x3(&i8c3, i8_in3, S/8, S/8, i8_out3, i8_scr);
+ i8_conv3x3(&i8c4, i8_out3, S/16, S/16, i8_out4, i8_scr);
+ }
+ double i8_late_ms = (i8_now() - t_i8) / HRUNS * 1000.0;
+
+ /* Compare with all-FP32 for same layers */
+ float* fp_in3 = (float*)calloc(64*(S/8)*(S/8), sizeof(float));
+ float* fp_out3 = (float*)calloc(128*(S/16)*(S/16), sizeof(float));
+ float* fp_out4 = (float*)calloc(256*(S/32)*(S/32), sizeof(float));
+
+ nn2_conv2d(&fp32->bb_conv[3], fp_in3, S/8, S/8, fp_out3, im);
+ nn2_conv2d(&fp32->bb_conv[4], fp_out3, S/16, S/16, fp_out4, im);
+
+ double t_fp2 = i8_now();
+ for (int r = 0; r < HRUNS; r++) {
+ nn2_conv2d(&fp32->bb_conv[3], fp_in3, S/8, S/8, fp_out3, im);
+ nn2_conv2d(&fp32->bb_conv[4], fp_out3, S/16, S/16, fp_out4, im);
+ }
+ double fp_late_ms = (i8_now() - t_fp2) / HRUNS * 1000.0;
+
+ printf(" FP32 early layers (conv0-2): %.3f ms\n", fp_early_ms);
+ printf(" FP32 late layers (conv3-4): %.3f ms\n", fp_late_ms);
+ printf(" INT8 late layers (conv3-4): %.3f ms\n", i8_late_ms);
+ printf(" Late layer speedup: %.2fx\n", fp_late_ms / i8_late_ms);
+ printf("\n Hybrid estimate: %.3f ms (FP32 early + INT8 late)\n",
+ fp_early_ms + i8_late_ms);
+ printf(" Full FP32: %.3f ms (conv0-4 only)\n",
+ fp_early_ms + fp_late_ms);
+
+ free_i8conv(&i8c3); free_i8conv(&i8c4);
+ free(i8_in3); free(i8_out3); free(i8_out4); free(i8_scr);
+ free(fp_in3); free(fp_out3); free(fp_out4);
+ free(inp);
+ }
+
+ /* ============ Individual 3x3 conv benchmark at C2f sizes ============ */
+ printf("\n=== C2f-sized 3x3 convs (INT8 vs FP32) ===\n");
+ {
+ /* C2f bottleneck convs: c→c, 3x3, s=1 */
+ struct { int c; int H; const char* name; } tests[] = {
+ {32, 80, "c2f0 (32ch@80x80)"},
+ {32, 40, "c2f1 (32ch@40x40)"},
+ {64, 20, "c2f2 (64ch@20x20)"},
+ {128, 10, "c2f3 (128ch@10x10)"},
+ /* head convs */
+ {64, 40, "head0 (64ch@40x40)"},
+ {128, 20, "head1 (128ch@20x20)"},
+ };
+ int ntests = sizeof(tests)/sizeof(tests[0]);
+
+ for (int t = 0; t < ntests; t++) {
+ int c = tests[t].c, Ht = tests[t].H;
+ /* Create dummy FP32 conv layer */
+ ConvLayer fl; memset(&fl, 0, sizeof(fl));
+ fl.cout = c; fl.cin = c; fl.k = 3; fl.stride = 1; fl.pad = 1; fl.act = 1;
+ int K = c * 9;
+ fl.w = (float*)calloc(c * K, sizeof(float));
+ fl.b = (float*)calloc(c, sizeof(float));
+ for (int i = 0; i < c*K; i++) fl.w[i] = 0.001f * (i%37-18);
+ for (int i = 0; i < c; i++) fl.b[i] = 0.01f * i;
+ fl.w_packed = nn2_pack_weight_a(fl.w, c, K);
+
+ I8Conv il;
+ init_i8conv(&il, &fl, default_scale, default_scale);
+
+ int sp = Ht * Ht;
+ int c_pad = C_PAD16(c);
+ int8_t* ii = (int8_t*)calloc(sp * c_pad, 1);
+ int8_t* io = (int8_t*)calloc(sp * c_pad, 1);
+ int8_t* is = (int8_t*)calloc(4*1024*1024, 1);
+ float* fi = (float*)calloc(c * sp, sizeof(float));
+ float* fo = (float*)calloc(c * sp, sizeof(float));
+ float* fc = (float*)calloc(4*1024*1024, sizeof(float));
+
+ int R = 200;
+ /* Warmup */
+ for(int r=0;r<5;r++) {
+ i8_conv3x3(&il, ii, Ht, Ht, io, is);
+ nn2_conv2d(&fl, fi, Ht, Ht, fo, fc);
+ }
+
+ double t0 = i8_now();
+ for(int r=0;r<R;r++) i8_conv3x3(&il, ii, Ht, Ht, io, is);
+ double ms_i8 = (i8_now()-t0)/R*1000.0;
+
+ t0 = i8_now();
+ for(int r=0;r<R;r++) nn2_conv2d(&fl, fi, Ht, Ht, fo, fc);
+ double ms_fp = (i8_now()-t0)/R*1000.0;
+
+ printf(" %-25s FP32=%.3f INT8=%.3f %.2fx\n",
+ tests[t].name, ms_fp, ms_i8, ms_fp/ms_i8);
+
+ free_i8conv(&il);
+ free(fl.w); free(fl.b); _aligned_free(fl.w_packed);
+ free(ii); free(io); free(is); free(fi); free(fo); free(fc);
+ }
+ }
+
+ /* Cleanup */
+ for (int i = 0; i < 5; i++) free_i8conv(&i8_bb_conv[i]);
+ free(input_i8); free(output_i8); free(scratch);
+ free(input_fp32); free(output_fp32); free(col_buf);
+ nn2_free(fp32);
+
+ return 0;
+}
diff --git a/nn2/src/int8_nhwc/nn2_int8.h b/nn2/src/int8_nhwc/nn2_int8.h
new file mode 100644
index 0000000..4abd52d
--- /dev/null
+++ b/nn2/src/int8_nhwc/nn2_int8.h
@@ -0,0 +1,139 @@
+/*
+ * nn2_int8.h — Full INT8 NHWC inference pipeline.
+ *
+ * Layout: activations are int8_t[H][W][C_pad16] (NHWC, C padded to 16).
+ * VNNI GEMM: A[M,K4] (uint8) × B_packed[K4,N16] (int8 VNNI) → int32 → int8
+ *
+ * Key insight: NHWC makes K-dimension (channels) contiguous.
+ * No transpose needed for VNNI — im2col output is naturally [spatial, K].
+ *
+ * Pipeline per conv:
+ * 1. im2col from INT8 NHWC input → INT8 [spatial, K4] (contiguous)
+ * 2. XOR trick: s8→u8 for VPDPBUSD's unsigned×signed requirement
+ * 3. VNNI GEMM: u8 × s8 → s32 accumulators
+ * 4. Dequant s32 → f32, apply bias + SiLU, requant → s8
+ * 5. Store INT8 NHWC output
+ */
+
+#ifndef NN2_INT8_H
+#define NN2_INT8_H
+
+#include <stdint.h>
+#include <stddef.h>
+
+/* Pad channel count to multiple of 16 for AVX-512 alignment */
+#define C_PAD16(c) (((c) + 15) & ~15)
+/* Pad K to multiple of 4 for VNNI (4 bytes per VPDPBUSD group) */
+#define K_PAD4(k) (((k) + 3) & ~3)
+
+/* Per-layer quantization parameters */
+typedef struct {
+ float scale; /* activation scale: float_val = int8_val * scale */
+ float inv_scale; /* 1.0 / scale for quantization */
+} QuantScale;
+
+/* INT8 NHWC convolution layer */
+typedef struct {
+ int8_t* w_packed; /* VNNI-packed: [Cout_pad/16][K4/4][64] */
+ int32_t* col_sums; /* [Cout] = 128 * sum(w[:,n]) for u8 offset compensation */
+ float* w_scales; /* [Cout] per-channel weight scale */
+ float* bias; /* [Cout] FP32 bias */
+ float act_scale; /* input activation scale */
+ float out_scale; /* output activation scale */
+ int cout, cin, k, stride, pad;
+ int act; /* 0=none, 1=SiLU, 2=sigmoid */
+ int K4; /* K_PAD4(cin * k * k) */
+ int cout_pad; /* C_PAD16(cout) */
+} I8Conv;
+
+/* INT8 NHWC C2f block */
+typedef struct {
+ I8Conv cv1;
+ I8Conv cv2;
+ struct { I8Conv cv1, cv2; } m[3];
+ int n, c, shortcut;
+} I8C2f;
+
+/* Full INT8 model */
+typedef struct {
+ /* Backbone */
+ I8Conv bb_conv[5];
+ I8C2f bb_c2f[4];
+ I8Conv sppf_cv1, sppf_cv2;
+ /* Neck */
+ I8C2f nk_c2f[4];
+ I8Conv nk_conv[2];
+ /* Head (stays FP32 for decode accuracy) */
+ /* ... head uses existing FP32 path */
+
+ int num_classes;
+ int input_size;
+
+ /* Workspace */
+ int8_t* ws_int8; /* INT8 workspace for activations */
+ float* ws_fp32; /* FP32 workspace for head + decode */
+ size_t ws_int8_size;
+ size_t ws_fp32_size;
+} I8Model;
+
+/* ============ VNNI GEMM ============ */
+
+/* INT8 VNNI GEMM: C_int32[M,N] = A_u8[M,K4] × B_packed[K4,N]
+ * Then: dequant + bias + SiLU + requant → int8 output.
+ * A is s8 input XOR'd to u8 (+128 offset).
+ * B_packed: [N/16][K4/4][64 bytes] VNNI format.
+ * col_sums: [N] = 128 * sum(B[:,n]) for compensation. */
+void i8_gemm_bias_act(
+ const int8_t* A, int M, int K4, int N,
+ const int8_t* B_packed,
+ const int32_t* col_sums,
+ const float* w_scales, /* [N] per-channel */
+ const float* bias, /* [N] */
+ float act_scale, /* input scale */
+ float out_scale, /* output scale */
+ int act, /* 0=none, 1=SiLU */
+ int8_t* output, /* [M, N_pad16] INT8 NHWC */
+ int out_stride); /* stride between output rows (= N_pad16) */
+
+/* ============ Weight packing ============ */
+
+/* Pack FP32 weights to INT8 VNNI format.
+ * weights: [Cout, K] FP32 row-major
+ * Returns: per-channel scales in w_scales[Cout] */
+void i8_pack_weights(const float* weights, int Cout, int K,
+ int8_t* packed, int32_t* col_sums,
+ float* w_scales);
+
+/* ============ INT8 NHWC Conv ============ */
+
+/* 1x1 conv: direct GEMM, no im2col */
+void i8_conv1x1(const I8Conv* L, const int8_t* input, int H, int W,
+ int8_t* output);
+
+/* 3x3 conv: im2col + GEMM */
+void i8_conv3x3(const I8Conv* L, const int8_t* input, int H, int W,
+ int8_t* output, int8_t* im2col_buf);
+
+/* ============ INT8 NHWC Ops ============ */
+
+/* Quantize FP32 CHW → INT8 NHWC */
+void i8_quantize_nhwc(const float* fp32_chw, int C, int H, int W,
+ float scale, int8_t* out_nhwc, int C_pad);
+
+/* Dequantize INT8 NHWC → FP32 CHW */
+void i8_dequant_to_chw(const int8_t* int8_nhwc, int C, int H, int W,
+ int C_pad, float scale, float* fp32_chw);
+
+/* Nearest-neighbor upsample 2× in NHWC (trivial: duplicate HW pixels) */
+void i8_upsample_2x(const int8_t* in, int C_pad, int H, int W, int8_t* out);
+
+/* Concat in NHWC: [H,W,Ca] + [H,W,Cb] → [H,W,Ca+Cb] */
+void i8_concat(const int8_t* a, int Ca_pad, const int8_t* b, int Cb_pad,
+ int H, int W, int8_t* out, int Cout_pad,
+ float scale_a, float scale_b, float scale_out);
+
+/* MaxPool 5×5 s=1 p=2 in INT8 NHWC */
+void i8_maxpool(const int8_t* in, int C_pad, int H, int W,
+ int k, int stride, int pad, int8_t* out);
+
+#endif /* NN2_INT8_H */
diff --git a/nn2/src/int8_nhwc/ops_int8.c b/nn2/src/int8_nhwc/ops_int8.c
new file mode 100644
index 0000000..d9ae0fe
--- /dev/null
+++ b/nn2/src/int8_nhwc/ops_int8.c
@@ -0,0 +1,188 @@
+/*
+ * ops_int8.c — INT8 NHWC operations: quantize, dequant, upsample, concat, maxpool.
+ *
+ * NHWC makes many ops trivial:
+ * - Upsample: duplicate [W,C_pad] rows → contiguous copy
+ * - Concat: copy Ca bytes then Cb bytes per pixel → simple interleave
+ * - MaxPool: compare int8 values directly (no float conversion!)
+ */
+
+#include "nn2_int8.h"
+#include "../nn2_internal.h"
+#include <string.h>
+#include <math.h>
+
+#ifdef __AVX512F__
+#include <immintrin.h>
+#endif
+
+/* ============ FP32 CHW → INT8 NHWC ============ */
+
+void i8_quantize_nhwc(const float* fp32_chw, int C, int H, int W,
+ float scale, int8_t* out_nhwc, int C_pad)
+{
+ float inv_scale = 1.0f / (scale + 1e-10f);
+ int spatial = H * W;
+
+ /* Transpose CHW → HWC and quantize */
+ for (int h = 0; h < H; h++) {
+ for (int w = 0; w < W; w++) {
+ int8_t* dst = out_nhwc + (h * W + w) * C_pad;
+ for (int c = 0; c < C; c++) {
+ float v = fp32_chw[c * spatial + h * W + w];
+ int q = (int)roundf(v * inv_scale);
+ dst[c] = (int8_t)(q < -127 ? -127 : q > 127 ? 127 : q);
+ }
+ /* Pad remaining channels to 0 */
+ for (int c = C; c < C_pad; c++) dst[c] = 0;
+ }
+ }
+}
+
+/* ============ INT8 NHWC → FP32 CHW ============ */
+
+void i8_dequant_to_chw(const int8_t* int8_nhwc, int C, int H, int W,
+ int C_pad, float scale, float* fp32_chw)
+{
+ int spatial = H * W;
+ for (int h = 0; h < H; h++) {
+ for (int w = 0; w < W; w++) {
+ const int8_t* src = int8_nhwc + (h * W + w) * C_pad;
+ for (int c = 0; c < C; c++)
+ fp32_chw[c * spatial + h * W + w] = (float)src[c] * scale;
+ }
+ }
+}
+
+/* ============ Upsample 2× in INT8 NHWC ============ */
+
+void i8_upsample_2x(const int8_t* in, int C_pad, int H, int W, int8_t* out)
+{
+ int Wout = W * 2;
+ /* NHWC upsample: each pixel [C_pad bytes] gets duplicated to 2×2 block.
+ * Row by row: copy each pixel twice, then duplicate the row. */
+ for (int h = 0; h < H; h++) {
+ const int8_t* srow = in + h * W * C_pad;
+ int8_t* drow0 = out + (h * 2) * Wout * C_pad;
+ int8_t* drow1 = drow0 + Wout * C_pad;
+
+ for (int w = 0; w < W; w++) {
+ const int8_t* px = srow + w * C_pad;
+ /* Write pixel to (2w, 2h) and (2w+1, 2h) */
+ memcpy(drow0 + (w * 2) * C_pad, px, C_pad);
+ memcpy(drow0 + (w * 2 + 1) * C_pad, px, C_pad);
+ }
+ /* Duplicate row: drow1 = drow0 */
+ memcpy(drow1, drow0, Wout * C_pad);
+ }
+}
+
+/* ============ Concat in INT8 NHWC ============ */
+
+void i8_concat(const int8_t* a, int Ca_pad, const int8_t* b, int Cb_pad,
+ int H, int W, int8_t* out, int Cout_pad,
+ float scale_a, float scale_b, float scale_out)
+{
+ int spatial = H * W;
+ int Ca = Ca_pad; /* actual padded sizes */
+ int Cb = Cb_pad;
+
+ /* If scales match, just copy bytes (no rescaling needed) */
+ if (fabsf(scale_a - scale_out) < 1e-6f && fabsf(scale_b - scale_out) < 1e-6f) {
+ for (int i = 0; i < spatial; i++) {
+ memcpy(out + i * Cout_pad, a + i * Ca_pad, Ca);
+ memcpy(out + i * Cout_pad + Ca, b + i * Cb_pad, Cb);
+ /* Zero-pad if Cout_pad > Ca + Cb */
+ if (Ca + Cb < Cout_pad)
+ memset(out + i * Cout_pad + Ca + Cb, 0, Cout_pad - Ca - Cb);
+ }
+ } else {
+ /* Different scales: requantize during concat */
+ float sa = scale_a / scale_out;
+ float sb = scale_b / scale_out;
+ for (int i = 0; i < spatial; i++) {
+ const int8_t* pa = a + i * Ca_pad;
+ const int8_t* pb = b + i * Cb_pad;
+ int8_t* po = out + i * Cout_pad;
+ for (int c = 0; c < Ca; c++) {
+ int v = (int)roundf((float)pa[c] * sa);
+ po[c] = (int8_t)(v < -127 ? -127 : v > 127 ? 127 : v);
+ }
+ for (int c = 0; c < Cb; c++) {
+ int v = (int)roundf((float)pb[c] * sb);
+ po[Ca + c] = (int8_t)(v < -127 ? -127 : v > 127 ? 127 : v);
+ }
+ if (Ca + Cb < Cout_pad)
+ memset(po + Ca + Cb, 0, Cout_pad - Ca - Cb);
+ }
+ }
+}
+
+/* ============ MaxPool in INT8 NHWC ============ */
+
+void i8_maxpool(const int8_t* in, int C_pad, int H, int W,
+ int k, int stride, int pad, int8_t* out)
+{
+ int Hout = (H + 2 * pad - k) / stride + 1;
+ int Wout = (W + 2 * pad - k) / stride + 1;
+
+ /* INT8 maxpool: compare bytes directly! Much faster than float. */
+ for (int oh = 0; oh < Hout; oh++) {
+ for (int ow = 0; ow < Wout; ow++) {
+ int8_t* dst = out + (oh * Wout + ow) * C_pad;
+ /* Init to minimum */
+ memset(dst, 0x80, C_pad); /* -128 */
+
+ for (int kh = 0; kh < k; kh++) {
+ int ih = oh * stride - pad + kh;
+ if (ih < 0 || ih >= H) continue;
+ for (int kw = 0; kw < k; kw++) {
+ int iw = ow * stride - pad + kw;
+ if (iw < 0 || iw >= W) continue;
+ const int8_t* src = in + (ih * W + iw) * C_pad;
+ /* Max per channel — can use SIMD! */
+ int c = 0;
+#ifdef __AVX512BW__
+ for (; c + 64 <= C_pad; c += 64) {
+ __m512i vd = _mm512_loadu_si512((__m512i*)(dst + c));
+ __m512i vs = _mm512_loadu_si512((__m512i*)(src + c));
+ _mm512_storeu_si512((__m512i*)(dst + c), _mm512_max_epi8(vd, vs));
+ }
+#endif
+ for (; c < C_pad; c++)
+ if (src[c] > dst[c]) dst[c] = src[c];
+ }
+ }
+ }
+ }
+}
+
+/* ============ Shortcut (residual) add in INT8 ============ */
+
+void i8_residual_add(int8_t* a, const int8_t* b, int total_bytes,
+ float scale_a, float scale_b, float scale_out)
+{
+ /* If all scales are the same, add and clamp */
+ if (fabsf(scale_a - scale_b) < 1e-6f && fabsf(scale_a - scale_out) < 1e-6f) {
+ int i = 0;
+#ifdef __AVX512BW__
+ for (; i + 64 <= total_bytes; i += 64) {
+ __m512i va = _mm512_loadu_si512((__m512i*)(a + i));
+ __m512i vb = _mm512_loadu_si512((__m512i*)(b + i));
+ _mm512_storeu_si512((__m512i*)(a + i), _mm512_adds_epi8(va, vb));
+ }
+#endif
+ for (; i < total_bytes; i++) {
+ int v = (int)a[i] + (int)b[i];
+ a[i] = (int8_t)(v < -127 ? -127 : v > 127 ? 127 : v);
+ }
+ } else {
+ /* Different scales: dequant, add, requant */
+ float sa = scale_a / scale_out;
+ float sb = scale_b / scale_out;
+ for (int i = 0; i < total_bytes; i++) {
+ int v = (int)roundf((float)a[i] * sa + (float)b[i] * sb);
+ a[i] = (int8_t)(v < -127 ? -127 : v > 127 ? 127 : v);
+ }
+ }
+}
diff --git a/nn2/src/main.c b/nn2/src/main.c
new file mode 100644
index 0000000..cd17e6b
--- /dev/null
+++ b/nn2/src/main.c
@@ -0,0 +1,87 @@
+/*
+ * main.c — CLI entry point for nn2 YOLO inference.
+ *
+ * Usage: nn2 <weights.bin> <image.raw> <width> <height>
+ * Image format: raw RGB uint8, HWC layout.
+ *
+ * For real use, integrate stb_image.h or feed from video decoder.
+ */
+
+#include "nn2_internal.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef _WIN32
+#include <windows.h>
+static double get_time_ms(void) {
+ LARGE_INTEGER freq, cnt;
+ QueryPerformanceFrequency(&freq);
+ QueryPerformanceCounter(&cnt);
+ return (double)cnt.QuadPart / freq.QuadPart * 1000.0;
+}
+#else
+#include <time.h>
+static double get_time_ms(void) {
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return ts.tv_sec * 1000.0 + ts.tv_nsec / 1e6;
+}
+#endif
+
+int main(int argc, char** argv)
+{
+ if (argc < 5) {
+ fprintf(stderr, "Usage: %s <weights.bin> <image.raw> <width> <height> [threads]\n", argv[0]);
+ fprintf(stderr, " image.raw: raw RGB uint8, HWC layout, width*height*3 bytes\n");
+ return 1;
+ }
+
+ const char* weights_path = argv[1];
+ const char* image_path = argv[2];
+ int width = atoi(argv[3]);
+ int height = atoi(argv[4]);
+ int n_threads = (argc > 5) ? atoi(argv[5]) : 0;
+
+ /* Load image */
+ FILE* f = fopen(image_path, "rb");
+ if (!f) { fprintf(stderr, "cannot open %s\n", image_path); return 1; }
+ size_t img_size = (size_t)width * height * 3;
+ uint8_t* img = (uint8_t*)malloc(img_size);
+ fread(img, 1, img_size, f);
+ fclose(f);
+
+ /* Init */
+ NN2* ctx = nn2_init(weights_path, n_threads);
+ if (!ctx) { fprintf(stderr, "failed to init nn2\n"); free(img); return 1; }
+
+ /* Warmup */
+ NN2Det dets[300];
+ nn2_detect(ctx, img, width, height, dets, 300);
+
+ /* Benchmark */
+ int N_RUNS = 50;
+ double t0 = get_time_ms();
+ int n_det = 0;
+ for (int i = 0; i < N_RUNS; i++)
+ n_det = nn2_detect(ctx, img, width, height, dets, 300);
+ double t1 = get_time_ms();
+
+ printf("nn2 v%s | %dx%d → %d input | %d threads\n",
+ nn2_version(), width, height, ctx->input_size,
+ nn2_tp_num_threads());
+ printf("avg %.1f ms (%.1f FPS) over %d runs | %d dispatches/inference\n",
+ (t1 - t0) / N_RUNS, N_RUNS / ((t1 - t0) / 1000.0), N_RUNS,
+ nn2_tp_dispatch_count() / N_RUNS);
+ nn2_tp_reset_dispatch_count();
+ printf("%d detections:\n", n_det);
+ for (int i = 0; i < n_det; i++) {
+ printf(" [%d] cls=%d score=%.3f box=(%.1f, %.1f, %.1f, %.1f)\n",
+ i, dets[i].cls, dets[i].score,
+ dets[i].x1, dets[i].y1, dets[i].x2, dets[i].y2);
+ }
+
+ nn2_free(ctx);
+ free(img);
+ return 0;
+}
diff --git a/nn2/src/main_annotate.c b/nn2/src/main_annotate.c
new file mode 100644
index 0000000..0d2556b
--- /dev/null
+++ b/nn2/src/main_annotate.c
@@ -0,0 +1,74 @@
+/*
+ * main_annotate.c — Detect objects and save annotated image with bboxes.
+ * Usage: nn2_annotate <weights.bin> <input.jpg> <output.jpg> [threads]
+ */
+
+#define STB_IMAGE_IMPLEMENTATION
+#include "stb_image.h"
+#define STB_IMAGE_WRITE_IMPLEMENTATION
+#include "stb_image_write.h"
+#include "nn2.h"
+#include "draw.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+static const char* coco_names[] = {
+ "person","bicycle","car","motorcycle","airplane","bus","train","truck","boat",
+ "traffic light","fire hydrant","stop sign","parking meter","bench","bird","cat",
+ "dog","horse","sheep","cow","elephant","bear","zebra","giraffe","backpack",
+ "umbrella","handbag","tie","suitcase","frisbee","skis","snowboard","sports ball",
+ "kite","baseball bat","baseball glove","skateboard","surfboard","tennis racket",
+ "bottle","wine glass","cup","fork","knife","spoon","bowl","banana","apple",
+ "sandwich","orange","broccoli","carrot","hot dog","pizza","donut","cake","chair",
+ "couch","potted plant","bed","dining table","toilet","tv","laptop","mouse",
+ "remote","keyboard","cell phone","microwave","oven","toaster","sink",
+ "refrigerator","book","clock","vase","scissors","teddy bear","hair drier","toothbrush"
+};
+
+int main(int argc, char** argv)
+{
+ if (argc < 4) {
+ fprintf(stderr, "Usage: %s <weights.bin> <input.jpg> <output.jpg> [threads]\n", argv[0]);
+ return 1;
+ }
+
+ int threads = (argc > 4) ? atoi(argv[4]) : 0;
+
+ /* Load image */
+ int w, h, channels;
+ uint8_t* img = stbi_load(argv[2], &w, &h, &channels, 3);
+ if (!img) { fprintf(stderr, "Failed to load %s\n", argv[2]); return 1; }
+ printf("Input: %s (%dx%d)\n", argv[2], w, h);
+
+ /* Init + detect */
+ NN2* ctx = nn2_init(argv[1], threads);
+ if (!ctx) { stbi_image_free(img); return 1; }
+
+ NN2Det dets[300];
+ int n = nn2_detect(ctx, img, w, h, dets, 300);
+ printf("%d detections:\n", n);
+ for (int i = 0; i < n; i++) {
+ const char* name = (dets[i].cls >= 0 && dets[i].cls < 80) ? coco_names[dets[i].cls] : "?";
+ printf(" [%d] %s %.0f%% (%.0f,%.0f)-(%.0f,%.0f)\n",
+ i, name, dets[i].score*100,
+ dets[i].x1, dets[i].y1, dets[i].x2, dets[i].y2);
+ }
+
+ /* Draw bboxes */
+ nn2_draw_detections(img, w, h, dets, n);
+
+ /* Save */
+ const char* out_path = argv[3];
+ int ok = 0;
+ if (strstr(out_path, ".png"))
+ ok = stbi_write_png(out_path, w, h, 3, img, w * 3);
+ else
+ ok = stbi_write_jpg(out_path, w, h, 3, img, 95);
+
+ if (ok) printf("Saved: %s\n", out_path);
+ else fprintf(stderr, "Failed to save %s\n", out_path);
+
+ nn2_free(ctx);
+ stbi_image_free(img);
+ return 0;
+}
diff --git a/nn2/src/main_antispoof.c b/nn2/src/main_antispoof.c
new file mode 100644
index 0000000..60cc5b5
--- /dev/null
+++ b/nn2/src/main_antispoof.c
@@ -0,0 +1,66 @@
+/*
+ * main_antispoof.c — CLI for the MiniFASNet port:
+ * nn2_antispoof_test <v2|v1se> <weights.bin> <80x80_bgr.bin> [iters]
+ *
+ * Reads a raw 80×80 BGR uint8 image (HWC, 19200 bytes) and runs N forward
+ * passes, prints predicted probabilities + average latency.
+ */
+
+#include "nn2_antispoof.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#ifdef _WIN32
+#include <windows.h>
+static double now_sec(void) {
+ LARGE_INTEGER f, c;
+ QueryPerformanceFrequency(&f); QueryPerformanceCounter(&c);
+ return (double)c.QuadPart / (double)f.QuadPart;
+}
+#else
+#include <time.h>
+static double now_sec(void) {
+ struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts);
+ return ts.tv_sec + ts.tv_nsec * 1e-9;
+}
+#endif
+
+int main(int argc, char** argv)
+{
+ if (argc < 4) {
+ fprintf(stderr, "usage: %s <v2|v1se> <weights.bin> <80x80_bgr.bin> [iters]\n", argv[0]);
+ return 1;
+ }
+ AntiSpoofVariant var = (strcmp(argv[1], "v2") == 0) ? NN2_AS_V2 : NN2_AS_V1SE;
+ int iters = (argc > 4) ? atoi(argv[4]) : 100;
+
+ AntiSpoofModel* m = nn2_antispoof_load(argv[2], var, 0);
+ if (!m) { fprintf(stderr, "load failed\n"); return 2; }
+
+ unsigned char bgr[80 * 80 * 3];
+ FILE* f = fopen(argv[3], "rb");
+ if (!f || fread(bgr, 1, sizeof(bgr), f) != sizeof(bgr)) {
+ fprintf(stderr, "cannot read 19200 bytes from %s\n", argv[3]);
+ if (f) fclose(f);
+ return 3;
+ }
+ fclose(f);
+
+ float probs[3];
+ /* Warm-up */
+ for (int i = 0; i < 5; i++) nn2_antispoof_predict(m, bgr, probs);
+
+ /* Timed run */
+ double t0 = now_sec();
+ for (int i = 0; i < iters; i++) nn2_antispoof_predict(m, bgr, probs);
+ double t1 = now_sec();
+ double ms = (t1 - t0) * 1000.0 / iters;
+
+ printf("variant=%s probs=[%.6f, %.6f, %.6f] P(live)=%.4f %.3f ms/iter (%d iters)\n",
+ argv[1], probs[0], probs[1], probs[2], probs[1], ms, iters);
+
+ nn2_antispoof_free(m);
+ return 0;
+}
diff --git a/nn2/src/main_img.c b/nn2/src/main_img.c
new file mode 100644
index 0000000..d3ae1ec
--- /dev/null
+++ b/nn2/src/main_img.c
@@ -0,0 +1,79 @@
+/*
+ * main_img.c — nn2 CLI with real image loading via stb_image.
+ * Usage: nn2_img <weights.bin> <image.jpg/png> [threads]
+ */
+#define STB_IMAGE_IMPLEMENTATION
+#include "stb_image.h"
+#include "nn2.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+#ifdef _WIN32
+#include <windows.h>
+static double get_time_ms(void) {
+ LARGE_INTEGER f, c;
+ QueryPerformanceFrequency(&f);
+ QueryPerformanceCounter(&c);
+ return (double)c.QuadPart / f.QuadPart * 1000.0;
+}
+#endif
+
+static const char* coco_names[] = {
+ "person","bicycle","car","motorcycle","airplane","bus","train","truck","boat",
+ "traffic light","fire hydrant","stop sign","parking meter","bench","bird","cat",
+ "dog","horse","sheep","cow","elephant","bear","zebra","giraffe","backpack",
+ "umbrella","handbag","tie","suitcase","frisbee","skis","snowboard","sports ball",
+ "kite","baseball bat","baseball glove","skateboard","surfboard","tennis racket",
+ "bottle","wine glass","cup","fork","knife","spoon","bowl","banana","apple",
+ "sandwich","orange","broccoli","carrot","hot dog","pizza","donut","cake","chair",
+ "couch","potted plant","bed","dining table","toilet","tv","laptop","mouse",
+ "remote","keyboard","cell phone","microwave","oven","toaster","sink",
+ "refrigerator","book","clock","vase","scissors","teddy bear","hair drier","toothbrush"
+};
+
+int main(int argc, char** argv)
+{
+ if (argc < 3) {
+ fprintf(stderr, "Usage: %s <weights.bin> <image.jpg/png> [threads]\n", argv[0]);
+ return 1;
+ }
+
+ int n_threads = (argc > 3) ? atoi(argv[3]) : 0;
+
+ /* Load image */
+ int w, h, channels;
+ uint8_t* img = stbi_load(argv[2], &w, &h, &channels, 3);
+ if (!img) { fprintf(stderr, "Failed to load %s\n", argv[2]); return 1; }
+ printf("Image: %s (%dx%d)\n", argv[2], w, h);
+
+ /* Init */
+ NN2* ctx = nn2_init(argv[1], n_threads);
+ if (!ctx) { stbi_image_free(img); return 1; }
+
+ /* Detect */
+ NN2Det dets[300];
+ double t0 = get_time_ms();
+ int n = nn2_detect(ctx, img, w, h, dets, 300);
+ double ms = get_time_ms() - t0;
+
+ printf("\n%d detections in %.1f ms:\n", n, ms);
+ for (int i = 0; i < n; i++) {
+ const char* name = (dets[i].cls >= 0 && dets[i].cls < 80) ? coco_names[dets[i].cls] : "?";
+ printf(" [%d] %s (%.1f%%) @ (%.0f,%.0f)-(%.0f,%.0f)\n",
+ i, name, dets[i].score * 100,
+ dets[i].x1, dets[i].y1, dets[i].x2, dets[i].y2);
+ }
+
+ /* Benchmark */
+ nn2_detect(ctx, img, w, h, dets, 300); /* warmup */
+ int N = 50;
+ t0 = get_time_ms();
+ for (int i = 0; i < N; i++)
+ nn2_detect(ctx, img, w, h, dets, 300);
+ ms = (get_time_ms() - t0) / N;
+ printf("\nBenchmark: %.1f ms (%.0f FPS) over %d runs\n", ms, 1000.0/ms, N);
+
+ nn2_free(ctx);
+ stbi_image_free(img);
+ return 0;
+}
diff --git a/nn2/src/main_nanodet.c b/nn2/src/main_nanodet.c
new file mode 100644
index 0000000..a27c65a
--- /dev/null
+++ b/nn2/src/main_nanodet.c
@@ -0,0 +1,42 @@
+#include "nn2.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef _WIN32
+#include <windows.h>
+static double get_time_ms(void){LARGE_INTEGER f,c;QueryPerformanceFrequency(&f);QueryPerformanceCounter(&c);return(double)c.QuadPart/f.QuadPart*1000.0;}
+#endif
+
+/* From nanodet.c */
+typedef struct NanoDet NanoDet;
+NanoDet* nanodet_init(const char* path, int n_threads);
+int nanodet_detect(NanoDet* nd, const uint8_t* rgb, int w, int h, NN2Det* out, int max);
+void nanodet_free(NanoDet* nd);
+
+int main(int argc, char** argv){
+ if(argc<5){fprintf(stderr,"Usage: %s <weights.bin> <image.raw> <w> <h> [threads]\n",argv[0]);return 1;}
+ const char*wp=argv[1];const char*ip=argv[2];
+ int w=atoi(argv[3]),h=atoi(argv[4]),nt=argc>5?atoi(argv[5]):0;
+
+ FILE*f=fopen(ip,"rb");if(!f)return 1;
+ uint8_t*img=(uint8_t*)malloc(w*h*3);fread(img,1,w*h*3,f);fclose(f);
+
+ NanoDet*nd=nanodet_init(wp,nt);
+ if(!nd)return 1;
+
+ NN2Det dets[300];
+ /* Warmup */
+ nanodet_detect(nd,img,w,h,dets,300);
+
+ int N=50;double t0=get_time_ms();int n=0;
+ for(int i=0;i<N;i++) n=nanodet_detect(nd,img,w,h,dets,300);
+ double ms=(get_time_ms()-t0)/N;
+ printf("NanoDet-Plus-m | %dx%d input | %d threads\n",w,h,nt);
+ printf("avg %.1f ms (%.1f FPS) over %d runs\n",ms,1000.0/ms,N);
+ printf("%d detections:\n",n);
+ for(int i=0;i<n&&i<10;i++)
+ printf(" cls=%d score=%.3f box=(%.0f,%.0f,%.0f,%.0f)\n",
+ dets[i].cls,dets[i].score,dets[i].x1,dets[i].y1,dets[i].x2,dets[i].y2);
+
+ nanodet_free(nd);free(img);return 0;
+}
diff --git a/nn2/src/main_nvr.c b/nn2/src/main_nvr.c
new file mode 100644
index 0000000..1be6345
--- /dev/null
+++ b/nn2/src/main_nvr.c
@@ -0,0 +1,132 @@
+/*
+ * main_nvr.c — NVR multi-camera simulation.
+ *
+ * Simulates N cameras pushing frames at 30fps.
+ * Shows how many cameras can be processed in real-time.
+ */
+
+#include "nn2_nvr.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef _WIN32
+#include <windows.h>
+static double get_ms(void) {
+ LARGE_INTEGER f, c;
+ QueryPerformanceFrequency(&f);
+ QueryPerformanceCounter(&c);
+ return (double)c.QuadPart / f.QuadPart * 1000.0;
+}
+#endif
+
+static const char* coco_names[] = {
+ "person","bicycle","car","motorcycle","airplane","bus","train","truck","boat",
+ "traffic light","fire hydrant","stop sign","parking meter","bench","bird","cat",
+ "dog","horse","sheep","cow","elephant","bear","zebra","giraffe","backpack",
+ "umbrella","handbag","tie","suitcase","frisbee","skis","snowboard","sports ball",
+ "kite","baseball bat","baseball glove","skateboard","surfboard","tennis racket",
+ "bottle","wine glass","cup","fork","knife","spoon","bowl","banana","apple",
+ "sandwich","orange","broccoli","carrot","hot dog","pizza","donut","cake","chair",
+ "couch","potted plant","bed","dining table","toilet","tv","laptop","mouse",
+ "remote","keyboard","cell phone","microwave","oven","toaster","sink",
+ "refrigerator","book","clock","vase","scissors","teddy bear","hair drier","toothbrush"
+};
+
+static void on_detection(const NN2NVREvent* event, void* userdata)
+{
+ (void)userdata;
+ printf(" [CAM %d] %d objects detected (%.1fms):",
+ event->cam_id, event->det_count, event->inference_ms);
+ for (int i = 0; i < event->det_count && i < 3; i++) {
+ const char* name = (event->dets[i].cls >= 0 && event->dets[i].cls < 80)
+ ? coco_names[event->dets[i].cls] : "?";
+ printf(" %s(%.0f%%)", name, event->dets[i].score * 100);
+ }
+ if (event->det_count > 3) printf(" +%d more", event->det_count - 3);
+ printf("\n");
+}
+
+int main(int argc, char** argv)
+{
+ int n_cameras = 8;
+ int n_threads = 6;
+ int sim_seconds = 5;
+ const char* weights = "weights/yolov8n_320.bin";
+
+ if (argc > 1) weights = argv[1];
+ if (argc > 2) n_cameras = atoi(argv[2]);
+ if (argc > 3) n_threads = atoi(argv[3]);
+
+ printf("nn2 NVR Simulation\n");
+ printf(" Model: %s\n", weights);
+ printf(" Cameras: %d\n", n_cameras);
+ printf(" Threads: %d\n", n_threads);
+ printf(" Skip: 5 (process every 5th frame)\n");
+ printf(" Simulating %d seconds at 30fps per camera\n\n", sim_seconds);
+
+ NN2NVR* nvr = nn2_nvr_create(weights, n_threads);
+ if (!nvr) { fprintf(stderr, "Failed to create NVR\n"); return 1; }
+
+ nn2_nvr_set_callback(nvr, on_detection, NULL);
+ nn2_nvr_set_skip_frames(nvr, 5);
+ nn2_nvr_set_conf_threshold(nvr, 0.25f);
+
+ for (int i = 0; i < n_cameras; i++) {
+ char name[32];
+ snprintf(name, sizeof(name), "Camera-%d", i);
+ nn2_nvr_add_camera(nvr, i, name);
+ }
+
+ /* Create fake camera frames (each camera gets a slightly different image) */
+ uint8_t** frames = (uint8_t**)malloc(n_cameras * sizeof(uint8_t*));
+ int fw = 640, fh = 480;
+ for (int c = 0; c < n_cameras; c++) {
+ frames[c] = (uint8_t*)malloc(fw * fh * 3);
+ /* Fill with camera-specific pattern */
+ for (int i = 0; i < fw * fh * 3; i++)
+ frames[c][i] = (uint8_t)((i + c * 17) % 256);
+ }
+
+ /* Simulate: 30fps × n_cameras for sim_seconds */
+ int total_frames = 30 * sim_seconds;
+ double t0 = get_ms();
+
+ for (int f = 0; f < total_frames; f++) {
+ /* Each camera pushes one frame per cycle */
+ for (int c = 0; c < n_cameras; c++) {
+ /* Slightly modify frame to simulate motion */
+ if (f > 0) {
+ int offset = (f * 7 + c * 13) % (fw * fh * 3);
+ frames[c][offset] = (uint8_t)(frames[c][offset] + 50);
+ }
+ nn2_nvr_push_frame(nvr, c, frames[c], fw, fh);
+ }
+ }
+
+ double elapsed = get_ms() - t0;
+
+ /* Results */
+ int tot_frames, tot_dets;
+ double avg_ms;
+ nn2_nvr_stats(nvr, &tot_frames, &tot_dets, &avg_ms);
+
+ printf("\n=== NVR Results ===\n");
+ printf(" Cameras: %d\n", n_cameras);
+ printf(" Total frames pushed: %d\n", tot_frames);
+ printf(" Inferences run: %d (skip=%d)\n",
+ tot_frames / n_cameras / 5 * n_cameras, 5);
+ printf(" Avg inference: %.1f ms\n", avg_ms);
+ printf(" Total time: %.0f ms\n", elapsed);
+ printf(" Throughput: %.0f frames/sec (all cameras)\n",
+ tot_frames / (elapsed / 1000.0));
+ printf(" Real-time capacity: %.0f cameras @ 30fps skip-5\n",
+ 1000.0 / avg_ms * 5.0 / 6.0); /* 6 inferences/sec per camera */
+ printf(" Total detections: %d\n", tot_dets);
+
+ /* Cleanup */
+ for (int c = 0; c < n_cameras; c++) free(frames[c]);
+ free(frames);
+ nn2_nvr_free(nvr);
+ return 0;
+}
diff --git a/nn2/src/main_nvr_full.c b/nn2/src/main_nvr_full.c
new file mode 100644
index 0000000..ad10b94
--- /dev/null
+++ b/nn2/src/main_nvr_full.c
@@ -0,0 +1,220 @@
+/*
+ * main_nvr_full.c — Realistic NVR deployment simulation.
+ *
+ * 8 cameras × 30fps × 30 seconds with detection + tracking + counting.
+ * Measures real-world throughput, latency, and capacity.
+ */
+
+#include "nn2.h"
+#include "nn2_track.h"
+#include "nn2_count.h"
+#include "nn2_json.h"
+#include "nn2_nvr.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+
+#ifdef _WIN32
+#include <windows.h>
+static double get_ms(void) {
+ LARGE_INTEGER f, c;
+ QueryPerformanceFrequency(&f);
+ QueryPerformanceCounter(&c);
+ return (double)c.QuadPart / f.QuadPart * 1000.0;
+}
+#endif
+
+#define MAX_CAMS 32
+
+typedef struct {
+ int id;
+ char name[32];
+ NN2Tracker* tracker;
+ NN2Counter* counter;
+ int frames_pushed;
+ int frames_processed;
+ int total_dets;
+ double total_inference_ms;
+} CamState;
+
+int main(int argc, char** argv)
+{
+ int n_cams = 8;
+ int fps = 30;
+ int sim_seconds = 30;
+ int skip = 5;
+ int threads = 6;
+ const char* weights = "weights/yolov8n_320.bin";
+
+ if (argc > 1) weights = argv[1];
+ if (argc > 2) n_cams = atoi(argv[2]);
+ if (argc > 3) threads = atoi(argv[3]);
+ if (argc > 4) sim_seconds = atoi(argv[4]);
+ if (n_cams > MAX_CAMS) n_cams = MAX_CAMS;
+
+ printf("╔══════════════════════════════════════════════╗\n");
+ printf("║ nn2 NVR Deployment Simulation ║\n");
+ printf("╠══════════════════════════════════════════════╣\n");
+ printf("║ Cameras: %-3d @ 640x480 30fps ║\n", n_cams);
+ printf("║ Model: YOLOv8n @ 320x320 ║\n");
+ printf("║ Skip: %d (%.1f detections/sec/cam) ║\n", skip, (float)fps/skip);
+ printf("║ Duration: %d seconds ║\n", sim_seconds);
+ printf("║ Threads: %d ║\n", threads);
+ printf("║ Pipeline: Detect → Track → Count → JSON ║\n");
+ printf("╚══════════════════════════════════════════════╝\n\n");
+
+ /* Init model */
+ NN2* model = nn2_init(weights, threads);
+ if (!model) return 1;
+
+ /* Init cameras with trackers and counters */
+ CamState cams[MAX_CAMS];
+ for (int i = 0; i < n_cams; i++) {
+ memset(&cams[i], 0, sizeof(CamState));
+ cams[i].id = i;
+ snprintf(cams[i].name, sizeof(cams[i].name), "Cam-%d", i);
+ cams[i].tracker = nn2_tracker_create(15, 2);
+ /* Horizontal counting line at y=240 (middle of 480px frame) */
+ cams[i].counter = nn2_counter_create(0, 240, 640, 240);
+ }
+
+ /* Open JSON log */
+ FILE* jlog = fopen("nvr_events.jsonl", "w");
+
+ /* Create camera frames (each slightly different) */
+ int fw = 640, fh = 480;
+ uint8_t** frames = (uint8_t**)malloc(n_cams * sizeof(uint8_t*));
+ for (int c = 0; c < n_cams; c++) {
+ frames[c] = (uint8_t*)malloc(fw * fh * 3);
+ for (int j = 0; j < fw * fh * 3; j++)
+ frames[c][j] = (uint8_t)((j * 7 + c * 31) % 200 + 30);
+ }
+
+ /* Simulation */
+ int total_frames = fps * sim_seconds;
+ double start = get_ms();
+ double last_report = start;
+ int global_dets = 0;
+ int global_inferences = 0;
+
+ printf("Running %d seconds of %d cameras...\n\n", sim_seconds, n_cams);
+
+ for (int f = 0; f < total_frames; f++) {
+ /* Simulate motion: modify some pixels each frame */
+ for (int c = 0; c < n_cams; c++) {
+ int offset = ((f + c * 17) * 137) % (fw * fh * 3 - 100);
+ for (int j = 0; j < 50; j++)
+ frames[c][offset + j] = (uint8_t)((frames[c][offset + j] + 37 + f) % 256);
+ }
+
+ /* Process each camera */
+ for (int c = 0; c < n_cams; c++) {
+ cams[c].frames_pushed++;
+
+ /* Skip frames */
+ if ((cams[c].frames_pushed % skip) != 0) continue;
+
+ /* Detect */
+ NN2Det dets[50];
+ double t0 = get_ms();
+ int n = nn2_detect(model, frames[c], fw, fh, dets, 50);
+ double ms = get_ms() - t0;
+
+ cams[c].frames_processed++;
+ cams[c].total_dets += n;
+ cams[c].total_inference_ms += ms;
+ global_dets += n;
+ global_inferences++;
+
+ /* Track */
+ NN2Track tracks[50];
+ int nt = nn2_tracker_update(cams[c].tracker, dets, n, tracks, 50);
+
+ /* Count */
+ nn2_counter_update(cams[c].counter, tracks, nt);
+
+ /* Log detections */
+ if (n > 0 && jlog) {
+ fprintf(jlog, "{\"camera\":%d,\"frame\":%d,\"time\":%.1f,"
+ "\"inference_ms\":%.1f,\"detections\":%d,"
+ "\"tracks\":%d,\"count_in\":%d,\"count_out\":%d}\n",
+ c, f, (get_ms() - start) / 1000.0,
+ ms, n, nt,
+ cams[c].counter->count_in,
+ cams[c].counter->count_out);
+ }
+ }
+
+ /* Progress report every 5 seconds */
+ double now = get_ms();
+ if (now - last_report > 5000) {
+ double elapsed = (now - start) / 1000.0;
+ int sim_sec = f / fps;
+ double det_rate = global_inferences / elapsed;
+ printf(" [%2ds/%ds] %d inferences (%.0f/sec), %d detections, "
+ "avg %.1fms\n",
+ sim_sec, sim_seconds, global_inferences, det_rate,
+ global_dets,
+ global_inferences > 0 ?
+ (now - start) / global_inferences : 0);
+ last_report = now;
+ }
+ }
+
+ double elapsed = (get_ms() - start) / 1000.0;
+ if (jlog) fclose(jlog);
+
+ /* Results */
+ printf("\n╔══════════════════════════════════════════════╗\n");
+ printf("║ Simulation Results ║\n");
+ printf("╠══════════════════════════════════════════════╣\n");
+ printf("║ Duration: %.1f sec (simulated %ds) \n", elapsed, sim_seconds);
+ printf("║ Total frames: %d (%d per camera) \n", total_frames * n_cams, total_frames);
+ printf("║ Inferences: %d \n", global_inferences);
+ printf("║ Detections: %d \n", global_dets);
+ printf("║ Inference rate: %.0f/sec \n", global_inferences / elapsed);
+ printf("║ \n");
+
+ double total_inf_ms = 0;
+ for (int c = 0; c < n_cams; c++) total_inf_ms += cams[c].total_inference_ms;
+ double avg_inf = global_inferences > 0 ? total_inf_ms / global_inferences : 0;
+
+ printf("║ Avg inference: %.1f ms \n", avg_inf);
+ printf("║ Throughput: %.0f fps (all cameras) \n",
+ total_frames * n_cams / elapsed);
+ printf("║ \n");
+
+ /* Can we keep up? */
+ double needed_rate = (double)n_cams * fps / skip; /* inferences needed per second */
+ double actual_rate = global_inferences / elapsed;
+ int realtime = actual_rate >= needed_rate * 0.95;
+ printf("║ Needed rate: %.0f inferences/sec \n", needed_rate);
+ printf("║ Actual rate: %.0f inferences/sec \n", actual_rate);
+ printf("║ Real-time: %s \n", realtime ? "YES" : "NO — OVERLOADED");
+ printf("║ Headroom: %.0f%% \n",
+ (actual_rate / needed_rate - 1.0) * 100);
+ printf("║ \n");
+
+ /* Per-camera stats */
+ printf("║ Per-camera: \n");
+ for (int c = 0; c < n_cams; c++) {
+ printf("║ %s: %d dets, %d tracks, In:%d Out:%d \n",
+ cams[c].name, cams[c].total_dets,
+ nn2_tracker_total_ids(cams[c].tracker),
+ cams[c].counter->count_in,
+ cams[c].counter->count_out);
+ }
+ printf("╚══════════════════════════════════════════════╝\n");
+ printf("\nJSON log: nvr_events.jsonl\n");
+
+ /* Cleanup */
+ for (int c = 0; c < n_cams; c++) {
+ free(frames[c]);
+ nn2_tracker_free(cams[c].tracker);
+ nn2_counter_free(cams[c].counter);
+ }
+ free(frames);
+ nn2_free(model);
+ return 0;
+}
diff --git a/nn2/src/main_pipeline.c b/nn2/src/main_pipeline.c
new file mode 100644
index 0000000..97ed772
--- /dev/null
+++ b/nn2/src/main_pipeline.c
@@ -0,0 +1,164 @@
+/*
+ * main_pipeline.c — Full NVR analytics pipeline demo.
+ *
+ * Detection → Tracking → Line Counting → JSON output.
+ * Processes raw video frames and shows real-time analytics.
+ */
+
+#include "nn2.h"
+#include "nn2_track.h"
+#include "nn2_count.h"
+#include "nn2_json.h"
+#include "nn2_nvr.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef _WIN32
+#include <windows.h>
+static double get_ms(void) {
+ LARGE_INTEGER f, c;
+ QueryPerformanceFrequency(&f);
+ QueryPerformanceCounter(&c);
+ return (double)c.QuadPart / f.QuadPart * 1000.0;
+}
+#endif
+
+static const char* coco_names[] = {
+ "person","bicycle","car","motorcycle","airplane","bus","train","truck","boat",
+ "traffic light","fire hydrant","stop sign","parking meter","bench","bird","cat",
+ "dog","horse","sheep","cow","elephant","bear","zebra","giraffe","backpack",
+ "umbrella","handbag","tie","suitcase","frisbee","skis","snowboard","sports ball",
+ "kite","baseball bat","baseball glove","skateboard","surfboard","tennis racket",
+ "bottle","wine glass","cup","fork","knife","spoon","bowl","banana","apple",
+ "sandwich","orange","broccoli","carrot","hot dog","pizza","donut","cake","chair",
+ "couch","potted plant","bed","dining table","toilet","tv","laptop","mouse",
+ "remote","keyboard","cell phone","microwave","oven","toaster","sink",
+ "refrigerator","book","clock","vase","scissors","teddy bear","hair drier","toothbrush"
+};
+
+int main(int argc, char** argv)
+{
+ const char* weights = (argc > 1) ? argv[1] : "weights/yolov8n_320.bin";
+ int threads = (argc > 2) ? atoi(argv[2]) : 6;
+ int n_frames = (argc > 3) ? atoi(argv[3]) : 150; /* 5 sec @ 30fps */
+
+ printf("=== nn2 Full Analytics Pipeline ===\n\n");
+ printf("Model: %s\n", weights);
+ printf("Frames: %d (simulated 30fps)\n", n_frames);
+ printf("Pipeline: Detection -> Tracking -> Counting -> JSON\n\n");
+
+ /* Init */
+ NN2* model = nn2_init(weights, threads);
+ if (!model) return 1;
+
+ NN2Tracker* tracker = nn2_tracker_create(15, 2);
+ /* Counting line: horizontal at y=240 (middle of 480px frame) */
+ NN2Counter* counter = nn2_counter_create(0, 240, 640, 240);
+
+ FILE* json_out = fopen("pipeline_events.jsonl", "w");
+
+ int fw = 640, fh = 480;
+ uint8_t* frame = (uint8_t*)malloc(fw * fh * 3);
+
+ /* Stats */
+ int total_dets = 0, total_tracks = 0;
+ double total_det_ms = 0, total_trk_ms = 0;
+ double start = get_ms();
+
+ printf("Processing %d frames...\n\n", n_frames);
+
+ for (int f = 0; f < n_frames; f++) {
+ /* Generate frame with varying content */
+ memset(frame, 140, fw * fh * 3); /* gray background */
+
+ /* Add moving colored rectangles (simulate objects) */
+ int obj_y = 50 + (f * 3) % 380;
+ int obj_x = 100 + (f * 5) % 440;
+ for (int y = obj_y; y < obj_y + 80 && y < fh; y++)
+ for (int x = obj_x; x < obj_x + 60 && x < fw; x++) {
+ frame[(y*fw+x)*3+0] = 200;
+ frame[(y*fw+x)*3+1] = 100;
+ frame[(y*fw+x)*3+2] = 80;
+ }
+
+ /* Second object moving opposite */
+ int obj2_y = 400 - (f * 2) % 350;
+ int obj2_x = 400 + (f * 3) % 200;
+ for (int y = obj2_y; y < obj2_y + 70 && y < fh; y++)
+ for (int x = obj2_x; x < obj2_x + 90 && x < fw; x++) {
+ if (y >= 0 && x >= 0) {
+ frame[(y*fw+x)*3+0] = 60;
+ frame[(y*fw+x)*3+1] = 60;
+ frame[(y*fw+x)*3+2] = 180;
+ }
+ }
+
+ /* Skip frames (process every 5th) */
+ if ((f % 5) != 0) continue;
+
+ /* 1. Detection */
+ NN2Det dets[50];
+ double t0 = get_ms();
+ int n_det = nn2_detect(model, frame, fw, fh, dets, 50);
+ double det_ms = get_ms() - t0;
+ total_det_ms += det_ms;
+ total_dets += n_det;
+
+ /* 2. Tracking */
+ NN2Track tracks[50];
+ double t1 = get_ms();
+ int n_trk = nn2_tracker_update(tracker, dets, n_det, tracks, 50);
+ double trk_ms = get_ms() - t1;
+ total_trk_ms += trk_ms;
+ total_tracks += n_trk;
+
+ /* 3. Counting */
+ nn2_counter_update(counter, tracks, n_trk);
+
+ /* 4. JSON output */
+ if (n_det > 0 && json_out) {
+ fprintf(json_out, "{\"frame\":%d,\"inference_ms\":%.1f,\"detections\":[", f, det_ms);
+ for (int i = 0; i < n_det; i++) {
+ const char* name = (dets[i].cls >= 0 && dets[i].cls < 80) ? coco_names[dets[i].cls] : "?";
+ fprintf(json_out, "%s{\"class\":\"%s\",\"score\":%.3f,\"bbox\":[%.0f,%.0f,%.0f,%.0f]}",
+ i?",":"", name, dets[i].score, dets[i].x1, dets[i].y1, dets[i].x2, dets[i].y2);
+ }
+ fprintf(json_out, "],\"tracks\":[");
+ for (int i = 0; i < n_trk; i++) {
+ fprintf(json_out, "%s{\"id\":%d,\"class\":%d,\"bbox\":[%.0f,%.0f,%.0f,%.0f]}",
+ i?",":"", tracks[i].id, tracks[i].cls,
+ tracks[i].x1, tracks[i].y1, tracks[i].x2, tracks[i].y2);
+ }
+ fprintf(json_out, "],\"count\":{\"in\":%d,\"out\":%d}}\n",
+ counter->count_in, counter->count_out);
+ }
+
+ /* Console output every 10 processed frames */
+ int processed = f / 5 + 1;
+ if (processed % 10 == 0 || f == n_frames - 1) {
+ printf(" Frame %3d: %d dets, %d tracks, In:%d Out:%d (%.1fms det + %.2fms trk)\n",
+ f, n_det, n_trk, counter->count_in, counter->count_out, det_ms, trk_ms);
+ }
+ }
+
+ double elapsed = get_ms() - start;
+ int processed = n_frames / 5;
+
+ printf("\n=== Pipeline Results ===\n");
+ printf(" Frames: %d total, %d processed (skip-5)\n", n_frames, processed);
+ printf(" Avg detection: %.1f ms\n", processed > 0 ? total_det_ms / processed : 0);
+ printf(" Avg tracking: %.2f ms\n", processed > 0 ? total_trk_ms / processed : 0);
+ printf(" Total detections: %d\n", total_dets);
+ printf(" Unique track IDs: %d\n", nn2_tracker_total_ids(tracker));
+ printf(" Line crossings — In: %d, Out: %d\n", counter->count_in, counter->count_out);
+ printf(" Pipeline FPS: %.0f (end-to-end)\n", n_frames / (elapsed / 1000.0));
+ printf(" JSON output: pipeline_events.jsonl\n");
+
+ if (json_out) fclose(json_out);
+ free(frame);
+ nn2_counter_free(counter);
+ nn2_tracker_free(tracker);
+ nn2_free(model);
+ return 0;
+}
diff --git a/nn2/src/main_server.c b/nn2/src/main_server.c
new file mode 100644
index 0000000..4a0bdf3
--- /dev/null
+++ b/nn2/src/main_server.c
@@ -0,0 +1,156 @@
+/*
+ * main_server.c — HTTP API server for nn2 detection.
+ *
+ * Usage: nn2_server <weights.bin> [port] [threads]
+ *
+ * Endpoints:
+ * POST /detect — upload JPEG/PNG body → JSON detections
+ * GET /health — {"status":"ok","model":"yolov8n","input_size":320}
+ * GET /stats — {"requests":N,"avg_ms":12.5,"total_detections":M}
+ *
+ * Example:
+ * curl -X POST http://localhost:8080/detect --data-binary @photo.jpg
+ */
+
+#define STB_IMAGE_IMPLEMENTATION
+#include "stb_image.h"
+#include "nn2.h"
+#include "http_server.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+#ifdef _WIN32
+#include <windows.h>
+static double get_ms(void) {
+ LARGE_INTEGER f, c;
+ QueryPerformanceFrequency(&f);
+ QueryPerformanceCounter(&c);
+ return (double)c.QuadPart / f.QuadPart * 1000.0;
+}
+#endif
+
+static const char* coco_names[] = {
+ "person","bicycle","car","motorcycle","airplane","bus","train","truck","boat",
+ "traffic light","fire hydrant","stop sign","parking meter","bench","bird","cat",
+ "dog","horse","sheep","cow","elephant","bear","zebra","giraffe","backpack",
+ "umbrella","handbag","tie","suitcase","frisbee","skis","snowboard","sports ball",
+ "kite","baseball bat","baseball glove","skateboard","surfboard","tennis racket",
+ "bottle","wine glass","cup","fork","knife","spoon","bowl","banana","apple",
+ "sandwich","orange","broccoli","carrot","hot dog","pizza","donut","cake","chair",
+ "couch","potted plant","bed","dining table","toilet","tv","laptop","mouse",
+ "remote","keyboard","cell phone","microwave","oven","toaster","sink",
+ "refrigerator","book","clock","vase","scissors","teddy bear","hair drier","toothbrush"
+};
+
+typedef struct {
+ NN2* model;
+ int requests;
+ int total_dets;
+ double total_ms;
+} ServerCtx;
+
+static void handle_request(const HttpRequest* req, socket_t client, void* userdata)
+{
+ ServerCtx* ctx = (ServerCtx*)userdata;
+
+ if (strcmp(req->path, "/health") == 0 && strcmp(req->method, "GET") == 0) {
+ char json[256];
+ snprintf(json, sizeof(json),
+ "{\"status\":\"ok\",\"engine\":\"nn2\",\"model\":\"yolov8n\"}");
+ http_send_json(client, 200, json);
+ return;
+ }
+
+ if (strcmp(req->path, "/stats") == 0 && strcmp(req->method, "GET") == 0) {
+ char json[256];
+ double avg = ctx->requests > 0 ? ctx->total_ms / ctx->requests : 0;
+ snprintf(json, sizeof(json),
+ "{\"requests\":%d,\"avg_ms\":%.1f,\"total_detections\":%d}",
+ ctx->requests, avg, ctx->total_dets);
+ http_send_json(client, 200, json);
+ return;
+ }
+
+ if (strcmp(req->path, "/detect") == 0 && strcmp(req->method, "POST") == 0) {
+ if (!req->body || req->content_length <= 0) {
+ http_send_json(client, 400, "{\"error\":\"no image data\"}");
+ return;
+ }
+
+ /* Decode image from memory */
+ int w, h, ch;
+ uint8_t* img = stbi_load_from_memory(
+ (const uint8_t*)req->body, req->content_length, &w, &h, &ch, 3);
+ if (!img) {
+ http_send_json(client, 400, "{\"error\":\"invalid image\"}");
+ return;
+ }
+
+ /* Detect */
+ NN2Det dets[100];
+ double t0 = get_ms();
+ int n = nn2_detect(ctx->model, img, w, h, dets, 100);
+ double ms = get_ms() - t0;
+ stbi_image_free(img);
+
+ ctx->requests++;
+ ctx->total_dets += n;
+ ctx->total_ms += ms;
+
+ /* Build JSON response */
+ char* json = (char*)malloc(n * 256 + 256);
+ int pos = sprintf(json,
+ "{\"inference_ms\":%.1f,\"image\":{\"width\":%d,\"height\":%d},\"detections\":[",
+ ms, w, h);
+
+ for (int i = 0; i < n; i++) {
+ const char* name = (dets[i].cls >= 0 && dets[i].cls < 80) ? coco_names[dets[i].cls] : "unknown";
+ pos += sprintf(json + pos,
+ "%s{\"class\":\"%s\",\"class_id\":%d,\"confidence\":%.3f,"
+ "\"bbox\":{\"x1\":%.1f,\"y1\":%.1f,\"x2\":%.1f,\"y2\":%.1f}}",
+ i > 0 ? "," : "", name, dets[i].cls, dets[i].score,
+ dets[i].x1, dets[i].y1, dets[i].x2, dets[i].y2);
+ }
+ pos += sprintf(json + pos, "]}");
+
+ http_send_json(client, 200, json);
+ free(json);
+
+ fprintf(stderr, " POST /detect %dx%d → %d dets (%.1fms)\n", w, h, n, ms);
+ return;
+ }
+
+ http_send_json(client, 404, "{\"error\":\"not found\",\"endpoints\":[\"/detect\",\"/health\",\"/stats\"]}");
+}
+
+int main(int argc, char** argv)
+{
+ if (argc < 2) {
+ fprintf(stderr, "Usage: %s <weights.bin> [port] [threads]\n", argv[0]);
+ fprintf(stderr, "\nEndpoints:\n");
+ fprintf(stderr, " POST /detect — upload JPEG/PNG, get JSON detections\n");
+ fprintf(stderr, " GET /health — health check\n");
+ fprintf(stderr, " GET /stats — inference statistics\n");
+ fprintf(stderr, "\nExample:\n");
+ fprintf(stderr, " %s weights/yolov8n_320.bin 8080 6\n", argv[0]);
+ fprintf(stderr, " curl -X POST http://localhost:8080/detect --data-binary @photo.jpg\n");
+ return 1;
+ }
+
+ int port = (argc > 2) ? atoi(argv[2]) : 8080;
+ int threads = (argc > 3) ? atoi(argv[3]) : 0;
+
+ ServerCtx ctx = {0};
+ ctx.model = nn2_init(argv[1], threads);
+ if (!ctx.model) return 1;
+
+ fprintf(stderr, "nn2 HTTP Detection Server\n");
+ fprintf(stderr, " Model: %s\n", argv[1]);
+ fprintf(stderr, " Port: %d\n", port);
+ fprintf(stderr, " Usage: curl -X POST http://localhost:%d/detect --data-binary @image.jpg\n\n", port);
+
+ http_listen(port, handle_request, &ctx);
+
+ nn2_free(ctx.model);
+ return 0;
+}
diff --git a/nn2/src/main_video.c b/nn2/src/main_video.c
new file mode 100644
index 0000000..bd6e2a2
--- /dev/null
+++ b/nn2/src/main_video.c
@@ -0,0 +1,213 @@
+/*
+ * main_video.c — Video detection via ffmpeg pipe.
+ *
+ * Usage:
+ * nn2_video <weights.bin> <video.mp4> [--skip N] [--threads T] [--json out.jsonl]
+ * nn2_video <weights.bin> rtsp://camera/stream [--skip 5]
+ *
+ * Spawns ffmpeg to decode video → raw RGB frames → nn2 detection → JSON output.
+ * Works with any format ffmpeg supports: mp4, avi, mkv, rtsp, http, etc.
+ */
+
+#include "nn2.h"
+#include "nn2_json.h"
+#include "nn2_nvr.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef _WIN32
+#include <windows.h>
+#define popen _popen
+#define pclose _pclose
+static double get_ms(void) {
+ LARGE_INTEGER f, c;
+ QueryPerformanceFrequency(&f);
+ QueryPerformanceCounter(&c);
+ return (double)c.QuadPart / f.QuadPart * 1000.0;
+}
+#else
+#include <time.h>
+static double get_ms(void) {
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return ts.tv_sec * 1000.0 + ts.tv_nsec / 1e6;
+}
+#endif
+
+static void usage(const char* prog)
+{
+ fprintf(stderr,
+ "Usage: %s <weights.bin> <video_or_rtsp> [options]\n"
+ "\n"
+ "Options:\n"
+ " --skip N Process every Nth frame (default: 5)\n"
+ " --threads T Number of threads (default: auto)\n"
+ " --json FILE Write detections as JSONL to file\n"
+ " --width W Input width for ffmpeg (default: 640)\n"
+ " --height H Input height for ffmpeg (default: 480)\n"
+ " --conf F Confidence threshold (default: 0.25)\n"
+ " --max-frames N Stop after N frames (0=unlimited)\n"
+ "\n"
+ "Examples:\n"
+ " %s weights/yolov8n_320.bin video.mp4 --skip 3 --json dets.jsonl\n"
+ " %s weights/yolov8n_320.bin rtsp://192.168.1.100:554/stream --skip 5\n"
+ , prog, prog, prog);
+}
+
+int main(int argc, char** argv)
+{
+ if (argc < 3) { usage(argv[0]); return 1; }
+
+ const char* weights = argv[1];
+ const char* source = argv[2];
+ int skip = 5;
+ int threads = 0;
+ int vw = 640, vh = 480;
+ float conf = 0.25f;
+ int max_frames = 0;
+ const char* json_path = NULL;
+
+ /* Parse options */
+ for (int i = 3; i < argc; i++) {
+ if (!strcmp(argv[i], "--skip") && i+1 < argc) skip = atoi(argv[++i]);
+ else if (!strcmp(argv[i], "--threads") && i+1 < argc) threads = atoi(argv[++i]);
+ else if (!strcmp(argv[i], "--json") && i+1 < argc) json_path = argv[++i];
+ else if (!strcmp(argv[i], "--width") && i+1 < argc) vw = atoi(argv[++i]);
+ else if (!strcmp(argv[i], "--height") && i+1 < argc) vh = atoi(argv[++i]);
+ else if (!strcmp(argv[i], "--conf") && i+1 < argc) conf = (float)atof(argv[++i]);
+ else if (!strcmp(argv[i], "--max-frames") && i+1 < argc) max_frames = atoi(argv[++i]);
+ }
+
+ /* Init model */
+ NN2* ctx = nn2_init(weights, threads);
+ if (!ctx) return 1;
+ nn2_set_conf_threshold(ctx, conf);
+
+ /* Open JSON output */
+ FILE* json_out = NULL;
+ if (json_path) {
+ json_out = fopen(json_path, "w");
+ if (!json_out) fprintf(stderr, "Warning: cannot open %s for writing\n", json_path);
+ }
+
+ fprintf(stderr, "nn2_video: source=%s %dx%d skip=%d conf=%.2f\n", source, vw, vh, skip, conf);
+
+ FILE* pipe;
+ int is_raw = 0;
+
+ /* Check if source is a .raw file or stdin "-" → read raw RGB directly */
+ if (strcmp(source, "-") == 0) {
+ /* Raw frames from stdin */
+ pipe = stdin;
+ is_raw = 1;
+ fprintf(stderr, "nn2_video: reading raw RGB frames from stdin\n");
+#ifdef _WIN32
+ _setmode(_fileno(stdin), 0x8000); /* _O_BINARY */
+#endif
+ } else if (strstr(source, ".raw")) {
+ pipe = fopen(source, "rb");
+ is_raw = 1;
+ fprintf(stderr, "nn2_video: reading raw RGB frames from %s\n", source);
+ } else {
+ /* Use ffmpeg to decode */
+ char cmd[2048];
+ snprintf(cmd, sizeof(cmd),
+ "ffmpeg -hide_banner -loglevel error"
+ " -i \"%s\""
+ " -f rawvideo -pix_fmt rgb24"
+ " -s %dx%d"
+ " -",
+ source, vw, vh);
+ fprintf(stderr, "nn2_video: ffmpeg cmd: %s\n", cmd);
+ pipe = popen(cmd, "rb");
+ if (!pipe) {
+ fprintf(stderr, "Failed to start ffmpeg. Is ffmpeg in PATH?\n");
+ nn2_free(ctx);
+ return 1;
+ }
+ }
+
+ if (!pipe) {
+ fprintf(stderr, "Failed to open source\n");
+ nn2_free(ctx);
+ return 1;
+ }
+
+ /* Read frames */
+ int frame_size = vw * vh * 3;
+ uint8_t* frame = (uint8_t*)malloc(frame_size);
+ NN2Det dets[100];
+ int frame_num = 0;
+ int total_dets = 0;
+ double total_ms = 0;
+ int total_inferences = 0;
+ double start_time = get_ms();
+
+ fprintf(stderr, "nn2_video: processing...\n");
+
+ while (fread(frame, 1, frame_size, pipe) == (size_t)frame_size) {
+ frame_num++;
+ if (max_frames > 0 && frame_num > max_frames) break;
+
+ /* Skip frames */
+ if ((frame_num % skip) != 0) continue;
+
+ /* Detect */
+ double t0 = get_ms();
+ int n = nn2_detect(ctx, frame, vw, vh, dets, 100);
+ double ms = get_ms() - t0;
+ total_ms += ms;
+ total_inferences++;
+ total_dets += n;
+
+ /* Output detections */
+ if (n > 0) {
+ if (json_out) {
+ /* Write as JSONL */
+ NN2NVREvent event;
+ event.cam_id = 0;
+ event.det_count = n;
+ memcpy(event.dets, dets, n * sizeof(NN2Det));
+ event.timestamp_ms = get_ms() - start_time;
+ event.inference_ms = ms;
+ nn2_event_to_file(&event, json_out);
+ }
+
+ /* Print to stderr */
+ fprintf(stderr, "\r frame %d: %d dets (%.1fms) ", frame_num, n, ms);
+ for (int i = 0; i < n && i < 3; i++) {
+ const char* name = (dets[i].cls >= 0 && dets[i].cls < 80)
+ ? nn2_coco_names[dets[i].cls] : "?";
+ fprintf(stderr, "%s(%.0f%%) ", name, dets[i].score * 100);
+ }
+ }
+
+ /* Stats every 100 inferences */
+ if (total_inferences % 100 == 0) {
+ double elapsed = get_ms() - start_time;
+ fprintf(stderr, "\n [%d frames, %d inferences, avg %.1fms, %.1f fps pipeline]\n",
+ frame_num, total_inferences, total_ms / total_inferences,
+ frame_num / (elapsed / 1000.0));
+ }
+ }
+
+ double elapsed = get_ms() - start_time;
+
+ fprintf(stderr, "\n\n=== nn2_video Results ===\n");
+ fprintf(stderr, " Frames: %d\n", frame_num);
+ fprintf(stderr, " Inferences: %d (skip=%d)\n", total_inferences, skip);
+ fprintf(stderr, " Avg inference: %.1f ms\n",
+ total_inferences > 0 ? total_ms / total_inferences : 0);
+ fprintf(stderr, " Total detections: %d\n", total_dets);
+ fprintf(stderr, " Pipeline FPS: %.1f\n", frame_num / (elapsed / 1000.0));
+ fprintf(stderr, " Elapsed: %.1f sec\n", elapsed / 1000.0);
+ if (json_path) fprintf(stderr, " JSON output: %s\n", json_path);
+
+ if (json_out) fclose(json_out);
+ free(frame);
+ if (!is_raw) pclose(pipe);
+ else if (pipe != stdin) fclose(pipe);
+ nn2_free(ctx);
+ return 0;
+}
diff --git a/nn2/src/minifasnet.c b/nn2/src/minifasnet.c
new file mode 100644
index 0000000..418ebe8
--- /dev/null
+++ b/nn2/src/minifasnet.c
@@ -0,0 +1,495 @@
+/*
+ * minifasnet.c — MiniFASNetV2 / V1SE forward pass for the nn2 engine.
+ *
+ * Mirrors `src/model_lib/MiniFASNet.py` from MinivisionAI's
+ * Silent-Face-Anti-Spoofing repo. Apache 2.0 weights.
+ *
+ * Architecture summary (input 80×80 → spatial 40,20,10,5,1):
+ * conv1 Conv 3x3 s=2 3→32 (80→40)
+ * conv2_dw DWConv 3x3 s=1 32→32 (40→40)
+ * conv_23 Depth_Wise s=2 (32→64, non-residual) (40→20)
+ * conv_3 4× Depth_Wise s=1 (64-channel residual)
+ * conv_34 Depth_Wise s=2 (64→128, non-residual) (20→10)
+ * conv_4 6× Depth_Wise s=1 (128-channel residual)
+ * conv_45 Depth_Wise s=2 (128→128, non-residual) (10→5)
+ * conv_5 2× Depth_Wise s=1 (128-channel residual)
+ * conv_6_sep Conv 1x1 128→512
+ * conv_6_dw DWConv 5x5 s=1 p=0 (5→1)
+ * linear FC 512→128 (BN1d folded into bias+weights)
+ * prob FC 128→3 (no bias)
+ *
+ * Every Conv_block uses PReLU (per-channel α). Project conv inside a
+ * Depth_Wise has NO activation.
+ *
+ * V1SE inserts an SE module (GAP → FC↓ → ReLU → FC↑ → sigmoid → multiply)
+ * after `project` in the LAST Depth_Wise of each Residual section.
+ *
+ * Weight file format (.bin) written by tools/export_minifasnet.py:
+ * [4] magic "MFN1"
+ * [4] uint32 variant (0=V2, 1=V1SE)
+ * [4] uint32 input_size (always 80)
+ * [4] uint32 num_tensors
+ * Per tensor: uint32 size_in_floats; float32[size]
+ */
+
+#include "nn2_internal.h"
+#include "nn2_antispoof.h"
+#include "nn2_antispoof_ops.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+#include <immintrin.h>
+
+
+/* ===== keep_dict from MiniFASNet.py ===== */
+static const int KEEP_18M[49] = {
+ 32, 32, 103, 103, 64, 13, 13, 64, 26, 26,
+ 64, 13, 13, 64, 52, 52, 64, 231, 231, 128,
+ 154, 154, 128, 52, 52, 128, 26, 26, 128, 52,
+ 52, 128, 26, 26, 128, 26, 26, 128, 308, 308,
+ 128, 26, 26, 128, 26, 26, 128, 512, 512
+};
+static const int KEEP_18M_[49] = {
+ 32, 32, 103, 103, 64, 13, 13, 64, 13, 13, 64, 13,
+ 13, 64, 13, 13, 64, 231, 231, 128, 231, 231, 128, 52,
+ 52, 128, 26, 26, 128, 77, 77, 128, 26, 26, 128, 26, 26,
+ 128, 308, 308, 128, 26, 26, 128, 26, 26, 128, 512, 512
+};
+
+/* ===== Per-layer structures ===== */
+
+typedef struct {
+ float *expand_w, *expand_b, *expand_prelu; /* 1x1, with PReLU */
+ float *dw_w, *dw_b, *dw_prelu; /* 3x3 DW, with PReLU */
+ float *project_w, *project_b; /* 1x1, no activation */
+ int c1_in, c1_out;
+ int c2_out;
+ int c3_out;
+ int stride;
+ int residual;
+ int has_se;
+ int se_reduct;
+ float *se_fc1_w, *se_fc1_b;
+ float *se_fc2_w, *se_fc2_b;
+} DepthWise;
+
+struct AntiSpoofModel {
+ AntiSpoofVariant variant;
+ int input_size;
+
+ /* conv1 / conv2_dw with PReLU */
+ float *conv1_w, *conv1_b, *conv1_alpha;
+ float *conv2_dw_w, *conv2_dw_b, *conv2_dw_alpha;
+
+ DepthWise conv_23;
+ DepthWise conv_3[4];
+ DepthWise conv_34;
+ DepthWise conv_4[6];
+ DepthWise conv_45;
+ DepthWise conv_5[2];
+
+ float *conv_6_sep_w, *conv_6_sep_b, *conv_6_sep_alpha;
+ float *conv_6_dw_w, *conv_6_dw_b;
+
+ float *fc1_w, *fc1_b; /* 128×512 + 128 (BN fused) */
+ float *fc2_w; /* 3×128 no bias */
+
+ /* Scratch buffers. Allocated big enough for the widest intermediate. */
+ float *act_a, *act_b; /* ping-pong activation buffers */
+ float *scratch_x; /* expand output / SE per-block tmp */
+ float *scratch_y; /* DW output */
+ float *im2col; /* im2col buffer for non-DW convs */
+ size_t buf_floats;
+ size_t im2col_floats;
+
+ int n_threads;
+};
+
+/* ===== Allocation helpers ===== */
+static float* aalloc(size_t n)
+{
+ return (float*)_mm_malloc(n * sizeof(float), 64);
+}
+static void afree(float* p) { if (p) _mm_free(p); }
+
+/* ===== Weight reading ===== */
+static int read_u32(FILE* f, uint32_t* out)
+{
+ return fread(out, 4, 1, f) == 1 ? 0 : -1;
+}
+
+static float* read_tensor(FILE* f, int expected)
+{
+ uint32_t sz;
+ if (read_u32(f, &sz) != 0) return NULL;
+ if ((int)sz != expected) {
+ fprintf(stderr, "minifasnet: tensor size mismatch: got %u expected %d\n", sz, expected);
+ return NULL;
+ }
+ float* buf = aalloc(sz);
+ if (!buf) return NULL;
+ if (fread(buf, 4, sz, f) != (size_t)sz) { afree(buf); return NULL; }
+ return buf;
+}
+
+static int load_conv(FILE* f, int cin, int cout, int k, int has_prelu,
+ float** w, float** b, float** prelu)
+{
+ *w = read_tensor(f, cout * cin * k * k);
+ *b = read_tensor(f, cout);
+ if (!*w || !*b) return -1;
+ if (has_prelu) {
+ *prelu = read_tensor(f, cout);
+ if (!*prelu) return -1;
+ } else if (prelu) {
+ *prelu = NULL;
+ }
+ return 0;
+}
+
+static int load_dw_block(FILE* f, int c1_in, int c1_out, int c3_out,
+ int stride, int residual, int has_se, int se_reduct,
+ DepthWise* d)
+{
+ d->c1_in = c1_in; d->c1_out = c1_out; d->c2_out = c1_out; d->c3_out = c3_out;
+ d->stride = stride; d->residual = residual;
+ if (load_conv(f, c1_in, c1_out, 1, 1, &d->expand_w, &d->expand_b, &d->expand_prelu) != 0) return -1;
+ if (load_conv(f, 1, c1_out, 3, 1, &d->dw_w, &d->dw_b, &d->dw_prelu) != 0) return -1;
+ if (load_conv(f, c1_out, c3_out, 1, 0, &d->project_w, &d->project_b, NULL) != 0) return -1;
+ d->has_se = 0;
+ if (has_se) {
+ d->has_se = 1; d->se_reduct = se_reduct;
+ int r = c3_out / se_reduct;
+ d->se_fc1_w = read_tensor(f, r * c3_out);
+ d->se_fc1_b = read_tensor(f, r);
+ d->se_fc2_w = read_tensor(f, c3_out * r);
+ d->se_fc2_b = read_tensor(f, c3_out);
+ if (!d->se_fc1_w || !d->se_fc1_b || !d->se_fc2_w || !d->se_fc2_b) return -1;
+ }
+ return 0;
+}
+
+static void free_dw(DepthWise* d)
+{
+ afree(d->expand_w); afree(d->expand_b); afree(d->expand_prelu);
+ afree(d->dw_w); afree(d->dw_b); afree(d->dw_prelu);
+ afree(d->project_w); afree(d->project_b);
+ if (d->has_se) {
+ afree(d->se_fc1_w); afree(d->se_fc1_b);
+ afree(d->se_fc2_w); afree(d->se_fc2_b);
+ }
+}
+
+/* ===== Conv wrapper: chooses 1x1 (no im2col) or im2col+GEMM ===== */
+static void conv_run(const float* in, int Cin, int H, int W,
+ const float* w, const float* b,
+ int Cout, int k, int stride, int pad,
+ float* col_buf, float* out)
+{
+ int Hout = (H + 2 * pad - k) / stride + 1;
+ int Wout = (W + 2 * pad - k) / stride + 1;
+ int K = Cin * k * k;
+ int N = Hout * Wout;
+ if (k == 1 && stride == 1 && pad == 0) {
+ nn2_sgemm_bias_act(Cout, K, N, w, K, in, N, out, N, b, 0);
+ } else {
+ nn2_im2col(in, Cin, H, W, k, k, stride, pad, col_buf);
+ nn2_sgemm_bias_act(Cout, K, N, w, K, col_buf, N, out, N, b, 0);
+ }
+}
+
+/* ===== Depth_Wise forward =====
+ * in [c1_in × H×W] → out [c3_out × Hout×Wout]; in and out MUST be different. */
+static void run_dw(const DepthWise* d, const float* in, int H, int W,
+ float* col_buf, float* scratch_x, float* scratch_y, float* out)
+{
+ int Hout = (H + 2 - 3) / d->stride + 1;
+ int Wout = (W + 2 - 3) / d->stride + 1;
+
+ /* 1. expand 1x1 → scratch_x [c1_out × H×W] */
+ conv_run(in, d->c1_in, H, W, d->expand_w, d->expand_b,
+ d->c1_out, 1, 1, 0, col_buf, scratch_x);
+ nn2_prelu(scratch_x, d->expand_prelu, d->c1_out, H * W);
+
+ /* 2. DW 3x3 → scratch_y [c2_out × Hout×Wout] */
+ nn2_dwconv2d(scratch_x, d->dw_w, d->dw_b, d->c2_out, H, W, 3, d->stride, 1, 0, scratch_y);
+ nn2_prelu(scratch_y, d->dw_prelu, d->c2_out, Hout * Wout);
+
+ /* 3. project 1x1 → out [c3_out × Hout×Wout], no activation */
+ conv_run(scratch_y, d->c2_out, Hout, Wout, d->project_w, d->project_b,
+ d->c3_out, 1, 1, 0, col_buf, out);
+
+ /* 4. Optional SE: out *= sigmoid(fc2(relu(fc1(GAP(out))))) */
+ if (d->has_se) {
+ int r = d->c3_out / d->se_reduct;
+ float gap[256], v1[64], v2[256];
+ nn2_global_avg_pool(out, d->c3_out, Hout * Wout, gap);
+ nn2_linear(gap, d->se_fc1_w, d->se_fc1_b, d->c3_out, r, v1);
+ for (int i = 0; i < r; i++) if (v1[i] < 0) v1[i] = 0;
+ nn2_linear(v1, d->se_fc2_w, d->se_fc2_b, r, d->c3_out, v2);
+ nn2_sigmoid_inplace(v2, d->c3_out);
+ nn2_channel_mul(out, v2, d->c3_out, Hout * Wout);
+ }
+
+ /* 5. Residual add — only valid when channels match and stride=1 */
+ if (d->residual && d->stride == 1 && d->c1_in == d->c3_out) {
+ nn2_add_inplace(out, in, d->c3_out * Hout * Wout);
+ }
+}
+
+/* ===== Loader ===== */
+
+AntiSpoofModel* nn2_antispoof_load(const char* path, AntiSpoofVariant variant, int n_threads)
+{
+ FILE* f = fopen(path, "rb");
+ if (!f) { fprintf(stderr, "minifasnet: cannot open %s\n", path); return NULL; }
+
+ char magic[4];
+ uint32_t var_u, sz_u, nt_u;
+ if (fread(magic, 1, 4, f) != 4 || memcmp(magic, "MFN1", 4) != 0
+ || read_u32(f, &var_u) || read_u32(f, &sz_u) || read_u32(f, &nt_u))
+ {
+ fprintf(stderr, "minifasnet: bad header\n"); fclose(f); return NULL;
+ }
+ if ((int)var_u != (int)variant) {
+ fprintf(stderr, "minifasnet: variant mismatch\n"); fclose(f); return NULL;
+ }
+
+ if (n_threads <= 0) n_threads = 4;
+ nn2_tp_init(n_threads);
+
+ AntiSpoofModel* m = (AntiSpoofModel*)calloc(1, sizeof(*m));
+ m->variant = variant;
+ m->input_size = (int)sz_u;
+ m->n_threads = n_threads;
+
+ const int* keep = (variant == NN2_AS_V2) ? KEEP_18M_ : KEEP_18M;
+ int se = (variant == NN2_AS_V1SE) ? 1 : 0;
+ int rc = 0;
+
+ /* conv1 3→32 k=3 s=2 */
+ rc |= load_conv(f, 3, keep[0], 3, 1, &m->conv1_w, &m->conv1_b, &m->conv1_alpha);
+ /* conv2_dw 32 dw k=3 s=1 */
+ rc |= load_conv(f, 1, keep[1], 3, 1, &m->conv2_dw_w, &m->conv2_dw_b, &m->conv2_dw_alpha);
+
+ /* conv_23: c1=(keep[1],keep[2]), c3_out=keep[4], stride=2, NOT residual, no SE */
+ rc |= load_dw_block(f, keep[1], keep[2], keep[4], 2, 0, 0, 0, &m->conv_23);
+
+ /* conv_3: 4 blocks. block i uses c1=(keep[4+3i], keep[5+3i]), c3_out=keep[7+3i]. All stride=1, residual, SE on last if V1SE. */
+ for (int i = 0; i < 4; i++) {
+ int ki = 4 + 3 * i;
+ int has_se_here = (se && i == 3) ? 1 : 0;
+ rc |= load_dw_block(f, keep[ki], keep[ki + 1], keep[ki + 3], 1, 1,
+ has_se_here, 4, &m->conv_3[i]);
+ }
+ /* conv_34: c1=(keep[16], keep[17]), c3_out=keep[19], stride=2 */
+ rc |= load_dw_block(f, keep[16], keep[17], keep[19], 2, 0, 0, 0, &m->conv_34);
+
+ /* conv_4: 6 blocks starting at keep[19] */
+ for (int i = 0; i < 6; i++) {
+ int ki = 19 + 3 * i;
+ int has_se_here = (se && i == 5) ? 1 : 0;
+ rc |= load_dw_block(f, keep[ki], keep[ki + 1], keep[ki + 3], 1, 1,
+ has_se_here, 4, &m->conv_4[i]);
+ }
+ /* conv_45: c1=(keep[37], keep[38]), c3_out=keep[40], stride=2 */
+ rc |= load_dw_block(f, keep[37], keep[38], keep[40], 2, 0, 0, 0, &m->conv_45);
+
+ /* conv_5: 2 blocks starting at keep[40] */
+ for (int i = 0; i < 2; i++) {
+ int ki = 40 + 3 * i;
+ int has_se_here = (se && i == 1) ? 1 : 0;
+ rc |= load_dw_block(f, keep[ki], keep[ki + 1], keep[ki + 3], 1, 1,
+ has_se_here, 4, &m->conv_5[i]);
+ }
+
+ /* conv_6_sep 1x1 keep[46]→keep[47] */
+ rc |= load_conv(f, keep[46], keep[47], 1, 1, &m->conv_6_sep_w, &m->conv_6_sep_b, &m->conv_6_sep_alpha);
+ /* conv_6_dw 5x5 DW (no activation, no PReLU) */
+ m->conv_6_dw_w = read_tensor(f, keep[48] * 5 * 5);
+ m->conv_6_dw_b = read_tensor(f, keep[48]);
+
+ /* Linear 512→128 (BN1d folded into [w, b]) */
+ m->fc1_w = read_tensor(f, 128 * 512);
+ m->fc1_b = read_tensor(f, 128);
+ /* prob 128→3, no bias */
+ m->fc2_w = read_tensor(f, 3 * 128);
+
+ if (rc != 0 || !m->fc2_w) {
+ fprintf(stderr, "minifasnet: weight load failed\n");
+ fclose(f); nn2_antispoof_free(m); return NULL;
+ }
+ fclose(f);
+
+ /* Allocate workspace. Widest intermediate: expand-hidden in conv_3/4
+ * with 231 channels at 20×20 (V1SE conv_3 first block: keep[5]=13 hmm
+ * but V2 has keep[5]=13 too). Actually keep[17]=231 at HxW=20×20=400 spatial.
+ * Max activation = 231 * 20 * 20 = 92400.
+ * For safety allocate 512 * 40 * 40 = 819200 floats = 3.2 MB. */
+ m->buf_floats = 512 * 40 * 40;
+ m->act_a = aalloc(m->buf_floats);
+ m->act_b = aalloc(m->buf_floats);
+ m->scratch_x = aalloc(m->buf_floats);
+ m->scratch_y = aalloc(m->buf_floats);
+ /* im2col worst case: conv1 needs 3*9 = 27 cols × (40*40) = 43200 floats */
+ m->im2col_floats = 27 * 40 * 40;
+ m->im2col = aalloc(m->im2col_floats);
+
+ if (!m->act_a || !m->act_b || !m->scratch_x || !m->scratch_y || !m->im2col) {
+ nn2_antispoof_free(m); return NULL;
+ }
+ return m;
+}
+
+void nn2_antispoof_free(AntiSpoofModel* m)
+{
+ if (!m) return;
+ afree(m->conv1_w); afree(m->conv1_b); afree(m->conv1_alpha);
+ afree(m->conv2_dw_w); afree(m->conv2_dw_b); afree(m->conv2_dw_alpha);
+ free_dw(&m->conv_23);
+ for (int i = 0; i < 4; i++) free_dw(&m->conv_3[i]);
+ free_dw(&m->conv_34);
+ for (int i = 0; i < 6; i++) free_dw(&m->conv_4[i]);
+ free_dw(&m->conv_45);
+ for (int i = 0; i < 2; i++) free_dw(&m->conv_5[i]);
+ afree(m->conv_6_sep_w); afree(m->conv_6_sep_b); afree(m->conv_6_sep_alpha);
+ afree(m->conv_6_dw_w); afree(m->conv_6_dw_b);
+ afree(m->fc1_w); afree(m->fc1_b); afree(m->fc2_w);
+ afree(m->act_a); afree(m->act_b); afree(m->scratch_x); afree(m->scratch_y);
+ afree(m->im2col);
+ free(m);
+}
+
+/* ===== Forward ===== */
+
+int nn2_antispoof_predict(AntiSpoofModel* m, const unsigned char* bgr_80x80,
+ float prob_out[3])
+{
+ if (!m || !bgr_80x80 || !prob_out) return -1;
+ const int S = 80;
+ int N = S * S;
+
+ /* Preprocess HWC BGR uint8 [0,255] → CHW float, NO /255. */
+ float* input = m->act_a;
+ for (int i = 0; i < N; i++) {
+ input[0 * N + i] = (float)bgr_80x80[i * 3 + 0];
+ input[1 * N + i] = (float)bgr_80x80[i * 3 + 1];
+ input[2 * N + i] = (float)bgr_80x80[i * 3 + 2];
+ }
+
+ float *cur = m->act_a, *nxt = m->act_b;
+
+ /* conv1: 3→32, k=3, s=2 (80→40) */
+ int H = 40, W = 40;
+ conv_run(cur, 3, S, S, m->conv1_w, m->conv1_b, 32, 3, 2, 1, m->im2col, nxt);
+ nn2_prelu(nxt, m->conv1_alpha, 32, H * W);
+ { float* t = cur; cur = nxt; nxt = t; }
+
+ /* conv2_dw: 32 DW, s=1 (40→40) */
+ nn2_dwconv2d(cur, m->conv2_dw_w, m->conv2_dw_b, 32, H, W, 3, 1, 1, 0, nxt);
+ nn2_prelu(nxt, m->conv2_dw_alpha, 32, H * W);
+ { float* t = cur; cur = nxt; nxt = t; }
+
+ /* conv_23: s=2, 32→hidden→64 (40→20) */
+ run_dw(&m->conv_23, cur, H, W, m->im2col, m->scratch_x, m->scratch_y, nxt);
+ { float* t = cur; cur = nxt; nxt = t; }
+ H = 20; W = 20;
+
+ /* conv_3: 4× s=1 residual, 64-channel */
+ for (int i = 0; i < 4; i++) {
+ run_dw(&m->conv_3[i], cur, H, W, m->im2col, m->scratch_x, m->scratch_y, nxt);
+ { float* t = cur; cur = nxt; nxt = t; }
+ }
+
+ /* conv_34: s=2, 64→hidden→128 (20→10) */
+ run_dw(&m->conv_34, cur, H, W, m->im2col, m->scratch_x, m->scratch_y, nxt);
+ { float* t = cur; cur = nxt; nxt = t; }
+ H = 10; W = 10;
+
+ /* conv_4: 6× s=1, 128-channel */
+ for (int i = 0; i < 6; i++) {
+ run_dw(&m->conv_4[i], cur, H, W, m->im2col, m->scratch_x, m->scratch_y, nxt);
+ { float* t = cur; cur = nxt; nxt = t; }
+ }
+
+ /* conv_45: s=2, 128→hidden→128 (10→5) */
+ run_dw(&m->conv_45, cur, H, W, m->im2col, m->scratch_x, m->scratch_y, nxt);
+ { float* t = cur; cur = nxt; nxt = t; }
+ H = 5; W = 5;
+
+ /* conv_5: 2× s=1 */
+ for (int i = 0; i < 2; i++) {
+ run_dw(&m->conv_5[i], cur, H, W, m->im2col, m->scratch_x, m->scratch_y, nxt);
+ { float* t = cur; cur = nxt; nxt = t; }
+ }
+
+ /* conv_6_sep: 1x1 128→512 with PReLU */
+ conv_run(cur, 128, H, W, m->conv_6_sep_w, m->conv_6_sep_b, 512, 1, 1, 0, m->im2col, nxt);
+ nn2_prelu(nxt, m->conv_6_sep_alpha, 512, H * W);
+ { float* t = cur; cur = nxt; nxt = t; }
+
+ /* conv_6_dw: DW 5x5 s=1 p=0 (5→1), no activation. Output: 512 floats. */
+ nn2_dwconv2d(cur, m->conv_6_dw_w, m->conv_6_dw_b, 512, H, W, 5, 1, 0, 0, nxt);
+ cur = nxt;
+
+ /* Linear 512→128, then prob 128→3 */
+ float fc1_out[128];
+ nn2_linear(cur, m->fc1_w, m->fc1_b, 512, 128, fc1_out);
+ float logits[3];
+ nn2_linear(fc1_out, m->fc2_w, NULL, 128, 3, logits);
+ nn2_softmax(logits, 3, prob_out);
+ return 0;
+}
+
+int nn2_antispoof_predict_rgb(AntiSpoofModel* m, const unsigned char* rgb,
+ int src_w, int src_h,
+ int bbox_x, int bbox_y, int bbox_w, int bbox_h,
+ float scale, float prob_out[3])
+{
+ /* CropImage._get_new_box logic (forward port of generate_patches.py). */
+ float s = scale;
+ float bh = (float)(src_h - 1) / bbox_h;
+ float bw = (float)(src_w - 1) / bbox_w;
+ if (bh < s) s = bh;
+ if (bw < s) s = bw;
+ float new_w = bbox_w * s, new_h = bbox_h * s;
+ float cx = bbox_x + bbox_w / 2.0f, cy = bbox_y + bbox_h / 2.0f;
+ float ltx = cx - new_w / 2, lty = cy - new_h / 2;
+ float rbx = cx + new_w / 2, rby = cy + new_h / 2;
+ if (ltx < 0) { rbx -= ltx; ltx = 0; }
+ if (lty < 0) { rby -= lty; lty = 0; }
+ if (rbx > src_w - 1) { ltx -= rbx - src_w + 1; rbx = src_w - 1; }
+ if (rby > src_h - 1) { lty -= rby - src_h + 1; rby = src_h - 1; }
+ int ix0 = (int)ltx, iy0 = (int)lty;
+ int ix1 = (int)rbx + 1, iy1 = (int)rby + 1;
+ int cw = ix1 - ix0, ch = iy1 - iy0;
+ if (cw <= 0 || ch <= 0) return -1;
+
+ /* Bilinear resize to 80×80 BGR uint8. */
+ const int S = 80;
+ unsigned char bgr[80 * 80 * 3];
+ for (int y = 0; y < S; y++) {
+ float fy = (float)y * (ch - 1) / (S - 1);
+ int y0 = (int)fy; int y1 = y0 + 1; if (y1 >= ch) y1 = ch - 1;
+ float wy = fy - y0;
+ for (int x = 0; x < S; x++) {
+ float fx = (float)x * (cw - 1) / (S - 1);
+ int x0 = (int)fx; int x1 = x0 + 1; if (x1 >= cw) x1 = cw - 1;
+ float wx = fx - x0;
+ for (int c = 0; c < 3; c++) {
+ int src_c = 2 - c; /* input RGB → output BGR */
+ float v00 = rgb[((iy0 + y0) * src_w + (ix0 + x0)) * 3 + src_c];
+ float v01 = rgb[((iy0 + y0) * src_w + (ix0 + x1)) * 3 + src_c];
+ float v10 = rgb[((iy0 + y1) * src_w + (ix0 + x0)) * 3 + src_c];
+ float v11 = rgb[((iy0 + y1) * src_w + (ix0 + x1)) * 3 + src_c];
+ float v0 = v00 * (1 - wx) + v01 * wx;
+ float v1 = v10 * (1 - wx) + v11 * wx;
+ float v = v0 * (1 - wy) + v1 * wy;
+ bgr[(y * S + x) * 3 + c] = (unsigned char)(v + 0.5f);
+ }
+ }
+ }
+ return nn2_antispoof_predict(m, bgr, prob_out);
+}
diff --git a/nn2/src/motion_gate.c b/nn2/src/motion_gate.c
new file mode 100644
index 0000000..2a2f24a
--- /dev/null
+++ b/nn2/src/motion_gate.c
@@ -0,0 +1,135 @@
+/*
+ * motion_gate.c — Fast motion detection via frame differencing.
+ *
+ * Compares current frame vs previous frame using Sum of Absolute Differences.
+ * If fewer than threshold pixels changed significantly → no motion → skip inference.
+ *
+ * AVX-512 SAD: processes 64 bytes (pixels) per cycle.
+ * For 320×320×3 = 307,200 bytes: ~4800 iterations = ~2μs at 2.7GHz.
+ *
+ * Returns: motion score (0.0 = identical, 1.0 = completely different)
+ * and bounding box of motion region for ROI-crop.
+ */
+
+#include "nn2_internal.h"
+#include <string.h>
+#include <stdlib.h>
+
+#ifdef __AVX512BW__
+#include <immintrin.h>
+#endif
+
+/* Motion detection result */
+typedef struct {
+ float score; /* 0.0-1.0: fraction of changed pixels */
+ int has_motion; /* 1 if score > threshold */
+ int roi_x1, roi_y1, roi_x2, roi_y2; /* bounding box of motion region */
+} MotionResult;
+
+/* Compute frame difference score + motion ROI.
+ * prev, curr: RGB HWC uint8, width*height*3 bytes.
+ * pixel_thresh: per-pixel change threshold (e.g., 25 = ~10% of 255)
+ * score_thresh: fraction of changed pixels to trigger motion (e.g., 0.005 = 0.5%)
+ */
+MotionResult nn2_motion_detect(const uint8_t* prev, const uint8_t* curr,
+ int width, int height,
+ int pixel_thresh, float score_thresh)
+{
+ MotionResult r = {0};
+ int total_pixels = width * height;
+ int changed = 0;
+
+ /* Track motion bounding box */
+ int min_x = width, min_y = height, max_x = 0, max_y = 0;
+
+ /* Downsampled check: compare every 4th pixel for speed */
+ int stride = 4;
+
+#ifdef __AVX512BW__
+ /* AVX-512 path: process 16 pixels at a time (48 bytes RGB) */
+ /* Simplified: compare grayscale approximation (R+G+B)/3 per pixel */
+ for (int y = 0; y < height; y += stride) {
+ const uint8_t* p = prev + y * width * 3;
+ const uint8_t* c = curr + y * width * 3;
+ for (int x = 0; x + 16 <= width; x += 16) {
+ /* Quick SAD on raw bytes (3 channels interleaved) */
+ int off = x * 3;
+ __m512i vp = _mm512_loadu_si512((__m512i*)(p + off));
+ __m512i vc = _mm512_loadu_si512((__m512i*)(c + off));
+ /* Absolute difference per byte */
+ __m512i vd = _mm512_abs_epi8(_mm512_sub_epi8(
+ _mm512_max_epu8(vp, vc), _mm512_min_epu8(vp, vc)));
+ /* Actually use SAD: sum of abs diff in groups of 8 bytes */
+ /* Simpler: check if any byte > threshold using mask */
+ __mmask64 mask = _mm512_cmpgt_epu8_mask(vd, _mm512_set1_epi8((char)pixel_thresh));
+ if (mask) {
+ /* Count changed pixels (each pixel = 3 bytes, any channel > thresh counts) */
+ int bits = __builtin_popcountll(mask);
+ changed += bits / 3 + 1; /* approximate */
+ /* Update ROI */
+ if (x < min_x) min_x = x;
+ if (x + 16 > max_x) max_x = x + 16;
+ if (y < min_y) min_y = y;
+ if (y + stride > max_y) max_y = y + stride;
+ }
+ }
+ }
+#else
+ /* Scalar fallback */
+ for (int y = 0; y < height; y += stride) {
+ for (int x = 0; x < width; x += stride) {
+ int off = (y * width + x) * 3;
+ int d = abs((int)prev[off] - (int)curr[off])
+ + abs((int)prev[off+1] - (int)curr[off+1])
+ + abs((int)prev[off+2] - (int)curr[off+2]);
+ if (d > pixel_thresh * 3) {
+ changed++;
+ if (x < min_x) min_x = x;
+ if (x > max_x) max_x = x;
+ if (y < min_y) min_y = y;
+ if (y > max_y) max_y = y;
+ }
+ }
+ }
+#endif
+
+ int checked = (total_pixels / (stride * stride)) + 1;
+ r.score = (float)changed / (float)checked;
+ r.has_motion = (r.score > score_thresh) ? 1 : 0;
+
+ if (r.has_motion) {
+ /* Expand ROI by 20% padding, clamp to image bounds */
+ int rw = max_x - min_x, rh = max_y - min_y;
+ int pad_x = rw / 5 + 16, pad_y = rh / 5 + 16;
+ r.roi_x1 = (min_x - pad_x > 0) ? min_x - pad_x : 0;
+ r.roi_y1 = (min_y - pad_y > 0) ? min_y - pad_y : 0;
+ r.roi_x2 = (max_x + pad_x < width) ? max_x + pad_x : width;
+ r.roi_y2 = (max_y + pad_y < height) ? max_y + pad_y : height;
+
+ /* Snap to multiple of 32 for YOLO input alignment */
+ r.roi_x1 = (r.roi_x1 / 32) * 32;
+ r.roi_y1 = (r.roi_y1 / 32) * 32;
+ r.roi_x2 = ((r.roi_x2 + 31) / 32) * 32;
+ r.roi_y2 = ((r.roi_y2 + 31) / 32) * 32;
+ if (r.roi_x2 > width) r.roi_x2 = width;
+ if (r.roi_y2 > height) r.roi_y2 = height;
+ }
+
+ return r;
+}
+
+/* ============ ROI Crop ============ */
+
+/* Crop RGB HWC image to ROI region */
+void nn2_crop_roi(const uint8_t* src, int src_w, int src_h,
+ int x1, int y1, int x2, int y2,
+ uint8_t* dst, int* dst_w, int* dst_h)
+{
+ *dst_w = x2 - x1;
+ *dst_h = y2 - y1;
+ for (int y = y1; y < y2; y++) {
+ memcpy(dst + (y - y1) * (*dst_w) * 3,
+ src + y * src_w * 3 + x1 * 3,
+ (*dst_w) * 3);
+ }
+}
diff --git a/nn2/src/nanodet.c b/nn2/src/nanodet.c
new file mode 100644
index 0000000..a0b960b
--- /dev/null
+++ b/nn2/src/nanodet.c
@@ -0,0 +1,524 @@
+/*
+ * nanodet.c — NanoDet-Plus-m complete forward pass.
+ *
+ * Architecture (110 convolutions):
+ * Backbone: ShuffleNetV2 (stem + 3 stages)
+ * Neck: Ghost-PAN (3 reduce + 3 ghost blocks + 2 downsample)
+ * Head: GFL (4 scales × DW-PW-DW-PW-PW + split + sigmoid)
+ *
+ * ShuffleNetV2 block:
+ * Stride: branch1(DW→PW) + branch2(PW→DW→PW) → concat
+ * Regular: split → PW→DW→PW + identity → concat → shuffle
+ *
+ * Ghost module (in PAN):
+ * primary = PW(in→out/2)
+ * ghost = DW(primary)
+ * concat(primary, ghost) → output
+ *
+ * Ghost block (in PAN):
+ * ghost1 → ghost2 → add(input_PW, ghost2)
+ */
+
+#include "nn2_internal.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+#include <immintrin.h>
+
+/* ============ Conv layer with weights ============ */
+
+typedef struct {
+ float* w;
+ float* b;
+ int cout, cin_per_g, k, stride, pad, groups, act;
+} NDConv;
+
+/* Run conv: dispatches to DW, PW, or regular */
+static void nd_run(const NDConv* L, const float* in, int H, int W,
+ float* out, float* col)
+{
+ if (L->groups > 1) {
+ nn2_dwconv2d(in, L->w, L->b, L->cout, H, W,
+ L->k, L->stride, L->pad, L->act, out);
+ } else {
+ int Hout = (H + 2*L->pad - L->k) / L->stride + 1;
+ int Wout = (W + 2*L->pad - L->k) / L->stride + 1;
+ int sp = Hout * Wout;
+ int cin = L->cin_per_g;
+
+ if (L->k == 1) {
+ nn2_sgemm_bias_act(L->cout, cin, sp, L->w, cin, in, sp,
+ out, sp, L->b, L->act);
+ } else {
+ int K = cin * L->k * L->k;
+ nn2_im2col(in, cin, H, W, L->k, L->k, L->stride, L->pad, col);
+ nn2_sgemm_bias_act(L->cout, K, sp, L->w, K, col, sp,
+ out, sp, L->b, L->act);
+ }
+ }
+}
+
+/* ============ NanoDet model ============ */
+
+typedef struct NanoDet {
+ NDConv cv[110]; /* all 110 conv layers */
+ int num_classes;
+ int input_size;
+ float* ws; /* workspace */
+ size_t ws_size;
+} NanoDet;
+
+/* ============ Load ============ */
+
+NanoDet* nanodet_init(const char* path, int n_threads)
+{
+ FILE* f = fopen(path, "rb");
+
+ char magic[4]; fread(magic, 1, 4, f);
+ if (memcmp(magic, "NN2N", 4)) { fclose(f); return NULL; }
+
+ NanoDet* nd = (NanoDet*)calloc(1, sizeof(NanoDet));
+ uint32_t nc, isz, nl;
+ fread(&nc, 4, 1, f); fread(&isz, 4, 1, f); fread(&nl, 4, 1, f);
+ nd->num_classes = nc; nd->input_size = isz;
+
+ for (int i = 0; i < (int)nl && i < 110; i++) {
+ NDConv* L = &nd->cv[i];
+ uint32_t v[7]; fread(v, 4, 7, f);
+ L->cout = v[0]; L->cin_per_g = v[1]; L->k = v[2];
+ L->stride = v[3]; L->pad = v[4]; L->groups = v[5]; L->act = v[6];
+ L->b = (float*)malloc(L->cout * 4);
+ fread(L->b, 4, L->cout, f);
+ int wsz = L->cout * L->cin_per_g * L->k * L->k;
+ L->w = (float*)malloc(wsz * 4);
+ fread(L->w, 4, wsz, f);
+ }
+ fclose(f);
+
+ nd->ws_size = 256 << 20; /* 256MB */
+ nd->ws = (float*)malloc(nd->ws_size);
+
+ nn2_tp_init(n_threads);
+ return nd;
+}
+
+/* ============ Helpers ============ */
+
+/* Channel split: first half / second half */
+static void split_channels(const float* in, int C, int sp,
+ const float** left, const float** right)
+{
+ *left = in;
+ *right = in + (C / 2) * sp;
+}
+
+/* Channel shuffle (groups=2) */
+static void shuffle2(const float* in, int C, int sp, float* out)
+{
+ int half = C / 2;
+ for (int c = 0; c < half; c++) {
+ memcpy(out + (2*c) * sp, in + c * sp, sp * 4);
+ memcpy(out + (2*c + 1) * sp, in + (half+c) * sp, sp * 4);
+ }
+}
+
+/* Nearest-neighbor upsample 2x */
+static void upsample2x(const float* in, int C, int H, int W, float* out)
+{
+ nn2_upsample_2x(in, C, H, W, out);
+}
+
+/* ============ ShuffleNetV2 blocks ============ */
+
+/* Stride block: no split, two branches, concat.
+ * branch1: DW(s=2) → PW
+ * branch2: PW → DW(s=2) → PW
+ * cvs[0]=DW, cvs[1]=PW, cvs[2]=PW, cvs[3]=DW, cvs[4]=PW */
+static void shufflev2_stride(const NDConv cvs[5], const float* in,
+ int C_in, int H, int W,
+ float* out, float* tmp, float* col)
+{
+ int Ho = H / 2, Wo = W / 2;
+ int c_out = cvs[1].cout; /* output channels per branch */
+
+
+ /* Branch 1: DW(s=2) → PW */
+ float* br1_dw = tmp;
+ nd_run(&cvs[0], in, H, W, br1_dw, col);
+ float* br1 = br1_dw + C_in * Ho * Wo;
+ nd_run(&cvs[1], br1_dw, Ho, Wo, br1, col);
+ float* br2_pw1 = br1 + c_out * Ho * Wo;
+ nd_run(&cvs[2], in, H, W, br2_pw1, col);
+ float* br2_dw = br2_pw1 + cvs[2].cout * H * W;
+ nd_run(&cvs[3], br2_pw1, H, W, br2_dw, col);
+ float* br2 = br2_dw + cvs[3].cout * Ho * Wo;
+ nd_run(&cvs[4], br2_dw, Ho, Wo, br2, col);
+
+ /* Concat: [br1, br2] */
+ int sp = Ho * Wo;
+ memcpy(out, br1, c_out * sp * 4);
+ memcpy(out + c_out * sp, br2, c_out * sp * 4);
+}
+
+/* Regular block: split → PW → DW → PW + identity → concat → shuffle.
+ * cvs[0]=PW, cvs[1]=DW, cvs[2]=PW */
+static void shufflev2_regular(const NDConv cvs[3], const float* in,
+ int C, int H, int W,
+ float* out, float* tmp, float* col)
+{
+ int sp = H * W;
+ int half = C / 2;
+ const float* left;
+ const float* right;
+ split_channels(in, C, sp, &left, &right);
+
+ /* Process right branch: PW → DW → PW */
+ float* pw1 = tmp;
+ nd_run(&cvs[0], right, H, W, pw1, col);
+ float* dw = pw1 + cvs[0].cout * sp;
+ nd_run(&cvs[1], pw1, H, W, dw, col);
+ float* pw2 = dw + cvs[1].cout * sp;
+ nd_run(&cvs[2], dw, H, W, pw2, col);
+
+ /* Fused concat+shuffle: write directly to interleaved output.
+ * Shuffle2 of [left, pw2] → out[2c]=left[c], out[2c+1]=pw2[c].
+ * Use SIMD memcpy for better bandwidth. */
+ int bytes = sp * 4;
+ for (int ci = 0; ci < half; ci++) {
+ memcpy(out + (2*ci) * sp, left + ci * sp, bytes);
+ memcpy(out + (2*ci + 1) * sp, pw2 + ci * sp, bytes);
+ }
+}
+
+/* ============ Ghost module (in PAN neck) ============ */
+
+/* Ghost module: PW(in→out/2) → DW → concat → out
+ * cvs[0]=PW(in→out/2), cvs[1]=DW(out/2) */
+static void ghost_module(const NDConv cvs[2], const float* in,
+ int H, int W, float* out, float* tmp, float* col)
+{
+ int sp = H * W;
+ /* Primary: PW */
+ float* primary = tmp;
+ nd_run(&cvs[0], in, H, W, primary, col);
+ int c_half = cvs[0].cout;
+ /* Ghost: DW on primary */
+ float* ghost = primary + c_half * sp;
+ nd_run(&cvs[1], primary, H, W, ghost, col);
+ /* Concat [primary, ghost] → out */
+ memcpy(out, primary, c_half * sp * 4);
+ memcpy(out + c_half * sp, ghost, c_half * sp * 4);
+}
+
+/* Ghost block: ghost1 → ghost2 → add(shortcut, ghost2)
+ * shortcut = DW5×5(input) → PW
+ * cvs: [ghost1_pw, ghost1_dw, ghost1_pw2, ghost1_dw2,
+ * shortcut_dw, shortcut_pw] (6 convs) */
+
+/* Ghost module — uses tmp for intermediates (no malloc) */
+static void nd_ghost_module(const NDConv cvs[2], const float* in,
+ int H, int W, float* out, float* tmp, float* col)
+{
+ int sp = H * W;
+ int c_half = cvs[0].cout;
+ float* primary = tmp;
+ nd_run(&cvs[0], in, H, W, primary, col);
+ float* ghost_out = tmp + c_half * sp;
+ nd_run(&cvs[1], primary, H, W, ghost_out, col);
+ memcpy(out, primary, c_half * sp * sizeof(float));
+ memcpy(out + c_half * sp, ghost_out, c_half * sp * sizeof(float));
+}
+
+/* Ghost block: ghost1→ghost2→shortcut(DW+PW)→add.
+ * Uses tmp for all intermediates — needs ~(ch_in + 96*4) * sp floats. */
+static void nd_ghost_block(const NDConv* cvs, int ch_in,
+ const float* in, int H, int W,
+ float* out, float* tmp, float* col)
+{
+ int sp = H * W;
+ /* Layout in tmp: [g1: 96*sp][g2: 96*sp][sc_dw: ch_in*sp][sc: 96*sp][ghost_scratch: 96*sp] */
+ float* g1 = tmp;
+ float* ghost_tmp = tmp + (96 + 96 + ch_in + 96) * sp; /* scratch for ghost module internals */
+ nd_ghost_module(&cvs[0], in, H, W, g1, ghost_tmp, col);
+ float* g2 = g1 + 96 * sp;
+ nd_ghost_module(&cvs[2], g1, H, W, g2, ghost_tmp, col);
+ float* sc_dw = g2 + 96 * sp;
+ nd_run(&cvs[4], in, H, W, sc_dw, col);
+ float* sc = sc_dw + ch_in * sp;
+ nd_run(&cvs[5], sc_dw, H, W, sc, col);
+ for (int i = 0; i < 96 * sp; i++) out[i] = g2[i] + sc[i];
+}
+
+/* ============ FORWARD PASS ============ */
+
+int nanodet_forward(NanoDet* nd, const float* input,
+ float* det_output, int* n_anchors)
+{
+ NDConv* c = nd->cv; /* shorthand */
+ int S = nd->input_size;
+ float* ws = nd->ws;
+ /* Workspace layout: [col 4M][A 1M][B 1M][tmp 50M] = 56M floats in 256MB ws */
+ float* col = ws;
+ float* A = ws + 4*1024*1024;
+ float* B = A + 1024*1024;
+ float* tmp = B + 1024*1024;
+ #define SWAP() do { float* _t = A; A = B; B = _t; } while(0)
+
+ int h = S, w = S;
+
+ /* === BACKBONE === */
+
+ /* Stem: cv[0] Conv(3→24, k=3, s=2) + MaxPool(k=3,s=2,p=1) */
+ nd_run(&c[0], input, h, w, A, col);
+ h /= 2; w /= 2; /* 160×160 */
+ /* MaxPool 3×3 s=2 p=1 */
+ nn2_maxpool2d(A, c[0].cout, h, w, 3, 2, 1, B);
+ SWAP();
+ h /= 2; w /= 2; /* 80×80 */
+ int stem_ch = 24;
+
+ /* Stage 1: stride block (cvs 1-5) → 116ch @ 80×80 */
+ shufflev2_stride(&c[1], A, stem_ch, h, w, B, tmp, col);
+ SWAP();
+ int s1_ch = c[1+1].cout * 2; /* 58*2 = 116 */
+
+ /* Stage 1: 3 regular blocks (cvs 6-8, 9-11, 12-14) */
+ for (int i = 0; i < 3; i++) {
+ shufflev2_regular(&c[6 + i*3], A, s1_ch, h, w, B, tmp, col);
+ SWAP();
+ }
+ float* feat_s1 = (float*)malloc(s1_ch * h * w * 4); /* P3: 116ch @ 80×80 */
+ memcpy(feat_s1, A, s1_ch * h * w * 4);
+
+ /* Stage 2: stride block (cvs 15-19) → 232ch @ 40×40 */
+ /* stage2 stride */
+ shufflev2_stride(&c[15], A, s1_ch, h, w, B, tmp, col);
+ SWAP();
+ h /= 2; w /= 2; /* 40×40 */
+ int s2_ch = c[15+1].cout * 2; /* 116*2 = 232 */
+
+ /* Stage 2: 7 regular blocks (cvs 20-40) */
+ for (int i = 0; i < 7; i++) {
+ shufflev2_regular(&c[20 + i*3], A, s2_ch, h, w, B, tmp, col);
+ SWAP();
+ }
+ float* feat_s2 = (float*)malloc(s2_ch * h * w * 4); /* P4: 232ch @ 40×40 */
+ memcpy(feat_s2, A, s2_ch * h * w * 4);
+
+ /* Stage 3: stride block (cvs 41-45) → 464ch @ 20×20 */
+ shufflev2_stride(&c[41], A, s2_ch, h, w, B, tmp, col);
+ SWAP();
+ h /= 2; w /= 2; /* 20×20 */
+ int s3_ch = c[41+1].cout * 2; /* 232*2 = 464 */
+
+ /* Stage 3: 3 regular blocks (cvs 46-54) */
+ for (int i = 0; i < 3; i++) {
+ shufflev2_regular(&c[46 + i*3], A, s3_ch, h, w, B, tmp, col);
+ SWAP();
+ }
+ float* feat_s3 = (float*)malloc(s3_ch * h * w * 4);
+ memcpy(feat_s3, A, s3_ch * h * w * 4);
+
+ /* === NECK (Ghost-PAN) === */
+
+ int h2=S/4, w2=S/4, h3=S/8, w3=S/8, h4=S/16, w4=S/16, h5=S/32, w5=S/32;
+ int sp2=h2*w2, sp3=h3*w3, sp4=h4*w4, sp5=h5*w5;
+ /* Bump allocator on tmp — no malloc in neck */
+ float* bump = tmp;
+ #define BUMP(n) (bump += (n), bump - (n))
+
+ /* Reduce: permanent until end of neck */
+ float*r1=BUMP(96*sp2); nd_run(&c[55],feat_s1,h2,w2,r1,col);
+ float*r2=BUMP(96*sp3); nd_run(&c[56],feat_s2,h3,w3,r2,col);
+ float*r3=BUMP(96*sp4); nd_run(&c[57],feat_s3,h4,w4,r3,col);
+ free(feat_s1);free(feat_s2);free(feat_s3);
+
+ /* Pan features: permanent until head */
+ float*pan_p4=BUMP(96*sp3);
+ float*pan_p3=BUMP(96*sp2);
+ float*pan_n4=BUMP(96*sp3);
+ float*pan_n5=BUMP(96*sp4);
+ float*pan_n6=BUMP(96*sp5);
+ /* ghost_block scratch: reused per block */
+ float*gscratch=bump; /* ~(192+96*4)*sp2 worst case */
+
+ /* Top-down */
+ { float*up1=gscratch; upsample2x(r3,96,h4,w4,up1);
+ float*cat1=up1+96*sp3; nn2_concat(up1,96,r2,96,h3,w3,cat1);
+ nd_ghost_block(&c[58],192,cat1,h3,w3,pan_p4,gscratch+192*sp3+96*sp3,col); }
+
+ { float*up2=gscratch; upsample2x(pan_p4,96,h3,w3,up2);
+ float*cat2=up2+96*sp2; nn2_concat(up2,96,r1,96,h2,w2,cat2);
+ nd_ghost_block(&c[64],192,cat2,h2,w2,pan_p3,gscratch+192*sp2+96*sp2,col); }
+
+ /* Bottom-up */
+ { float*ds_dw=gscratch; nd_run(&c[70],pan_p3,h2,w2,ds_dw,col);
+ float*ds=ds_dw+96*sp3; nd_run(&c[71],ds_dw,h3,w3,ds,col);
+ float*cat3=ds+96*sp3; nn2_concat(ds,96,pan_p4,96,h3,w3,cat3);
+ nd_ghost_block(&c[72],192,cat3,h3,w3,pan_n4,cat3+192*sp3,col); }
+
+ { float*ds_dw=gscratch; nd_run(&c[78],pan_n4,h3,w3,ds_dw,col);
+ float*ds=ds_dw+96*sp4; nd_run(&c[79],ds_dw,h4,w4,ds,col);
+ float*cat4=ds+96*sp4; nn2_concat(ds,96,r3,96,h4,w4,cat4);
+ nd_ghost_block(&c[80],192,cat4,h4,w4,pan_n5,cat4+192*sp4,col); }
+
+ /* Extra downsample for 4th scale */
+ { float*ds3_dw=gscratch; nd_run(&c[86],r3,h4,w4,ds3_dw,col);
+ float*ds3=ds3_dw+96*sp5; nd_run(&c[87],ds3_dw,h5,w5,ds3,col);
+ float*ds4_dw=ds3+96*sp5; nd_run(&c[88],pan_n5,h4,w4,ds4_dw,col);
+ float*ds4=ds4_dw+96*sp5; nd_run(&c[89],ds4_dw,h5,w5,ds4,col);
+ for(int i=0;i<96*sp5;i++) pan_n6[i]=ds3[i]+ds4[i]; }
+ #undef BUMP
+
+ /* === HEAD === */
+ float*feats[4]={pan_p3,pan_n4,pan_n5,pan_n6};
+ int hh[4]={h2,h3,h4,h5}, hw[4]={w2,w3,w4,w5};
+ int total_anchors=0;
+ for(int s=0;s<4;s++) total_anchors+=hh[s]*hw[s];
+ float*head_out=det_output;
+ int aoff=0;
+ for(int s=0;s<4;s++){
+ int ci=90+s*5, fh=hh[s], fw=hw[s], fsp=fh*fw;
+ /* Reuse gscratch for head intermediates — no malloc */
+ float*x0=gscratch;
+ nd_run(&c[ci],feats[s],fh,fw,x0,col);
+ float*x1=x0+96*fsp;
+ nd_run(&c[ci+1],x0,fh,fw,x1,col);
+ float*x2=x1+96*fsp;
+ nd_run(&c[ci+2],x1,fh,fw,x2,col);
+ float*x3=x2+96*fsp;
+ nd_run(&c[ci+3],x2,fh,fw,x3,col);
+ float*x4=x3+96*fsp;
+ nd_run(&c[ci+4],x3,fh,fw,x4,col);
+ for(int a=0;a<fsp;a++)
+ for(int ch=0;ch<112;ch++)
+ head_out[(aoff+a)*112+ch]=x4[ch*fsp+a];
+ aoff+=fsp;
+ }
+
+ /* A, B, tmp are workspace-based — no free needed */
+ *n_anchors=total_anchors;
+ return 0;
+ #undef SWAP
+}
+
+/* ============ Detect ============ */
+
+int nanodet_detect(NanoDet* nd, const uint8_t* rgb, int width, int height,
+ NN2Det* out, int max_det)
+{
+ int S = nd->input_size;
+
+ /* Preprocess: letterbox + normalize */
+ float scale = (float)S / (width > height ? width : height);
+ int nw = (int)(width * scale), nh = (int)(height * scale);
+ int px = (S - nw) / 2, py = (S - nh) / 2;
+
+ /* NanoDet normalization: (pixel - mean) / std */
+ /* mean=[103.53, 116.28, 123.675], std=[57.375, 57.12, 58.395] */
+ float mean[3] = {103.53f, 116.28f, 123.675f};
+ float istd[3] = {1.0f/57.375f, 1.0f/57.12f, 1.0f/58.395f};
+
+ float* input = nd->ws + 56*1024*1024; /* safe offset past forward workspace */
+ /* Fill with normalized mean (gray) */
+ for (int c = 0; c < 3; c++) {
+ float fill = -mean[c] * istd[c];
+ float* ch = input + c * S * S;
+ for (int i = 0; i < S * S; i++) ch[i] = fill;
+ }
+ /* Bilinear resize + normalize */
+ float inv_s = 1.0f / scale;
+ for (int y = 0; y < nh; y++) {
+ float sy = y * inv_s;
+ int iy = (int)sy; float fy = sy - iy;
+ if (iy >= height-1) { iy = height-2; fy = 1.0f; }
+ for (int x = 0; x < nw; x++) {
+ float sx = x * inv_s;
+ int ix = (int)sx; float fx = sx - ix;
+ if (ix >= width-1) { ix = width-2; fx = 1.0f; }
+ const uint8_t* p00 = rgb + (iy*width+ix)*3;
+ const uint8_t* p01 = p00+3, *p10 = p00+width*3, *p11 = p10+3;
+ float w00=(1-fx)*(1-fy), w01=fx*(1-fy), w10=(1-fx)*fy, w11=fx*fy;
+ int dy = y + py, dx = x + px;
+ for (int c = 0; c < 3; c++) {
+ float v = p00[c]*w00 + p01[c]*w01 + p10[c]*w10 + p11[c]*w11;
+ input[c*S*S + dy*S + dx] = (v - mean[c]) * istd[c];
+ }
+ }
+ }
+
+ /* Forward — use end of workspace for detection buffer */
+ float* det_buf = nd->ws + (nd->ws_size / sizeof(float)) - 8500 * 112;
+ int n_anchors = 0;
+ nanodet_forward(nd, input, det_buf, &n_anchors);
+
+ /* Decode GFL output: [n_anchors, 112] → 112 = 32 (bbox DFL×4×8) + 80 (classes) */
+ int nc = nd->num_classes; /* 80 */
+ int reg_max = 8; /* NanoDet uses reg_max=7+1=8 (not 16 like YOLOv8) */
+ int strides[4] = {8, 16, 32, 64};
+ int grid_h[4], grid_w[4];
+ for (int s = 0; s < 4; s++) {
+ grid_h[s] = S / strides[s];
+ grid_w[s] = S / strides[s];
+ }
+
+ int n_det = 0;
+ int offset = 0;
+ for (int si = 0; si < 4; si++) {
+ int gh = grid_h[si], gw = grid_w[si];
+ int stride = strides[si];
+ for (int a = 0; a < gh * gw && n_det < max_det; a++) {
+ float* row = det_buf + (offset + a) * 112;
+ /* Classes: row[32..112], find best */
+ float* cls = row + 4 * reg_max;
+ /* Sigmoid + find max */
+ float best = -1e9f; int best_c = 0;
+ for (int ci = 0; ci < nc; ci++) {
+ float v = 1.0f / (1.0f + expf(-cls[ci]));
+ if (v > best) { best = v; best_c = ci; }
+ }
+ if (best < 0.25f) continue;
+
+ /* DFL decode bbox: 4 distances × reg_max bins */
+ float ltrb[4];
+ for (int d = 0; d < 4; d++) {
+ float* logits = row + d * reg_max;
+ /* softmax → weighted sum */
+ float maxv = logits[0];
+ for (int r = 1; r < reg_max; r++)
+ if (logits[r] > maxv) maxv = logits[r];
+ float sum = 0, val = 0;
+ for (int r = 0; r < reg_max; r++) {
+ float e = expf(logits[r] - maxv);
+ sum += e; val += e * r;
+ }
+ ltrb[d] = val / sum;
+ }
+
+ int ay = a / gw, ax = a % gw;
+ float cx = (ax + 0.5f) * stride;
+ float cy = (ay + 0.5f) * stride;
+
+ NN2Det* d = &out[n_det++];
+ d->x1 = (cx - ltrb[0] * stride - px) / scale;
+ d->y1 = (cy - ltrb[1] * stride - py) / scale;
+ d->x2 = (cx + ltrb[2] * stride - px) / scale;
+ d->y2 = (cy + ltrb[3] * stride - py) / scale;
+ d->score = best;
+ d->cls = best_c;
+ }
+ offset += gh * gw;
+ }
+
+ /* NMS */
+ n_det = nn2_nms(out, n_det, 0.45f);
+ return n_det;
+}
+
+void nanodet_free(NanoDet* nd)
+{
+ if (!nd) return;
+ for (int i = 0; i < 110; i++) { free(nd->cv[i].w); free(nd->cv[i].b); }
+ free(nd->ws); nn2_tp_destroy(); free(nd);
+}
diff --git a/nn2/src/nd_timed.c b/nn2/src/nd_timed.c
new file mode 100644
index 0000000..4724750
--- /dev/null
+++ b/nn2/src/nd_timed.c
@@ -0,0 +1,27 @@
+#include "nn2_internal.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef _WIN32
+#include <windows.h>
+static double now(void){LARGE_INTEGER f,c;QueryPerformanceFrequency(&f);QueryPerformanceCounter(&c);return(double)c.QuadPart/f.QuadPart*1000.0;}
+#endif
+typedef struct NanoDet NanoDet;
+NanoDet* nanodet_init(const char* p, int t);
+int nanodet_detect(NanoDet* nd, const uint8_t* rgb, int w, int h, NN2Det* out, int max);
+void nanodet_free(NanoDet* nd);
+
+int main(void){
+ NanoDet*nd=nanodet_init("weights/nanodet_plus_m_320.bin",6);
+ if(!nd)return 1;
+ uint8_t*img=(uint8_t*)calloc(640*480*3,1);
+ NN2Det dets[300];
+ /* Warmup */
+ nanodet_detect(nd,img,640,480,dets,300);
+ /* Timed */
+ int N=20;double t0=now();
+ for(int i=0;i<N;i++) nanodet_detect(nd,img,640,480,dets,300);
+ double ms=(now()-t0)/N;
+ printf("NanoDet 320 6t: %.1f ms (%.0f FPS)\n",ms,1000/ms);
+ nanodet_free(nd);free(img);return 0;
+}
diff --git a/nn2/src/net.c b/nn2/src/net.c
new file mode 100644
index 0000000..142bb28
--- /dev/null
+++ b/nn2/src/net.c
@@ -0,0 +1,390 @@
+/*
+ * net.c — YOLOv8n hardcoded forward pass + weight loading.
+ *
+ * Memory strategy:
+ * - 2 ping-pong buffers (buf[0], buf[1]) for sequential layer I/O
+ * - 1 reusable im2col buffer (largest needed: ~4M floats)
+ * - Dedicated save slots for skip connections (P3, P4, P5, N3)
+ * - Temp area for C2f internals
+ */
+
+#include "nn2_internal.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+/* No explicit SIMD here — compiler auto-vectorizes with -O3 */
+
+/* ============ Weight file format ============ */
+
+static float* read_tensor(FILE* f, int* out_size)
+{
+ uint32_t sz;
+ if (fread(&sz, 4, 1, f) != 1) return NULL;
+ float* data = (float*)malloc(sz * sizeof(float));
+ if (!data) return NULL;
+ if (fread(data, sizeof(float), sz, f) != sz) { free(data); return NULL; }
+ *out_size = (int)sz;
+ return data;
+}
+
+static int load_conv(FILE* f, ConvLayer* L, int cout, int cin, int k, int stride, int pad, int act)
+{
+ int wsz, bsz;
+ L->w = read_tensor(f, &wsz);
+ L->b = read_tensor(f, &bsz);
+ if (!L->w || !L->b) return -1;
+ L->cout = cout; L->cin = cin; L->k = k;
+ L->stride = stride; L->pad = pad; L->act = act;
+ return 0;
+}
+
+static int load_c2f(FILE* f, C2fBlock* blk, int cin, int cout, int n, int shortcut)
+{
+ int c = cout / 2;
+ blk->n = n;
+ blk->c = c;
+ blk->shortcut = shortcut;
+
+ if (load_conv(f, &blk->cv1, 2 * c, cin, 1, 1, 0, 1)) return -1;
+ for (int i = 0; i < n; i++) {
+ if (load_conv(f, &blk->m[i].cv1, c, c, 3, 1, 1, 1)) return -1;
+ if (load_conv(f, &blk->m[i].cv2, c, c, 3, 1, 1, 1)) return -1;
+ }
+ if (load_conv(f, &blk->cv2, cout, (2 + n) * c, 1, 1, 0, 1)) return -1;
+ return 0;
+}
+
+int nn2_load_weights(NN2* ctx, const char* path)
+{
+ FILE* f = fopen(path, "rb");
+ if (!f) { fprintf(stderr, "nn2: cannot open %s\n", path); return -1; }
+
+ char magic[4];
+ fread(magic, 1, 4, f);
+ if (memcmp(magic, "NN2W", 4) != 0) {
+ fprintf(stderr, "nn2: invalid weight file\n");
+ fclose(f); return -1;
+ }
+
+ uint32_t nc, isz, ntensors;
+ fread(&nc, 4, 1, f);
+ fread(&isz, 4, 1, f);
+ fread(&ntensors, 4, 1, f);
+ ctx->num_classes = (int)nc;
+ ctx->input_size = (int)isz;
+
+ int ch[] = {3, 16, 32, 64, 128, 256};
+ for (int i = 0; i < 5; i++)
+ if (load_conv(f, &ctx->bb_conv[i], ch[i+1], ch[i], 3, 2, 1, 1)) goto fail;
+
+ int c2f_ch[] = {32, 64, 128, 256};
+ int c2f_n[] = {1, 2, 2, 1};
+ for (int i = 0; i < 4; i++)
+ if (load_c2f(f, &ctx->bb_c2f[i], c2f_ch[i], c2f_ch[i], c2f_n[i], 1)) goto fail;
+
+ if (load_conv(f, &ctx->sppf_cv1, 128, 256, 1, 1, 0, 1)) goto fail;
+ if (load_conv(f, &ctx->sppf_cv2, 256, 512, 1, 1, 0, 1)) goto fail;
+
+ int nk_cin[] = {384, 192, 192, 384};
+ int nk_cout[] = {128, 64, 128, 256};
+ for (int i = 0; i < 4; i++)
+ if (load_c2f(f, &ctx->nk_c2f[i], nk_cin[i], nk_cout[i], 1, 0)) goto fail;
+
+ if (load_conv(f, &ctx->nk_conv[0], 64, 64, 3, 2, 1, 1)) goto fail;
+ if (load_conv(f, &ctx->nk_conv[1], 128, 128, 3, 2, 1, 1)) goto fail;
+
+ int head_ch[] = {64, 128, 256};
+ int bbox_c2 = 64;
+ int min_nc_100 = (int)nc < 100 ? (int)nc : 100;
+ int cls_c3 = head_ch[0] > min_nc_100 ? head_ch[0] : min_nc_100;
+
+ for (int s = 0; s < 3; s++) {
+ if (load_conv(f, &ctx->head[s].bbox[0], bbox_c2, head_ch[s], 3, 1, 1, 1)) goto fail;
+ if (load_conv(f, &ctx->head[s].bbox[1], bbox_c2, bbox_c2, 3, 1, 1, 1)) goto fail;
+ if (load_conv(f, &ctx->head[s].bbox[2], 4 * NN2_REG_MAX, bbox_c2, 1, 1, 0, 0)) goto fail;
+ if (load_conv(f, &ctx->head[s].cls[0], cls_c3, head_ch[s], 3, 1, 1, 1)) goto fail;
+ if (load_conv(f, &ctx->head[s].cls[1], cls_c3, cls_c3, 3, 1, 1, 1)) goto fail;
+ if (load_conv(f, &ctx->head[s].cls[2], (int)nc, cls_c3, 1, 1, 0, 0)) goto fail;
+ }
+
+ fclose(f);
+ return 0;
+
+fail:
+ fprintf(stderr, "nn2: failed to load weights\n");
+ fclose(f);
+ return -1;
+}
+
+/* ============ Memory layout ============
+ * workspace is carved into fixed regions:
+ *
+ * [im2col_buf][buf_a][buf_b][save_p3][save_p4][save_p5][save_n3][c2f_tmp]
+ *
+ * im2col_buf: 4M floats (reused by every conv)
+ * buf_a/buf_b: ping-pong, 4M floats each (max feature map)
+ * save_*: skip connections, permanently allocated
+ * c2f_tmp: scratch for C2f internals, 8M floats
+ */
+
+#define IM2COL_SIZE (4 * 1024 * 1024) /* 16MB */
+#define BUF_SIZE (4 * 1024 * 1024) /* 16MB each */
+#define C2F_TMP_SIZE (8 * 1024 * 1024) /* 32MB */
+
+typedef struct {
+ float* im2col; /* reusable im2col buffer */
+ float* buf[2]; /* ping-pong buffers */
+ int cur; /* current output buffer index (0 or 1) */
+ float* save[4]; /* P3, P4, P5, N3 */
+ float* c2f_tmp; /* scratch for C2f internals */
+} MemPool;
+
+static void conv_run(const ConvLayer* L, const float* in, int H, int W,
+ float* out, float* im2col)
+{
+ nn2_conv2d(L, in, H, W, out, im2col);
+}
+
+static void c2f_run(const C2fBlock* blk, const float* in, int H, int W,
+ float* out, float* im2col, float* tmp)
+{
+ int spatial = H * W;
+ int c = blk->c;
+
+ int total_ch = (2 + blk->n) * c;
+
+ /* Allocate concat buffer FIRST — write all chunks directly into it */
+ float* cat = tmp;
+ float* scratch = tmp + total_ch * spatial;
+
+ /* cv1 output goes directly into cat[0..2c*spatial-1] */
+ conv_run(&blk->cv1, in, H, W, cat, im2col);
+ /* cat[0..c-1] = chunk0 (identity branch) */
+ /* cat[c..2c-1] = chunk1 (first bottleneck input) */
+
+ float* bn_in = cat + c * spatial;
+ for (int i = 0; i < blk->n; i++) {
+ /* Bottleneck cv1 → scratch (temporary) */
+ conv_run(&blk->m[i].cv1, bn_in, H, W, scratch, im2col);
+
+ /* Bottleneck cv2 → directly into cat[(2+i)*c] position */
+ float* bn_out = cat + (2 + i) * c * spatial;
+ if (blk->shortcut && blk->m[i].cv2.w_packed && spatial < 2500) {
+ /* Fused: im2col + GEMM+bias+act+residual in one store pass */
+ const ConvLayer* L = &blk->m[i].cv2;
+ int K_gemm = L->cin * L->k * L->k;
+ nn2_im2col(scratch, L->cin, H, W, L->k, L->k, L->stride, L->pad, im2col);
+ nn2_sgemm_bias_act_res_packed(L->cout, K_gemm, spatial,
+ L->w_packed, im2col,
+ bn_out, spatial, L->b, L->act,
+ bn_in, spatial);
+ } else {
+ conv_run(&blk->m[i].cv2, scratch, H, W, bn_out, im2col);
+ if (blk->shortcut)
+ for (int j = 0; j < c * spatial; j++) bn_out[j] += bn_in[j];
+ }
+ bn_in = bn_out;
+ }
+
+ /* cat is already contiguous — no memcpy needed! */
+ conv_run(&blk->cv2, cat, H, W, out, im2col);
+}
+
+/* ============ Forward pass ============ */
+
+int nn2_forward(NN2* ctx, const float* input, float* bbox_out, float* cls_out)
+{
+ int S = ctx->input_size;
+ float* ws = ctx->workspace;
+
+ /* Carve memory regions */
+ MemPool mp;
+ mp.im2col = ws; ws += IM2COL_SIZE;
+ mp.buf[0] = ws; ws += BUF_SIZE;
+ mp.buf[1] = ws; ws += BUF_SIZE;
+ mp.save[0] = ws; ws += 64 * (S/8) * (S/8); /* P3: 64ch @ S/8 */
+ mp.save[1] = ws; ws += 128 * (S/16) * (S/16); /* P4: 128ch @ S/16 */
+ mp.save[2] = ws; ws += 256 * (S/32) * (S/32); /* P5: 256ch @ S/32 */
+ mp.save[3] = ws; ws += 128 * (S/16) * (S/16); /* N3: 128ch @ S/16 */
+ mp.c2f_tmp = ws; /* rest is C2f scratch */
+ mp.cur = 0;
+
+ #define CUR mp.buf[mp.cur]
+ #define NEXT mp.buf[1 - mp.cur]
+ #define SWAP() mp.cur = 1 - mp.cur
+
+ int h = S, w = S;
+
+ /* === Backbone === */
+
+ /* Conv0: 3→16, s=2 → S/2 */
+ int h0 = S/2, w0 = S/2;
+ conv_run(&ctx->bb_conv[0], input, h, w, CUR, mp.im2col);
+ /* CUR = 16ch @ h0×w0 */
+
+ /* Conv1: 16→32, s=2 → S/4 */
+ int h1 = S/4, w1 = S/4;
+ conv_run(&ctx->bb_conv[1], CUR, h0, w0, NEXT, mp.im2col);
+ SWAP();
+
+ /* C2f_0: 32→32, n=1 */
+ c2f_run(&ctx->bb_c2f[0], CUR, h1, w1, NEXT, mp.im2col, mp.c2f_tmp);
+ SWAP();
+
+ /* Conv2: 32→64, s=2 → S/8 */
+ int h2 = S/8, w2 = S/8;
+ conv_run(&ctx->bb_conv[2], CUR, h1, w1, NEXT, mp.im2col);
+ SWAP();
+
+ /* C2f_1: 64→64, n=2 → P3 */
+ c2f_run(&ctx->bb_c2f[1], CUR, h2, w2, NEXT, mp.im2col, mp.c2f_tmp);
+ SWAP();
+ memcpy(mp.save[0], CUR, 64 * h2 * w2 * sizeof(float)); /* save P3 */
+
+ /* Conv3: 64→128, s=2 → S/16 */
+ int h3 = S/16, w3 = S/16;
+ conv_run(&ctx->bb_conv[3], CUR, h2, w2, NEXT, mp.im2col);
+ SWAP();
+
+ /* C2f_2: 128→128, n=2 → P4 */
+ c2f_run(&ctx->bb_c2f[2], CUR, h3, w3, NEXT, mp.im2col, mp.c2f_tmp);
+ SWAP();
+ memcpy(mp.save[1], CUR, 128 * h3 * w3 * sizeof(float)); /* save P4 */
+
+ /* Conv4: 128→256, s=2 → S/32 */
+ int h4 = S/32, w4 = S/32;
+ conv_run(&ctx->bb_conv[4], CUR, h3, w3, NEXT, mp.im2col);
+ SWAP();
+
+ /* C2f_3: 256→256, n=1 */
+ c2f_run(&ctx->bb_c2f[3], CUR, h4, w4, NEXT, mp.im2col, mp.c2f_tmp);
+ SWAP();
+
+ /* SPPF: cv1(256→128) → maxpool×3 → concat(512) → cv2(512→256) */
+ conv_run(&ctx->sppf_cv1, CUR, h4, w4, NEXT, mp.im2col);
+ SWAP();
+ /* CUR = 128ch @ h4×w4 */
+ {
+ int sp = h4 * w4;
+ float* sppf_in = CUR;
+ float* cat = mp.c2f_tmp; /* concat output: 512ch */
+
+ float* mp1 = cat + 512 * sp;
+ float* mp2 = mp1 + 128 * sp;
+ float* mp3 = mp2 + 128 * sp;
+
+ nn2_maxpool2d(sppf_in, 128, h4, w4, 5, 1, 2, mp1);
+ nn2_maxpool2d(mp1, 128, h4, w4, 5, 1, 2, mp2);
+ nn2_maxpool2d(mp2, 128, h4, w4, 5, 1, 2, mp3);
+
+ memcpy(cat, sppf_in, 128 * sp * sizeof(float));
+ memcpy(cat + 128 * sp, mp1, 128 * sp * sizeof(float));
+ memcpy(cat + 256 * sp, mp2, 128 * sp * sizeof(float));
+ memcpy(cat + 384 * sp, mp3, 128 * sp * sizeof(float));
+
+ conv_run(&ctx->sppf_cv2, cat, h4, w4, NEXT, mp.im2col);
+ SWAP();
+ }
+ /* CUR = 256ch @ h4×w4 = P5 */
+ memcpy(mp.save[2], CUR, 256 * h4 * w4 * sizeof(float)); /* save P5 */
+
+ /* === Neck === */
+
+ /* Upsample P5 (h4→h3) + concat P4 → 384ch */
+ {
+ float* up = mp.c2f_tmp;
+ nn2_upsample_2x(CUR, 256, h4, w4, up); /* 256ch @ h3×w3 */
+ float* cat = NEXT;
+ nn2_concat(up, 256, mp.save[1], 128, h3, w3, cat); /* 384ch */
+ SWAP();
+ }
+
+ /* C2f neck_0: 384→128 → N3 */
+ c2f_run(&ctx->nk_c2f[0], CUR, h3, w3, NEXT, mp.im2col, mp.c2f_tmp);
+ SWAP();
+ memcpy(mp.save[3], CUR, 128 * h3 * w3 * sizeof(float)); /* save N3 */
+
+ /* Upsample N3 (h3→h2) + concat P3 → 192ch */
+ {
+ float* up = mp.c2f_tmp;
+ nn2_upsample_2x(CUR, 128, h3, w3, up); /* 128ch @ h2×w2 */
+ float* cat = NEXT;
+ nn2_concat(up, 128, mp.save[0], 64, h2, w2, cat); /* 192ch */
+ SWAP();
+ }
+
+ /* C2f neck_1: 192→64 → N2 (scale 0 feature) */
+ float* feat_n2 = mp.save[0]; /* reuse P3 slot (no longer needed) */
+ c2f_run(&ctx->nk_c2f[1], CUR, h2, w2, feat_n2, mp.im2col, mp.c2f_tmp);
+
+ /* Downsample N2 + concat N3 → 192ch */
+ conv_run(&ctx->nk_conv[0], feat_n2, h2, w2, CUR, mp.im2col); /* 64ch @ h3 */
+ {
+ float* cat = NEXT;
+ nn2_concat(CUR, 64, mp.save[3], 128, h3, w3, cat); /* 192ch */
+ SWAP();
+ }
+
+ /* C2f neck_2: 192→128 → N4 (scale 1 feature) */
+ float* feat_n4 = mp.save[1]; /* reuse P4 slot */
+ c2f_run(&ctx->nk_c2f[2], CUR, h3, w3, feat_n4, mp.im2col, mp.c2f_tmp);
+
+ /* Downsample N4 + concat P5 → 384ch */
+ conv_run(&ctx->nk_conv[1], feat_n4, h3, w3, CUR, mp.im2col); /* 128ch @ h4 */
+ {
+ float* cat = NEXT;
+ nn2_concat(CUR, 128, mp.save[2], 256, h4, w4, cat); /* 384ch */
+ SWAP();
+ }
+
+ /* C2f neck_3: 384→256 → N5 (scale 2 feature) */
+ float* feat_n5 = mp.save[2]; /* reuse P5 slot */
+ c2f_run(&ctx->nk_c2f[3], CUR, h4, w4, feat_n5, mp.im2col, mp.c2f_tmp);
+
+ /* === Head === */
+ float* feats[3] = {feat_n2, feat_n4, feat_n5};
+ int feat_h[3] = {h2, h3, h4};
+ int feat_w[3] = {w2, w3, w4};
+
+ int total_anchors = h2*w2 + h3*w3 + h4*w4;
+ int bbox_ch = 4 * NN2_REG_MAX;
+ int cls_ch = ctx->num_classes;
+
+ int offset = 0;
+ for (int s = 0; s < 3; s++) {
+ int fh = feat_h[s], fw = feat_w[s];
+ int spatial = fh * fw;
+ float* tmp = mp.c2f_tmp;
+
+ /* Bbox: conv3x3 → conv3x3 → conv1x1 */
+ float* bx1 = tmp;
+ conv_run(&ctx->head[s].bbox[0], feats[s], fh, fw, bx1, mp.im2col);
+ float* bx2 = tmp + ctx->head[s].bbox[0].cout * spatial;
+ conv_run(&ctx->head[s].bbox[1], bx1, fh, fw, bx2, mp.im2col);
+ float* bx3 = bx2 + ctx->head[s].bbox[1].cout * spatial;
+ conv_run(&ctx->head[s].bbox[2], bx2, fh, fw, bx3, mp.im2col);
+
+ /* Cls: conv3x3 → conv3x3 → conv1x1 */
+ float* cx1 = bx3 + bbox_ch * spatial;
+ conv_run(&ctx->head[s].cls[0], feats[s], fh, fw, cx1, mp.im2col);
+ float* cx2 = cx1 + ctx->head[s].cls[0].cout * spatial;
+ conv_run(&ctx->head[s].cls[1], cx1, fh, fw, cx2, mp.im2col);
+ float* cx3 = cx2 + ctx->head[s].cls[1].cout * spatial;
+ conv_run(&ctx->head[s].cls[2], cx2, fh, fw, cx3, mp.im2col);
+
+ /* Copy to output arrays (CHW interleaved across scales) */
+ for (int c = 0; c < bbox_ch; c++)
+ memcpy(bbox_out + c * total_anchors + offset,
+ bx3 + c * spatial, spatial * sizeof(float));
+ for (int c = 0; c < cls_ch; c++)
+ memcpy(cls_out + c * total_anchors + offset,
+ cx3 + c * spatial, spatial * sizeof(float));
+
+ offset += spatial;
+ }
+
+ #undef CUR
+ #undef NEXT
+ #undef SWAP
+ return total_anchors;
+}
diff --git a/nn2/src/nn2.c b/nn2/src/nn2.c
new file mode 100644
index 0000000..4988f7b
--- /dev/null
+++ b/nn2/src/nn2.c
@@ -0,0 +1,350 @@
+/*
+ * nn2.c — Public API: init, detect, free.
+ *
+ * Preprocessing: resize + normalize (0-255 → 0-1) + HWC→CHW.
+ */
+
+#include "nn2_internal.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+
+#ifdef __AVX2__
+#include <immintrin.h>
+#endif
+
+const char* nn2_version(void) { return "0.1.0"; }
+
+/* Declared in net.c */
+int nn2_load_weights(NN2* ctx, const char* path);
+
+NN2* nn2_init(const char* weights_path, int n_threads)
+{
+ NN2* ctx = (NN2*)calloc(1, sizeof(NN2));
+ if (!ctx) return NULL;
+
+ ctx->conf_thresh = 0.25f;
+ ctx->nms_thresh = 0.45f;
+
+ /* DFL weights: [0, 1, 2, ..., 15] */
+ for (int i = 0; i < NN2_REG_MAX; i++)
+ ctx->dfl_weight[i] = (float)i;
+
+ /* Load weights */
+ if (nn2_load_weights(ctx, weights_path) != 0) {
+ free(ctx);
+ return NULL;
+ }
+
+ /* Allocate workspace: 256MB for 640, 64MB for 320 */
+ ctx->ws_size = (ctx->input_size >= 640) ? (256 << 20) : (64 << 20);
+ ctx->workspace = (float*)malloc(ctx->ws_size);
+ if (!ctx->workspace) {
+ fprintf(stderr, "nn2: workspace alloc failed\n");
+ nn2_free(ctx);
+ return NULL;
+ }
+
+ /* Pre-pack weight matrices for all conv layers (BLIS-style A-packing).
+ * Eliminates stride-lda access during GEMM — weights become sequential in memory. */
+ {
+ /* Helper to pack a ConvLayer's weights */
+ #define PACK_CONV(layer) do { \
+ int _K = (layer)->cin * (layer)->k * (layer)->k; \
+ (layer)->w_packed = nn2_pack_weight_a((layer)->w, (layer)->cout, _K); \
+ } while(0)
+
+ for (int i = 0; i < 5; i++) PACK_CONV(&ctx->bb_conv[i]);
+ for (int i = 0; i < 4; i++) {
+ PACK_CONV(&ctx->bb_c2f[i].cv1);
+ PACK_CONV(&ctx->bb_c2f[i].cv2);
+ for (int j = 0; j < ctx->bb_c2f[i].n; j++) {
+ PACK_CONV(&ctx->bb_c2f[i].m[j].cv1);
+ PACK_CONV(&ctx->bb_c2f[i].m[j].cv2);
+ }
+ }
+ PACK_CONV(&ctx->sppf_cv1); PACK_CONV(&ctx->sppf_cv2);
+ for (int i = 0; i < 4; i++) {
+ PACK_CONV(&ctx->nk_c2f[i].cv1);
+ PACK_CONV(&ctx->nk_c2f[i].cv2);
+ for (int j = 0; j < ctx->nk_c2f[i].n; j++) {
+ PACK_CONV(&ctx->nk_c2f[i].m[j].cv1);
+ PACK_CONV(&ctx->nk_c2f[i].m[j].cv2);
+ }
+ }
+ for (int i = 0; i < 2; i++) PACK_CONV(&ctx->nk_conv[i]);
+ for (int s = 0; s < 3; s++) {
+ for (int j = 0; j < 3; j++) { PACK_CONV(&ctx->head[s].bbox[j]); PACK_CONV(&ctx->head[s].cls[j]); }
+ }
+ #undef PACK_CONV
+ }
+
+ /* Detect fused normalization: if first conv weights are very small (< 0.1),
+ * they were pre-divided by 255 at export time → skip normalize in preprocessing. */
+ {
+ float maxw = 0;
+ int wsize = ctx->bb_conv[0].cout * ctx->bb_conv[0].cin *
+ ctx->bb_conv[0].k * ctx->bb_conv[0].k;
+ for (int i = 0; i < wsize; i++) {
+ float a = ctx->bb_conv[0].w[i];
+ if (a < 0) a = -a;
+ if (a > maxw) maxw = a;
+ }
+ ctx->_fused_norm = (maxw < 0.5f) ? 1 : 0; /* normal weights are ~1-20 range */
+ if (ctx->_fused_norm)
+ fprintf(stderr, "nn2: detected fused normalization in weights\n");
+ }
+
+ /* Thread pool */
+ ctx->n_threads = n_threads;
+ nn2_tp_init(n_threads);
+
+ fprintf(stderr, "nn2: loaded model (classes=%d, input=%d, threads=%d)\n",
+ ctx->num_classes, ctx->input_size, nn2_tp_num_threads());
+
+ return ctx;
+}
+
+/* ============ Preprocessing ============ */
+
+typedef struct { const uint8_t* rgb; float* ch0; float* ch1; float* ch2;
+ int src_w,src_h,S,new_w,pad_x,pad_y; float inv_scale,inv255; } PPCtx;
+
+void preprocess_worker(void* arg, int y_start, int y_end) {
+ PPCtx* p = (PPCtx*)arg;
+ for (int y = y_start; y < y_end; y++) {
+ float sy = y * p->inv_scale;
+ int iy = (int)sy; float fy = sy - iy;
+ if (iy >= p->src_h - 1) { iy = p->src_h - 2; fy = 1.0f; }
+ float fy1 = 1.0f - fy;
+ int dy = y + p->pad_y;
+ if (dy >= p->S) continue;
+ const uint8_t* row0 = p->rgb + iy * p->src_w * 3;
+ const uint8_t* row1 = row0 + p->src_w * 3;
+ for (int x = 0; x < p->new_w; x++) {
+ float sx = x * p->inv_scale;
+ int ix = (int)sx; float fx = sx - ix;
+ if (ix >= p->src_w - 1) { ix = p->src_w - 2; fx = 1.0f; }
+ float fx1 = 1.0f - fx;
+ int dx = x + p->pad_x;
+ if (dx >= p->S) continue;
+ int idx = dy * p->S + dx;
+ const uint8_t* p00 = row0+ix*3, *p01 = p00+3;
+ const uint8_t* p10 = row1+ix*3, *p11 = p10+3;
+ float w00=fx1*fy1, w01=fx*fy1, w10=fx1*fy, w11=fx*fy;
+ p->ch0[idx] = (p00[0]*w00+p01[0]*w01+p10[0]*w10+p11[0]*w11) * p->inv255;
+ p->ch1[idx] = (p00[1]*w00+p01[1]*w01+p10[1]*w10+p11[1]*w11) * p->inv255;
+ p->ch2[idx] = (p00[2]*w00+p01[2]*w01+p10[2]*w10+p11[2]*w11) * p->inv255;
+ }
+ }
+}
+
+static void preprocess(const uint8_t* rgb_hwc, int src_w, int src_h,
+ int dst_size, float* chw_out, int fused_norm)
+{
+ float scale = (float)dst_size / (src_w > src_h ? src_w : src_h);
+ int new_w = (int)(src_w * scale);
+ int new_h = (int)(src_h * scale);
+ int pad_x = (dst_size - new_w) / 2;
+ int pad_y = (dst_size - new_h) / 2;
+ int S = dst_size;
+ /* If normalization fused into first conv, skip /255 here — just cast to float */
+ float inv255 = fused_norm ? 1.0f : (1.0f / 255.0f);
+ float gray = fused_norm ? 114.0f : (114.0f / 255.0f);
+
+ /* Init gray padding */
+ int total = 3 * S * S;
+ int i = 0;
+#ifdef __AVX2__
+ __m256 vg = _mm256_set1_ps(gray);
+ for (; i + 8 <= total; i += 8)
+ _mm256_storeu_ps(chw_out + i, vg);
+#endif
+ for (; i < total; i++)
+ chw_out[i] = gray;
+
+ /* HWC→CHW + normalize (with bilinear resize if needed) */
+ float inv_scale = 1.0f / scale;
+ float* ch0 = chw_out;
+ float* ch1 = chw_out + S * S;
+ float* ch2 = chw_out + 2 * S * S;
+
+ /* Fast path: scale is exactly 1.0 (input fits width) */
+ if (new_w == src_w && scale > 0.999f && scale < 1.001f) {
+ for (int y = 0; y < new_h; y++) {
+ int dy = y + pad_y;
+ const uint8_t* row = rgb_hwc + y * src_w * 3;
+ int base = dy * S + pad_x;
+ int x = 0;
+#ifdef __AVX2__
+ /* Process 8 pixels: load 24 bytes RGB, deinterleave, convert float, normalize */
+ __m256 vinv = _mm256_set1_ps(1.0f / 255.0f);
+ for (; x + 8 <= new_w; x += 8) {
+ /* Load 8 RGB pixels (24 bytes) and deinterleave to R,G,B */
+ const uint8_t* p = row + x * 3;
+ /* Manual deinterleave: extract R,G,B into separate int arrays */
+ __m256i r_i32 = _mm256_setr_epi32(p[0], p[3], p[6], p[9], p[12], p[15], p[18], p[21]);
+ __m256i g_i32 = _mm256_setr_epi32(p[1], p[4], p[7], p[10], p[13], p[16], p[19], p[22]);
+ __m256i b_i32 = _mm256_setr_epi32(p[2], p[5], p[8], p[11], p[14], p[17], p[20], p[23]);
+ __m256 rf = _mm256_mul_ps(_mm256_cvtepi32_ps(r_i32), vinv);
+ __m256 gf = _mm256_mul_ps(_mm256_cvtepi32_ps(g_i32), vinv);
+ __m256 bf = _mm256_mul_ps(_mm256_cvtepi32_ps(b_i32), vinv);
+ _mm256_storeu_ps(ch0 + base + x, rf);
+ _mm256_storeu_ps(ch1 + base + x, gf);
+ _mm256_storeu_ps(ch2 + base + x, bf);
+ }
+#endif
+ for (; x < new_w; x++) {
+ const uint8_t* p = row + x * 3;
+ ch0[base + x] = p[0] * inv255;
+ ch1[base + x] = p[1] * inv255;
+ ch2[base + x] = p[2] * inv255;
+ }
+ }
+ } else {
+ /* General bilinear resize path — parallelized across rows */
+ typedef struct { const uint8_t* rgb; float* ch0; float* ch1; float* ch2;
+ int src_w,src_h,S,new_w,pad_x,pad_y; float inv_scale,inv255; } PPCtx;
+ /* Worker declared at file scope below */
+ PPCtx pp = {rgb_hwc, ch0, ch1, ch2, src_w, src_h, S, new_w, pad_x, pad_y, inv_scale, inv255};
+ nn2_tp_parallel_for(preprocess_worker, &pp, new_h, new_h > 60 ? new_h / 6 : 1);
+ }
+ return;
+ /* Dead code — original loop kept for reference */
+ {
+ int new_h_unused = new_h;
+ (void)new_h_unused;
+ for (int y = 0; y < new_h; y++) {
+ float sy = y * inv_scale;
+ int iy = (int)sy;
+ float fy = sy - iy;
+ if (iy >= src_h - 1) { iy = src_h - 2; fy = 1.0f; }
+ float fy1 = 1.0f - fy;
+ int dy = y + pad_y;
+ if (dy >= S) continue;
+
+ const uint8_t* row0 = rgb_hwc + iy * src_w * 3;
+ const uint8_t* row1 = row0 + src_w * 3;
+
+ for (int x = 0; x < new_w; x++) {
+ float sx = x * inv_scale;
+ int ix = (int)sx;
+ float fx = sx - ix;
+ if (ix >= src_w - 1) { ix = src_w - 2; fx = 1.0f; }
+ float fx1 = 1.0f - fx;
+ int dx = x + pad_x;
+ if (dx >= S) continue;
+
+ int idx = dy * S + dx;
+ const uint8_t* p00 = row0 + ix * 3;
+ const uint8_t* p01 = p00 + 3;
+ const uint8_t* p10 = row1 + ix * 3;
+ const uint8_t* p11 = p10 + 3;
+
+ float w00 = fx1 * fy1, w01 = fx * fy1;
+ float w10 = fx1 * fy, w11 = fx * fy;
+
+ ch0[idx] = (p00[0]*w00 + p01[0]*w01 + p10[0]*w10 + p11[0]*w11) * inv255;
+ ch1[idx] = (p00[1]*w00 + p01[1]*w01 + p10[1]*w10 + p11[1]*w11) * inv255;
+ ch2[idx] = (p00[2]*w00 + p01[2]*w01 + p10[2]*w10 + p11[2]*w11) * inv255;
+ }
+ }
+ }
+}
+
+/* ============ Detection ============ */
+
+int nn2_detect(NN2* ctx, const uint8_t* rgb_hwc, int width, int height,
+ NN2Det* out, int max_det)
+{
+ int S = ctx->input_size;
+
+ /* Preprocess: letterbox + normalize + HWC→CHW */
+ float* input = ctx->workspace;
+ preprocess(rgb_hwc, width, height, S, input, ctx->_fused_norm);
+
+ /* Compute scale for mapping back to original coords */
+ float scale = (float)S / (width > height ? width : height);
+ int new_w = (int)(width * scale);
+ int new_h = (int)(height * scale);
+ float pad_x = (float)((S - new_w) / 2);
+ float pad_y = (float)((S - new_h) / 2);
+
+ /* Forward pass */
+ int total_anchors = 0;
+ for (int s = 0; s < 3; s++) {
+ int gs = S / (8 << s);
+ total_anchors += gs * gs;
+ }
+
+ /* Use end of workspace for bbox/cls feat (avoid malloc per frame) */
+ size_t feat_offset = ctx->ws_size / sizeof(float)
+ - (4 * NN2_REG_MAX + ctx->num_classes) * total_anchors;
+ float* bbox_feat = ctx->workspace + feat_offset;
+ float* cls_feat = bbox_feat + 4 * NN2_REG_MAX * total_anchors;
+
+ /* Shift workspace past input to avoid overwriting */
+ float* saved_ws = ctx->workspace;
+ size_t saved_sz = ctx->ws_size;
+ ctx->workspace = saved_ws + 3 * S * S;
+ ctx->ws_size = saved_sz - 3 * S * S * sizeof(float);
+
+ nn2_forward(ctx, input, bbox_feat, cls_feat);
+
+ ctx->workspace = saved_ws;
+ ctx->ws_size = saved_sz;
+
+ /* Decode + NMS (use stack for raw dets — max ~2100 for 320, ~8400 for 640) */
+ NN2Det raw[NN2_MAX_DET * 2]; /* generous stack buffer */
+ int max_raw = sizeof(raw) / sizeof(raw[0]);
+ int n = nn2_decode(bbox_feat, cls_feat, ctx->num_classes, S,
+ ctx->conf_thresh, ctx->dfl_weight, raw, max_raw);
+ n = nn2_nms(raw, n, ctx->nms_thresh);
+
+ /* Map coords back to original image */
+ int n_out = n < max_det ? n : max_det;
+ for (int i = 0; i < n_out; i++) {
+ out[i] = raw[i];
+ out[i].x1 = (out[i].x1 - pad_x) / scale;
+ out[i].y1 = (out[i].y1 - pad_y) / scale;
+ out[i].x2 = (out[i].x2 - pad_x) / scale;
+ out[i].y2 = (out[i].y2 - pad_y) / scale;
+ }
+
+ return n_out;
+}
+
+void nn2_set_conf_threshold(NN2* ctx, float threshold) { ctx->conf_thresh = threshold; }
+void nn2_set_nms_threshold(NN2* ctx, float threshold) { ctx->nms_thresh = threshold; }
+void nn2_set_input_size(NN2* ctx, int size) { ctx->input_size = size; }
+
+/* ============ Cleanup ============ */
+
+static void free_conv(ConvLayer* L) { free(L->w); _aligned_free(L->w_packed); free(L->b); free(L->w_wino); }
+static void free_c2f(C2fBlock* blk) {
+ free_conv(&blk->cv1);
+ free_conv(&blk->cv2);
+ for (int i = 0; i < blk->n; i++) {
+ free_conv(&blk->m[i].cv1);
+ free_conv(&blk->m[i].cv2);
+ }
+}
+
+void nn2_free(NN2* ctx)
+{
+ if (!ctx) return;
+ for (int i = 0; i < 5; i++) free_conv(&ctx->bb_conv[i]);
+ for (int i = 0; i < 4; i++) free_c2f(&ctx->bb_c2f[i]);
+ free_conv(&ctx->sppf_cv1);
+ free_conv(&ctx->sppf_cv2);
+ for (int i = 0; i < 4; i++) free_c2f(&ctx->nk_c2f[i]);
+ for (int i = 0; i < 2; i++) free_conv(&ctx->nk_conv[i]);
+ for (int s = 0; s < 3; s++) {
+ for (int j = 0; j < 3; j++) free_conv(&ctx->head[s].bbox[j]);
+ for (int j = 0; j < 3; j++) free_conv(&ctx->head[s].cls[j]);
+ }
+ free(ctx->workspace);
+ nn2_tp_destroy();
+ free(ctx);
+}
diff --git a/nn2/src/nn2_antispoof_ops.h b/nn2/src/nn2_antispoof_ops.h
new file mode 100644
index 0000000..f025c03
--- /dev/null
+++ b/nn2/src/nn2_antispoof_ops.h
@@ -0,0 +1,39 @@
+/*
+ * nn2_antispoof_ops.h — Internal ops added for MiniFASNet.
+ * Not exposed in the public header.
+ */
+
+#ifndef NN2_ANTISPOOF_OPS_H
+#define NN2_ANTISPOOF_OPS_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* PReLU on a (C, H*W) tensor, per-channel alpha. */
+void nn2_prelu(float* x, const float* alpha, int C, int HW);
+
+/* 1D PReLU after Linear: per-element alpha[N]. */
+void nn2_prelu_1d(float* x, const float* alpha, int N);
+
+/* Global avg pool: (C, H*W) → (C,) — mean over spatial. */
+void nn2_global_avg_pool(const float* x, int C, int HW, float* out);
+
+/* Per-channel scale: x[c, :] *= scale[c] in place. */
+void nn2_channel_mul(float* x, const float* scale, int C, int HW);
+
+/* In-place elementwise add: out[i] += in[i]. */
+void nn2_add_inplace(float* out, const float* in, int N);
+
+/* Dense matmul: y = W * x + b, W is [out_f, in_f] row-major. */
+void nn2_linear(const float* x, const float* W, const float* b,
+ int in_f, int out_f, float* y);
+
+/* Softmax over N (typically 3 for antispoof). */
+void nn2_softmax(const float* x, int N, float* y);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* NN2_ANTISPOOF_OPS_H */
diff --git a/nn2/src/nn2_internal.h b/nn2/src/nn2_internal.h
new file mode 100644
index 0000000..da421d7
--- /dev/null
+++ b/nn2/src/nn2_internal.h
@@ -0,0 +1,184 @@
+/*
+ * nn2_internal.h — Internal types and function declarations.
+ */
+
+#ifndef NN2_INTERNAL_H
+#define NN2_INTERNAL_H
+
+#include "nn2.h"
+#include <stddef.h>
+
+/* ============ GEMM config ============ */
+#define NN2_MR 6
+#define NN2_NR 16
+
+/* ============ YOLO config ============ */
+#define NN2_REG_MAX 16
+#define NN2_MAX_ANCHORS 8400 /* 80*80 + 40*40 + 20*20 at 640 */
+#define NN2_MAX_DET 300
+
+/* ============ Convolution layer (fused Conv+BN) ============ */
+typedef struct {
+ float* w; /* [cout, cin*k*k] FP32 row-major */
+ float* w_packed; /* A-packed for GEMM: [ceil(cout/MR)][K][MR] or NULL */
+ float* b; /* [cout] fused bias */
+ float* w_wino; /* [16][cout][cin] Winograd-transformed, or NULL */
+ /* INT8 quantized path */
+ void* w_int8_packed; /* packed INT8 weights (VNNI format), or NULL */
+ int32_t* col_sums; /* [cout] compensation: 128 * sum(w) */
+ float* w_scales; /* [cout] per-channel weight scale */
+ float act_in_scale; /* input activation scale */
+ float act_out_scale; /* output activation scale */
+ int cout, cin, k, stride, pad;
+ int act; /* 0=none, 1=SiLU, 2=sigmoid */
+} ConvLayer;
+
+/* ============ C2f block ============ */
+typedef struct {
+ ConvLayer cv1; /* 1x1: in → 2*c */
+ ConvLayer cv2; /* 1x1: (2+n)*c → out */
+ struct {
+ ConvLayer cv1; /* 3x3: c → c */
+ ConvLayer cv2; /* 3x3: c → c */
+ } m[3]; /* max 3 bottlenecks */
+ int n; /* actual bottleneck count */
+ int c; /* hidden channels = out/2 */
+ int shortcut; /* residual in bottleneck */
+} C2fBlock;
+
+/* ============ Full model ============ */
+struct NN2 {
+ /* Backbone */
+ ConvLayer bb_conv[5]; /* 0: 3→16, 1: 16→32, 2: 32→64, 3: 64→128, 4: 128→256 */
+ C2fBlock bb_c2f[4]; /* 0: 32→32(n=1), 1: 64→64(n=2), 2: 128→128(n=2), 3: 256→256(n=1) */
+ ConvLayer sppf_cv1; /* 256→128 */
+ ConvLayer sppf_cv2; /* 512→256 */
+
+ /* Neck */
+ C2fBlock nk_c2f[4]; /* 0: 384→128, 1: 192→64, 2: 192→128, 3: 384→256 */
+ ConvLayer nk_conv[2]; /* 0: 64→64 s=2, 1: 128→128 s=2 */
+
+ /* Head (3 scales) */
+ struct {
+ ConvLayer bbox[3]; /* conv3x3, conv3x3, conv1x1(→64) */
+ ConvLayer cls[3]; /* conv3x3, conv3x3, conv1x1(→nc) */
+ } head[3];
+
+ /* DFL weight: softmax over reg_max bins → weighted sum */
+ float dfl_weight[NN2_REG_MAX]; /* [0, 1, 2, ..., 15] */
+
+ /* Config */
+ int num_classes;
+ int input_size; /* 320 or 640 */
+ float conf_thresh;
+ float nms_thresh;
+
+ /* Workspace */
+ float* workspace; /* big slab for all temporaries */
+ size_t ws_size;
+ int n_threads;
+ int _fused_norm; /* 1 if normalization fused into first conv weights */
+};
+
+/* ============ GEMM ============ */
+void nn2_sgemm(int M, int K, int N,
+ const float* A, int lda,
+ const float* B, int ldb,
+ float* C, int ldc);
+
+/* Pre-pack weight matrix A for faster GEMM */
+float* nn2_pack_weight_a(const float* A, int M, int K);
+
+/* Fused GEMM: C = A×B + bias + activation, in one memory pass */
+void nn2_sgemm_bias_act(int M, int K, int N,
+ const float* A, int lda,
+ const float* B, int ldb,
+ float* C, int ldc,
+ const float* bias, int act);
+/* Fused GEMM with pre-packed A (sequential weight access) */
+void nn2_sgemm_bias_act_packed(int M, int K, int N,
+ const float* Ap, const float* B,
+ float* C, int ldc,
+ const float* bias, int act);
+/* Fused GEMM + bias + act + residual add (saves 2 memory passes) */
+void nn2_sgemm_bias_act_res_packed(int M, int K, int N,
+ const float* Ap, const float* B,
+ float* C, int ldc,
+ const float* bias, int act,
+ const float* residual, int ldr);
+
+/* ============ Conv ============ */
+void nn2_im2col(const float* in, int C, int H, int W,
+ int kH, int kW, int stride, int pad,
+ float* col);
+
+/* Conv + bias + activation. out must be pre-allocated [cout, Hout*Wout]. */
+void nn2_conv2d(const ConvLayer* layer, const float* in, int H, int W,
+ float* out, float* col_buf);
+
+/* ============ Ops ============ */
+void nn2_silu_inplace(float* x, int n);
+void nn2_sigmoid_inplace(float* x, int n);
+void nn2_upsample_2x(const float* in, int C, int H, int W, float* out);
+void nn2_concat(const float* a, int ca, const float* b, int cb,
+ int H, int W, float* out);
+void nn2_maxpool2d(const float* in, int C, int H, int W,
+ int k, int stride, int pad, float* out);
+void nn2_dwconv2d(const float* in, const float* w, const float* bias,
+ int C, int H, int W, int k, int stride, int pad,
+ int act, float* out); /* depthwise conv: group=C */
+void nn2_channel_shuffle(const float* in, int C, int H, int W,
+ int groups, float* out);
+
+/* ============ Decode ============ */
+int nn2_decode(const float* bbox_feat, const float* cls_feat,
+ int num_classes, int input_size, float conf_thresh,
+ const float* dfl_w, NN2Det* dets, int max_det);
+
+int nn2_nms(NN2Det* dets, int n, float iou_thresh);
+
+/* ============ Thread pool ============ */
+typedef void (*nn2_task_fn)(void* ctx, int start, int end);
+void nn2_tp_init(int n_threads);
+void nn2_tp_parallel_for(nn2_task_fn fn, void* ctx, int total, int grain);
+void nn2_tp_destroy(void);
+int nn2_tp_num_threads(void);
+int nn2_tp_dispatch_count(void);
+void nn2_tp_reset_dispatch_count(void);
+
+/* ============ Winograd ============ */
+void nn2_prepare_winograd(ConvLayer* L);
+void nn2_winograd_transform_weights(const float* W, int Cout, int Cin, float* U);
+void nn2_winograd_conv3x3(const float* input, int Cin, int H, int W,
+ const float* U, const float* bias, int Cout, int act,
+ float* output, float* workspace);
+
+/* ============ INT8 GEMM ============ */
+void nn2_int8_pack_weights(const int8_t* w, int K, int Cout, void* out, int32_t* col_sums);
+int nn2_int8_packed_size(int K, int Cout);
+void nn2_int8_gemm_fused(const int8_t* A, int M, int K, int N,
+ const void* B_packed, const int32_t* col_sums,
+ const float* w_scales, const float* bias,
+ float act_scale, float out_scale, int act_type,
+ float* output);
+
+/* ============ Implicit im2col conv (no buffer, loads from input directly) ============ */
+void nn2_conv3x3_s1_implicit(const float* input, const float* weight, const float* bias,
+ int Cin, int Cout, int H, int W, int act, float* output,
+ const float* w_packed);
+void nn2_conv3x3_s2_implicit(const float* input, const float* weight, const float* bias,
+ int Cin, int Cout, int H, int W, int act, float* output);
+
+/* ============ Cross-layer fused bottleneck ============ */
+void nn2_bottleneck_fused(const float* input, int Cin, int H, int W,
+ const ConvLayer* cv1, const ConvLayer* cv2,
+ const float* residual, float* output, float* line_buf);
+
+/* ============ Fused conv (no im2col buffer needed) ============ */
+void nn2_conv3x3_s1_fused(const ConvLayer* L, const float* in, int H, int W, float* out);
+void nn2_conv3x3_s2_fused(const ConvLayer* L, const float* in, int H, int W, float* out);
+
+/* ============ Net forward ============ */
+int nn2_forward(NN2* ctx, const float* input, float* bbox_out, float* cls_out);
+
+#endif /* NN2_INTERNAL_H */
diff --git a/nn2/src/nvr.c b/nn2/src/nvr.c
new file mode 100644
index 0000000..09518c4
--- /dev/null
+++ b/nn2/src/nvr.c
@@ -0,0 +1,223 @@
+/*
+ * nvr.c — Multi-camera NVR pipeline with motion gating.
+ *
+ * Architecture:
+ * - Single NN2 model shared across all cameras
+ * - Round-robin frame processing with skip-N
+ * - Simple motion detection: frame difference > threshold
+ * - Callback on detection events
+ */
+
+#include "nn2_nvr.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+
+#ifdef _WIN32
+#include <windows.h>
+static double get_ms(void) {
+ LARGE_INTEGER f, c;
+ QueryPerformanceFrequency(&f);
+ QueryPerformanceCounter(&c);
+ return (double)c.QuadPart / f.QuadPart * 1000.0;
+}
+#else
+#include <time.h>
+static double get_ms(void) {
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return ts.tv_sec * 1000.0 + ts.tv_nsec / 1e6;
+}
+#endif
+
+typedef struct {
+ int id;
+ char name[64];
+ int frame_count;
+ int det_count;
+ /* Previous frame for motion detection (downsampled grayscale) */
+ uint8_t* prev_gray; /* 80×60 downsampled */
+ int prev_w, prev_h;
+ int active;
+} CameraState;
+
+struct NN2NVR {
+ NN2* model;
+ CameraState cameras[NN2_NVR_MAX_CAMERAS];
+ int n_cameras;
+ int skip_frames; /* process every N-th frame */
+ float motion_thresh; /* 0 = disabled */
+ float conf_thresh;
+ nn2_nvr_callback callback;
+ void* cb_userdata;
+ /* Stats */
+ int total_frames;
+ int total_inferences;
+ int total_detections;
+ double total_inference_ms;
+};
+
+NN2NVR* nn2_nvr_create(const char* weights_path, int n_threads)
+{
+ NN2NVR* nvr = (NN2NVR*)calloc(1, sizeof(NN2NVR));
+ if (!nvr) return NULL;
+
+ nvr->model = nn2_init(weights_path, n_threads);
+ if (!nvr->model) { free(nvr); return NULL; }
+
+ nvr->skip_frames = 5;
+ nvr->motion_thresh = 0.0f; /* disabled by default */
+ nvr->conf_thresh = 0.25f;
+ nn2_set_conf_threshold(nvr->model, nvr->conf_thresh);
+
+ return nvr;
+}
+
+int nn2_nvr_add_camera(NN2NVR* nvr, int cam_id, const char* name)
+{
+ if (nvr->n_cameras >= NN2_NVR_MAX_CAMERAS) return -1;
+
+ CameraState* cam = &nvr->cameras[nvr->n_cameras++];
+ cam->id = cam_id;
+ strncpy(cam->name, name ? name : "cam", sizeof(cam->name) - 1);
+ cam->active = 1;
+ cam->prev_gray = NULL;
+ cam->prev_w = 80;
+ cam->prev_h = 60;
+
+ return 0;
+}
+
+void nn2_nvr_set_callback(NN2NVR* nvr, nn2_nvr_callback cb, void* userdata)
+{
+ nvr->callback = cb;
+ nvr->cb_userdata = userdata;
+}
+
+void nn2_nvr_set_skip_frames(NN2NVR* nvr, int skip)
+{
+ nvr->skip_frames = (skip > 0) ? skip : 1;
+}
+
+void nn2_nvr_set_motion_threshold(NN2NVR* nvr, float thresh)
+{
+ nvr->motion_thresh = thresh;
+}
+
+void nn2_nvr_set_conf_threshold(NN2NVR* nvr, float thresh)
+{
+ nvr->conf_thresh = thresh;
+ nn2_set_conf_threshold(nvr->model, thresh);
+}
+
+/* Simple motion detection: compare downsampled grayscale frames */
+static int detect_motion(CameraState* cam, const uint8_t* rgb, int w, int h,
+ float threshold)
+{
+ if (threshold <= 0.0f) return 1; /* motion detection disabled */
+
+ int dw = cam->prev_w, dh = cam->prev_h;
+ int pixels = dw * dh;
+
+ /* Allocate prev frame if needed */
+ if (!cam->prev_gray) {
+ cam->prev_gray = (uint8_t*)calloc(pixels, 1);
+ }
+
+ /* Downsample current frame to grayscale */
+ uint8_t* curr = (uint8_t*)malloc(pixels);
+ float sx = (float)w / dw, sy = (float)h / dh;
+ for (int y = 0; y < dh; y++) {
+ int iy = (int)(y * sy);
+ if (iy >= h) iy = h - 1;
+ for (int x = 0; x < dw; x++) {
+ int ix = (int)(x * sx);
+ if (ix >= w) ix = w - 1;
+ const uint8_t* p = rgb + (iy * w + ix) * 3;
+ curr[y * dw + x] = (uint8_t)((p[0] * 77 + p[1] * 150 + p[2] * 29) >> 8);
+ }
+ }
+
+ /* Frame difference */
+ int diff_sum = 0;
+ for (int i = 0; i < pixels; i++)
+ diff_sum += abs((int)curr[i] - (int)cam->prev_gray[i]);
+
+ float avg_diff = (float)diff_sum / pixels;
+
+ /* Update prev */
+ memcpy(cam->prev_gray, curr, pixels);
+ free(curr);
+
+ return (avg_diff > threshold * 255.0f);
+}
+
+static CameraState* find_camera(NN2NVR* nvr, int cam_id)
+{
+ for (int i = 0; i < nvr->n_cameras; i++)
+ if (nvr->cameras[i].id == cam_id) return &nvr->cameras[i];
+ return NULL;
+}
+
+int nn2_nvr_push_frame(NN2NVR* nvr, int cam_id,
+ const uint8_t* rgb_hwc, int width, int height)
+{
+ CameraState* cam = find_camera(nvr, cam_id);
+ if (!cam || !cam->active) return 0;
+
+ nvr->total_frames++;
+ cam->frame_count++;
+
+ /* Skip frames */
+ if ((cam->frame_count % nvr->skip_frames) != 0)
+ return 0;
+
+ /* Motion check */
+ if (!detect_motion(cam, rgb_hwc, width, height, nvr->motion_thresh))
+ return 0;
+
+ /* Run detection */
+ NN2Det dets[50];
+ double t0 = get_ms();
+ int n = nn2_detect(nvr->model, rgb_hwc, width, height, dets, 50);
+ double ms = get_ms() - t0;
+
+ nvr->total_inferences++;
+ nvr->total_inference_ms += ms;
+ nvr->total_detections += n;
+ cam->det_count += n;
+
+ /* Fire callback */
+ if (n > 0 && nvr->callback) {
+ NN2NVREvent event;
+ event.cam_id = cam_id;
+ event.det_count = n;
+ memcpy(event.dets, dets, n * sizeof(NN2Det));
+ event.timestamp_ms = get_ms();
+ event.inference_ms = ms;
+ nvr->callback(&event, nvr->cb_userdata);
+ }
+
+ return 1;
+}
+
+void nn2_nvr_stats(const NN2NVR* nvr, int* total_frames, int* total_detections,
+ double* avg_inference_ms)
+{
+ if (total_frames) *total_frames = nvr->total_frames;
+ if (total_detections) *total_detections = nvr->total_detections;
+ if (avg_inference_ms) {
+ *avg_inference_ms = (nvr->total_inferences > 0)
+ ? nvr->total_inference_ms / nvr->total_inferences : 0;
+ }
+}
+
+void nn2_nvr_free(NN2NVR* nvr)
+{
+ if (!nvr) return;
+ for (int i = 0; i < nvr->n_cameras; i++)
+ free(nvr->cameras[i].prev_gray);
+ nn2_free(nvr->model);
+ free(nvr);
+}
diff --git a/nn2/src/nvr_prod.c b/nn2/src/nvr_prod.c
new file mode 100644
index 0000000..21ad517
--- /dev/null
+++ b/nn2/src/nvr_prod.c
@@ -0,0 +1,554 @@
+/*
+ * nvr_prod.c — Production NVR server.
+ *
+ * Single binary: RTSP intake → smart pipeline → web dashboard → alerts.
+ *
+ * Usage:
+ * nn2_nvr_prod -w weights/yolov8n_320.bin -p 8080
+ * Then open http://localhost:8080 for dashboard.
+ *
+ * API:
+ * GET / — web dashboard (embedded HTML)
+ * GET /api/status — JSON: all cameras status, FPS, detections
+ * GET /api/cameras — JSON: camera list with config
+ * POST /api/camera/add — add RTSP camera {"url":"rtsp://...","name":"..."}
+ * POST /api/camera/del — remove camera {"id":0}
+ * POST /api/detect — upload image, get detections
+ * GET /api/events — recent detection events (last 100)
+ * GET /api/health — {"status":"ok"}
+ *
+ * Architecture:
+ * Main thread: HTTP server (handles API + dashboard)
+ * Camera threads: 1 per camera, ffmpeg RTSP → frame decode → smart pipeline
+ * Detection: shared nn2 model (thread-safe via mutex)
+ */
+
+#define STB_IMAGE_IMPLEMENTATION
+#include "stb_image.h"
+#include "nn2.h"
+#include "nn2_track.h"
+#include "nn2_count.h"
+#include "nn2_json.h"
+#include "nn2_nvr.h"
+#include "http_server.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#ifdef _WIN32
+#include <windows.h>
+#include <process.h>
+static double prod_now(void) {
+ static LARGE_INTEGER freq; static int init=0;
+ if(!init){QueryPerformanceFrequency(&freq);init=1;}
+ LARGE_INTEGER t; QueryPerformanceCounter(&t);
+ return (double)t.QuadPart/(double)freq.QuadPart;
+}
+#define MUTEX_T CRITICAL_SECTION
+#define MUTEX_INIT(m) InitializeCriticalSection(m)
+#define MUTEX_LOCK(m) EnterCriticalSection(m)
+#define MUTEX_UNLOCK(m) LeaveCriticalSection(m)
+#define MUTEX_DESTROY(m) DeleteCriticalSection(m)
+#else
+#include <pthread.h>
+#include <unistd.h>
+#define MUTEX_T pthread_mutex_t
+#define MUTEX_INIT(m) pthread_mutex_init(m, NULL)
+#define MUTEX_LOCK(m) pthread_mutex_lock(m)
+#define MUTEX_UNLOCK(m) pthread_mutex_unlock(m)
+#define MUTEX_DESTROY(m) pthread_mutex_destroy(m)
+#endif
+
+/* ============ Camera state ============ */
+
+#define MAX_PROD_CAMERAS 32
+#define MAX_EVENTS 200
+
+typedef struct {
+ int id;
+ int active;
+ char name[64];
+ char url[512]; /* RTSP URL or "test" for synthetic */
+
+ /* Stats */
+ int frame_count;
+ int detect_count;
+ int skip_count;
+ int track_count;
+ double total_inference_ms;
+ double last_fps;
+ int last_n_dets;
+
+ /* Tracking */
+ NN2Tracker* tracker;
+ NN2Track tracks[64];
+ int n_tracks;
+
+ /* Motion gate */
+ uint8_t* prev_frame;
+ int prev_w, prev_h;
+ int frames_since_detect;
+ int detect_interval;
+
+ /* Thread */
+#ifdef _WIN32
+ HANDLE thread;
+#else
+ pthread_t thread;
+#endif
+ volatile int running;
+} ProdCamera;
+
+/* Detection event for event log */
+typedef struct {
+ int cam_id;
+ char cam_name[64];
+ double timestamp;
+ int n_dets;
+ NN2Det dets[16];
+ float inference_ms;
+} DetEvent;
+
+/* ============ Server context ============ */
+
+typedef struct {
+ NN2* model;
+ MUTEX_T model_mutex; /* protect nn2_detect (not thread-safe) */
+
+ ProdCamera cameras[MAX_PROD_CAMERAS];
+ int n_cameras;
+
+ /* Event ring buffer */
+ DetEvent events[MAX_EVENTS];
+ int event_head;
+ int event_count;
+ MUTEX_T event_mutex;
+
+ /* Global stats */
+ int total_frames;
+ int total_detections;
+ double uptime_start;
+
+ /* Config */
+ int detect_interval;
+ float conf_threshold;
+ float motion_threshold;
+ char webhook_url[512];
+} ProdServer;
+
+static ProdServer g_server;
+
+/* ============ Event log ============ */
+
+static void push_event(ProdServer* s, const DetEvent* ev) {
+ MUTEX_LOCK(&s->event_mutex);
+ s->events[s->event_head] = *ev;
+ s->event_head = (s->event_head + 1) % MAX_EVENTS;
+ if (s->event_count < MAX_EVENTS) s->event_count++;
+ MUTEX_UNLOCK(&s->event_mutex);
+}
+
+/* ============ Camera frame processing ============ */
+
+static void process_camera_frame(ProdServer* srv, ProdCamera* cam,
+ const uint8_t* frame, int w, int h)
+{
+ cam->frame_count++;
+ cam->prev_w = w;
+ cam->prev_h = h;
+
+ /* Motion gate */
+ if (cam->prev_frame) {
+ int total = w * h * 3;
+ int diff = 0, stride = 8;
+ for (int i = 0; i < total; i += stride * 3) {
+ int d = abs((int)frame[i] - (int)cam->prev_frame[i]);
+ if (d > 25) diff++;
+ }
+ float score = (float)diff / (float)(total / (stride * 3));
+ if (score < (srv->motion_threshold > 0 ? srv->motion_threshold : 0.005f)) {
+ cam->skip_count++;
+ memcpy(cam->prev_frame, frame, w * h * 3);
+ return;
+ }
+ } else {
+ cam->prev_frame = (uint8_t*)malloc(w * h * 3);
+ }
+ memcpy(cam->prev_frame, frame, w * h * 3);
+
+ /* Temporal skip */
+ cam->frames_since_detect++;
+ if (cam->frames_since_detect < cam->detect_interval && cam->n_tracks > 0) {
+ /* Kalman predict */
+ for (int i = 0; i < cam->n_tracks; i++) {
+ cam->tracks[i].x1 += 0; /* predict keeps position (simple) */
+ cam->tracks[i].time_since_update++;
+ }
+ cam->track_count++;
+ cam->last_n_dets = cam->n_tracks;
+ return;
+ }
+
+ /* Full detection */
+ cam->frames_since_detect = 0;
+ NN2Det dets[64];
+ double t0 = prod_now();
+
+ MUTEX_LOCK(&srv->model_mutex);
+ int nd = nn2_detect(srv->model, frame, w, h, dets, 64);
+ MUTEX_UNLOCK(&srv->model_mutex);
+
+ double ms = (prod_now() - t0) * 1000.0;
+
+ cam->detect_count++;
+ cam->total_inference_ms += ms;
+ cam->last_n_dets = nd;
+ srv->total_frames++;
+ srv->total_detections += nd;
+
+ /* Update tracker */
+ if (cam->tracker)
+ cam->n_tracks = nn2_tracker_update(cam->tracker, dets, nd, cam->tracks, 64);
+
+ /* Log event if detections found */
+ if (nd > 0) {
+ DetEvent ev = {0};
+ ev.cam_id = cam->id;
+ strncpy(ev.cam_name, cam->name, 63);
+ ev.timestamp = prod_now() - srv->uptime_start;
+ ev.n_dets = nd > 16 ? 16 : nd;
+ memcpy(ev.dets, dets, ev.n_dets * sizeof(NN2Det));
+ ev.inference_ms = (float)ms;
+ push_event(srv, &ev);
+ }
+}
+
+/* ============ Embedded Web Dashboard ============ */
+
+static const char* DASHBOARD_HTML =
+"<!DOCTYPE html><html><head><meta charset='utf-8'>"
+"<title>nn2 NVR Dashboard</title>"
+"<meta name='viewport' content='width=device-width,initial-scale=1'>"
+"<style>"
+"*{margin:0;padding:0;box-sizing:border-box}"
+"body{font-family:system-ui,-apple-system,sans-serif;background:#0a0a0f;color:#e0e0e0}"
+"header{background:#12121a;padding:16px 24px;border-bottom:1px solid #2a2a3a;display:flex;justify-content:space-between;align-items:center}"
+"header h1{font-size:20px;font-weight:600;color:#fff}header h1 span{color:#4f9;font-weight:400}"
+".stats{display:flex;gap:24px;font-size:13px;color:#888}"
+".stats .val{color:#4f9;font-weight:600;font-size:15px}"
+".grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:16px;padding:20px}"
+".cam{background:#15151f;border:1px solid #2a2a3a;border-radius:8px;padding:16px;transition:border-color .2s}"
+".cam.active{border-color:#4f9}.cam.idle{border-color:#333}"
+".cam h3{font-size:14px;margin-bottom:8px;display:flex;justify-content:space-between}"
+".cam h3 .status{font-size:11px;padding:2px 8px;border-radius:10px;background:#1a2a1a;color:#4f9}"
+".cam h3 .status.idle{background:#2a2a1a;color:#fa3}"
+".cam .info{display:grid;grid-template-columns:1fr 1fr;gap:4px;font-size:12px;color:#999}"
+".cam .info .label{color:#666}.cam .info .value{text-align:right;color:#ccc}"
+".events{max-width:900px;margin:20px auto;padding:0 20px}"
+".events h2{font-size:16px;margin-bottom:12px;color:#fff}"
+".event{background:#15151f;border:1px solid #2a2a3a;border-radius:6px;padding:10px 14px;margin-bottom:6px;font-size:12px;display:flex;justify-content:space-between}"
+".event .time{color:#666;min-width:80px}.event .cam-name{color:#4f9;min-width:80px}"
+".event .dets{color:#ccc;flex:1;margin:0 12px}"
+"</style></head><body>"
+"<header><h1>nn2 <span>NVR Dashboard</span></h1>"
+"<div class='stats' id='gstats'></div></header>"
+"<div class='grid' id='cameras'></div>"
+"<div class='events'><h2>Recent Events</h2><div id='events'></div></div>"
+"<script>"
+"const cn=['person','bicycle','car','motorcycle','airplane','bus','train','truck'];"
+"function fmt(ms){return ms<1?ms.toFixed(2)+'ms':ms.toFixed(1)+'ms'}"
+"async function refresh(){"
+" try{"
+" let r=await fetch('/api/status');let d=await r.json();"
+" document.getElementById('gstats').innerHTML="
+" `<div>Cameras <span class='val'>${d.cameras_active}/${d.cameras_total}</span></div>`+"
+" `<div>Total Frames <span class='val'>${d.total_frames}</span></div>`+"
+" `<div>Detections <span class='val'>${d.total_detections}</span></div>`+"
+" `<div>Uptime <span class='val'>${Math.floor(d.uptime_s)}s</span></div>`;"
+" let h='';"
+" for(let c of d.cameras){"
+" let act=c.frame_count>0;let avgMs=c.detect_count>0?(c.total_inference_ms/c.detect_count):0;"
+" h+=`<div class='cam ${act?\"active\":\"idle\"}'>`+"
+" `<h3>${c.name} <span class='status ${act?\"\":\"idle\"}'>${act?'LIVE':'IDLE'}</span></h3>`+"
+" `<div class='info'>`+"
+" `<span class='label'>Frames</span><span class='value'>${c.frame_count}</span>`+"
+" `<span class='label'>Detections</span><span class='value'>${c.detect_count}</span>`+"
+" `<span class='label'>Skipped</span><span class='value'>${c.skip_count}</span>`+"
+" `<span class='label'>Tracked</span><span class='value'>${c.track_count}</span>`+"
+" `<span class='label'>Avg Inference</span><span class='value'>${fmt(avgMs)}</span>`+"
+" `<span class='label'>Objects</span><span class='value'>${c.last_n_dets}</span>`+"
+" `</div></div>`}"
+" document.getElementById('cameras').innerHTML=h;"
+" let er=await fetch('/api/events');let ev=await er.json();"
+" let eh='';"
+" for(let e of ev.events.slice(-20).reverse()){"
+" let ds=e.dets.map(d=>(cn[d.cls]||'obj')+' '+Math.round(d.score*100)+'%').join(', ');"
+" eh+=`<div class='event'><span class='time'>${e.timestamp.toFixed(1)}s</span>`+"
+" `<span class='cam-name'>${e.cam_name}</span>`+"
+" `<span class='dets'>${ds}</span>`+"
+" `<span>${fmt(e.inference_ms)}</span></div>`}"
+" document.getElementById('events').innerHTML=eh||'<div class=\"event\">No events yet</div>';"
+" }catch(e){}"
+"}"
+"setInterval(refresh,1000);refresh();"
+"</script></body></html>";
+
+/* ============ HTTP Handler ============ */
+
+static const char* coco_names[] = {
+ "person","bicycle","car","motorcycle","airplane","bus","train","truck","boat",
+ "traffic light","fire hydrant","stop sign","parking meter","bench","bird","cat",
+ "dog","horse","sheep","cow","elephant","bear","zebra","giraffe","backpack",
+ "umbrella","handbag","tie","suitcase","frisbee","skis","snowboard","sports ball",
+ "kite","baseball bat","baseball glove","skateboard","surfboard","tennis racket",
+ "bottle","wine glass","cup","fork","knife","spoon","bowl","banana","apple",
+ "sandwich","orange","broccoli","carrot","hot dog","pizza","donut","cake","chair",
+ "couch","potted plant","bed","dining table","toilet","tv","laptop","mouse",
+ "remote","keyboard","cell phone","microwave","oven","toaster","sink",
+ "refrigerator","book","clock","vase","scissors","teddy bear","hair drier","toothbrush"
+};
+
+static void nvr_http_handler(const HttpRequest* req, socket_t client, void* userdata)
+{
+ ProdServer* srv = (ProdServer*)userdata;
+
+ /* Dashboard */
+ if ((strcmp(req->path, "/") == 0 || strcmp(req->path, "/index.html") == 0)
+ && strcmp(req->method, "GET") == 0) {
+ http_send(client, 200, "text/html", DASHBOARD_HTML, (int)strlen(DASHBOARD_HTML));
+ return;
+ }
+
+ /* Health check */
+ if (strcmp(req->path, "/api/health") == 0) {
+ http_send_json(client, 200, "{\"status\":\"ok\",\"engine\":\"nn2\"}");
+ return;
+ }
+
+ /* Status — all cameras + global stats */
+ if (strcmp(req->path, "/api/status") == 0) {
+ char* json = (char*)malloc(srv->n_cameras * 512 + 512);
+ int n = sprintf(json,
+ "{\"cameras_total\":%d,\"cameras_active\":%d,"
+ "\"total_frames\":%d,\"total_detections\":%d,"
+ "\"uptime_s\":%.1f,\"cameras\":[",
+ srv->n_cameras, srv->n_cameras,
+ srv->total_frames, srv->total_detections,
+ prod_now() - srv->uptime_start);
+
+ for (int i = 0; i < srv->n_cameras; i++) {
+ ProdCamera* c = &srv->cameras[i];
+ n += sprintf(json + n,
+ "%s{\"id\":%d,\"name\":\"%s\",\"frame_count\":%d,"
+ "\"detect_count\":%d,\"skip_count\":%d,\"track_count\":%d,"
+ "\"total_inference_ms\":%.1f,\"last_n_dets\":%d}",
+ i > 0 ? "," : "", c->id, c->name, c->frame_count,
+ c->detect_count, c->skip_count, c->track_count,
+ c->total_inference_ms, c->last_n_dets);
+ }
+ n += sprintf(json + n, "]}");
+ http_send_json(client, 200, json);
+ free(json);
+ return;
+ }
+
+ /* Events */
+ if (strcmp(req->path, "/api/events") == 0) {
+ MUTEX_LOCK(&srv->event_mutex);
+ char* json = (char*)malloc(srv->event_count * 512 + 256);
+ int n = sprintf(json, "{\"count\":%d,\"events\":[", srv->event_count);
+ for (int i = 0; i < srv->event_count; i++) {
+ int idx = (srv->event_head - srv->event_count + i + MAX_EVENTS) % MAX_EVENTS;
+ DetEvent* e = &srv->events[idx];
+ n += sprintf(json + n, "%s{\"cam_id\":%d,\"cam_name\":\"%s\","
+ "\"timestamp\":%.1f,\"inference_ms\":%.1f,\"dets\":[",
+ i > 0 ? "," : "", e->cam_id, e->cam_name, e->timestamp, e->inference_ms);
+ for (int d = 0; d < e->n_dets; d++) {
+ const char* nm = (e->dets[d].cls >= 0 && e->dets[d].cls < 80)
+ ? coco_names[e->dets[d].cls] : "obj";
+ n += sprintf(json + n, "%s{\"class\":\"%s\",\"cls\":%d,\"score\":%.2f,"
+ "\"bbox\":[%.0f,%.0f,%.0f,%.0f]}",
+ d > 0 ? "," : "", nm, e->dets[d].cls, e->dets[d].score,
+ e->dets[d].x1, e->dets[d].y1, e->dets[d].x2, e->dets[d].y2);
+ }
+ n += sprintf(json + n, "]}");
+ }
+ n += sprintf(json + n, "]}");
+ MUTEX_UNLOCK(&srv->event_mutex);
+ http_send_json(client, 200, json);
+ free(json);
+ return;
+ }
+
+ /* POST /api/detect — single image detection */
+ if (strcmp(req->path, "/api/detect") == 0 && strcmp(req->method, "POST") == 0) {
+ if (!req->body || req->content_length <= 0) {
+ http_send_json(client, 400, "{\"error\":\"no image\"}");
+ return;
+ }
+ int w, h, ch;
+ uint8_t* img = stbi_load_from_memory(
+ (const uint8_t*)req->body, req->content_length, &w, &h, &ch, 3);
+ if (!img) { http_send_json(client, 400, "{\"error\":\"bad image\"}"); return; }
+
+ NN2Det dets[100];
+ double t0 = prod_now();
+ MUTEX_LOCK(&srv->model_mutex);
+ int nd = nn2_detect(srv->model, img, w, h, dets, 100);
+ MUTEX_UNLOCK(&srv->model_mutex);
+ double ms = (prod_now() - t0) * 1000.0;
+ stbi_image_free(img);
+
+ char* json = (char*)malloc(nd * 256 + 256);
+ int n = sprintf(json, "{\"ms\":%.1f,\"w\":%d,\"h\":%d,\"dets\":[", ms, w, h);
+ for (int i = 0; i < nd; i++) {
+ const char* nm = (dets[i].cls >= 0 && dets[i].cls < 80)
+ ? coco_names[dets[i].cls] : "obj";
+ n += sprintf(json + n,
+ "%s{\"class\":\"%s\",\"score\":%.3f,\"bbox\":[%.1f,%.1f,%.1f,%.1f]}",
+ i > 0 ? "," : "", nm, dets[i].score,
+ dets[i].x1, dets[i].y1, dets[i].x2, dets[i].y2);
+ }
+ n += sprintf(json + n, "]}");
+ http_send_json(client, 200, json);
+ free(json);
+ return;
+ }
+
+ /* POST /api/camera/add */
+ if (strcmp(req->path, "/api/camera/add") == 0 && strcmp(req->method, "POST") == 0) {
+ if (srv->n_cameras >= MAX_PROD_CAMERAS) {
+ http_send_json(client, 400, "{\"error\":\"max cameras reached\"}");
+ return;
+ }
+ /* Parse simple JSON: {"name":"...", "url":"..."} */
+ char name[64] = "Camera", url[512] = "test";
+ if (req->body) {
+ char* p;
+ if ((p = strstr(req->body, "\"name\"")) != NULL) {
+ p = strchr(p + 6, '"'); if (p) { p++; char* e = strchr(p, '"');
+ if (e) { int l = (int)(e-p); if (l > 63) l = 63; memcpy(name, p, l); name[l]=0; }}
+ }
+ if ((p = strstr(req->body, "\"url\"")) != NULL) {
+ p = strchr(p + 5, '"'); if (p) { p++; char* e = strchr(p, '"');
+ if (e) { int l = (int)(e-p); if (l > 511) l = 511; memcpy(url, p, l); url[l]=0; }}
+ }
+ }
+ int id = srv->n_cameras;
+ ProdCamera* cam = &srv->cameras[id];
+ memset(cam, 0, sizeof(ProdCamera));
+ cam->id = id;
+ cam->active = 1;
+ cam->detect_interval = srv->detect_interval;
+ strncpy(cam->name, name, 63);
+ strncpy(cam->url, url, 511);
+ cam->tracker = nn2_tracker_create(30, 2);
+ srv->n_cameras++;
+
+ char resp[256];
+ snprintf(resp, sizeof(resp), "{\"id\":%d,\"name\":\"%s\",\"status\":\"added\"}", id, name);
+ http_send_json(client, 200, resp);
+ fprintf(stderr, " + Camera %d: %s (%s)\n", id, name, url);
+ return;
+ }
+
+ /* POST /api/camera/sim — simulate a frame push for testing */
+ if (strcmp(req->path, "/api/camera/sim") == 0 && strcmp(req->method, "POST") == 0) {
+ /* Push a synthetic frame to all cameras */
+ for (int c = 0; c < srv->n_cameras; c++) {
+ uint8_t* frame = (uint8_t*)malloc(320 * 240 * 3);
+ for (int i = 0; i < 320*240*3; i++)
+ frame[i] = (uint8_t)((i + srv->cameras[c].frame_count * 7) % 200 + 30);
+ process_camera_frame(srv, &srv->cameras[c], frame, 320, 240);
+ free(frame);
+ }
+ char resp[128];
+ snprintf(resp, sizeof(resp), "{\"pushed\":%d}", srv->n_cameras);
+ http_send_json(client, 200, resp);
+ return;
+ }
+
+ http_send_json(client, 404,
+ "{\"error\":\"not found\",\"endpoints\":"
+ "[\"/\",\"/api/status\",\"/api/events\",\"/api/detect\","
+ "\"/api/camera/add\",\"/api/camera/sim\",\"/api/health\"]}");
+}
+
+/* ============ Main ============ */
+
+int main(int argc, char** argv)
+{
+ const char* weights = "weights/yolov8n_320.bin";
+ int port = 8080;
+ int threads = 0;
+ int detect_interval = 5;
+
+ for (int i = 1; i < argc; i++) {
+ if (strcmp(argv[i], "-w") == 0 && i+1 < argc) weights = argv[++i];
+ else if (strcmp(argv[i], "-p") == 0 && i+1 < argc) port = atoi(argv[++i]);
+ else if (strcmp(argv[i], "-t") == 0 && i+1 < argc) threads = atoi(argv[++i]);
+ else if (strcmp(argv[i], "-i") == 0 && i+1 < argc) detect_interval = atoi(argv[++i]);
+ else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
+ printf("nn2 NVR Production Server\n\n");
+ printf("Usage: %s [options]\n", argv[0]);
+ printf(" -w <path> Weight file (default: weights/yolov8n_320.bin)\n");
+ printf(" -p <port> HTTP port (default: 8080)\n");
+ printf(" -t <N> Threads (default: auto)\n");
+ printf(" -i <N> Detect interval (default: 5)\n");
+ printf("\nAPI:\n");
+ printf(" GET / Web dashboard\n");
+ printf(" GET /api/status Camera status + stats\n");
+ printf(" GET /api/events Recent detection events\n");
+ printf(" POST /api/detect Upload image → JSON detections\n");
+ printf(" POST /api/camera/add Add camera {\"name\":\"...\",\"url\":\"...\"}\n");
+ printf(" POST /api/camera/sim Simulate frame push\n");
+ return 0;
+ }
+ }
+
+ /* Init server */
+ memset(&g_server, 0, sizeof(g_server));
+ g_server.model = nn2_init(weights, threads);
+ if (!g_server.model) { fprintf(stderr, "Failed to load model\n"); return 1; }
+ MUTEX_INIT(&g_server.model_mutex);
+ MUTEX_INIT(&g_server.event_mutex);
+ g_server.detect_interval = detect_interval;
+ g_server.conf_threshold = 0.25f;
+ g_server.motion_threshold = 0.005f;
+ g_server.uptime_start = prod_now();
+
+ fprintf(stderr, "\n");
+ fprintf(stderr, " nn2 NVR Production Server\n");
+ fprintf(stderr, " ========================\n");
+ fprintf(stderr, " Engine: nn2 v%s (pure C, AVX-512)\n", nn2_version());
+ fprintf(stderr, " Model: %s\n", weights);
+ fprintf(stderr, " Inference: ~8.5ms (117 FPS)\n");
+ fprintf(stderr, " Smart: motion gate + Kalman skip (0.56ms avg)\n");
+ fprintf(stderr, " Capacity: ~70 cameras @ 25fps\n");
+ fprintf(stderr, " Dashboard: http://localhost:%d\n", port);
+ fprintf(stderr, " API: http://localhost:%d/api/status\n", port);
+ fprintf(stderr, "\n");
+ fprintf(stderr, " Quick start:\n");
+ fprintf(stderr, " 1. Open http://localhost:%d in browser\n", port);
+ fprintf(stderr, " 2. Add camera: curl -X POST http://localhost:%d/api/camera/add "
+ "-d '{\"name\":\"Front Door\"}'\n", port);
+ fprintf(stderr, " 3. Sim frames: curl -X POST http://localhost:%d/api/camera/sim\n", port);
+ fprintf(stderr, " 4. Detect: curl -X POST http://localhost:%d/api/detect "
+ "--data-binary @photo.jpg\n", port);
+ fprintf(stderr, "\n");
+
+ /* Start HTTP server (blocking) */
+ http_listen(port, nvr_http_handler, &g_server);
+
+ /* Cleanup */
+ for (int i = 0; i < g_server.n_cameras; i++) {
+ free(g_server.cameras[i].prev_frame);
+ if (g_server.cameras[i].tracker)
+ nn2_tracker_free(g_server.cameras[i].tracker);
+ }
+ MUTEX_DESTROY(&g_server.model_mutex);
+ MUTEX_DESTROY(&g_server.event_mutex);
+ nn2_free(g_server.model);
+ return 0;
+}
diff --git a/nn2/src/ops.c b/nn2/src/ops.c
new file mode 100644
index 0000000..7abcfeb
--- /dev/null
+++ b/nn2/src/ops.c
@@ -0,0 +1,517 @@
+/*
+ * ops.c — Utility operations: SiLU, sigmoid, upsample, concat, maxpool.
+ */
+
+#include "nn2_internal.h"
+#include <math.h>
+#include <string.h>
+#include <float.h>
+
+#ifdef __AVX2__
+#include <immintrin.h>
+#endif
+
+/* ============ SiLU (x * sigmoid(x)) in-place ============ */
+
+#include "fast_exp.h"
+
+void nn2_silu_inplace(float* x, int n)
+{
+ int i = 0;
+#ifdef __AVX512F__
+ for (; i + 16 <= n; i += 16) {
+ __m512 v = _mm512_loadu_ps(x + i);
+ _mm512_storeu_ps(x + i, _mm512_silu_fast(v));
+ }
+#endif
+#ifdef __AVX2__
+ /* AVX2 fast sigmoid approximation: x/(1+|x|) * 0.5 + 0.5, then x*sigmoid */
+ __m256 one = _mm256_set1_ps(1.0f);
+ __m256 half = _mm256_set1_ps(0.5f);
+ __m256 sign_mask = _mm256_set1_ps(-0.0f);
+ for (; i + 8 <= n; i += 8) {
+ __m256 v = _mm256_loadu_ps(x + i);
+ __m256 abs_v = _mm256_andnot_ps(sign_mask, v);
+ __m256 denom = _mm256_add_ps(one, abs_v);
+ __m256 sig = _mm256_fmadd_ps(_mm256_div_ps(v, denom), half, half);
+ _mm256_storeu_ps(x + i, _mm256_mul_ps(v, sig));
+ }
+#endif
+ for (; i < n; i++) {
+ float v = x[i];
+ x[i] = v / (1.0f + expf(-v));
+ }
+}
+
+/* ============ Sigmoid in-place ============ */
+
+void nn2_sigmoid_inplace(float* x, int n)
+{
+ int i = 0;
+#ifdef __AVX512F__
+ for (; i + 16 <= n; i += 16) {
+ __m512 v = _mm512_loadu_ps(x + i);
+ _mm512_storeu_ps(x + i, _mm512_sigmoid_fast(v));
+ }
+#endif
+#ifdef __AVX2__
+ __m256 one = _mm256_set1_ps(1.0f);
+ __m256 half = _mm256_set1_ps(0.5f);
+ __m256 sign_mask = _mm256_set1_ps(-0.0f);
+ for (; i + 8 <= n; i += 8) {
+ __m256 v = _mm256_loadu_ps(x + i);
+ __m256 abs_v = _mm256_andnot_ps(sign_mask, v);
+ __m256 denom = _mm256_add_ps(one, abs_v);
+ __m256 sig = _mm256_fmadd_ps(_mm256_div_ps(v, denom), half, half);
+ _mm256_storeu_ps(x + i, sig);
+ }
+#endif
+ for (; i < n; i++)
+ x[i] = 1.0f / (1.0f + expf(-x[i]));
+}
+
+/* ============ Nearest-neighbor upsample 2x ============ */
+
+typedef struct { const float* in; float* out; int C, H, W; } UpsampleCtx;
+
+static void upsample_worker(void* arg, int start, int end)
+{
+ UpsampleCtx* ctx = (UpsampleCtx*)arg;
+ int H = ctx->H, W = ctx->W, Wout = W * 2;
+ for (int c = start; c < end; c++) {
+ const float* src = ctx->in + c * H * W;
+ float* dst = ctx->out + c * H * 2 * Wout;
+ for (int h = 0; h < H; h++) {
+ const float* srow = src + h * W;
+ float* drow0 = dst + (h * 2) * Wout;
+ float* drow1 = drow0 + Wout;
+ int w = 0;
+#ifdef __AVX512F__
+ /* Process 16 input pixels → 32 output pixels per row pair */
+ for (; w + 16 <= W; w += 16) {
+ __m512 v = _mm512_loadu_ps(srow + w);
+ /* Interleave: [a,b,c,...] → [a,a,b,b,c,c,...] */
+ /* Use permutex2var to duplicate each element */
+ __m512i idx_lo = _mm512_setr_epi32(0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7);
+ __m512i idx_hi = _mm512_setr_epi32(8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15);
+ __m512 lo = _mm512_permutexvar_ps(idx_lo, v);
+ __m512 hi = _mm512_permutexvar_ps(idx_hi, v);
+ _mm512_storeu_ps(drow0 + w * 2, lo);
+ _mm512_storeu_ps(drow0 + w * 2 + 16, hi);
+ _mm512_storeu_ps(drow1 + w * 2, lo);
+ _mm512_storeu_ps(drow1 + w * 2 + 16, hi);
+ }
+#endif
+ for (; w < W; w++) {
+ float v = srow[w];
+ drow0[w*2] = v; drow0[w*2+1] = v;
+ drow1[w*2] = v; drow1[w*2+1] = v;
+ }
+ }
+ }
+}
+
+void nn2_upsample_2x(const float* in, int C, int H, int W, float* out)
+{
+ UpsampleCtx ctx = {in, out, C, H, W};
+ if (C >= 32)
+ nn2_tp_parallel_for(upsample_worker, &ctx, C, 8);
+ else
+ upsample_worker(&ctx, 0, C);
+}
+
+/* ============ Channel concat ============ */
+
+void nn2_concat(const float* a, int ca, const float* b, int cb,
+ int H, int W, float* out)
+{
+ int spatial = H * W;
+ memcpy(out, a, (size_t)ca * spatial * sizeof(float));
+ memcpy(out + ca * spatial, b, (size_t)cb * spatial * sizeof(float));
+}
+
+/* ============ MaxPool2d ============ */
+
+/* ============ Depthwise Conv2d (AVX-512 + threaded) ============ */
+
+#include <immintrin.h>
+
+typedef struct {
+ const float* in; const float* w; const float* bias;
+ int C, H, W, k, stride, pad, act;
+ float* out;
+ int Hout, Wout;
+} DWConvCtx;
+
+static void dwconv_worker(void* arg, int start, int end)
+{
+ DWConvCtx* ctx = (DWConvCtx*)arg;
+ int H = ctx->H, W = ctx->W, k = ctx->k;
+ int stride = ctx->stride, pad = ctx->pad;
+ int Hout = ctx->Hout, Wout = ctx->Wout;
+ int act = ctx->act;
+
+ for (int c = start; c < end; c++) {
+ const float* src = ctx->in + c * H * W;
+ const float* wt = ctx->w + c * k * k;
+ float b = ctx->bias ? ctx->bias[c] : 0.0f;
+ float* dst = ctx->out + c * Hout * Wout;
+
+ /* Optimized path for 3x3 stride-1 pad-1 (most common DW in ShuffleNet) */
+ if (k == 3 && stride == 1 && pad == 1) {
+ float w00=wt[0],w01=wt[1],w02=wt[2];
+ float w10=wt[3],w11=wt[4],w12=wt[5];
+ float w20=wt[6],w21=wt[7],w22=wt[8];
+
+ for (int oh = 0; oh < Hout; oh++) {
+ const float* r0 = (oh > 0) ? src + (oh-1)*W : NULL;
+ const float* r1 = src + oh*W;
+ const float* r2 = (oh < H-1) ? src + (oh+1)*W : NULL;
+ int ow = 0;
+
+#ifdef __AVX512F__
+ __m512 vb = _mm512_set1_ps(b);
+ __m512 vw00=_mm512_set1_ps(w00),vw01=_mm512_set1_ps(w01),vw02=_mm512_set1_ps(w02);
+ __m512 vw10=_mm512_set1_ps(w10),vw11=_mm512_set1_ps(w11),vw12=_mm512_set1_ps(w12);
+ __m512 vw20=_mm512_set1_ps(w20),vw21=_mm512_set1_ps(w21),vw22=_mm512_set1_ps(w22);
+ __m512 vleak = _mm512_set1_ps(0.1f);
+ __m512 vzero = _mm512_setzero_ps();
+
+ for (; ow + 16 <= Wout; ow += 16) {
+ __m512 sum = vb;
+ /* Row 0 */
+ if (r0) {
+ __m512 left = (ow>0) ? _mm512_loadu_ps(r0+ow-1) : _mm512_maskz_loadu_ps(0xFFFE, r0+ow-1);
+ __m512 center = _mm512_loadu_ps(r0+ow);
+ __m512 right = (ow+16<W) ? _mm512_loadu_ps(r0+ow+1) : _mm512_maskz_loadu_ps(0x7FFF, r0+ow);
+ if (ow+16 >= W) right = _mm512_loadu_ps(r0+ow+1); /* safe if W padded */
+ sum = _mm512_fmadd_ps(vw00, left, sum);
+ sum = _mm512_fmadd_ps(vw01, center, sum);
+ sum = _mm512_fmadd_ps(vw02, right, sum);
+ }
+ /* Row 1 */
+ {
+ __m512 left = (ow>0) ? _mm512_loadu_ps(r1+ow-1) : _mm512_maskz_loadu_ps(0xFFFE, r1+ow-1);
+ __m512 center = _mm512_loadu_ps(r1+ow);
+ __m512 right = _mm512_loadu_ps(r1+ow+1);
+ sum = _mm512_fmadd_ps(vw10, left, sum);
+ sum = _mm512_fmadd_ps(vw11, center, sum);
+ sum = _mm512_fmadd_ps(vw12, right, sum);
+ }
+ /* Row 2 */
+ if (r2) {
+ __m512 left = (ow>0) ? _mm512_loadu_ps(r2+ow-1) : _mm512_maskz_loadu_ps(0xFFFE, r2+ow-1);
+ __m512 center = _mm512_loadu_ps(r2+ow);
+ __m512 right = _mm512_loadu_ps(r2+ow+1);
+ sum = _mm512_fmadd_ps(vw20, left, sum);
+ sum = _mm512_fmadd_ps(vw21, center, sum);
+ sum = _mm512_fmadd_ps(vw22, right, sum);
+ }
+ /* LeakyReLU */
+ if (act == 3) {
+ __mmask16 neg = _mm512_cmplt_ps_mask(sum, vzero);
+ sum = _mm512_mask_mul_ps(sum, neg, sum, vleak);
+ }
+ _mm512_storeu_ps(dst + oh*Wout + ow, sum);
+ }
+#endif
+ /* Scalar tail */
+ for (; ow < Wout; ow++) {
+ float s = b;
+ if (r0) {
+ if (ow>0) s += r0[ow-1]*w00;
+ s += r0[ow]*w01;
+ if (ow<W-1) s += r0[ow+1]*w02;
+ }
+ if (ow>0) s += r1[ow-1]*w10;
+ s += r1[ow]*w11;
+ if (ow<W-1) s += r1[ow+1]*w12;
+ if (r2) {
+ if (ow>0) s += r2[ow-1]*w20;
+ s += r2[ow]*w21;
+ if (ow<W-1) s += r2[ow+1]*w22;
+ }
+ if (act == 3 && s < 0) s *= 0.1f;
+ dst[oh*Wout + ow] = s;
+ }
+ }
+ continue;
+ }
+
+ /* Optimized 5x5 stride-1 pad-2 (Ghost-PAN uses this heavily) */
+ if (k == 5 && stride == 1 && pad == 2) {
+#ifdef __AVX512F__
+ __m512 vw[25], vb512 = _mm512_set1_ps(b);
+ __m512 vleak = _mm512_set1_ps(0.1f), vzero = _mm512_setzero_ps();
+ for (int i = 0; i < 25; i++) vw[i] = _mm512_set1_ps(wt[i]);
+
+ for (int oh = 0; oh < Hout; oh++) {
+ int ow = 0;
+ for (; ow + 16 <= Wout; ow += 16) {
+ __m512 sum = vb512;
+ for (int kh = 0; kh < 5; kh++) {
+ int ih = oh - 2 + kh;
+ if (ih < 0 || ih >= H) continue;
+ const float* row = src + ih * W;
+ for (int kw = 0; kw < 5; kw++) {
+ int iw_base = ow - 2 + kw;
+ __m512 v;
+ if (iw_base >= 0 && iw_base + 16 <= W) {
+ v = _mm512_loadu_ps(row + iw_base);
+ } else {
+ /* Edge: masked load */
+ __mmask16 mask = 0;
+ for (int j = 0; j < 16; j++) {
+ int iw = iw_base + j;
+ if (iw >= 0 && iw < W) mask |= (1 << j);
+ }
+ v = _mm512_maskz_loadu_ps(mask, row + iw_base);
+ }
+ sum = _mm512_fmadd_ps(vw[kh*5+kw], v, sum);
+ }
+ }
+ if (act == 3) {
+ __mmask16 neg = _mm512_cmplt_ps_mask(sum, vzero);
+ sum = _mm512_mask_mul_ps(sum, neg, sum, vleak);
+ }
+ _mm512_storeu_ps(dst + oh * Wout + ow, sum);
+ }
+ /* Scalar tail */
+ for (; ow < Wout; ow++) {
+ float s = b;
+ for (int kh = 0; kh < 5; kh++) {
+ int ih = oh - 2 + kh;
+ if (ih < 0 || ih >= H) continue;
+ for (int kw = 0; kw < 5; kw++) {
+ int iw = ow - 2 + kw;
+ if (iw >= 0 && iw < W) s += src[ih*W+iw] * wt[kh*5+kw];
+ }
+ }
+ if (act == 3 && s < 0) s *= 0.1f;
+ dst[oh * Wout + ow] = s;
+ }
+ }
+ continue;
+#endif
+ }
+
+ /* Optimized 5x5 stride-2 pad-2 (downsample in Ghost-PAN) */
+ if (k == 5 && stride == 2 && pad == 2) {
+#ifdef __AVX512F__
+ __m512 vw5[25], vb512 = _mm512_set1_ps(b);
+ __m512 vleak = _mm512_set1_ps(0.1f), vzero = _mm512_setzero_ps();
+ __m256i vidx8 = _mm256_setr_epi32(0,2,4,6,8,10,12,14);
+ for (int i = 0; i < 25; i++) vw5[i] = _mm512_set1_ps(wt[i]);
+
+ for (int oh = 0; oh < Hout; oh++) {
+ int ow = 0;
+ for (; ow + 8 <= Wout; ow += 8) {
+ __m256 sum8 = _mm256_set1_ps(b);
+ for (int kh = 0; kh < 5; kh++) {
+ int ih = oh * 2 - 2 + kh;
+ if (ih < 0 || ih >= H) continue;
+ const float* row = src + ih * W;
+ for (int kw = 0; kw < 5; kw++) {
+ int iw_base = ow * 2 - 2 + kw;
+ __m256 v;
+ if (iw_base >= 0 && iw_base + 14 < W) {
+ v = _mm256_i32gather_ps(row + iw_base, vidx8, 4);
+ } else {
+ float tmp[8] = {0};
+ for (int j = 0; j < 8; j++) {
+ int iw = iw_base + j * 2;
+ if (iw >= 0 && iw < W) tmp[j] = row[iw];
+ }
+ v = _mm256_loadu_ps(tmp);
+ }
+ __m256 wv = _mm256_set1_ps(wt[kh*5+kw]);
+ sum8 = _mm256_fmadd_ps(wv, v, sum8);
+ }
+ }
+ if (act == 3) {
+ __m256 neg = _mm256_cmp_ps(sum8, _mm256_setzero_ps(), _CMP_LT_OQ);
+ sum8 = _mm256_blendv_ps(sum8, _mm256_mul_ps(sum8, _mm256_set1_ps(0.1f)), neg);
+ }
+ _mm256_storeu_ps(dst + oh * Wout + ow, sum8);
+ }
+ for (; ow < Wout; ow++) {
+ float s = b;
+ for (int kh = 0; kh < 5; kh++) {
+ int ih = oh*2-2+kh;
+ if (ih<0||ih>=H) continue;
+ for (int kw = 0; kw < 5; kw++) {
+ int iw = ow*2-2+kw;
+ if (iw>=0&&iw<W) s += src[ih*W+iw]*wt[kh*5+kw];
+ }
+ }
+ if (act==3&&s<0) s*=0.1f;
+ dst[oh*Wout+ow] = s;
+ }
+ }
+ continue;
+#endif
+ }
+
+ /* Generic fallback */
+ for (int oh = 0; oh < Hout; oh++) {
+ for (int ow = 0; ow < Wout; ow++) {
+ float sum = b;
+ for (int kh = 0; kh < k; kh++) {
+ int ih = oh * stride - pad + kh;
+ if (ih < 0 || ih >= H) continue;
+ for (int kw = 0; kw < k; kw++) {
+ int iw = ow * stride - pad + kw;
+ if (iw < 0 || iw >= W) continue;
+ sum += src[ih * W + iw] * wt[kh * k + kw];
+ }
+ }
+ if (act == 1) { float s = 1.0f/(1.0f+expf(-sum)); sum *= s; }
+ else if (act == 3 && sum < 0) sum *= 0.1f;
+ dst[oh * Wout + ow] = sum;
+ }
+ }
+ }
+}
+
+void nn2_dwconv2d(const float* in, const float* w, const float* bias,
+ int C, int H, int W, int k, int stride, int pad,
+ int act, float* out)
+{
+ int Hout = (H + 2 * pad - k) / stride + 1;
+ int Wout = (W + 2 * pad - k) / stride + 1;
+ DWConvCtx ctx = {in, w, bias, C, H, W, k, stride, pad, act, out, Hout, Wout};
+
+ if (C >= 8)
+ nn2_tp_parallel_for(dwconv_worker, &ctx, C, 4);
+ else
+ dwconv_worker(&ctx, 0, C);
+}
+
+/* ============ Channel shuffle (ShuffleNetV2) ============ */
+
+void nn2_channel_shuffle(const float* in, int C, int H, int W,
+ int groups, float* out)
+{
+ int channels_per_group = C / groups;
+ int spatial = H * W;
+ for (int g = 0; g < groups; g++) {
+ for (int c = 0; c < channels_per_group; c++) {
+ int src_ch = g * channels_per_group + c;
+ int dst_ch = c * groups + g;
+ memcpy(out + dst_ch * spatial, in + src_ch * spatial,
+ spatial * sizeof(float));
+ }
+ }
+}
+
+/* ============ MaxPool2d ============ */
+
+/* Parallel maxpool worker: process channels [start, end) */
+typedef struct { const float* in; float* out; int C, H, W, k, stride, pad; } MaxPoolCtx;
+
+static void maxpool_worker(void* arg, int start, int end)
+{
+ MaxPoolCtx* ctx = (MaxPoolCtx*)arg;
+ int H = ctx->H, W = ctx->W, k = ctx->k, stride = ctx->stride, pad = ctx->pad;
+ int Hout = (H + 2*pad - k) / stride + 1;
+ int Wout = (W + 2*pad - k) / stride + 1;
+
+ for (int c = start; c < end; c++) {
+ const float* src = ctx->in + c * H * W;
+ float* dst = ctx->out + c * Hout * Wout;
+
+ /* Fast path: SPPF-style same-size maxpool (stride=1) with separable passes.
+ * For k=5,s=1,p=2: do 2 sequential k=3,s=1,p=1 maxpools (5=3+3-1). */
+ if (stride == 1 && k == 5 && pad == 2 && Hout == H && Wout == W) {
+ /* Two-pass k=3 maxpool (horizontal then vertical, repeated).
+ * But simpler: just process each output position with 5×5 window
+ * using AVX-512 across the width dimension. */
+ for (int oh = 0; oh < Hout; oh++) {
+ int ow = 0;
+#ifdef __AVX512F__
+ for (; ow + 16 <= Wout; ow += 16) {
+ __m512 vmax = _mm512_set1_ps(-FLT_MAX);
+ for (int kh = 0; kh < 5; kh++) {
+ int ih = oh - 2 + kh;
+ if (ih < 0 || ih >= H) continue;
+ const float* srow = src + ih * W;
+ for (int kw = 0; kw < 5; kw++) {
+ int iw = ow - 2 + kw;
+ /* Need to handle boundaries per-element */
+ if (iw >= 0 && iw + 16 <= W) {
+ __m512 v = _mm512_loadu_ps(srow + iw);
+ vmax = _mm512_max_ps(vmax, v);
+ } else {
+ /* Boundary: load with mask */
+ __mmask16 mask = 0;
+ for (int j = 0; j < 16; j++)
+ if (iw + j >= 0 && iw + j < W) mask |= (1 << j);
+ if (mask) {
+ __m512 v = _mm512_maskz_loadu_ps(mask, srow + (iw >= 0 ? iw : 0));
+ /* Shift loaded values if iw < 0 */
+ if (iw < 0) {
+ /* fallback to scalar for boundary */
+ for (int j = 0; j < 16; j++) {
+ if (iw+j >= 0 && iw+j < W) {
+ float sv = srow[iw+j];
+ float cv = ((float*)&vmax)[j];
+ if (sv > cv) ((float*)&vmax)[j] = sv;
+ }
+ }
+ continue;
+ }
+ vmax = _mm512_max_ps(vmax, v);
+ }
+ }
+ }
+ }
+ _mm512_storeu_ps(dst + oh * Wout + ow, vmax);
+ }
+#endif
+ for (; ow < Wout; ow++) {
+ float maxv = -FLT_MAX;
+ for (int kh = 0; kh < 5; kh++) {
+ int ih = oh - 2 + kh;
+ if (ih < 0 || ih >= H) continue;
+ for (int kw = 0; kw < 5; kw++) {
+ int iw = ow - 2 + kw;
+ if (iw < 0 || iw >= W) continue;
+ float v = src[ih * W + iw];
+ if (v > maxv) maxv = v;
+ }
+ }
+ dst[oh * Wout + ow] = maxv;
+ }
+ }
+ continue;
+ }
+
+ /* Generic path */
+ for (int oh = 0; oh < Hout; oh++) {
+ for (int ow = 0; ow < Wout; ow++) {
+ float maxv = -FLT_MAX;
+ for (int kh = 0; kh < k; kh++) {
+ int ih = oh * stride - pad + kh;
+ if (ih < 0 || ih >= H) continue;
+ for (int kw = 0; kw < k; kw++) {
+ int iw = ow * stride - pad + kw;
+ if (iw < 0 || iw >= W) continue;
+ float v = src[ih * W + iw];
+ if (v > maxv) maxv = v;
+ }
+ }
+ dst[oh * Wout + ow] = maxv;
+ }
+ }
+ }
+}
+
+void nn2_maxpool2d(const float* in, int C, int H, int W,
+ int k, int stride, int pad, float* out)
+{
+ MaxPoolCtx ctx = {in, out, C, H, W, k, stride, pad};
+ if (C >= 16)
+ nn2_tp_parallel_for(maxpool_worker, &ctx, C, 4);
+ else
+ maxpool_worker(&ctx, 0, C);
+}
diff --git a/nn2/src/pool.c b/nn2/src/pool.c
new file mode 100644
index 0000000..c5f0c25
--- /dev/null
+++ b/nn2/src/pool.c
@@ -0,0 +1,217 @@
+/*
+ * pool.c — Lock-free thread pool (from facex pattern).
+ *
+ * Atomic counter + WaitOnAddress/futex. Workers spin ~1µs before sleeping.
+ * Main thread participates in work.
+ */
+
+#include "nn2_internal.h"
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef _WIN32
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#include <process.h>
+#else
+#include <pthread.h>
+#include <unistd.h>
+#include <linux/futex.h>
+#include <sys/syscall.h>
+#endif
+
+#if defined(__GNUC__) || defined(__clang__)
+#define ATOMIC_LOAD(p) __atomic_load_n(p, __ATOMIC_ACQUIRE)
+#define ATOMIC_STORE(p, v) __atomic_store_n(p, v, __ATOMIC_RELEASE)
+#define ATOMIC_ADD(p, v) __atomic_fetch_add(p, v, __ATOMIC_ACQ_REL)
+#elif defined(_MSC_VER)
+#include <intrin.h>
+#define ATOMIC_LOAD(p) (*(volatile int*)(p))
+#define ATOMIC_STORE(p, v) (*(volatile int*)(p) = (v))
+#define ATOMIC_ADD(p, v) _InterlockedExchangeAdd((volatile long*)(p), (v))
+#else
+#include <stdatomic.h>
+#define ATOMIC_LOAD(p) atomic_load(p)
+#define ATOMIC_STORE(p, v) atomic_store(p, v)
+#define ATOMIC_ADD(p, v) atomic_fetch_add(p, v)
+#endif
+
+#define MAX_THREADS 16
+
+typedef struct {
+ nn2_task_fn fn;
+ void* ctx;
+ volatile int next_idx;
+ int total;
+ int grain;
+ volatile int done_count;
+ int n_workers;
+ volatile int phase;
+} TaskState;
+
+static TaskState g_task;
+
+typedef struct {
+ int id;
+#ifdef _WIN32
+ HANDLE handle;
+#else
+ pthread_t handle;
+#endif
+} Worker;
+
+static Worker g_workers[MAX_THREADS];
+static int g_n_threads = 0;
+static volatile int g_shutdown = 0;
+
+static
+#ifdef _WIN32
+unsigned __stdcall
+#else
+void*
+#endif
+worker_fn(void* arg)
+{
+ int last_phase = 0;
+
+ while (!ATOMIC_LOAD(&g_shutdown)) {
+ int phase = ATOMIC_LOAD(&g_task.phase);
+ if (phase == last_phase) {
+ int spins = 100;
+ while (spins-- > 0) {
+ phase = ATOMIC_LOAD(&g_task.phase);
+ if (phase != last_phase) break;
+#ifdef _WIN32
+ YieldProcessor();
+#else
+ __asm__ __volatile__("pause");
+#endif
+ }
+ if (phase == last_phase) {
+#ifdef _WIN32
+ WaitOnAddress((volatile void*)&g_task.phase, &last_phase,
+ sizeof(int), INFINITE);
+#else
+ syscall(SYS_futex, &g_task.phase, FUTEX_WAIT, last_phase,
+ NULL, NULL, 0);
+#endif
+ continue;
+ }
+ }
+ last_phase = phase;
+
+ while (1) {
+ int idx = ATOMIC_ADD(&g_task.next_idx, g_task.grain);
+ if (idx >= g_task.total) break;
+ int end = idx + g_task.grain;
+ if (end > g_task.total) end = g_task.total;
+ g_task.fn(g_task.ctx, idx, end);
+ }
+
+ ATOMIC_ADD(&g_task.done_count, 1);
+ }
+
+#ifdef _WIN32
+ return 0;
+#else
+ return NULL;
+#endif
+}
+
+void nn2_tp_init(int n_threads)
+{
+ if (n_threads <= 0) {
+#ifdef _WIN32
+ SYSTEM_INFO si; GetSystemInfo(&si);
+ n_threads = si.dwNumberOfProcessors;
+#else
+ n_threads = sysconf(_SC_NPROCESSORS_ONLN);
+#endif
+ if (n_threads > MAX_THREADS) n_threads = MAX_THREADS;
+ if (n_threads < 1) n_threads = 1;
+ }
+
+ g_n_threads = n_threads;
+ int n_workers = n_threads - 1;
+ memset(&g_task, 0, sizeof(g_task));
+ ATOMIC_STORE(&g_shutdown, 0);
+
+ for (int i = 0; i < n_workers; i++) {
+ g_workers[i].id = i;
+#ifdef _WIN32
+ g_workers[i].handle = (HANDLE)_beginthreadex(
+ NULL, 0, worker_fn, &g_workers[i], 0, NULL);
+#else
+ pthread_create(&g_workers[i].handle, NULL, worker_fn, &g_workers[i]);
+#endif
+ }
+}
+
+static volatile int g_dispatch_count = 0;
+int nn2_tp_dispatch_count(void) { return g_dispatch_count; }
+void nn2_tp_reset_dispatch_count(void) { g_dispatch_count = 0; }
+
+void nn2_tp_parallel_for(nn2_task_fn fn, void* ctx, int total, int grain)
+{
+ if (total <= 0) return;
+ if (grain <= 0) grain = 1;
+
+ int n_workers = g_n_threads - 1;
+ if (n_workers <= 0 || total <= grain) {
+ fn(ctx, 0, total);
+ return;
+ }
+ g_dispatch_count++;
+
+ g_task.fn = fn;
+ g_task.ctx = ctx;
+ g_task.total = total;
+ g_task.grain = grain;
+ ATOMIC_STORE(&g_task.next_idx, 0);
+ ATOMIC_STORE(&g_task.done_count, 0);
+ g_task.n_workers = n_workers;
+
+ ATOMIC_ADD(&g_task.phase, 1);
+#ifdef _WIN32
+ WakeByAddressAll((void*)&g_task.phase);
+#else
+ syscall(SYS_futex, &g_task.phase, FUTEX_WAKE, n_workers, NULL, NULL, 0);
+#endif
+
+ /* Main thread participates */
+ while (1) {
+ int idx = ATOMIC_ADD(&g_task.next_idx, grain);
+ if (idx >= total) break;
+ int end = idx + grain;
+ if (end > total) end = total;
+ fn(ctx, idx, end);
+ }
+
+ /* Spin-wait for workers — pure spin, no sleep (fastest for short tasks) */
+ while (ATOMIC_LOAD(&g_task.done_count) < n_workers) {
+#ifdef _WIN32
+ YieldProcessor();
+#else
+ __asm__ __volatile__("pause");
+#endif
+ }
+}
+
+void nn2_tp_destroy(void)
+{
+ int n_workers = g_n_threads - 1;
+ ATOMIC_STORE(&g_shutdown, 1);
+ ATOMIC_ADD(&g_task.phase, 1);
+#ifdef _WIN32
+ WakeByAddressAll((void*)&g_task.phase);
+ for (int i = 0; i < n_workers; i++)
+ WaitForSingleObject(g_workers[i].handle, INFINITE);
+#else
+ syscall(SYS_futex, &g_task.phase, FUTEX_WAKE, MAX_THREADS, NULL, NULL, 0);
+ for (int i = 0; i < n_workers; i++)
+ pthread_join(g_workers[i].handle, NULL);
+#endif
+ g_n_threads = 0;
+}
+
+int nn2_tp_num_threads(void) { return g_n_threads; }
diff --git a/nn2/src/smart_pipeline.c b/nn2/src/smart_pipeline.c
new file mode 100644
index 0000000..d2f565d
--- /dev/null
+++ b/nn2/src/smart_pipeline.c
@@ -0,0 +1,298 @@
+/*
+ * smart_pipeline.c — Smart NVR inference pipeline.
+ *
+ * Combines 3 strategies to minimize compute:
+ * 1. Motion gate: skip inference on static frames (~0.05ms vs 8.5ms)
+ * 2. ROI crop: detect only in motion region (10-50% of pixels)
+ * 3. Temporal skip: full detection every N frames, Kalman track between
+ *
+ * For NVR scenario (15 cameras, 25fps, mostly static):
+ * - ~90% frames: motion gate skip = 0.05ms each
+ * - ~8% frames: temporal skip (Kalman predict only) = 0.01ms each
+ * - ~2% frames: full/ROI detection = 4-8ms each
+ * - Effective: ~0.25ms average per frame = 4000 effective FPS
+ */
+
+#include "nn2_internal.h"
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <math.h>
+
+#ifdef _WIN32
+#include <windows.h>
+static double sp_now(void) {
+ static LARGE_INTEGER freq; static int init=0;
+ if(!init){QueryPerformanceFrequency(&freq);init=1;}
+ LARGE_INTEGER t; QueryPerformanceCounter(&t);
+ return (double)t.QuadPart/(double)freq.QuadPart;
+}
+#endif
+
+/* From motion_gate.c */
+typedef struct {
+ float score;
+ int has_motion;
+ int roi_x1, roi_y1, roi_x2, roi_y2;
+} MotionResult;
+
+extern MotionResult nn2_motion_detect(const uint8_t* prev, const uint8_t* curr,
+ int width, int height,
+ int pixel_thresh, float score_thresh);
+extern void nn2_crop_roi(const uint8_t* src, int src_w, int src_h,
+ int x1, int y1, int x2, int y2,
+ uint8_t* dst, int* dst_w, int* dst_h);
+
+/* ============ Simple Kalman 1D (for bbox tracking) ============ */
+
+typedef struct {
+ float x, v; /* position, velocity */
+ float p, q, r; /* covariance, process noise, measurement noise */
+} Kalman1D;
+
+static void kalman_init(Kalman1D* k, float x0) {
+ k->x = x0; k->v = 0; k->p = 100; k->q = 1; k->r = 10;
+}
+
+static float kalman_predict(Kalman1D* k) {
+ k->x += k->v;
+ k->p += k->q;
+ return k->x;
+}
+
+static void kalman_update(Kalman1D* k, float z) {
+ float kg = k->p / (k->p + k->r);
+ float innov = z - k->x;
+ k->v = k->v + kg * innov * 0.3f; /* smooth velocity update */
+ k->x = k->x + kg * innov;
+ k->p = (1 - kg) * k->p;
+}
+
+/* ============ Per-camera state ============ */
+
+#define MAX_TRACKS 32
+
+typedef struct {
+ int active;
+ int cls;
+ float score;
+ Kalman1D kx1, ky1, kx2, ky2;
+ int frames_since_detect;
+} Track;
+
+typedef struct {
+ uint8_t* prev_frame; /* previous frame for motion detection */
+ int width, height;
+ Track tracks[MAX_TRACKS];
+ int n_tracks;
+ int frame_count;
+ int detect_interval; /* full detect every N frames */
+ int frames_since_detect;
+} CameraState;
+
+/* ============ Smart pipeline per frame ============ */
+
+typedef struct {
+ int n_dets;
+ NN2Det dets[64];
+ float inference_ms;
+ const char* action; /* "skip", "track", "detect", "roi_detect" */
+} FrameResult;
+
+static FrameResult smart_process_frame(
+ NN2* ctx, CameraState* cam,
+ const uint8_t* frame, int width, int height)
+{
+ FrameResult res = {0};
+ cam->frame_count++;
+
+ /* Step 1: Motion gate */
+ if (cam->prev_frame) {
+ double t0 = sp_now();
+ MotionResult mr = nn2_motion_detect(cam->prev_frame, frame,
+ width, height, 25, 0.003f);
+ res.inference_ms = (float)((sp_now() - t0) * 1000.0);
+
+ if (!mr.has_motion) {
+ /* No motion — predict tracks and return */
+ res.action = "skip";
+ for (int i = 0; i < cam->n_tracks; i++) {
+ if (!cam->tracks[i].active) continue;
+ cam->tracks[i].frames_since_detect++;
+ if (cam->tracks[i].frames_since_detect > 30) {
+ cam->tracks[i].active = 0; /* expire old track */
+ continue;
+ }
+ res.dets[res.n_dets].x1 = kalman_predict(&cam->tracks[i].kx1);
+ res.dets[res.n_dets].y1 = kalman_predict(&cam->tracks[i].ky1);
+ res.dets[res.n_dets].x2 = kalman_predict(&cam->tracks[i].kx2);
+ res.dets[res.n_dets].y2 = kalman_predict(&cam->tracks[i].ky2);
+ res.dets[res.n_dets].cls = cam->tracks[i].cls;
+ res.dets[res.n_dets].score = cam->tracks[i].score * 0.95f;
+ res.n_dets++;
+ }
+ memcpy(cam->prev_frame, frame, width * height * 3);
+ return res;
+ }
+ }
+
+ /* Step 2: Temporal skip — only detect every N frames, track between */
+ cam->frames_since_detect++;
+ if (cam->frames_since_detect < cam->detect_interval) {
+ res.action = "track";
+ double t0 = sp_now();
+ for (int i = 0; i < cam->n_tracks; i++) {
+ if (!cam->tracks[i].active) continue;
+ cam->tracks[i].frames_since_detect++;
+ res.dets[res.n_dets].x1 = kalman_predict(&cam->tracks[i].kx1);
+ res.dets[res.n_dets].y1 = kalman_predict(&cam->tracks[i].ky1);
+ res.dets[res.n_dets].x2 = kalman_predict(&cam->tracks[i].kx2);
+ res.dets[res.n_dets].y2 = kalman_predict(&cam->tracks[i].ky2);
+ res.dets[res.n_dets].cls = cam->tracks[i].cls;
+ res.dets[res.n_dets].score = cam->tracks[i].score * 0.98f;
+ res.n_dets++;
+ }
+ res.inference_ms = (float)((sp_now() - t0) * 1000.0);
+ memcpy(cam->prev_frame, frame, width * height * 3);
+ return res;
+ }
+
+ /* Step 3: Full detection */
+ res.action = "detect";
+ cam->frames_since_detect = 0;
+ double t0 = sp_now();
+ res.n_dets = nn2_detect(ctx, frame, width, height, res.dets, 64);
+ res.inference_ms = (float)((sp_now() - t0) * 1000.0);
+
+ /* Update tracks from detections */
+ cam->n_tracks = 0;
+ for (int i = 0; i < res.n_dets && cam->n_tracks < MAX_TRACKS; i++) {
+ Track* t = &cam->tracks[cam->n_tracks++];
+ t->active = 1;
+ t->cls = res.dets[i].cls;
+ t->score = res.dets[i].score;
+ t->frames_since_detect = 0;
+ kalman_init(&t->kx1, res.dets[i].x1);
+ kalman_init(&t->ky1, res.dets[i].y1);
+ kalman_init(&t->kx2, res.dets[i].x2);
+ kalman_init(&t->ky2, res.dets[i].y2);
+ }
+
+ memcpy(cam->prev_frame, frame, width * height * 3);
+ return res;
+}
+
+/* ============ NVR Simulation Benchmark ============ */
+
+int main(int argc, char** argv)
+{
+ const char* wpath = "weights/yolov8n_320.bin";
+ if (argc > 1) wpath = argv[1];
+
+ NN2* ctx = nn2_init(wpath, 0);
+ if (!ctx) { fprintf(stderr, "Failed\n"); return 1; }
+ int S = ctx->input_size;
+
+ /* Simulate 15 cameras, 25fps, 10 seconds = 250 frames per camera */
+ int N_CAMERAS = 15;
+ int N_FRAMES = 250;
+ int W = 320, H = 240; /* typical NVR resolution */
+ int detect_interval = 5; /* detect every 5 frames */
+
+ printf("=== Smart NVR Pipeline Simulation ===\n");
+ printf(" Cameras: %d, Frames/cam: %d, Resolution: %dx%d\n",
+ N_CAMERAS, N_FRAMES, W, H);
+ printf(" Detect interval: every %d frames\n", detect_interval);
+ printf(" Model: YOLOv8n@%d\n\n", S);
+
+ /* Init camera states */
+ CameraState* cams = (CameraState*)calloc(N_CAMERAS, sizeof(CameraState));
+ for (int c = 0; c < N_CAMERAS; c++) {
+ cams[c].width = W;
+ cams[c].height = H;
+ cams[c].prev_frame = (uint8_t*)calloc(W * H * 3, 1);
+ cams[c].detect_interval = detect_interval;
+ }
+
+ /* Generate synthetic frames:
+ * - Cameras 0-9: mostly static (95% identical frames)
+ * - Cameras 10-12: periodic motion (person walking)
+ * - Cameras 13-14: constant motion (traffic) */
+ uint8_t* frame = (uint8_t*)malloc(W * H * 3);
+
+ int total_frames = 0;
+ int skip_count = 0, track_count = 0, detect_count = 0;
+ double total_time = 0;
+ double detect_time = 0;
+
+ double t_start = sp_now();
+
+ for (int f = 0; f < N_FRAMES; f++) {
+ for (int c = 0; c < N_CAMERAS; c++) {
+ /* Generate frame content */
+ memset(frame, 128, W * H * 3); /* gray background */
+
+ int has_change = 0;
+ if (c < 10) {
+ /* Static cameras: change every ~20 frames */
+ has_change = (f % 20 == 0);
+ } else if (c < 13) {
+ /* Periodic motion: change every 3 frames */
+ has_change = (f % 3 == 0);
+ } else {
+ /* Constant motion */
+ has_change = 1;
+ }
+
+ if (has_change) {
+ /* Add some "motion" pixels */
+ int mx = (f * 7 + c * 31) % (W - 50);
+ int my = (f * 11 + c * 17) % (H - 80);
+ for (int y = my; y < my + 80 && y < H; y++)
+ for (int x = mx; x < mx + 50 && x < W; x++) {
+ int off = (y * W + x) * 3;
+ frame[off] = 200; frame[off+1] = 100; frame[off+2] = 50;
+ }
+ }
+
+ /* Process frame through smart pipeline */
+ FrameResult r = smart_process_frame(ctx, &cams[c], frame, W, H);
+ total_frames++;
+ total_time += r.inference_ms;
+
+ if (strcmp(r.action, "skip") == 0) skip_count++;
+ else if (strcmp(r.action, "track") == 0) track_count++;
+ else { detect_count++; detect_time += r.inference_ms; }
+ }
+ }
+
+ double wall_ms = (sp_now() - t_start) * 1000.0;
+
+ printf("=== Results ===\n");
+ printf(" Total frames: %d\n", total_frames);
+ printf(" Actions:\n");
+ printf(" Skip (motion gate): %d (%.1f%%)\n", skip_count, 100.0*skip_count/total_frames);
+ printf(" Track (Kalman): %d (%.1f%%)\n", track_count, 100.0*track_count/total_frames);
+ printf(" Detect (full CNN): %d (%.1f%%)\n", detect_count, 100.0*detect_count/total_frames);
+ printf("\n Timing:\n");
+ printf(" Wall clock: %.0f ms\n", wall_ms);
+ printf(" Total inference: %.1f ms\n", total_time);
+ printf(" Avg per frame: %.3f ms\n", total_time / total_frames);
+ printf(" Avg per detection: %.1f ms\n", detect_count > 0 ? detect_time/detect_count : 0);
+ printf(" Effective FPS: %.0f\n", total_frames / (wall_ms / 1000.0));
+ printf("\n Comparison:\n");
+ printf(" Naive (every frame): %.0f ms (%.0f FPS for %d cams)\n",
+ 8.5 * total_frames / 1000.0 * 1000.0,
+ (double)N_CAMERAS * 25.0, N_CAMERAS);
+ double naive_fps = 1000.0 / 8.5;
+ double smart_fps = total_frames / (wall_ms / 1000.0);
+ printf(" Smart pipeline: %.0f effective FPS\n", smart_fps);
+ double naive_total_fps = 1000.0 / 8.5;
+ printf(" Speedup: %.1fx\n", smart_fps / naive_total_fps);
+
+ /* Cleanup */
+ for (int c = 0; c < N_CAMERAS; c++) free(cams[c].prev_frame);
+ free(cams); free(frame);
+ nn2_free(ctx);
+ return 0;
+}
diff --git a/nn2/src/specialized/forward_spec.c b/nn2/src/specialized/forward_spec.c
new file mode 100644
index 0000000..8183ad0
--- /dev/null
+++ b/nn2/src/specialized/forward_spec.c
@@ -0,0 +1,298 @@
+/*
+ * forward_spec.c — Specialized forward pass for YOLOv8n@320.
+ *
+ * Key optimization: direct GEMM calls with hardcoded dimensions,
+ * skip conv2d dispatcher overhead (branch checks, im2col dispatch decisions).
+ *
+ * For 1x1 convs: call packed GEMM directly (no im2col, no dispatch check).
+ * For 3x3 convs with spatial >= 2500: use implicit conv (already fast).
+ * For 3x3 convs with spatial < 2500: inline im2col + GEMM.
+ *
+ * Also: single-thread GEMM for layers with few N-tiles (avoid dispatch overhead).
+ */
+
+#include "../nn2_internal.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef _WIN32
+#include <windows.h>
+static double spec_now(void) {
+ static LARGE_INTEGER freq; static int init=0;
+ if(!init){QueryPerformanceFrequency(&freq);init=1;}
+ LARGE_INTEGER t; QueryPerformanceCounter(&t);
+ return (double)t.QuadPart/(double)freq.QuadPart;
+}
+#endif
+
+/* Direct 1x1 conv: just GEMM, no dispatch overhead */
+static inline void conv1x1_direct(const ConvLayer* L, const float* in,
+ int spatial, float* out)
+{
+ nn2_sgemm_bias_act_packed(L->cout, L->cin, spatial,
+ L->w_packed, in, out, spatial, L->b, L->act);
+}
+
+/* Direct 3x3 s=1 conv: im2col (single-threaded for small) + GEMM */
+static inline void conv3x3s1_direct(const ConvLayer* L, const float* in,
+ int H, int W, float* out, float* im2col)
+{
+ int spatial = H * W;
+ /* Implicit conv for large spatial */
+ if (L->w_packed && spatial >= 2500) {
+ nn2_conv3x3_s1_implicit(in, L->w, L->b, L->cin, L->cout, H, W,
+ L->act, out, L->w_packed);
+ return;
+ }
+ int K = L->cin * 9;
+ nn2_im2col(in, L->cin, H, W, 3, 3, 1, 1, im2col);
+ nn2_sgemm_bias_act_packed(L->cout, K, spatial,
+ L->w_packed, im2col, out, spatial, L->b, L->act);
+}
+
+/* Direct 3x3 s=2 conv */
+static inline void conv3x3s2_direct(const ConvLayer* L, const float* in,
+ int H, int W, float* out, float* im2col)
+{
+ int Hout = (H + 1) / 2, Wout = (W + 1) / 2;
+ int spatial = Hout * Wout;
+ int K = L->cin * 9;
+ nn2_im2col(in, L->cin, H, W, 3, 3, 2, 1, im2col);
+ nn2_sgemm_bias_act_packed(L->cout, K, spatial,
+ L->w_packed, im2col, out, spatial, L->b, L->act);
+}
+
+/* Direct 3x3 s=2 + fused residual */
+static inline void conv3x3s1_res_direct(const ConvLayer* L, const float* in,
+ int H, int W, float* out, float* im2col,
+ const float* residual)
+{
+ int spatial = H * W;
+ int K = L->cin * 9;
+
+ if (L->w_packed && spatial >= 2500) {
+ nn2_conv3x3_s1_implicit(in, L->w, L->b, L->cin, L->cout, H, W,
+ L->act, out, L->w_packed);
+ for (int i = 0; i < L->cout * spatial; i++) out[i] += residual[i];
+ return;
+ }
+
+ nn2_im2col(in, L->cin, H, W, 3, 3, 1, 1, im2col);
+ nn2_sgemm_bias_act_res_packed(L->cout, K, spatial,
+ L->w_packed, im2col, out, spatial,
+ L->b, L->act, residual, spatial);
+}
+
+/* Specialized C2f block: all paths known at compile time */
+static void c2f_spec(const C2fBlock* blk, const float* in, int H, int W,
+ float* out, float* im2col, float* tmp)
+{
+ int spatial = H * W;
+ int c = blk->c;
+ int total_ch = (2 + blk->n) * c;
+ float* cat = tmp;
+ float* scratch = tmp + total_ch * spatial;
+
+ /* cv1: always 1x1 */
+ conv1x1_direct(&blk->cv1, in, spatial, cat);
+
+ float* bn_in = cat + c * spatial;
+ for (int i = 0; i < blk->n; i++) {
+ /* bn.cv1: always 3x3 s=1 */
+ conv3x3s1_direct(&blk->m[i].cv1, bn_in, H, W, scratch, im2col);
+
+ /* bn.cv2: 3x3 s=1 + residual */
+ float* bn_out = cat + (2 + i) * c * spatial;
+ if (blk->shortcut) {
+ conv3x3s1_res_direct(&blk->m[i].cv2, scratch, H, W, bn_out, im2col, bn_in);
+ } else {
+ conv3x3s1_direct(&blk->m[i].cv2, scratch, H, W, bn_out, im2col);
+ }
+ bn_in = bn_out;
+ }
+
+ /* cv2: always 1x1 */
+ conv1x1_direct(&blk->cv2, cat, spatial, out);
+}
+
+/* ============ Specialized forward pass ============ */
+
+int nn2_forward_spec(NN2* ctx, const float* input, float* bbox_out, float* cls_out)
+{
+ int S = ctx->input_size;
+ float* ws = ctx->workspace;
+
+ float* im2col = ws; ws += 4*1024*1024;
+ float* buf0 = ws; ws += 4*1024*1024;
+ float* buf1 = ws; ws += 4*1024*1024;
+ ws += 64*(S/8)*(S/8); /* skip save slots — we use direct pointers */
+ ws += 128*(S/16)*(S/16);
+ ws += 256*(S/32)*(S/32);
+ ws += 128*(S/16)*(S/16);
+ float* c2f_tmp = ws;
+
+ int h = S, w = S;
+ int h0=S/2,w0=S/2, h1=S/4,w1=S/4, h2=S/8,w2=S/8;
+ int h3=S/16,w3=S/16, h4=S/32,w4=S/32;
+ float *cur = buf0, *nxt = buf1;
+ #define SWAP() { float* t_=cur; cur=nxt; nxt=t_; }
+
+ /* === Backbone — direct calls, no dispatcher === */
+ conv3x3s2_direct(&ctx->bb_conv[0], input, h, w, cur, im2col);
+ conv3x3s2_direct(&ctx->bb_conv[1], cur, h0, w0, nxt, im2col); SWAP();
+ c2f_spec(&ctx->bb_c2f[0], cur, h1, w1, nxt, im2col, c2f_tmp); SWAP();
+
+ conv3x3s2_direct(&ctx->bb_conv[2], cur, h1, w1, nxt, im2col); SWAP();
+ c2f_spec(&ctx->bb_c2f[1], cur, h2, w2, nxt, im2col, c2f_tmp); SWAP();
+ /* save P3 */
+ float* save_p3 = ctx->workspace + 12*1024*1024; /* reuse save slot area */
+ memcpy(save_p3, cur, 64*h2*w2*sizeof(float));
+
+ conv3x3s2_direct(&ctx->bb_conv[3], cur, h2, w2, nxt, im2col); SWAP();
+ c2f_spec(&ctx->bb_c2f[2], cur, h3, w3, nxt, im2col, c2f_tmp); SWAP();
+ float* save_p4 = save_p3 + 64*h2*w2;
+ memcpy(save_p4, cur, 128*h3*w3*sizeof(float));
+
+ conv3x3s2_direct(&ctx->bb_conv[4], cur, h3, w3, nxt, im2col); SWAP();
+ c2f_spec(&ctx->bb_c2f[3], cur, h4, w4, nxt, im2col, c2f_tmp); SWAP();
+
+ /* SPPF */
+ conv1x1_direct(&ctx->sppf_cv1, cur, h4*w4, nxt); SWAP();
+ {
+ int sp = h4 * w4;
+ float* sppf_in = cur;
+ float* cat = c2f_tmp;
+ float* mp1 = cat + 512*sp, *mp2 = mp1+128*sp, *mp3 = mp2+128*sp;
+ nn2_maxpool2d(sppf_in, 128, h4, w4, 5, 1, 2, mp1);
+ nn2_maxpool2d(mp1, 128, h4, w4, 5, 1, 2, mp2);
+ nn2_maxpool2d(mp2, 128, h4, w4, 5, 1, 2, mp3);
+ memcpy(cat, sppf_in, 128*sp*sizeof(float));
+ memcpy(cat+128*sp, mp1, 128*sp*sizeof(float));
+ memcpy(cat+256*sp, mp2, 128*sp*sizeof(float));
+ memcpy(cat+384*sp, mp3, 128*sp*sizeof(float));
+ conv1x1_direct(&ctx->sppf_cv2, cat, sp, nxt); SWAP();
+ }
+ float* save_p5 = save_p4 + 128*h3*w3;
+ memcpy(save_p5, cur, 256*h4*w4*sizeof(float));
+
+ /* === Neck === */
+ {
+ float* up = c2f_tmp;
+ nn2_upsample_2x(cur, 256, h4, w4, up);
+ nn2_concat(up, 256, save_p4, 128, h3, w3, nxt);
+ SWAP();
+ }
+ c2f_spec(&ctx->nk_c2f[0], cur, h3, w3, nxt, im2col, c2f_tmp); SWAP();
+ float* save_n3 = save_p5 + 256*h4*w4;
+ memcpy(save_n3, cur, 128*h3*w3*sizeof(float));
+
+ {
+ float* up = c2f_tmp;
+ nn2_upsample_2x(cur, 128, h3, w3, up);
+ nn2_concat(up, 128, save_p3, 64, h2, w2, nxt);
+ SWAP();
+ }
+ float* feat_n2 = save_p3; /* reuse */
+ c2f_spec(&ctx->nk_c2f[1], cur, h2, w2, feat_n2, im2col, c2f_tmp);
+
+ conv3x3s2_direct(&ctx->nk_conv[0], feat_n2, h2, w2, cur, im2col);
+ { nn2_concat(cur, 64, save_n3, 128, h3, w3, nxt); SWAP(); }
+ float* feat_n4 = save_p4;
+ c2f_spec(&ctx->nk_c2f[2], cur, h3, w3, feat_n4, im2col, c2f_tmp);
+
+ conv3x3s2_direct(&ctx->nk_conv[1], feat_n4, h3, w3, cur, im2col);
+ { nn2_concat(cur, 128, save_p5, 256, h4, w4, nxt); SWAP(); }
+ float* feat_n5 = save_p5;
+ c2f_spec(&ctx->nk_c2f[3], cur, h4, w4, feat_n5, im2col, c2f_tmp);
+
+ /* === Head — direct calls === */
+ float* feats[3] = {feat_n2, feat_n4, feat_n5};
+ int feat_h[] = {h2, h3, h4};
+ int feat_w[] = {w2, w3, w4};
+ int total_anchors = h2*w2 + h3*w3 + h4*w4;
+ int bbox_ch = 4 * NN2_REG_MAX;
+ int cls_ch = ctx->num_classes;
+ int offset = 0;
+
+ for (int s = 0; s < 3; s++) {
+ int fh = feat_h[s], fw = feat_w[s], sp = fh * fw;
+ float* tmp = c2f_tmp;
+
+ float* bx1 = tmp;
+ conv3x3s1_direct(&ctx->head[s].bbox[0], feats[s], fh, fw, bx1, im2col);
+ float* bx2 = bx1 + ctx->head[s].bbox[0].cout * sp;
+ conv3x3s1_direct(&ctx->head[s].bbox[1], bx1, fh, fw, bx2, im2col);
+ float* bx3 = bx2 + ctx->head[s].bbox[1].cout * sp;
+ conv1x1_direct(&ctx->head[s].bbox[2], bx2, sp, bx3);
+
+ float* cx1 = bx3 + bbox_ch * sp;
+ conv3x3s1_direct(&ctx->head[s].cls[0], feats[s], fh, fw, cx1, im2col);
+ float* cx2 = cx1 + ctx->head[s].cls[0].cout * sp;
+ conv3x3s1_direct(&ctx->head[s].cls[1], cx1, fh, fw, cx2, im2col);
+ float* cx3 = cx2 + ctx->head[s].cls[1].cout * sp;
+ conv1x1_direct(&ctx->head[s].cls[2], cx2, sp, cx3);
+
+ for (int c = 0; c < bbox_ch; c++)
+ memcpy(bbox_out + c*total_anchors + offset, bx3 + c*sp, sp*sizeof(float));
+ for (int c = 0; c < cls_ch; c++)
+ memcpy(cls_out + c*total_anchors + offset, cx3 + c*sp, sp*sizeof(float));
+ offset += sp;
+ }
+
+ #undef SWAP
+ return total_anchors;
+}
+
+/* ============ Benchmark ============ */
+
+int main(int argc, char** argv)
+{
+ const char* wpath = "weights/yolov8n_320.bin";
+ if (argc > 1) wpath = argv[1];
+
+ NN2* ctx = nn2_init(wpath, 0);
+ if (!ctx) { fprintf(stderr, "Failed\n"); return 1; }
+ int S = ctx->input_size;
+
+ float* input = (float*)calloc(3*S*S, sizeof(float));
+ for (int i = 0; i < 3*S*S; i++) input[i] = 0.5f;
+ int ta = (S/8)*(S/8)+(S/16)*(S/16)+(S/32)*(S/32);
+ float* bbox = (float*)calloc(64*ta, sizeof(float));
+ float* cls = (float*)calloc(80*ta, sizeof(float));
+
+ /* Warmup both paths */
+ for (int i = 0; i < 3; i++) {
+ nn2_forward(ctx, input, bbox, cls);
+ nn2_forward_spec(ctx, input, bbox, cls);
+ }
+
+ int RUNS = 50;
+
+ /* Benchmark original */
+ nn2_tp_reset_dispatch_count();
+ double t0 = spec_now();
+ for (int i = 0; i < RUNS; i++)
+ nn2_forward(ctx, input, bbox, cls);
+ double orig_ms = (spec_now() - t0) / RUNS * 1000.0;
+ int orig_disp = nn2_tp_dispatch_count() / RUNS;
+
+ /* Benchmark specialized */
+ nn2_tp_reset_dispatch_count();
+ t0 = spec_now();
+ for (int i = 0; i < RUNS; i++)
+ nn2_forward_spec(ctx, input, bbox, cls);
+ double spec_ms = (spec_now() - t0) / RUNS * 1000.0;
+ int spec_disp = nn2_tp_dispatch_count() / RUNS;
+
+ printf("=== Specialized Forward Pass ===\n");
+ printf(" Original: %.2f ms (%d dispatches)\n", orig_ms, orig_disp);
+ printf(" Specialized: %.2f ms (%d dispatches)\n", spec_ms, spec_disp);
+ printf(" Speedup: %.2fx\n", orig_ms / spec_ms);
+ printf(" Dispatch reduction: %d → %d (%.0f%% fewer)\n",
+ orig_disp, spec_disp, 100.0*(1.0 - (double)spec_disp/orig_disp));
+
+ free(input); free(bbox); free(cls);
+ nn2_free(ctx);
+ return 0;
+}
diff --git a/nn2/src/specialized/gen_forward.py b/nn2/src/specialized/gen_forward.py
new file mode 100644
index 0000000..1c838b8
--- /dev/null
+++ b/nn2/src/specialized/gen_forward.py
@@ -0,0 +1,105 @@
+#!/usr/bin/env python3
+"""
+Generate a compile-time specialized forward pass for YOLOv8n@320.
+
+Every conv layer gets hardcoded dimensions, no runtime dispatch.
+GEMM calls use exact tile counts, skip all branches.
+"""
+
+S = 320
+MR = 6
+NR = 32
+
+# YOLOv8n architecture: (name, cin, cout, k, stride, pad, act, H_in, W_in)
+layers = []
+
+def add_conv(name, cin, cout, k, stride, pad, act, H, W):
+ Hout = (H + 2*pad - k) // stride + 1
+ Wout = (W + 2*pad - k) // stride + 1
+ spatial = Hout * Wout
+ K = cin * k * k
+ n_tiles = (spatial + NR - 1) // NR
+ m_panels = (cout + MR - 1) // MR
+ flops = 2 * cout * K * spatial
+ layers.append({
+ 'name': name, 'cin': cin, 'cout': cout, 'k': k,
+ 'stride': stride, 'pad': pad, 'act': act,
+ 'H': H, 'W': W, 'Hout': Hout, 'Wout': Wout,
+ 'spatial': spatial, 'K': K,
+ 'n_tiles': n_tiles, 'm_panels': m_panels, 'flops': flops
+ })
+ return Hout, Wout
+
+def add_c2f(name, cin, cout, n_bn, shortcut, H, W):
+ c = cout // 2
+ add_conv(f'{name}.cv1', cin, 2*c, 1, 1, 0, 1, H, W)
+ for i in range(n_bn):
+ add_conv(f'{name}.bn{i}.cv1', c, c, 3, 1, 1, 1, H, W)
+ add_conv(f'{name}.bn{i}.cv2', c, c, 3, 1, 1, 1, H, W)
+ total_c = (2 + n_bn) * c
+ add_conv(f'{name}.cv2', total_c, cout, 1, 1, 0, 1, H, W)
+
+h, w = S, S
+
+# Backbone
+h0, w0 = add_conv('bb_conv0', 3, 16, 3, 2, 1, 1, h, w)
+h1, w1 = add_conv('bb_conv1', 16, 32, 3, 2, 1, 1, h0, w0)
+add_c2f('bb_c2f0', 32, 32, 1, 1, h1, w1)
+h2, w2 = add_conv('bb_conv2', 32, 64, 3, 2, 1, 1, h1, w1)
+add_c2f('bb_c2f1', 64, 64, 2, 1, h2, w2)
+h3, w3 = add_conv('bb_conv3', 64, 128, 3, 2, 1, 1, h2, w2)
+add_c2f('bb_c2f2', 128, 128, 2, 1, h3, w3)
+h4, w4 = add_conv('bb_conv4', 128, 256, 3, 2, 1, 1, h3, w3)
+add_c2f('bb_c2f3', 256, 256, 1, 1, h4, w4)
+
+# SPPF
+add_conv('sppf_cv1', 256, 128, 1, 1, 0, 1, h4, w4)
+add_conv('sppf_cv2', 512, 256, 1, 1, 0, 1, h4, w4)
+
+# Neck
+add_c2f('nk_c2f0', 384, 128, 1, 0, h3, w3)
+add_c2f('nk_c2f1', 192, 64, 1, 0, h2, w2)
+add_conv('nk_conv0', 64, 64, 3, 2, 1, 1, h2, w2)
+add_c2f('nk_c2f2', 192, 128, 1, 0, h3, w3)
+add_conv('nk_conv1', 128, 128, 3, 2, 1, 1, h3, w3)
+add_c2f('nk_c2f3', 384, 256, 1, 0, h4, w4)
+
+# Head
+head_ch = [64, 128, 256]
+feat_h = [h2, h3, h4]
+feat_w = [w2, w3, w4]
+for s in range(3):
+ fh, fw = feat_h[s], feat_w[s]
+ add_conv(f'head{s}_bbox0', head_ch[s], 64, 3, 1, 1, 1, fh, fw)
+ add_conv(f'head{s}_bbox1', 64, 64, 3, 1, 1, 1, fh, fw)
+ add_conv(f'head{s}_bbox2', 64, 64, 1, 1, 0, 0, fh, fw)
+ add_conv(f'head{s}_cls0', head_ch[s], 64, 3, 1, 1, 1, fh, fw)
+ add_conv(f'head{s}_cls1', 64, 64, 3, 1, 1, 1, fh, fw)
+ add_conv(f'head{s}_cls2', 64, 80, 1, 1, 0, 0, fh, fw)
+
+# Print summary
+print(f"YOLOv8n@{S}: {len(layers)} conv layers")
+total_flops = sum(l['flops'] for l in layers)
+print(f"Total FLOPs: {total_flops/1e6:.1f}M")
+print(f"Total dispatches (1 GEMM + im2col each): ~{len(layers)*2}")
+print()
+
+# Categorize by size
+small = [l for l in layers if l['flops'] < 1_000_000]
+medium = [l for l in layers if 1_000_000 <= l['flops'] < 10_000_000]
+large = [l for l in layers if l['flops'] >= 10_000_000]
+print(f"Small (<1M FLOPs): {len(small)} layers — single-thread candidates")
+print(f"Medium (1-10M): {len(medium)} layers")
+print(f"Large (>10M): {len(large)} layers — main compute")
+print()
+
+# Show layers that should be single-threaded
+print("Layers to run single-threaded (< 500K FLOPs):")
+for l in layers:
+ if l['flops'] < 500_000:
+ print(f" {l['name']:30s} {l['cout']:3d}x{l['K']:4d}x{l['spatial']:5d} = {l['flops']/1e3:.0f}K FLOPs")
+
+print()
+print("Top 10 heaviest layers:")
+for l in sorted(layers, key=lambda x: -x['flops'])[:10]:
+ print(f" {l['name']:30s} {l['cout']:3d}x{l['K']:4d}x{l['spatial']:5d} = {l['flops']/1e6:.1f}M FLOPs, {l['n_tiles']} tiles")
diff --git a/nn2/src/stb_image.h b/nn2/src/stb_image.h
new file mode 100644
index 0000000..9eedabe
--- /dev/null
+++ b/nn2/src/stb_image.h
@@ -0,0 +1,7988 @@
+/* stb_image - v2.30 - public domain image loader - http://nothings.org/stb
+ no warranty implied; use at your own risk
+
+ Do this:
+ #define STB_IMAGE_IMPLEMENTATION
+ before you include this file in *one* C or C++ file to create the implementation.
+
+ // i.e. it should look like this:
+ #include ...
+ #include ...
+ #include ...
+ #define STB_IMAGE_IMPLEMENTATION
+ #include "stb_image.h"
+
+ You can #define STBI_ASSERT(x) before the #include to avoid using assert.h.
+ And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free
+
+
+ QUICK NOTES:
+ Primarily of interest to game developers and other people who can
+ avoid problematic images and only need the trivial interface
+
+ JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib)
+ PNG 1/2/4/8/16-bit-per-channel
+
+ TGA (not sure what subset, if a subset)
+ BMP non-1bpp, non-RLE
+ PSD (composited view only, no extra channels, 8/16 bit-per-channel)
+
+ GIF (*comp always reports as 4-channel)
+ HDR (radiance rgbE format)
+ PIC (Softimage PIC)
+ PNM (PPM and PGM binary only)
+
+ Animated GIF still needs a proper API, but here's one way to do it:
+ http://gist.github.com/urraka/685d9a6340b26b830d49
+
+ - decode from memory or through FILE (define STBI_NO_STDIO to remove code)
+ - decode from arbitrary I/O callbacks
+ - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON)
+
+ Full documentation under "DOCUMENTATION" below.
+
+
+LICENSE
+
+ See end of file for license information.
+
+RECENT REVISION HISTORY:
+
+ 2.30 (2024-05-31) avoid erroneous gcc warning
+ 2.29 (2023-05-xx) optimizations
+ 2.28 (2023-01-29) many error fixes, security errors, just tons of stuff
+ 2.27 (2021-07-11) document stbi_info better, 16-bit PNM support, bug fixes
+ 2.26 (2020-07-13) many minor fixes
+ 2.25 (2020-02-02) fix warnings
+ 2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically
+ 2.23 (2019-08-11) fix clang static analysis warning
+ 2.22 (2019-03-04) gif fixes, fix warnings
+ 2.21 (2019-02-25) fix typo in comment
+ 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs
+ 2.19 (2018-02-11) fix warning
+ 2.18 (2018-01-30) fix warnings
+ 2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings
+ 2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes
+ 2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC
+ 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs
+ 2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes
+ 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes
+ 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64
+ RGB-format JPEG; remove white matting in PSD;
+ allocate large structures on the stack;
+ correct channel count for PNG & BMP
+ 2.10 (2016-01-22) avoid warning introduced in 2.09
+ 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED
+
+ See end of file for full revision history.
+
+
+ ============================ Contributors =========================
+
+ Image formats Extensions, features
+ Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info)
+ Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info)
+ Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG)
+ Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks)
+ Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG)
+ Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip)
+ Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD)
+ github:urraka (animated gif) Junggon Kim (PNM comments)
+ Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA)
+ socks-the-fox (16-bit PNG)
+ Jeremy Sawicki (handle all ImageNet JPGs)
+ Optimizations & bugfixes Mikhail Morozov (1-bit BMP)
+ Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query)
+ Arseny Kapoulkine Simon Breuss (16-bit PNM)
+ John-Mark Allen
+ Carmelo J Fdez-Aguera
+
+ Bug & warning fixes
+ Marc LeBlanc David Woo Guillaume George Martins Mozeiko
+ Christpher Lloyd Jerry Jansson Joseph Thomson Blazej Dariusz Roszkowski
+ Phil Jordan Dave Moore Roy Eltham
+ Hayaki Saito Nathan Reed Won Chun
+ Luke Graham Johan Duparc Nick Verigakis the Horde3D community
+ Thomas Ruf Ronny Chevalier github:rlyeh
+ Janez Zemva John Bartholomew Michal Cichon github:romigrou
+ Jonathan Blow Ken Hamada Tero Hanninen github:svdijk
+ Eugene Golushkov Laurent Gomila Cort Stratton github:snagar
+ Aruelien Pocheville Sergio Gonzalez Thibault Reuille github:Zelex
+ Cass Everitt Ryamond Barbiero github:grim210
+ Paul Du Bois Engin Manap Aldo Culquicondor github:sammyhw
+ Philipp Wiesemann Dale Weiler Oriol Ferrer Mesia github:phprus
+ Josh Tobin Neil Bickford Matthew Gregan github:poppolopoppo
+ Julian Raschke Gregory Mullen Christian Floisand github:darealshinji
+ Baldur Karlsson Kevin Schmidt JR Smith github:Michaelangel007
+ Brad Weinberger Matvey Cherevko github:mosra
+ Luca Sas Alexander Veselov Zack Middleton [reserved]
+ Ryan C. Gordon [reserved] [reserved]
+ DO NOT ADD YOUR NAME HERE
+
+ Jacko Dirks
+
+ To add your name to the credits, pick a random blank space in the middle and fill it.
+ 80% of merge conflicts on stb PRs are due to people adding their name at the end
+ of the credits.
+*/
+
+#ifndef STBI_INCLUDE_STB_IMAGE_H
+#define STBI_INCLUDE_STB_IMAGE_H
+
+// DOCUMENTATION
+//
+// Limitations:
+// - no 12-bit-per-channel JPEG
+// - no JPEGs with arithmetic coding
+// - GIF always returns *comp=4
+//
+// Basic usage (see HDR discussion below for HDR usage):
+// int x,y,n;
+// unsigned char *data = stbi_load(filename, &x, &y, &n, 0);
+// // ... process data if not NULL ...
+// // ... x = width, y = height, n = # 8-bit components per pixel ...
+// // ... replace '0' with '1'..'4' to force that many components per pixel
+// // ... but 'n' will always be the number that it would have been if you said 0
+// stbi_image_free(data);
+//
+// Standard parameters:
+// int *x -- outputs image width in pixels
+// int *y -- outputs image height in pixels
+// int *channels_in_file -- outputs # of image components in image file
+// int desired_channels -- if non-zero, # of image components requested in result
+//
+// The return value from an image loader is an 'unsigned char *' which points
+// to the pixel data, or NULL on an allocation failure or if the image is
+// corrupt or invalid. The pixel data consists of *y scanlines of *x pixels,
+// with each pixel consisting of N interleaved 8-bit components; the first
+// pixel pointed to is top-left-most in the image. There is no padding between
+// image scanlines or between pixels, regardless of format. The number of
+// components N is 'desired_channels' if desired_channels is non-zero, or
+// *channels_in_file otherwise. If desired_channels is non-zero,
+// *channels_in_file has the number of components that _would_ have been
+// output otherwise. E.g. if you set desired_channels to 4, you will always
+// get RGBA output, but you can check *channels_in_file to see if it's trivially
+// opaque because e.g. there were only 3 channels in the source image.
+//
+// An output image with N components has the following components interleaved
+// in this order in each pixel:
+//
+// N=#comp components
+// 1 grey
+// 2 grey, alpha
+// 3 red, green, blue
+// 4 red, green, blue, alpha
+//
+// If image loading fails for any reason, the return value will be NULL,
+// and *x, *y, *channels_in_file will be unchanged. The function
+// stbi_failure_reason() can be queried for an extremely brief, end-user
+// unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS
+// to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly
+// more user-friendly ones.
+//
+// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized.
+//
+// To query the width, height and component count of an image without having to
+// decode the full file, you can use the stbi_info family of functions:
+//
+// int x,y,n,ok;
+// ok = stbi_info(filename, &x, &y, &n);
+// // returns ok=1 and sets x, y, n if image is a supported format,
+// // 0 otherwise.
+//
+// Note that stb_image pervasively uses ints in its public API for sizes,
+// including sizes of memory buffers. This is now part of the API and thus
+// hard to change without causing breakage. As a result, the various image
+// loaders all have certain limits on image size; these differ somewhat
+// by format but generally boil down to either just under 2GB or just under
+// 1GB. When the decoded image would be larger than this, stb_image decoding
+// will fail.
+//
+// Additionally, stb_image will reject image files that have any of their
+// dimensions set to a larger value than the configurable STBI_MAX_DIMENSIONS,
+// which defaults to 2**24 = 16777216 pixels. Due to the above memory limit,
+// the only way to have an image with such dimensions load correctly
+// is for it to have a rather extreme aspect ratio. Either way, the
+// assumption here is that such larger images are likely to be malformed
+// or malicious. If you do need to load an image with individual dimensions
+// larger than that, and it still fits in the overall size limit, you can
+// #define STBI_MAX_DIMENSIONS on your own to be something larger.
+//
+// ===========================================================================
+//
+// UNICODE:
+//
+// If compiling for Windows and you wish to use Unicode filenames, compile
+// with
+// #define STBI_WINDOWS_UTF8
+// and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert
+// Windows wchar_t filenames to utf8.
+//
+// ===========================================================================
+//
+// Philosophy
+//
+// stb libraries are designed with the following priorities:
+//
+// 1. easy to use
+// 2. easy to maintain
+// 3. good performance
+//
+// Sometimes I let "good performance" creep up in priority over "easy to maintain",
+// and for best performance I may provide less-easy-to-use APIs that give higher
+// performance, in addition to the easy-to-use ones. Nevertheless, it's important
+// to keep in mind that from the standpoint of you, a client of this library,
+// all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all.
+//
+// Some secondary priorities arise directly from the first two, some of which
+// provide more explicit reasons why performance can't be emphasized.
+//
+// - Portable ("ease of use")
+// - Small source code footprint ("easy to maintain")
+// - No dependencies ("ease of use")
+//
+// ===========================================================================
+//
+// I/O callbacks
+//
+// I/O callbacks allow you to read from arbitrary sources, like packaged
+// files or some other source. Data read from callbacks are processed
+// through a small internal buffer (currently 128 bytes) to try to reduce
+// overhead.
+//
+// The three functions you must define are "read" (reads some bytes of data),
+// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end).
+//
+// ===========================================================================
+//
+// SIMD support
+//
+// The JPEG decoder will try to automatically use SIMD kernels on x86 when
+// supported by the compiler. For ARM Neon support, you must explicitly
+// request it.
+//
+// (The old do-it-yourself SIMD API is no longer supported in the current
+// code.)
+//
+// On x86, SSE2 will automatically be used when available based on a run-time
+// test; if not, the generic C versions are used as a fall-back. On ARM targets,
+// the typical path is to have separate builds for NEON and non-NEON devices
+// (at least this is true for iOS and Android). Therefore, the NEON support is
+// toggled by a build flag: define STBI_NEON to get NEON loops.
+//
+// If for some reason you do not want to use any of SIMD code, or if
+// you have issues compiling it, you can disable it entirely by
+// defining STBI_NO_SIMD.
+//
+// ===========================================================================
+//
+// HDR image support (disable by defining STBI_NO_HDR)
+//
+// stb_image supports loading HDR images in general, and currently the Radiance
+// .HDR file format specifically. You can still load any file through the existing
+// interface; if you attempt to load an HDR file, it will be automatically remapped
+// to LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;
+// both of these constants can be reconfigured through this interface:
+//
+// stbi_hdr_to_ldr_gamma(2.2f);
+// stbi_hdr_to_ldr_scale(1.0f);
+//
+// (note, do not use _inverse_ constants; stbi_image will invert them
+// appropriately).
+//
+// Additionally, there is a new, parallel interface for loading files as
+// (linear) floats to preserve the full dynamic range:
+//
+// float *data = stbi_loadf(filename, &x, &y, &n, 0);
+//
+// If you load LDR images through this interface, those images will
+// be promoted to floating point values, run through the inverse of
+// constants corresponding to the above:
+//
+// stbi_ldr_to_hdr_scale(1.0f);
+// stbi_ldr_to_hdr_gamma(2.2f);
+//
+// Finally, given a filename (or an open file or memory block--see header
+// file for details) containing image data, you can query for the "most
+// appropriate" interface to use (that is, whether the image is HDR or
+// not), using:
+//
+// stbi_is_hdr(char *filename);
+//
+// ===========================================================================
+//
+// iPhone PNG support:
+//
+// We optionally support converting iPhone-formatted PNGs (which store
+// premultiplied BGRA) back to RGB, even though they're internally encoded
+// differently. To enable this conversion, call
+// stbi_convert_iphone_png_to_rgb(1).
+//
+// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per
+// pixel to remove any premultiplied alpha *only* if the image file explicitly
+// says there's premultiplied data (currently only happens in iPhone images,
+// and only if iPhone convert-to-rgb processing is on).
+//
+// ===========================================================================
+//
+// ADDITIONAL CONFIGURATION
+//
+// - You can suppress implementation of any of the decoders to reduce
+// your code footprint by #defining one or more of the following
+// symbols before creating the implementation.
+//
+// STBI_NO_JPEG
+// STBI_NO_PNG
+// STBI_NO_BMP
+// STBI_NO_PSD
+// STBI_NO_TGA
+// STBI_NO_GIF
+// STBI_NO_HDR
+// STBI_NO_PIC
+// STBI_NO_PNM (.ppm and .pgm)
+//
+// - You can request *only* certain decoders and suppress all other ones
+// (this will be more forward-compatible, as addition of new decoders
+// doesn't require you to disable them explicitly):
+//
+// STBI_ONLY_JPEG
+// STBI_ONLY_PNG
+// STBI_ONLY_BMP
+// STBI_ONLY_PSD
+// STBI_ONLY_TGA
+// STBI_ONLY_GIF
+// STBI_ONLY_HDR
+// STBI_ONLY_PIC
+// STBI_ONLY_PNM (.ppm and .pgm)
+//
+// - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still
+// want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB
+//
+// - If you define STBI_MAX_DIMENSIONS, stb_image will reject images greater
+// than that size (in either width or height) without further processing.
+// This is to let programs in the wild set an upper bound to prevent
+// denial-of-service attacks on untrusted data, as one could generate a
+// valid image of gigantic dimensions and force stb_image to allocate a
+// huge block of memory and spend disproportionate time decoding it. By
+// default this is set to (1 << 24), which is 16777216, but that's still
+// very big.
+
+#ifndef STBI_NO_STDIO
+#include <stdio.h>
+#endif // STBI_NO_STDIO
+
+#define STBI_VERSION 1
+
+enum
+{
+ STBI_default = 0, // only used for desired_channels
+
+ STBI_grey = 1,
+ STBI_grey_alpha = 2,
+ STBI_rgb = 3,
+ STBI_rgb_alpha = 4
+};
+
+#include <stdlib.h>
+typedef unsigned char stbi_uc;
+typedef unsigned short stbi_us;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef STBIDEF
+#ifdef STB_IMAGE_STATIC
+#define STBIDEF static
+#else
+#define STBIDEF extern
+#endif
+#endif
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// PRIMARY API - works on images of any type
+//
+
+//
+// load image by filename, open file, or memory buffer
+//
+
+typedef struct
+{
+ int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read
+ void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative
+ int (*eof) (void *user); // returns nonzero if we are at end of file/data
+} stbi_io_callbacks;
+
+////////////////////////////////////
+//
+// 8-bits-per-channel interface
+//
+
+STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *channels_in_file, int desired_channels);
+STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *channels_in_file, int desired_channels);
+
+#ifndef STBI_NO_STDIO
+STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels);
+STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels);
+// for stbi_load_from_file, file pointer is left pointing immediately after image
+#endif
+
+#ifndef STBI_NO_GIF
+STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp);
+#endif
+
+#ifdef STBI_WINDOWS_UTF8
+STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input);
+#endif
+
+////////////////////////////////////
+//
+// 16-bits-per-channel interface
+//
+
+STBIDEF stbi_us *stbi_load_16_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels);
+STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels);
+
+#ifndef STBI_NO_STDIO
+STBIDEF stbi_us *stbi_load_16 (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels);
+STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels);
+#endif
+
+////////////////////////////////////
+//
+// float-per-channel interface
+//
+#ifndef STBI_NO_LINEAR
+ STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels);
+ STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels);
+
+ #ifndef STBI_NO_STDIO
+ STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels);
+ STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels);
+ #endif
+#endif
+
+#ifndef STBI_NO_HDR
+ STBIDEF void stbi_hdr_to_ldr_gamma(float gamma);
+ STBIDEF void stbi_hdr_to_ldr_scale(float scale);
+#endif // STBI_NO_HDR
+
+#ifndef STBI_NO_LINEAR
+ STBIDEF void stbi_ldr_to_hdr_gamma(float gamma);
+ STBIDEF void stbi_ldr_to_hdr_scale(float scale);
+#endif // STBI_NO_LINEAR
+
+// stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR
+STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user);
+STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len);
+#ifndef STBI_NO_STDIO
+STBIDEF int stbi_is_hdr (char const *filename);
+STBIDEF int stbi_is_hdr_from_file(FILE *f);
+#endif // STBI_NO_STDIO
+
+
+// get a VERY brief reason for failure
+// on most compilers (and ALL modern mainstream compilers) this is threadsafe
+STBIDEF const char *stbi_failure_reason (void);
+
+// free the loaded image -- this is just free()
+STBIDEF void stbi_image_free (void *retval_from_stbi_load);
+
+// get image dimensions & components without fully decoding
+STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
+STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp);
+STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len);
+STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *clbk, void *user);
+
+#ifndef STBI_NO_STDIO
+STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp);
+STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp);
+STBIDEF int stbi_is_16_bit (char const *filename);
+STBIDEF int stbi_is_16_bit_from_file(FILE *f);
+#endif
+
+
+
+// for image formats that explicitly notate that they have premultiplied alpha,
+// we just return the colors as stored in the file. set this flag to force
+// unpremultiplication. results are undefined if the unpremultiply overflow.
+STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply);
+
+// indicate whether we should process iphone images back to canonical format,
+// or just pass them through "as-is"
+STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert);
+
+// flip the image vertically, so the first pixel in the output array is the bottom left
+STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip);
+
+// as above, but only applies to images loaded on the thread that calls the function
+// this function is only available if your compiler supports thread-local variables;
+// calling it will fail to link if your compiler doesn't
+STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply);
+STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert);
+STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip);
+
+// ZLIB client - used by PNG, available for other purposes
+
+STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen);
+STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header);
+STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen);
+STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
+
+STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen);
+STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+//
+//
+//// end header file /////////////////////////////////////////////////////
+#endif // STBI_INCLUDE_STB_IMAGE_H
+
+#ifdef STB_IMAGE_IMPLEMENTATION
+
+#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \
+ || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \
+ || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \
+ || defined(STBI_ONLY_ZLIB)
+ #ifndef STBI_ONLY_JPEG
+ #define STBI_NO_JPEG
+ #endif
+ #ifndef STBI_ONLY_PNG
+ #define STBI_NO_PNG
+ #endif
+ #ifndef STBI_ONLY_BMP
+ #define STBI_NO_BMP
+ #endif
+ #ifndef STBI_ONLY_PSD
+ #define STBI_NO_PSD
+ #endif
+ #ifndef STBI_ONLY_TGA
+ #define STBI_NO_TGA
+ #endif
+ #ifndef STBI_ONLY_GIF
+ #define STBI_NO_GIF
+ #endif
+ #ifndef STBI_ONLY_HDR
+ #define STBI_NO_HDR
+ #endif
+ #ifndef STBI_ONLY_PIC
+ #define STBI_NO_PIC
+ #endif
+ #ifndef STBI_ONLY_PNM
+ #define STBI_NO_PNM
+ #endif
+#endif
+
+#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB)
+#define STBI_NO_ZLIB
+#endif
+
+
+#include <stdarg.h>
+#include <stddef.h> // ptrdiff_t on osx
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+
+#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR)
+#include <math.h> // ldexp, pow
+#endif
+
+#ifndef STBI_NO_STDIO
+#include <stdio.h>
+#endif
+
+#ifndef STBI_ASSERT
+#include <assert.h>
+#define STBI_ASSERT(x) assert(x)
+#endif
+
+#ifdef __cplusplus
+#define STBI_EXTERN extern "C"
+#else
+#define STBI_EXTERN extern
+#endif
+
+
+#ifndef _MSC_VER
+ #ifdef __cplusplus
+ #define stbi_inline inline
+ #else
+ #define stbi_inline
+ #endif
+#else
+ #define stbi_inline __forceinline
+#endif
+
+#ifndef STBI_NO_THREAD_LOCALS
+ #if defined(__cplusplus) && __cplusplus >= 201103L
+ #define STBI_THREAD_LOCAL thread_local
+ #elif defined(__GNUC__) && __GNUC__ < 5
+ #define STBI_THREAD_LOCAL __thread
+ #elif defined(_MSC_VER)
+ #define STBI_THREAD_LOCAL __declspec(thread)
+ #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__)
+ #define STBI_THREAD_LOCAL _Thread_local
+ #endif
+
+ #ifndef STBI_THREAD_LOCAL
+ #if defined(__GNUC__)
+ #define STBI_THREAD_LOCAL __thread
+ #endif
+ #endif
+#endif
+
+#if defined(_MSC_VER) || defined(__SYMBIAN32__)
+typedef unsigned short stbi__uint16;
+typedef signed short stbi__int16;
+typedef unsigned int stbi__uint32;
+typedef signed int stbi__int32;
+#else
+#include <stdint.h>
+typedef uint16_t stbi__uint16;
+typedef int16_t stbi__int16;
+typedef uint32_t stbi__uint32;
+typedef int32_t stbi__int32;
+#endif
+
+// should produce compiler error if size is wrong
+typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1];
+
+#ifdef _MSC_VER
+#define STBI_NOTUSED(v) (void)(v)
+#else
+#define STBI_NOTUSED(v) (void)sizeof(v)
+#endif
+
+#ifdef _MSC_VER
+#define STBI_HAS_LROTL
+#endif
+
+#ifdef STBI_HAS_LROTL
+ #define stbi_lrot(x,y) _lrotl(x,y)
+#else
+ #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (-(y) & 31)))
+#endif
+
+#if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED))
+// ok
+#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED)
+// ok
+#else
+#error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)."
+#endif
+
+#ifndef STBI_MALLOC
+#define STBI_MALLOC(sz) malloc(sz)
+#define STBI_REALLOC(p,newsz) realloc(p,newsz)
+#define STBI_FREE(p) free(p)
+#endif
+
+#ifndef STBI_REALLOC_SIZED
+#define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz)
+#endif
+
+// x86/x64 detection
+#if defined(__x86_64__) || defined(_M_X64)
+#define STBI__X64_TARGET
+#elif defined(__i386) || defined(_M_IX86)
+#define STBI__X86_TARGET
+#endif
+
+#if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD)
+// gcc doesn't support sse2 intrinsics unless you compile with -msse2,
+// which in turn means it gets to use SSE2 everywhere. This is unfortunate,
+// but previous attempts to provide the SSE2 functions with runtime
+// detection caused numerous issues. The way architecture extensions are
+// exposed in GCC/Clang is, sadly, not really suited for one-file libs.
+// New behavior: if compiled with -msse2, we use SSE2 without any
+// detection; if not, we don't use it at all.
+#define STBI_NO_SIMD
+#endif
+
+#if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD)
+// Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET
+//
+// 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the
+// Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant.
+// As a result, enabling SSE2 on 32-bit MinGW is dangerous when not
+// simultaneously enabling "-mstackrealign".
+//
+// See https://github.com/nothings/stb/issues/81 for more information.
+//
+// So default to no SSE2 on 32-bit MinGW. If you've read this far and added
+// -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2.
+#define STBI_NO_SIMD
+#endif
+
+#if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET))
+#define STBI_SSE2
+#include <emmintrin.h>
+
+#ifdef _MSC_VER
+
+#if _MSC_VER >= 1400 // not VC6
+#include <intrin.h> // __cpuid
+static int stbi__cpuid3(void)
+{
+ int info[4];
+ __cpuid(info,1);
+ return info[3];
+}
+#else
+static int stbi__cpuid3(void)
+{
+ int res;
+ __asm {
+ mov eax,1
+ cpuid
+ mov res,edx
+ }
+ return res;
+}
+#endif
+
+#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name
+
+#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2)
+static int stbi__sse2_available(void)
+{
+ int info3 = stbi__cpuid3();
+ return ((info3 >> 26) & 1) != 0;
+}
+#endif
+
+#else // assume GCC-style if not VC++
+#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16)))
+
+#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2)
+static int stbi__sse2_available(void)
+{
+ // If we're even attempting to compile this on GCC/Clang, that means
+ // -msse2 is on, which means the compiler is allowed to use SSE2
+ // instructions at will, and so are we.
+ return 1;
+}
+#endif
+
+#endif
+#endif
+
+// ARM NEON
+#if defined(STBI_NO_SIMD) && defined(STBI_NEON)
+#undef STBI_NEON
+#endif
+
+#ifdef STBI_NEON
+#include <arm_neon.h>
+#ifdef _MSC_VER
+#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name
+#else
+#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16)))
+#endif
+#endif
+
+#ifndef STBI_SIMD_ALIGN
+#define STBI_SIMD_ALIGN(type, name) type name
+#endif
+
+#ifndef STBI_MAX_DIMENSIONS
+#define STBI_MAX_DIMENSIONS (1 << 24)
+#endif
+
+///////////////////////////////////////////////
+//
+// stbi__context struct and start_xxx functions
+
+// stbi__context structure is our basic context used by all images, so it
+// contains all the IO context, plus some basic image information
+typedef struct
+{
+ stbi__uint32 img_x, img_y;
+ int img_n, img_out_n;
+
+ stbi_io_callbacks io;
+ void *io_user_data;
+
+ int read_from_callbacks;
+ int buflen;
+ stbi_uc buffer_start[128];
+ int callback_already_read;
+
+ stbi_uc *img_buffer, *img_buffer_end;
+ stbi_uc *img_buffer_original, *img_buffer_original_end;
+} stbi__context;
+
+
+static void stbi__refill_buffer(stbi__context *s);
+
+// initialize a memory-decode context
+static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len)
+{
+ s->io.read = NULL;
+ s->read_from_callbacks = 0;
+ s->callback_already_read = 0;
+ s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer;
+ s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len;
+}
+
+// initialize a callback-based context
+static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user)
+{
+ s->io = *c;
+ s->io_user_data = user;
+ s->buflen = sizeof(s->buffer_start);
+ s->read_from_callbacks = 1;
+ s->callback_already_read = 0;
+ s->img_buffer = s->img_buffer_original = s->buffer_start;
+ stbi__refill_buffer(s);
+ s->img_buffer_original_end = s->img_buffer_end;
+}
+
+#ifndef STBI_NO_STDIO
+
+static int stbi__stdio_read(void *user, char *data, int size)
+{
+ return (int) fread(data,1,size,(FILE*) user);
+}
+
+static void stbi__stdio_skip(void *user, int n)
+{
+ int ch;
+ fseek((FILE*) user, n, SEEK_CUR);
+ ch = fgetc((FILE*) user); /* have to read a byte to reset feof()'s flag */
+ if (ch != EOF) {
+ ungetc(ch, (FILE *) user); /* push byte back onto stream if valid. */
+ }
+}
+
+static int stbi__stdio_eof(void *user)
+{
+ return feof((FILE*) user) || ferror((FILE *) user);
+}
+
+static stbi_io_callbacks stbi__stdio_callbacks =
+{
+ stbi__stdio_read,
+ stbi__stdio_skip,
+ stbi__stdio_eof,
+};
+
+static void stbi__start_file(stbi__context *s, FILE *f)
+{
+ stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f);
+}
+
+//static void stop_file(stbi__context *s) { }
+
+#endif // !STBI_NO_STDIO
+
+static void stbi__rewind(stbi__context *s)
+{
+ // conceptually rewind SHOULD rewind to the beginning of the stream,
+ // but we just rewind to the beginning of the initial buffer, because
+ // we only use it after doing 'test', which only ever looks at at most 92 bytes
+ s->img_buffer = s->img_buffer_original;
+ s->img_buffer_end = s->img_buffer_original_end;
+}
+
+enum
+{
+ STBI_ORDER_RGB,
+ STBI_ORDER_BGR
+};
+
+typedef struct
+{
+ int bits_per_channel;
+ int num_channels;
+ int channel_order;
+} stbi__result_info;
+
+#ifndef STBI_NO_JPEG
+static int stbi__jpeg_test(stbi__context *s);
+static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp);
+#endif
+
+#ifndef STBI_NO_PNG
+static int stbi__png_test(stbi__context *s);
+static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp);
+static int stbi__png_is16(stbi__context *s);
+#endif
+
+#ifndef STBI_NO_BMP
+static int stbi__bmp_test(stbi__context *s);
+static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp);
+#endif
+
+#ifndef STBI_NO_TGA
+static int stbi__tga_test(stbi__context *s);
+static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp);
+#endif
+
+#ifndef STBI_NO_PSD
+static int stbi__psd_test(stbi__context *s);
+static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc);
+static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp);
+static int stbi__psd_is16(stbi__context *s);
+#endif
+
+#ifndef STBI_NO_HDR
+static int stbi__hdr_test(stbi__context *s);
+static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp);
+#endif
+
+#ifndef STBI_NO_PIC
+static int stbi__pic_test(stbi__context *s);
+static void *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp);
+#endif
+
+#ifndef STBI_NO_GIF
+static int stbi__gif_test(stbi__context *s);
+static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp);
+static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp);
+#endif
+
+#ifndef STBI_NO_PNM
+static int stbi__pnm_test(stbi__context *s);
+static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp);
+static int stbi__pnm_is16(stbi__context *s);
+#endif
+
+static
+#ifdef STBI_THREAD_LOCAL
+STBI_THREAD_LOCAL
+#endif
+const char *stbi__g_failure_reason;
+
+STBIDEF const char *stbi_failure_reason(void)
+{
+ return stbi__g_failure_reason;
+}
+
+#ifndef STBI_NO_FAILURE_STRINGS
+static int stbi__err(const char *str)
+{
+ stbi__g_failure_reason = str;
+ return 0;
+}
+#endif
+
+static void *stbi__malloc(size_t size)
+{
+ return STBI_MALLOC(size);
+}
+
+// stb_image uses ints pervasively, including for offset calculations.
+// therefore the largest decoded image size we can support with the
+// current code, even on 64-bit targets, is INT_MAX. this is not a
+// significant limitation for the intended use case.
+//
+// we do, however, need to make sure our size calculations don't
+// overflow. hence a few helper functions for size calculations that
+// multiply integers together, making sure that they're non-negative
+// and no overflow occurs.
+
+// return 1 if the sum is valid, 0 on overflow.
+// negative terms are considered invalid.
+static int stbi__addsizes_valid(int a, int b)
+{
+ if (b < 0) return 0;
+ // now 0 <= b <= INT_MAX, hence also
+ // 0 <= INT_MAX - b <= INTMAX.
+ // And "a + b <= INT_MAX" (which might overflow) is the
+ // same as a <= INT_MAX - b (no overflow)
+ return a <= INT_MAX - b;
+}
+
+// returns 1 if the product is valid, 0 on overflow.
+// negative factors are considered invalid.
+static int stbi__mul2sizes_valid(int a, int b)
+{
+ if (a < 0 || b < 0) return 0;
+ if (b == 0) return 1; // mul-by-0 is always safe
+ // portable way to check for no overflows in a*b
+ return a <= INT_MAX/b;
+}
+
+#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR)
+// returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow
+static int stbi__mad2sizes_valid(int a, int b, int add)
+{
+ return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add);
+}
+#endif
+
+// returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow
+static int stbi__mad3sizes_valid(int a, int b, int c, int add)
+{
+ return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) &&
+ stbi__addsizes_valid(a*b*c, add);
+}
+
+// returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow
+#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM)
+static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add)
+{
+ return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) &&
+ stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add);
+}
+#endif
+
+#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR)
+// mallocs with size overflow checking
+static void *stbi__malloc_mad2(int a, int b, int add)
+{
+ if (!stbi__mad2sizes_valid(a, b, add)) return NULL;
+ return stbi__malloc(a*b + add);
+}
+#endif
+
+static void *stbi__malloc_mad3(int a, int b, int c, int add)
+{
+ if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL;
+ return stbi__malloc(a*b*c + add);
+}
+
+#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM)
+static void *stbi__malloc_mad4(int a, int b, int c, int d, int add)
+{
+ if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL;
+ return stbi__malloc(a*b*c*d + add);
+}
+#endif
+
+// returns 1 if the sum of two signed ints is valid (between -2^31 and 2^31-1 inclusive), 0 on overflow.
+static int stbi__addints_valid(int a, int b)
+{
+ if ((a >= 0) != (b >= 0)) return 1; // a and b have different signs, so no overflow
+ if (a < 0 && b < 0) return a >= INT_MIN - b; // same as a + b >= INT_MIN; INT_MIN - b cannot overflow since b < 0.
+ return a <= INT_MAX - b;
+}
+
+// returns 1 if the product of two ints fits in a signed short, 0 on overflow.
+static int stbi__mul2shorts_valid(int a, int b)
+{
+ if (b == 0 || b == -1) return 1; // multiplication by 0 is always 0; check for -1 so SHRT_MIN/b doesn't overflow
+ if ((a >= 0) == (b >= 0)) return a <= SHRT_MAX/b; // product is positive, so similar to mul2sizes_valid
+ if (b < 0) return a <= SHRT_MIN / b; // same as a * b >= SHRT_MIN
+ return a >= SHRT_MIN / b;
+}
+
+// stbi__err - error
+// stbi__errpf - error returning pointer to float
+// stbi__errpuc - error returning pointer to unsigned char
+
+#ifdef STBI_NO_FAILURE_STRINGS
+ #define stbi__err(x,y) 0
+#elif defined(STBI_FAILURE_USERMSG)
+ #define stbi__err(x,y) stbi__err(y)
+#else
+ #define stbi__err(x,y) stbi__err(x)
+#endif
+
+#define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL))
+#define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL))
+
+STBIDEF void stbi_image_free(void *retval_from_stbi_load)
+{
+ STBI_FREE(retval_from_stbi_load);
+}
+
+#ifndef STBI_NO_LINEAR
+static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp);
+#endif
+
+#ifndef STBI_NO_HDR
+static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp);
+#endif
+
+static int stbi__vertically_flip_on_load_global = 0;
+
+STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip)
+{
+ stbi__vertically_flip_on_load_global = flag_true_if_should_flip;
+}
+
+#ifndef STBI_THREAD_LOCAL
+#define stbi__vertically_flip_on_load stbi__vertically_flip_on_load_global
+#else
+static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set;
+
+STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip)
+{
+ stbi__vertically_flip_on_load_local = flag_true_if_should_flip;
+ stbi__vertically_flip_on_load_set = 1;
+}
+
+#define stbi__vertically_flip_on_load (stbi__vertically_flip_on_load_set \
+ ? stbi__vertically_flip_on_load_local \
+ : stbi__vertically_flip_on_load_global)
+#endif // STBI_THREAD_LOCAL
+
+static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc)
+{
+ memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields
+ ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed
+ ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order
+ ri->num_channels = 0;
+
+ // test the formats with a very explicit header first (at least a FOURCC
+ // or distinctive magic number first)
+ #ifndef STBI_NO_PNG
+ if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp, ri);
+ #endif
+ #ifndef STBI_NO_BMP
+ if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp, ri);
+ #endif
+ #ifndef STBI_NO_GIF
+ if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp, ri);
+ #endif
+ #ifndef STBI_NO_PSD
+ if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp, ri, bpc);
+ #else
+ STBI_NOTUSED(bpc);
+ #endif
+ #ifndef STBI_NO_PIC
+ if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp, ri);
+ #endif
+
+ // then the formats that can end up attempting to load with just 1 or 2
+ // bytes matching expectations; these are prone to false positives, so
+ // try them later
+ #ifndef STBI_NO_JPEG
+ if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri);
+ #endif
+ #ifndef STBI_NO_PNM
+ if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp, ri);
+ #endif
+
+ #ifndef STBI_NO_HDR
+ if (stbi__hdr_test(s)) {
+ float *hdr = stbi__hdr_load(s, x,y,comp,req_comp, ri);
+ return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
+ }
+ #endif
+
+ #ifndef STBI_NO_TGA
+ // test tga last because it's a crappy test!
+ if (stbi__tga_test(s))
+ return stbi__tga_load(s,x,y,comp,req_comp, ri);
+ #endif
+
+ return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt");
+}
+
+static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels)
+{
+ int i;
+ int img_len = w * h * channels;
+ stbi_uc *reduced;
+
+ reduced = (stbi_uc *) stbi__malloc(img_len);
+ if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory");
+
+ for (i = 0; i < img_len; ++i)
+ reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling
+
+ STBI_FREE(orig);
+ return reduced;
+}
+
+static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels)
+{
+ int i;
+ int img_len = w * h * channels;
+ stbi__uint16 *enlarged;
+
+ enlarged = (stbi__uint16 *) stbi__malloc(img_len*2);
+ if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory");
+
+ for (i = 0; i < img_len; ++i)
+ enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff
+
+ STBI_FREE(orig);
+ return enlarged;
+}
+
+static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel)
+{
+ int row;
+ size_t bytes_per_row = (size_t)w * bytes_per_pixel;
+ stbi_uc temp[2048];
+ stbi_uc *bytes = (stbi_uc *)image;
+
+ for (row = 0; row < (h>>1); row++) {
+ stbi_uc *row0 = bytes + row*bytes_per_row;
+ stbi_uc *row1 = bytes + (h - row - 1)*bytes_per_row;
+ // swap row0 with row1
+ size_t bytes_left = bytes_per_row;
+ while (bytes_left) {
+ size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp);
+ memcpy(temp, row0, bytes_copy);
+ memcpy(row0, row1, bytes_copy);
+ memcpy(row1, temp, bytes_copy);
+ row0 += bytes_copy;
+ row1 += bytes_copy;
+ bytes_left -= bytes_copy;
+ }
+ }
+}
+
+#ifndef STBI_NO_GIF
+static void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel)
+{
+ int slice;
+ int slice_size = w * h * bytes_per_pixel;
+
+ stbi_uc *bytes = (stbi_uc *)image;
+ for (slice = 0; slice < z; ++slice) {
+ stbi__vertical_flip(bytes, w, h, bytes_per_pixel);
+ bytes += slice_size;
+ }
+}
+#endif
+
+static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__result_info ri;
+ void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8);
+
+ if (result == NULL)
+ return NULL;
+
+ // it is the responsibility of the loaders to make sure we get either 8 or 16 bit.
+ STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16);
+
+ if (ri.bits_per_channel != 8) {
+ result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp);
+ ri.bits_per_channel = 8;
+ }
+
+ // @TODO: move stbi__convert_format to here
+
+ if (stbi__vertically_flip_on_load) {
+ int channels = req_comp ? req_comp : *comp;
+ stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc));
+ }
+
+ return (unsigned char *) result;
+}
+
+static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__result_info ri;
+ void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16);
+
+ if (result == NULL)
+ return NULL;
+
+ // it is the responsibility of the loaders to make sure we get either 8 or 16 bit.
+ STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16);
+
+ if (ri.bits_per_channel != 16) {
+ result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp);
+ ri.bits_per_channel = 16;
+ }
+
+ // @TODO: move stbi__convert_format16 to here
+ // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision
+
+ if (stbi__vertically_flip_on_load) {
+ int channels = req_comp ? req_comp : *comp;
+ stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16));
+ }
+
+ return (stbi__uint16 *) result;
+}
+
+#if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR)
+static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp)
+{
+ if (stbi__vertically_flip_on_load && result != NULL) {
+ int channels = req_comp ? req_comp : *comp;
+ stbi__vertical_flip(result, *x, *y, channels * sizeof(float));
+ }
+}
+#endif
+
+#ifndef STBI_NO_STDIO
+
+#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)
+STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide);
+STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default);
+#endif
+
+#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)
+STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input)
+{
+ return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL);
+}
+#endif
+
+static FILE *stbi__fopen(char const *filename, char const *mode)
+{
+ FILE *f;
+#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)
+ wchar_t wMode[64];
+ wchar_t wFilename[1024];
+ if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename)))
+ return 0;
+
+ if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode)))
+ return 0;
+
+#if defined(_MSC_VER) && _MSC_VER >= 1400
+ if (0 != _wfopen_s(&f, wFilename, wMode))
+ f = 0;
+#else
+ f = _wfopen(wFilename, wMode);
+#endif
+
+#elif defined(_MSC_VER) && _MSC_VER >= 1400
+ if (0 != fopen_s(&f, filename, mode))
+ f=0;
+#else
+ f = fopen(filename, mode);
+#endif
+ return f;
+}
+
+
+STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)
+{
+ FILE *f = stbi__fopen(filename, "rb");
+ unsigned char *result;
+ if (!f) return stbi__errpuc("can't fopen", "Unable to open file");
+ result = stbi_load_from_file(f,x,y,comp,req_comp);
+ fclose(f);
+ return result;
+}
+
+STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
+{
+ unsigned char *result;
+ stbi__context s;
+ stbi__start_file(&s,f);
+ result = stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp);
+ if (result) {
+ // need to 'unget' all the characters in the IO buffer
+ fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR);
+ }
+ return result;
+}
+
+STBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__uint16 *result;
+ stbi__context s;
+ stbi__start_file(&s,f);
+ result = stbi__load_and_postprocess_16bit(&s,x,y,comp,req_comp);
+ if (result) {
+ // need to 'unget' all the characters in the IO buffer
+ fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR);
+ }
+ return result;
+}
+
+STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp)
+{
+ FILE *f = stbi__fopen(filename, "rb");
+ stbi__uint16 *result;
+ if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file");
+ result = stbi_load_from_file_16(f,x,y,comp,req_comp);
+ fclose(f);
+ return result;
+}
+
+
+#endif //!STBI_NO_STDIO
+
+STBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels)
+{
+ stbi__context s;
+ stbi__start_mem(&s,buffer,len);
+ return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels);
+}
+
+STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels)
+{
+ stbi__context s;
+ stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user);
+ return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels);
+}
+
+STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__context s;
+ stbi__start_mem(&s,buffer,len);
+ return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp);
+}
+
+STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__context s;
+ stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
+ return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp);
+}
+
+#ifndef STBI_NO_GIF
+STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp)
+{
+ unsigned char *result;
+ stbi__context s;
+ stbi__start_mem(&s,buffer,len);
+
+ result = (unsigned char*) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp);
+ if (stbi__vertically_flip_on_load) {
+ stbi__vertical_flip_slices( result, *x, *y, *z, *comp );
+ }
+
+ return result;
+}
+#endif
+
+#ifndef STBI_NO_LINEAR
+static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp)
+{
+ unsigned char *data;
+ #ifndef STBI_NO_HDR
+ if (stbi__hdr_test(s)) {
+ stbi__result_info ri;
+ float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp, &ri);
+ if (hdr_data)
+ stbi__float_postprocess(hdr_data,x,y,comp,req_comp);
+ return hdr_data;
+ }
+ #endif
+ data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp);
+ if (data)
+ return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
+ return stbi__errpf("unknown image type", "Image not of any known type, or corrupt");
+}
+
+STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__context s;
+ stbi__start_mem(&s,buffer,len);
+ return stbi__loadf_main(&s,x,y,comp,req_comp);
+}
+
+STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__context s;
+ stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
+ return stbi__loadf_main(&s,x,y,comp,req_comp);
+}
+
+#ifndef STBI_NO_STDIO
+STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)
+{
+ float *result;
+ FILE *f = stbi__fopen(filename, "rb");
+ if (!f) return stbi__errpf("can't fopen", "Unable to open file");
+ result = stbi_loadf_from_file(f,x,y,comp,req_comp);
+ fclose(f);
+ return result;
+}
+
+STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__context s;
+ stbi__start_file(&s,f);
+ return stbi__loadf_main(&s,x,y,comp,req_comp);
+}
+#endif // !STBI_NO_STDIO
+
+#endif // !STBI_NO_LINEAR
+
+// these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is
+// defined, for API simplicity; if STBI_NO_LINEAR is defined, it always
+// reports false!
+
+STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)
+{
+ #ifndef STBI_NO_HDR
+ stbi__context s;
+ stbi__start_mem(&s,buffer,len);
+ return stbi__hdr_test(&s);
+ #else
+ STBI_NOTUSED(buffer);
+ STBI_NOTUSED(len);
+ return 0;
+ #endif
+}
+
+#ifndef STBI_NO_STDIO
+STBIDEF int stbi_is_hdr (char const *filename)
+{
+ FILE *f = stbi__fopen(filename, "rb");
+ int result=0;
+ if (f) {
+ result = stbi_is_hdr_from_file(f);
+ fclose(f);
+ }
+ return result;
+}
+
+STBIDEF int stbi_is_hdr_from_file(FILE *f)
+{
+ #ifndef STBI_NO_HDR
+ long pos = ftell(f);
+ int res;
+ stbi__context s;
+ stbi__start_file(&s,f);
+ res = stbi__hdr_test(&s);
+ fseek(f, pos, SEEK_SET);
+ return res;
+ #else
+ STBI_NOTUSED(f);
+ return 0;
+ #endif
+}
+#endif // !STBI_NO_STDIO
+
+STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user)
+{
+ #ifndef STBI_NO_HDR
+ stbi__context s;
+ stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
+ return stbi__hdr_test(&s);
+ #else
+ STBI_NOTUSED(clbk);
+ STBI_NOTUSED(user);
+ return 0;
+ #endif
+}
+
+#ifndef STBI_NO_LINEAR
+static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f;
+
+STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; }
+STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; }
+#endif
+
+static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f;
+
+STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; }
+STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; }
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// Common code used by all image loaders
+//
+
+enum
+{
+ STBI__SCAN_load=0,
+ STBI__SCAN_type,
+ STBI__SCAN_header
+};
+
+static void stbi__refill_buffer(stbi__context *s)
+{
+ int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen);
+ s->callback_already_read += (int) (s->img_buffer - s->img_buffer_original);
+ if (n == 0) {
+ // at end of file, treat same as if from memory, but need to handle case
+ // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file
+ s->read_from_callbacks = 0;
+ s->img_buffer = s->buffer_start;
+ s->img_buffer_end = s->buffer_start+1;
+ *s->img_buffer = 0;
+ } else {
+ s->img_buffer = s->buffer_start;
+ s->img_buffer_end = s->buffer_start + n;
+ }
+}
+
+stbi_inline static stbi_uc stbi__get8(stbi__context *s)
+{
+ if (s->img_buffer < s->img_buffer_end)
+ return *s->img_buffer++;
+ if (s->read_from_callbacks) {
+ stbi__refill_buffer(s);
+ return *s->img_buffer++;
+ }
+ return 0;
+}
+
+#if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM)
+// nothing
+#else
+stbi_inline static int stbi__at_eof(stbi__context *s)
+{
+ if (s->io.read) {
+ if (!(s->io.eof)(s->io_user_data)) return 0;
+ // if feof() is true, check if buffer = end
+ // special case: we've only got the special 0 character at the end
+ if (s->read_from_callbacks == 0) return 1;
+ }
+
+ return s->img_buffer >= s->img_buffer_end;
+}
+#endif
+
+#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC)
+// nothing
+#else
+static void stbi__skip(stbi__context *s, int n)
+{
+ if (n == 0) return; // already there!
+ if (n < 0) {
+ s->img_buffer = s->img_buffer_end;
+ return;
+ }
+ if (s->io.read) {
+ int blen = (int) (s->img_buffer_end - s->img_buffer);
+ if (blen < n) {
+ s->img_buffer = s->img_buffer_end;
+ (s->io.skip)(s->io_user_data, n - blen);
+ return;
+ }
+ }
+ s->img_buffer += n;
+}
+#endif
+
+#if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && defined(STBI_NO_PNM)
+// nothing
+#else
+static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n)
+{
+ if (s->io.read) {
+ int blen = (int) (s->img_buffer_end - s->img_buffer);
+ if (blen < n) {
+ int res, count;
+
+ memcpy(buffer, s->img_buffer, blen);
+
+ count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen);
+ res = (count == (n-blen));
+ s->img_buffer = s->img_buffer_end;
+ return res;
+ }
+ }
+
+ if (s->img_buffer+n <= s->img_buffer_end) {
+ memcpy(buffer, s->img_buffer, n);
+ s->img_buffer += n;
+ return 1;
+ } else
+ return 0;
+}
+#endif
+
+#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC)
+// nothing
+#else
+static int stbi__get16be(stbi__context *s)
+{
+ int z = stbi__get8(s);
+ return (z << 8) + stbi__get8(s);
+}
+#endif
+
+#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC)
+// nothing
+#else
+static stbi__uint32 stbi__get32be(stbi__context *s)
+{
+ stbi__uint32 z = stbi__get16be(s);
+ return (z << 16) + stbi__get16be(s);
+}
+#endif
+
+#if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF)
+// nothing
+#else
+static int stbi__get16le(stbi__context *s)
+{
+ int z = stbi__get8(s);
+ return z + (stbi__get8(s) << 8);
+}
+#endif
+
+#ifndef STBI_NO_BMP
+static stbi__uint32 stbi__get32le(stbi__context *s)
+{
+ stbi__uint32 z = stbi__get16le(s);
+ z += (stbi__uint32)stbi__get16le(s) << 16;
+ return z;
+}
+#endif
+
+#define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings
+
+#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM)
+// nothing
+#else
+//////////////////////////////////////////////////////////////////////////////
+//
+// generic converter from built-in img_n to req_comp
+// individual types do this automatically as much as possible (e.g. jpeg
+// does all cases internally since it needs to colorspace convert anyway,
+// and it never has alpha, so very few cases ). png can automatically
+// interleave an alpha=255 channel, but falls back to this for other cases
+//
+// assume data buffer is malloced, so malloc a new one and free that one
+// only failure mode is malloc failing
+
+static stbi_uc stbi__compute_y(int r, int g, int b)
+{
+ return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8);
+}
+#endif
+
+#if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM)
+// nothing
+#else
+static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y)
+{
+ int i,j;
+ unsigned char *good;
+
+ if (req_comp == img_n) return data;
+ STBI_ASSERT(req_comp >= 1 && req_comp <= 4);
+
+ good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0);
+ if (good == NULL) {
+ STBI_FREE(data);
+ return stbi__errpuc("outofmem", "Out of memory");
+ }
+
+ for (j=0; j < (int) y; ++j) {
+ unsigned char *src = data + j * x * img_n ;
+ unsigned char *dest = good + j * x * req_comp;
+
+ #define STBI__COMBO(a,b) ((a)*8+(b))
+ #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)
+ // convert source image with img_n components to one with req_comp components;
+ // avoid switch per pixel, so use switch per scanline and massive macros
+ switch (STBI__COMBO(img_n, req_comp)) {
+ STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=255; } break;
+ STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break;
+ STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=255; } break;
+ STBI__CASE(2,1) { dest[0]=src[0]; } break;
+ STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break;
+ STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break;
+ STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=255; } break;
+ STBI__CASE(3,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break;
+ STBI__CASE(3,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = 255; } break;
+ STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break;
+ STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = src[3]; } break;
+ STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break;
+ default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return stbi__errpuc("unsupported", "Unsupported format conversion");
+ }
+ #undef STBI__CASE
+ }
+
+ STBI_FREE(data);
+ return good;
+}
+#endif
+
+#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD)
+// nothing
+#else
+static stbi__uint16 stbi__compute_y_16(int r, int g, int b)
+{
+ return (stbi__uint16) (((r*77) + (g*150) + (29*b)) >> 8);
+}
+#endif
+
+#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD)
+// nothing
+#else
+static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y)
+{
+ int i,j;
+ stbi__uint16 *good;
+
+ if (req_comp == img_n) return data;
+ STBI_ASSERT(req_comp >= 1 && req_comp <= 4);
+
+ good = (stbi__uint16 *) stbi__malloc(req_comp * x * y * 2);
+ if (good == NULL) {
+ STBI_FREE(data);
+ return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory");
+ }
+
+ for (j=0; j < (int) y; ++j) {
+ stbi__uint16 *src = data + j * x * img_n ;
+ stbi__uint16 *dest = good + j * x * req_comp;
+
+ #define STBI__COMBO(a,b) ((a)*8+(b))
+ #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)
+ // convert source image with img_n components to one with req_comp components;
+ // avoid switch per pixel, so use switch per scanline and massive macros
+ switch (STBI__COMBO(img_n, req_comp)) {
+ STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=0xffff; } break;
+ STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break;
+ STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=0xffff; } break;
+ STBI__CASE(2,1) { dest[0]=src[0]; } break;
+ STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break;
+ STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break;
+ STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=0xffff; } break;
+ STBI__CASE(3,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break;
+ STBI__CASE(3,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = 0xffff; } break;
+ STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break;
+ STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = src[3]; } break;
+ STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break;
+ default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return (stbi__uint16*) stbi__errpuc("unsupported", "Unsupported format conversion");
+ }
+ #undef STBI__CASE
+ }
+
+ STBI_FREE(data);
+ return good;
+}
+#endif
+
+#ifndef STBI_NO_LINEAR
+static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp)
+{
+ int i,k,n;
+ float *output;
+ if (!data) return NULL;
+ output = (float *) stbi__malloc_mad4(x, y, comp, sizeof(float), 0);
+ if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); }
+ // compute number of non-alpha components
+ if (comp & 1) n = comp; else n = comp-1;
+ for (i=0; i < x*y; ++i) {
+ for (k=0; k < n; ++k) {
+ output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale);
+ }
+ }
+ if (n < comp) {
+ for (i=0; i < x*y; ++i) {
+ output[i*comp + n] = data[i*comp + n]/255.0f;
+ }
+ }
+ STBI_FREE(data);
+ return output;
+}
+#endif
+
+#ifndef STBI_NO_HDR
+#define stbi__float2int(x) ((int) (x))
+static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp)
+{
+ int i,k,n;
+ stbi_uc *output;
+ if (!data) return NULL;
+ output = (stbi_uc *) stbi__malloc_mad3(x, y, comp, 0);
+ if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); }
+ // compute number of non-alpha components
+ if (comp & 1) n = comp; else n = comp-1;
+ for (i=0; i < x*y; ++i) {
+ for (k=0; k < n; ++k) {
+ float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f;
+ if (z < 0) z = 0;
+ if (z > 255) z = 255;
+ output[i*comp + k] = (stbi_uc) stbi__float2int(z);
+ }
+ if (k < comp) {
+ float z = data[i*comp+k] * 255 + 0.5f;
+ if (z < 0) z = 0;
+ if (z > 255) z = 255;
+ output[i*comp + k] = (stbi_uc) stbi__float2int(z);
+ }
+ }
+ STBI_FREE(data);
+ return output;
+}
+#endif
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// "baseline" JPEG/JFIF decoder
+//
+// simple implementation
+// - doesn't support delayed output of y-dimension
+// - simple interface (only one output format: 8-bit interleaved RGB)
+// - doesn't try to recover corrupt jpegs
+// - doesn't allow partial loading, loading multiple at once
+// - still fast on x86 (copying globals into locals doesn't help x86)
+// - allocates lots of intermediate memory (full size of all components)
+// - non-interleaved case requires this anyway
+// - allows good upsampling (see next)
+// high-quality
+// - upsampled channels are bilinearly interpolated, even across blocks
+// - quality integer IDCT derived from IJG's 'slow'
+// performance
+// - fast huffman; reasonable integer IDCT
+// - some SIMD kernels for common paths on targets with SSE2/NEON
+// - uses a lot of intermediate memory, could cache poorly
+
+#ifndef STBI_NO_JPEG
+
+// huffman decoding acceleration
+#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache
+
+typedef struct
+{
+ stbi_uc fast[1 << FAST_BITS];
+ // weirdly, repacking this into AoS is a 10% speed loss, instead of a win
+ stbi__uint16 code[256];
+ stbi_uc values[256];
+ stbi_uc size[257];
+ unsigned int maxcode[18];
+ int delta[17]; // old 'firstsymbol' - old 'firstcode'
+} stbi__huffman;
+
+typedef struct
+{
+ stbi__context *s;
+ stbi__huffman huff_dc[4];
+ stbi__huffman huff_ac[4];
+ stbi__uint16 dequant[4][64];
+ stbi__int16 fast_ac[4][1 << FAST_BITS];
+
+// sizes for components, interleaved MCUs
+ int img_h_max, img_v_max;
+ int img_mcu_x, img_mcu_y;
+ int img_mcu_w, img_mcu_h;
+
+// definition of jpeg image component
+ struct
+ {
+ int id;
+ int h,v;
+ int tq;
+ int hd,ha;
+ int dc_pred;
+
+ int x,y,w2,h2;
+ stbi_uc *data;
+ void *raw_data, *raw_coeff;
+ stbi_uc *linebuf;
+ short *coeff; // progressive only
+ int coeff_w, coeff_h; // number of 8x8 coefficient blocks
+ } img_comp[4];
+
+ stbi__uint32 code_buffer; // jpeg entropy-coded buffer
+ int code_bits; // number of valid bits
+ unsigned char marker; // marker seen while filling entropy buffer
+ int nomore; // flag if we saw a marker so must stop
+
+ int progressive;
+ int spec_start;
+ int spec_end;
+ int succ_high;
+ int succ_low;
+ int eob_run;
+ int jfif;
+ int app14_color_transform; // Adobe APP14 tag
+ int rgb;
+
+ int scan_n, order[4];
+ int restart_interval, todo;
+
+// kernels
+ void (*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]);
+ void (*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step);
+ stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs);
+} stbi__jpeg;
+
+static int stbi__build_huffman(stbi__huffman *h, int *count)
+{
+ int i,j,k=0;
+ unsigned int code;
+ // build size list for each symbol (from JPEG spec)
+ for (i=0; i < 16; ++i) {
+ for (j=0; j < count[i]; ++j) {
+ h->size[k++] = (stbi_uc) (i+1);
+ if(k >= 257) return stbi__err("bad size list","Corrupt JPEG");
+ }
+ }
+ h->size[k] = 0;
+
+ // compute actual symbols (from jpeg spec)
+ code = 0;
+ k = 0;
+ for(j=1; j <= 16; ++j) {
+ // compute delta to add to code to compute symbol id
+ h->delta[j] = k - code;
+ if (h->size[k] == j) {
+ while (h->size[k] == j)
+ h->code[k++] = (stbi__uint16) (code++);
+ if (code-1 >= (1u << j)) return stbi__err("bad code lengths","Corrupt JPEG");
+ }
+ // compute largest code + 1 for this size, preshifted as needed later
+ h->maxcode[j] = code << (16-j);
+ code <<= 1;
+ }
+ h->maxcode[j] = 0xffffffff;
+
+ // build non-spec acceleration table; 255 is flag for not-accelerated
+ memset(h->fast, 255, 1 << FAST_BITS);
+ for (i=0; i < k; ++i) {
+ int s = h->size[i];
+ if (s <= FAST_BITS) {
+ int c = h->code[i] << (FAST_BITS-s);
+ int m = 1 << (FAST_BITS-s);
+ for (j=0; j < m; ++j) {
+ h->fast[c+j] = (stbi_uc) i;
+ }
+ }
+ }
+ return 1;
+}
+
+// build a table that decodes both magnitude and value of small ACs in
+// one go.
+static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h)
+{
+ int i;
+ for (i=0; i < (1 << FAST_BITS); ++i) {
+ stbi_uc fast = h->fast[i];
+ fast_ac[i] = 0;
+ if (fast < 255) {
+ int rs = h->values[fast];
+ int run = (rs >> 4) & 15;
+ int magbits = rs & 15;
+ int len = h->size[fast];
+
+ if (magbits && len + magbits <= FAST_BITS) {
+ // magnitude code followed by receive_extend code
+ int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits);
+ int m = 1 << (magbits - 1);
+ if (k < m) k += (~0U << magbits) + 1;
+ // if the result is small enough, we can fit it in fast_ac table
+ if (k >= -128 && k <= 127)
+ fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) + (len + magbits));
+ }
+ }
+ }
+}
+
+static void stbi__grow_buffer_unsafe(stbi__jpeg *j)
+{
+ do {
+ unsigned int b = j->nomore ? 0 : stbi__get8(j->s);
+ if (b == 0xff) {
+ int c = stbi__get8(j->s);
+ while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes
+ if (c != 0) {
+ j->marker = (unsigned char) c;
+ j->nomore = 1;
+ return;
+ }
+ }
+ j->code_buffer |= b << (24 - j->code_bits);
+ j->code_bits += 8;
+ } while (j->code_bits <= 24);
+}
+
+// (1 << n) - 1
+static const stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};
+
+// decode a jpeg huffman value from the bitstream
+stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h)
+{
+ unsigned int temp;
+ int c,k;
+
+ if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
+
+ // look at the top FAST_BITS and determine what symbol ID it is,
+ // if the code is <= FAST_BITS
+ c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);
+ k = h->fast[c];
+ if (k < 255) {
+ int s = h->size[k];
+ if (s > j->code_bits)
+ return -1;
+ j->code_buffer <<= s;
+ j->code_bits -= s;
+ return h->values[k];
+ }
+
+ // naive test is to shift the code_buffer down so k bits are
+ // valid, then test against maxcode. To speed this up, we've
+ // preshifted maxcode left so that it has (16-k) 0s at the
+ // end; in other words, regardless of the number of bits, it
+ // wants to be compared against something shifted to have 16;
+ // that way we don't need to shift inside the loop.
+ temp = j->code_buffer >> 16;
+ for (k=FAST_BITS+1 ; ; ++k)
+ if (temp < h->maxcode[k])
+ break;
+ if (k == 17) {
+ // error! code not found
+ j->code_bits -= 16;
+ return -1;
+ }
+
+ if (k > j->code_bits)
+ return -1;
+
+ // convert the huffman code to the symbol id
+ c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k];
+ if(c < 0 || c >= 256) // symbol id out of bounds!
+ return -1;
+ STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]);
+
+ // convert the id to a symbol
+ j->code_bits -= k;
+ j->code_buffer <<= k;
+ return h->values[c];
+}
+
+// bias[n] = (-1<<n) + 1
+static const int stbi__jbias[16] = {0,-1,-3,-7,-15,-31,-63,-127,-255,-511,-1023,-2047,-4095,-8191,-16383,-32767};
+
+// combined JPEG 'receive' and JPEG 'extend', since baseline
+// always extends everything it receives.
+stbi_inline static int stbi__extend_receive(stbi__jpeg *j, int n)
+{
+ unsigned int k;
+ int sgn;
+ if (j->code_bits < n) stbi__grow_buffer_unsafe(j);
+ if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing
+
+ sgn = j->code_buffer >> 31; // sign bit always in MSB; 0 if MSB clear (positive), 1 if MSB set (negative)
+ k = stbi_lrot(j->code_buffer, n);
+ j->code_buffer = k & ~stbi__bmask[n];
+ k &= stbi__bmask[n];
+ j->code_bits -= n;
+ return k + (stbi__jbias[n] & (sgn - 1));
+}
+
+// get some unsigned bits
+stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n)
+{
+ unsigned int k;
+ if (j->code_bits < n) stbi__grow_buffer_unsafe(j);
+ if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing
+ k = stbi_lrot(j->code_buffer, n);
+ j->code_buffer = k & ~stbi__bmask[n];
+ k &= stbi__bmask[n];
+ j->code_bits -= n;
+ return k;
+}
+
+stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j)
+{
+ unsigned int k;
+ if (j->code_bits < 1) stbi__grow_buffer_unsafe(j);
+ if (j->code_bits < 1) return 0; // ran out of bits from stream, return 0s intead of continuing
+ k = j->code_buffer;
+ j->code_buffer <<= 1;
+ --j->code_bits;
+ return k & 0x80000000;
+}
+
+// given a value that's at position X in the zigzag stream,
+// where does it appear in the 8x8 matrix coded as row-major?
+static const stbi_uc stbi__jpeg_dezigzag[64+15] =
+{
+ 0, 1, 8, 16, 9, 2, 3, 10,
+ 17, 24, 32, 25, 18, 11, 4, 5,
+ 12, 19, 26, 33, 40, 48, 41, 34,
+ 27, 20, 13, 6, 7, 14, 21, 28,
+ 35, 42, 49, 56, 57, 50, 43, 36,
+ 29, 22, 15, 23, 30, 37, 44, 51,
+ 58, 59, 52, 45, 38, 31, 39, 46,
+ 53, 60, 61, 54, 47, 55, 62, 63,
+ // let corrupt input sample past end
+ 63, 63, 63, 63, 63, 63, 63, 63,
+ 63, 63, 63, 63, 63, 63, 63
+};
+
+// decode one 64-entry block--
+static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi__uint16 *dequant)
+{
+ int diff,dc,k;
+ int t;
+
+ if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
+ t = stbi__jpeg_huff_decode(j, hdc);
+ if (t < 0 || t > 15) return stbi__err("bad huffman code","Corrupt JPEG");
+
+ // 0 all the ac values now so we can do it 32-bits at a time
+ memset(data,0,64*sizeof(data[0]));
+
+ diff = t ? stbi__extend_receive(j, t) : 0;
+ if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta","Corrupt JPEG");
+ dc = j->img_comp[b].dc_pred + diff;
+ j->img_comp[b].dc_pred = dc;
+ if (!stbi__mul2shorts_valid(dc, dequant[0])) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
+ data[0] = (short) (dc * dequant[0]);
+
+ // decode AC components, see JPEG spec
+ k = 1;
+ do {
+ unsigned int zig;
+ int c,r,s;
+ if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
+ c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);
+ r = fac[c];
+ if (r) { // fast-AC path
+ k += (r >> 4) & 15; // run
+ s = r & 15; // combined length
+ if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available");
+ j->code_buffer <<= s;
+ j->code_bits -= s;
+ // decode into unzigzag'd location
+ zig = stbi__jpeg_dezigzag[k++];
+ data[zig] = (short) ((r >> 8) * dequant[zig]);
+ } else {
+ int rs = stbi__jpeg_huff_decode(j, hac);
+ if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG");
+ s = rs & 15;
+ r = rs >> 4;
+ if (s == 0) {
+ if (rs != 0xf0) break; // end block
+ k += 16;
+ } else {
+ k += r;
+ // decode into unzigzag'd location
+ zig = stbi__jpeg_dezigzag[k++];
+ data[zig] = (short) (stbi__extend_receive(j,s) * dequant[zig]);
+ }
+ }
+ } while (k < 64);
+ return 1;
+}
+
+static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b)
+{
+ int diff,dc;
+ int t;
+ if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
+
+ if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
+
+ if (j->succ_high == 0) {
+ // first scan for DC coefficient, must be first
+ memset(data,0,64*sizeof(data[0])); // 0 all the ac values now
+ t = stbi__jpeg_huff_decode(j, hdc);
+ if (t < 0 || t > 15) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
+ diff = t ? stbi__extend_receive(j, t) : 0;
+
+ if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta", "Corrupt JPEG");
+ dc = j->img_comp[b].dc_pred + diff;
+ j->img_comp[b].dc_pred = dc;
+ if (!stbi__mul2shorts_valid(dc, 1 << j->succ_low)) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
+ data[0] = (short) (dc * (1 << j->succ_low));
+ } else {
+ // refinement scan for DC coefficient
+ if (stbi__jpeg_get_bit(j))
+ data[0] += (short) (1 << j->succ_low);
+ }
+ return 1;
+}
+
+// @OPTIMIZE: store non-zigzagged during the decode passes,
+// and only de-zigzag when dequantizing
+static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac)
+{
+ int k;
+ if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
+
+ if (j->succ_high == 0) {
+ int shift = j->succ_low;
+
+ if (j->eob_run) {
+ --j->eob_run;
+ return 1;
+ }
+
+ k = j->spec_start;
+ do {
+ unsigned int zig;
+ int c,r,s;
+ if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
+ c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);
+ r = fac[c];
+ if (r) { // fast-AC path
+ k += (r >> 4) & 15; // run
+ s = r & 15; // combined length
+ if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available");
+ j->code_buffer <<= s;
+ j->code_bits -= s;
+ zig = stbi__jpeg_dezigzag[k++];
+ data[zig] = (short) ((r >> 8) * (1 << shift));
+ } else {
+ int rs = stbi__jpeg_huff_decode(j, hac);
+ if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG");
+ s = rs & 15;
+ r = rs >> 4;
+ if (s == 0) {
+ if (r < 15) {
+ j->eob_run = (1 << r);
+ if (r)
+ j->eob_run += stbi__jpeg_get_bits(j, r);
+ --j->eob_run;
+ break;
+ }
+ k += 16;
+ } else {
+ k += r;
+ zig = stbi__jpeg_dezigzag[k++];
+ data[zig] = (short) (stbi__extend_receive(j,s) * (1 << shift));
+ }
+ }
+ } while (k <= j->spec_end);
+ } else {
+ // refinement scan for these AC coefficients
+
+ short bit = (short) (1 << j->succ_low);
+
+ if (j->eob_run) {
+ --j->eob_run;
+ for (k = j->spec_start; k <= j->spec_end; ++k) {
+ short *p = &data[stbi__jpeg_dezigzag[k]];
+ if (*p != 0)
+ if (stbi__jpeg_get_bit(j))
+ if ((*p & bit)==0) {
+ if (*p > 0)
+ *p += bit;
+ else
+ *p -= bit;
+ }
+ }
+ } else {
+ k = j->spec_start;
+ do {
+ int r,s;
+ int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh
+ if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG");
+ s = rs & 15;
+ r = rs >> 4;
+ if (s == 0) {
+ if (r < 15) {
+ j->eob_run = (1 << r) - 1;
+ if (r)
+ j->eob_run += stbi__jpeg_get_bits(j, r);
+ r = 64; // force end of block
+ } else {
+ // r=15 s=0 should write 16 0s, so we just do
+ // a run of 15 0s and then write s (which is 0),
+ // so we don't have to do anything special here
+ }
+ } else {
+ if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG");
+ // sign bit
+ if (stbi__jpeg_get_bit(j))
+ s = bit;
+ else
+ s = -bit;
+ }
+
+ // advance by r
+ while (k <= j->spec_end) {
+ short *p = &data[stbi__jpeg_dezigzag[k++]];
+ if (*p != 0) {
+ if (stbi__jpeg_get_bit(j))
+ if ((*p & bit)==0) {
+ if (*p > 0)
+ *p += bit;
+ else
+ *p -= bit;
+ }
+ } else {
+ if (r == 0) {
+ *p = (short) s;
+ break;
+ }
+ --r;
+ }
+ }
+ } while (k <= j->spec_end);
+ }
+ }
+ return 1;
+}
+
+// take a -128..127 value and stbi__clamp it and convert to 0..255
+stbi_inline static stbi_uc stbi__clamp(int x)
+{
+ // trick to use a single test to catch both cases
+ if ((unsigned int) x > 255) {
+ if (x < 0) return 0;
+ if (x > 255) return 255;
+ }
+ return (stbi_uc) x;
+}
+
+#define stbi__f2f(x) ((int) (((x) * 4096 + 0.5)))
+#define stbi__fsh(x) ((x) * 4096)
+
+// derived from jidctint -- DCT_ISLOW
+#define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \
+ int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \
+ p2 = s2; \
+ p3 = s6; \
+ p1 = (p2+p3) * stbi__f2f(0.5411961f); \
+ t2 = p1 + p3*stbi__f2f(-1.847759065f); \
+ t3 = p1 + p2*stbi__f2f( 0.765366865f); \
+ p2 = s0; \
+ p3 = s4; \
+ t0 = stbi__fsh(p2+p3); \
+ t1 = stbi__fsh(p2-p3); \
+ x0 = t0+t3; \
+ x3 = t0-t3; \
+ x1 = t1+t2; \
+ x2 = t1-t2; \
+ t0 = s7; \
+ t1 = s5; \
+ t2 = s3; \
+ t3 = s1; \
+ p3 = t0+t2; \
+ p4 = t1+t3; \
+ p1 = t0+t3; \
+ p2 = t1+t2; \
+ p5 = (p3+p4)*stbi__f2f( 1.175875602f); \
+ t0 = t0*stbi__f2f( 0.298631336f); \
+ t1 = t1*stbi__f2f( 2.053119869f); \
+ t2 = t2*stbi__f2f( 3.072711026f); \
+ t3 = t3*stbi__f2f( 1.501321110f); \
+ p1 = p5 + p1*stbi__f2f(-0.899976223f); \
+ p2 = p5 + p2*stbi__f2f(-2.562915447f); \
+ p3 = p3*stbi__f2f(-1.961570560f); \
+ p4 = p4*stbi__f2f(-0.390180644f); \
+ t3 += p1+p4; \
+ t2 += p2+p3; \
+ t1 += p2+p4; \
+ t0 += p1+p3;
+
+static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64])
+{
+ int i,val[64],*v=val;
+ stbi_uc *o;
+ short *d = data;
+
+ // columns
+ for (i=0; i < 8; ++i,++d, ++v) {
+ // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
+ if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0
+ && d[40]==0 && d[48]==0 && d[56]==0) {
+ // no shortcut 0 seconds
+ // (1|2|3|4|5|6|7)==0 0 seconds
+ // all separate -0.047 seconds
+ // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds
+ int dcterm = d[0]*4;
+ v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
+ } else {
+ STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56])
+ // constants scaled things up by 1<<12; let's bring them back
+ // down, but keep 2 extra bits of precision
+ x0 += 512; x1 += 512; x2 += 512; x3 += 512;
+ v[ 0] = (x0+t3) >> 10;
+ v[56] = (x0-t3) >> 10;
+ v[ 8] = (x1+t2) >> 10;
+ v[48] = (x1-t2) >> 10;
+ v[16] = (x2+t1) >> 10;
+ v[40] = (x2-t1) >> 10;
+ v[24] = (x3+t0) >> 10;
+ v[32] = (x3-t0) >> 10;
+ }
+ }
+
+ for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {
+ // no fast case since the first 1D IDCT spread components out
+ STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])
+ // constants scaled things up by 1<<12, plus we had 1<<2 from first
+ // loop, plus horizontal and vertical each scale by sqrt(8) so together
+ // we've got an extra 1<<3, so 1<<17 total we need to remove.
+ // so we want to round that, which means adding 0.5 * 1<<17,
+ // aka 65536. Also, we'll end up with -128 to 127 that we want
+ // to encode as 0..255 by adding 128, so we'll add that before the shift
+ x0 += 65536 + (128<<17);
+ x1 += 65536 + (128<<17);
+ x2 += 65536 + (128<<17);
+ x3 += 65536 + (128<<17);
+ // tried computing the shifts into temps, or'ing the temps to see
+ // if any were out of range, but that was slower
+ o[0] = stbi__clamp((x0+t3) >> 17);
+ o[7] = stbi__clamp((x0-t3) >> 17);
+ o[1] = stbi__clamp((x1+t2) >> 17);
+ o[6] = stbi__clamp((x1-t2) >> 17);
+ o[2] = stbi__clamp((x2+t1) >> 17);
+ o[5] = stbi__clamp((x2-t1) >> 17);
+ o[3] = stbi__clamp((x3+t0) >> 17);
+ o[4] = stbi__clamp((x3-t0) >> 17);
+ }
+}
+
+#ifdef STBI_SSE2
+// sse2 integer IDCT. not the fastest possible implementation but it
+// produces bit-identical results to the generic C version so it's
+// fully "transparent".
+static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64])
+{
+ // This is constructed to match our regular (generic) integer IDCT exactly.
+ __m128i row0, row1, row2, row3, row4, row5, row6, row7;
+ __m128i tmp;
+
+ // dot product constant: even elems=x, odd elems=y
+ #define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y))
+
+ // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit)
+ // out(1) = c1[even]*x + c1[odd]*y
+ #define dct_rot(out0,out1, x,y,c0,c1) \
+ __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \
+ __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \
+ __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \
+ __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \
+ __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \
+ __m128i out1##_h = _mm_madd_epi16(c0##hi, c1)
+
+ // out = in << 12 (in 16-bit, out 32-bit)
+ #define dct_widen(out, in) \
+ __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \
+ __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4)
+
+ // wide add
+ #define dct_wadd(out, a, b) \
+ __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \
+ __m128i out##_h = _mm_add_epi32(a##_h, b##_h)
+
+ // wide sub
+ #define dct_wsub(out, a, b) \
+ __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \
+ __m128i out##_h = _mm_sub_epi32(a##_h, b##_h)
+
+ // butterfly a/b, add bias, then shift by "s" and pack
+ #define dct_bfly32o(out0, out1, a,b,bias,s) \
+ { \
+ __m128i abiased_l = _mm_add_epi32(a##_l, bias); \
+ __m128i abiased_h = _mm_add_epi32(a##_h, bias); \
+ dct_wadd(sum, abiased, b); \
+ dct_wsub(dif, abiased, b); \
+ out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \
+ out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \
+ }
+
+ // 8-bit interleave step (for transposes)
+ #define dct_interleave8(a, b) \
+ tmp = a; \
+ a = _mm_unpacklo_epi8(a, b); \
+ b = _mm_unpackhi_epi8(tmp, b)
+
+ // 16-bit interleave step (for transposes)
+ #define dct_interleave16(a, b) \
+ tmp = a; \
+ a = _mm_unpacklo_epi16(a, b); \
+ b = _mm_unpackhi_epi16(tmp, b)
+
+ #define dct_pass(bias,shift) \
+ { \
+ /* even part */ \
+ dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \
+ __m128i sum04 = _mm_add_epi16(row0, row4); \
+ __m128i dif04 = _mm_sub_epi16(row0, row4); \
+ dct_widen(t0e, sum04); \
+ dct_widen(t1e, dif04); \
+ dct_wadd(x0, t0e, t3e); \
+ dct_wsub(x3, t0e, t3e); \
+ dct_wadd(x1, t1e, t2e); \
+ dct_wsub(x2, t1e, t2e); \
+ /* odd part */ \
+ dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \
+ dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \
+ __m128i sum17 = _mm_add_epi16(row1, row7); \
+ __m128i sum35 = _mm_add_epi16(row3, row5); \
+ dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \
+ dct_wadd(x4, y0o, y4o); \
+ dct_wadd(x5, y1o, y5o); \
+ dct_wadd(x6, y2o, y5o); \
+ dct_wadd(x7, y3o, y4o); \
+ dct_bfly32o(row0,row7, x0,x7,bias,shift); \
+ dct_bfly32o(row1,row6, x1,x6,bias,shift); \
+ dct_bfly32o(row2,row5, x2,x5,bias,shift); \
+ dct_bfly32o(row3,row4, x3,x4,bias,shift); \
+ }
+
+ __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f));
+ __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f( 0.765366865f), stbi__f2f(0.5411961f));
+ __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f));
+ __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f));
+ __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f( 0.298631336f), stbi__f2f(-1.961570560f));
+ __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f( 3.072711026f));
+ __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f( 2.053119869f), stbi__f2f(-0.390180644f));
+ __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f( 1.501321110f));
+
+ // rounding biases in column/row passes, see stbi__idct_block for explanation.
+ __m128i bias_0 = _mm_set1_epi32(512);
+ __m128i bias_1 = _mm_set1_epi32(65536 + (128<<17));
+
+ // load
+ row0 = _mm_load_si128((const __m128i *) (data + 0*8));
+ row1 = _mm_load_si128((const __m128i *) (data + 1*8));
+ row2 = _mm_load_si128((const __m128i *) (data + 2*8));
+ row3 = _mm_load_si128((const __m128i *) (data + 3*8));
+ row4 = _mm_load_si128((const __m128i *) (data + 4*8));
+ row5 = _mm_load_si128((const __m128i *) (data + 5*8));
+ row6 = _mm_load_si128((const __m128i *) (data + 6*8));
+ row7 = _mm_load_si128((const __m128i *) (data + 7*8));
+
+ // column pass
+ dct_pass(bias_0, 10);
+
+ {
+ // 16bit 8x8 transpose pass 1
+ dct_interleave16(row0, row4);
+ dct_interleave16(row1, row5);
+ dct_interleave16(row2, row6);
+ dct_interleave16(row3, row7);
+
+ // transpose pass 2
+ dct_interleave16(row0, row2);
+ dct_interleave16(row1, row3);
+ dct_interleave16(row4, row6);
+ dct_interleave16(row5, row7);
+
+ // transpose pass 3
+ dct_interleave16(row0, row1);
+ dct_interleave16(row2, row3);
+ dct_interleave16(row4, row5);
+ dct_interleave16(row6, row7);
+ }
+
+ // row pass
+ dct_pass(bias_1, 17);
+
+ {
+ // pack
+ __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7
+ __m128i p1 = _mm_packus_epi16(row2, row3);
+ __m128i p2 = _mm_packus_epi16(row4, row5);
+ __m128i p3 = _mm_packus_epi16(row6, row7);
+
+ // 8bit 8x8 transpose pass 1
+ dct_interleave8(p0, p2); // a0e0a1e1...
+ dct_interleave8(p1, p3); // c0g0c1g1...
+
+ // transpose pass 2
+ dct_interleave8(p0, p1); // a0c0e0g0...
+ dct_interleave8(p2, p3); // b0d0f0h0...
+
+ // transpose pass 3
+ dct_interleave8(p0, p2); // a0b0c0d0...
+ dct_interleave8(p1, p3); // a4b4c4d4...
+
+ // store
+ _mm_storel_epi64((__m128i *) out, p0); out += out_stride;
+ _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride;
+ _mm_storel_epi64((__m128i *) out, p2); out += out_stride;
+ _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride;
+ _mm_storel_epi64((__m128i *) out, p1); out += out_stride;
+ _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride;
+ _mm_storel_epi64((__m128i *) out, p3); out += out_stride;
+ _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e));
+ }
+
+#undef dct_const
+#undef dct_rot
+#undef dct_widen
+#undef dct_wadd
+#undef dct_wsub
+#undef dct_bfly32o
+#undef dct_interleave8
+#undef dct_interleave16
+#undef dct_pass
+}
+
+#endif // STBI_SSE2
+
+#ifdef STBI_NEON
+
+// NEON integer IDCT. should produce bit-identical
+// results to the generic C version.
+static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64])
+{
+ int16x8_t row0, row1, row2, row3, row4, row5, row6, row7;
+
+ int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f));
+ int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f));
+ int16x4_t rot0_2 = vdup_n_s16(stbi__f2f( 0.765366865f));
+ int16x4_t rot1_0 = vdup_n_s16(stbi__f2f( 1.175875602f));
+ int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f));
+ int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f));
+ int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f));
+ int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f));
+ int16x4_t rot3_0 = vdup_n_s16(stbi__f2f( 0.298631336f));
+ int16x4_t rot3_1 = vdup_n_s16(stbi__f2f( 2.053119869f));
+ int16x4_t rot3_2 = vdup_n_s16(stbi__f2f( 3.072711026f));
+ int16x4_t rot3_3 = vdup_n_s16(stbi__f2f( 1.501321110f));
+
+#define dct_long_mul(out, inq, coeff) \
+ int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \
+ int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff)
+
+#define dct_long_mac(out, acc, inq, coeff) \
+ int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \
+ int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff)
+
+#define dct_widen(out, inq) \
+ int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \
+ int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12)
+
+// wide add
+#define dct_wadd(out, a, b) \
+ int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \
+ int32x4_t out##_h = vaddq_s32(a##_h, b##_h)
+
+// wide sub
+#define dct_wsub(out, a, b) \
+ int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \
+ int32x4_t out##_h = vsubq_s32(a##_h, b##_h)
+
+// butterfly a/b, then shift using "shiftop" by "s" and pack
+#define dct_bfly32o(out0,out1, a,b,shiftop,s) \
+ { \
+ dct_wadd(sum, a, b); \
+ dct_wsub(dif, a, b); \
+ out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \
+ out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \
+ }
+
+#define dct_pass(shiftop, shift) \
+ { \
+ /* even part */ \
+ int16x8_t sum26 = vaddq_s16(row2, row6); \
+ dct_long_mul(p1e, sum26, rot0_0); \
+ dct_long_mac(t2e, p1e, row6, rot0_1); \
+ dct_long_mac(t3e, p1e, row2, rot0_2); \
+ int16x8_t sum04 = vaddq_s16(row0, row4); \
+ int16x8_t dif04 = vsubq_s16(row0, row4); \
+ dct_widen(t0e, sum04); \
+ dct_widen(t1e, dif04); \
+ dct_wadd(x0, t0e, t3e); \
+ dct_wsub(x3, t0e, t3e); \
+ dct_wadd(x1, t1e, t2e); \
+ dct_wsub(x2, t1e, t2e); \
+ /* odd part */ \
+ int16x8_t sum15 = vaddq_s16(row1, row5); \
+ int16x8_t sum17 = vaddq_s16(row1, row7); \
+ int16x8_t sum35 = vaddq_s16(row3, row5); \
+ int16x8_t sum37 = vaddq_s16(row3, row7); \
+ int16x8_t sumodd = vaddq_s16(sum17, sum35); \
+ dct_long_mul(p5o, sumodd, rot1_0); \
+ dct_long_mac(p1o, p5o, sum17, rot1_1); \
+ dct_long_mac(p2o, p5o, sum35, rot1_2); \
+ dct_long_mul(p3o, sum37, rot2_0); \
+ dct_long_mul(p4o, sum15, rot2_1); \
+ dct_wadd(sump13o, p1o, p3o); \
+ dct_wadd(sump24o, p2o, p4o); \
+ dct_wadd(sump23o, p2o, p3o); \
+ dct_wadd(sump14o, p1o, p4o); \
+ dct_long_mac(x4, sump13o, row7, rot3_0); \
+ dct_long_mac(x5, sump24o, row5, rot3_1); \
+ dct_long_mac(x6, sump23o, row3, rot3_2); \
+ dct_long_mac(x7, sump14o, row1, rot3_3); \
+ dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \
+ dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \
+ dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \
+ dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \
+ }
+
+ // load
+ row0 = vld1q_s16(data + 0*8);
+ row1 = vld1q_s16(data + 1*8);
+ row2 = vld1q_s16(data + 2*8);
+ row3 = vld1q_s16(data + 3*8);
+ row4 = vld1q_s16(data + 4*8);
+ row5 = vld1q_s16(data + 5*8);
+ row6 = vld1q_s16(data + 6*8);
+ row7 = vld1q_s16(data + 7*8);
+
+ // add DC bias
+ row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0));
+
+ // column pass
+ dct_pass(vrshrn_n_s32, 10);
+
+ // 16bit 8x8 transpose
+ {
+// these three map to a single VTRN.16, VTRN.32, and VSWP, respectively.
+// whether compilers actually get this is another story, sadly.
+#define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; }
+#define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); }
+#define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); }
+
+ // pass 1
+ dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6
+ dct_trn16(row2, row3);
+ dct_trn16(row4, row5);
+ dct_trn16(row6, row7);
+
+ // pass 2
+ dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4
+ dct_trn32(row1, row3);
+ dct_trn32(row4, row6);
+ dct_trn32(row5, row7);
+
+ // pass 3
+ dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0
+ dct_trn64(row1, row5);
+ dct_trn64(row2, row6);
+ dct_trn64(row3, row7);
+
+#undef dct_trn16
+#undef dct_trn32
+#undef dct_trn64
+ }
+
+ // row pass
+ // vrshrn_n_s32 only supports shifts up to 16, we need
+ // 17. so do a non-rounding shift of 16 first then follow
+ // up with a rounding shift by 1.
+ dct_pass(vshrn_n_s32, 16);
+
+ {
+ // pack and round
+ uint8x8_t p0 = vqrshrun_n_s16(row0, 1);
+ uint8x8_t p1 = vqrshrun_n_s16(row1, 1);
+ uint8x8_t p2 = vqrshrun_n_s16(row2, 1);
+ uint8x8_t p3 = vqrshrun_n_s16(row3, 1);
+ uint8x8_t p4 = vqrshrun_n_s16(row4, 1);
+ uint8x8_t p5 = vqrshrun_n_s16(row5, 1);
+ uint8x8_t p6 = vqrshrun_n_s16(row6, 1);
+ uint8x8_t p7 = vqrshrun_n_s16(row7, 1);
+
+ // again, these can translate into one instruction, but often don't.
+#define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; }
+#define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); }
+#define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); }
+
+ // sadly can't use interleaved stores here since we only write
+ // 8 bytes to each scan line!
+
+ // 8x8 8-bit transpose pass 1
+ dct_trn8_8(p0, p1);
+ dct_trn8_8(p2, p3);
+ dct_trn8_8(p4, p5);
+ dct_trn8_8(p6, p7);
+
+ // pass 2
+ dct_trn8_16(p0, p2);
+ dct_trn8_16(p1, p3);
+ dct_trn8_16(p4, p6);
+ dct_trn8_16(p5, p7);
+
+ // pass 3
+ dct_trn8_32(p0, p4);
+ dct_trn8_32(p1, p5);
+ dct_trn8_32(p2, p6);
+ dct_trn8_32(p3, p7);
+
+ // store
+ vst1_u8(out, p0); out += out_stride;
+ vst1_u8(out, p1); out += out_stride;
+ vst1_u8(out, p2); out += out_stride;
+ vst1_u8(out, p3); out += out_stride;
+ vst1_u8(out, p4); out += out_stride;
+ vst1_u8(out, p5); out += out_stride;
+ vst1_u8(out, p6); out += out_stride;
+ vst1_u8(out, p7);
+
+#undef dct_trn8_8
+#undef dct_trn8_16
+#undef dct_trn8_32
+ }
+
+#undef dct_long_mul
+#undef dct_long_mac
+#undef dct_widen
+#undef dct_wadd
+#undef dct_wsub
+#undef dct_bfly32o
+#undef dct_pass
+}
+
+#endif // STBI_NEON
+
+#define STBI__MARKER_none 0xff
+// if there's a pending marker from the entropy stream, return that
+// otherwise, fetch from the stream and get a marker. if there's no
+// marker, return 0xff, which is never a valid marker value
+static stbi_uc stbi__get_marker(stbi__jpeg *j)
+{
+ stbi_uc x;
+ if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; }
+ x = stbi__get8(j->s);
+ if (x != 0xff) return STBI__MARKER_none;
+ while (x == 0xff)
+ x = stbi__get8(j->s); // consume repeated 0xff fill bytes
+ return x;
+}
+
+// in each scan, we'll have scan_n components, and the order
+// of the components is specified by order[]
+#define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7)
+
+// after a restart interval, stbi__jpeg_reset the entropy decoder and
+// the dc prediction
+static void stbi__jpeg_reset(stbi__jpeg *j)
+{
+ j->code_bits = 0;
+ j->code_buffer = 0;
+ j->nomore = 0;
+ j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0;
+ j->marker = STBI__MARKER_none;
+ j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;
+ j->eob_run = 0;
+ // no more than 1<<31 MCUs if no restart_interal? that's plenty safe,
+ // since we don't even allow 1<<30 pixels
+}
+
+static int stbi__parse_entropy_coded_data(stbi__jpeg *z)
+{
+ stbi__jpeg_reset(z);
+ if (!z->progressive) {
+ if (z->scan_n == 1) {
+ int i,j;
+ STBI_SIMD_ALIGN(short, data[64]);
+ int n = z->order[0];
+ // non-interleaved data, we just need to process one block at a time,
+ // in trivial scanline order
+ // number of blocks to do just depends on how many actual "pixels" this
+ // component has, independent of interleaved MCU blocking and such
+ int w = (z->img_comp[n].x+7) >> 3;
+ int h = (z->img_comp[n].y+7) >> 3;
+ for (j=0; j < h; ++j) {
+ for (i=0; i < w; ++i) {
+ int ha = z->img_comp[n].ha;
+ if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0;
+ z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data);
+ // every data block is an MCU, so countdown the restart interval
+ if (--z->todo <= 0) {
+ if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
+ // if it's NOT a restart, then just bail, so we get corrupt data
+ // rather than no data
+ if (!STBI__RESTART(z->marker)) return 1;
+ stbi__jpeg_reset(z);
+ }
+ }
+ }
+ return 1;
+ } else { // interleaved
+ int i,j,k,x,y;
+ STBI_SIMD_ALIGN(short, data[64]);
+ for (j=0; j < z->img_mcu_y; ++j) {
+ for (i=0; i < z->img_mcu_x; ++i) {
+ // scan an interleaved mcu... process scan_n components in order
+ for (k=0; k < z->scan_n; ++k) {
+ int n = z->order[k];
+ // scan out an mcu's worth of this component; that's just determined
+ // by the basic H and V specified for the component
+ for (y=0; y < z->img_comp[n].v; ++y) {
+ for (x=0; x < z->img_comp[n].h; ++x) {
+ int x2 = (i*z->img_comp[n].h + x)*8;
+ int y2 = (j*z->img_comp[n].v + y)*8;
+ int ha = z->img_comp[n].ha;
+ if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0;
+ z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data);
+ }
+ }
+ }
+ // after all interleaved components, that's an interleaved MCU,
+ // so now count down the restart interval
+ if (--z->todo <= 0) {
+ if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
+ if (!STBI__RESTART(z->marker)) return 1;
+ stbi__jpeg_reset(z);
+ }
+ }
+ }
+ return 1;
+ }
+ } else {
+ if (z->scan_n == 1) {
+ int i,j;
+ int n = z->order[0];
+ // non-interleaved data, we just need to process one block at a time,
+ // in trivial scanline order
+ // number of blocks to do just depends on how many actual "pixels" this
+ // component has, independent of interleaved MCU blocking and such
+ int w = (z->img_comp[n].x+7) >> 3;
+ int h = (z->img_comp[n].y+7) >> 3;
+ for (j=0; j < h; ++j) {
+ for (i=0; i < w; ++i) {
+ short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w);
+ if (z->spec_start == 0) {
+ if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n))
+ return 0;
+ } else {
+ int ha = z->img_comp[n].ha;
+ if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha]))
+ return 0;
+ }
+ // every data block is an MCU, so countdown the restart interval
+ if (--z->todo <= 0) {
+ if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
+ if (!STBI__RESTART(z->marker)) return 1;
+ stbi__jpeg_reset(z);
+ }
+ }
+ }
+ return 1;
+ } else { // interleaved
+ int i,j,k,x,y;
+ for (j=0; j < z->img_mcu_y; ++j) {
+ for (i=0; i < z->img_mcu_x; ++i) {
+ // scan an interleaved mcu... process scan_n components in order
+ for (k=0; k < z->scan_n; ++k) {
+ int n = z->order[k];
+ // scan out an mcu's worth of this component; that's just determined
+ // by the basic H and V specified for the component
+ for (y=0; y < z->img_comp[n].v; ++y) {
+ for (x=0; x < z->img_comp[n].h; ++x) {
+ int x2 = (i*z->img_comp[n].h + x);
+ int y2 = (j*z->img_comp[n].v + y);
+ short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w);
+ if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n))
+ return 0;
+ }
+ }
+ }
+ // after all interleaved components, that's an interleaved MCU,
+ // so now count down the restart interval
+ if (--z->todo <= 0) {
+ if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
+ if (!STBI__RESTART(z->marker)) return 1;
+ stbi__jpeg_reset(z);
+ }
+ }
+ }
+ return 1;
+ }
+ }
+}
+
+static void stbi__jpeg_dequantize(short *data, stbi__uint16 *dequant)
+{
+ int i;
+ for (i=0; i < 64; ++i)
+ data[i] *= dequant[i];
+}
+
+static void stbi__jpeg_finish(stbi__jpeg *z)
+{
+ if (z->progressive) {
+ // dequantize and idct the data
+ int i,j,n;
+ for (n=0; n < z->s->img_n; ++n) {
+ int w = (z->img_comp[n].x+7) >> 3;
+ int h = (z->img_comp[n].y+7) >> 3;
+ for (j=0; j < h; ++j) {
+ for (i=0; i < w; ++i) {
+ short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w);
+ stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]);
+ z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data);
+ }
+ }
+ }
+ }
+}
+
+static int stbi__process_marker(stbi__jpeg *z, int m)
+{
+ int L;
+ switch (m) {
+ case STBI__MARKER_none: // no marker found
+ return stbi__err("expected marker","Corrupt JPEG");
+
+ case 0xDD: // DRI - specify restart interval
+ if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG");
+ z->restart_interval = stbi__get16be(z->s);
+ return 1;
+
+ case 0xDB: // DQT - define quantization table
+ L = stbi__get16be(z->s)-2;
+ while (L > 0) {
+ int q = stbi__get8(z->s);
+ int p = q >> 4, sixteen = (p != 0);
+ int t = q & 15,i;
+ if (p != 0 && p != 1) return stbi__err("bad DQT type","Corrupt JPEG");
+ if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG");
+
+ for (i=0; i < 64; ++i)
+ z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s));
+ L -= (sixteen ? 129 : 65);
+ }
+ return L==0;
+
+ case 0xC4: // DHT - define huffman table
+ L = stbi__get16be(z->s)-2;
+ while (L > 0) {
+ stbi_uc *v;
+ int sizes[16],i,n=0;
+ int q = stbi__get8(z->s);
+ int tc = q >> 4;
+ int th = q & 15;
+ if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG");
+ for (i=0; i < 16; ++i) {
+ sizes[i] = stbi__get8(z->s);
+ n += sizes[i];
+ }
+ if(n > 256) return stbi__err("bad DHT header","Corrupt JPEG"); // Loop over i < n would write past end of values!
+ L -= 17;
+ if (tc == 0) {
+ if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0;
+ v = z->huff_dc[th].values;
+ } else {
+ if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0;
+ v = z->huff_ac[th].values;
+ }
+ for (i=0; i < n; ++i)
+ v[i] = stbi__get8(z->s);
+ if (tc != 0)
+ stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th);
+ L -= n;
+ }
+ return L==0;
+ }
+
+ // check for comment block or APP blocks
+ if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) {
+ L = stbi__get16be(z->s);
+ if (L < 2) {
+ if (m == 0xFE)
+ return stbi__err("bad COM len","Corrupt JPEG");
+ else
+ return stbi__err("bad APP len","Corrupt JPEG");
+ }
+ L -= 2;
+
+ if (m == 0xE0 && L >= 5) { // JFIF APP0 segment
+ static const unsigned char tag[5] = {'J','F','I','F','\0'};
+ int ok = 1;
+ int i;
+ for (i=0; i < 5; ++i)
+ if (stbi__get8(z->s) != tag[i])
+ ok = 0;
+ L -= 5;
+ if (ok)
+ z->jfif = 1;
+ } else if (m == 0xEE && L >= 12) { // Adobe APP14 segment
+ static const unsigned char tag[6] = {'A','d','o','b','e','\0'};
+ int ok = 1;
+ int i;
+ for (i=0; i < 6; ++i)
+ if (stbi__get8(z->s) != tag[i])
+ ok = 0;
+ L -= 6;
+ if (ok) {
+ stbi__get8(z->s); // version
+ stbi__get16be(z->s); // flags0
+ stbi__get16be(z->s); // flags1
+ z->app14_color_transform = stbi__get8(z->s); // color transform
+ L -= 6;
+ }
+ }
+
+ stbi__skip(z->s, L);
+ return 1;
+ }
+
+ return stbi__err("unknown marker","Corrupt JPEG");
+}
+
+// after we see SOS
+static int stbi__process_scan_header(stbi__jpeg *z)
+{
+ int i;
+ int Ls = stbi__get16be(z->s);
+ z->scan_n = stbi__get8(z->s);
+ if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count","Corrupt JPEG");
+ if (Ls != 6+2*z->scan_n) return stbi__err("bad SOS len","Corrupt JPEG");
+ for (i=0; i < z->scan_n; ++i) {
+ int id = stbi__get8(z->s), which;
+ int q = stbi__get8(z->s);
+ for (which = 0; which < z->s->img_n; ++which)
+ if (z->img_comp[which].id == id)
+ break;
+ if (which == z->s->img_n) return 0; // no match
+ z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG");
+ z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG");
+ z->order[i] = which;
+ }
+
+ {
+ int aa;
+ z->spec_start = stbi__get8(z->s);
+ z->spec_end = stbi__get8(z->s); // should be 63, but might be 0
+ aa = stbi__get8(z->s);
+ z->succ_high = (aa >> 4);
+ z->succ_low = (aa & 15);
+ if (z->progressive) {
+ if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13)
+ return stbi__err("bad SOS", "Corrupt JPEG");
+ } else {
+ if (z->spec_start != 0) return stbi__err("bad SOS","Corrupt JPEG");
+ if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS","Corrupt JPEG");
+ z->spec_end = 63;
+ }
+ }
+
+ return 1;
+}
+
+static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why)
+{
+ int i;
+ for (i=0; i < ncomp; ++i) {
+ if (z->img_comp[i].raw_data) {
+ STBI_FREE(z->img_comp[i].raw_data);
+ z->img_comp[i].raw_data = NULL;
+ z->img_comp[i].data = NULL;
+ }
+ if (z->img_comp[i].raw_coeff) {
+ STBI_FREE(z->img_comp[i].raw_coeff);
+ z->img_comp[i].raw_coeff = 0;
+ z->img_comp[i].coeff = 0;
+ }
+ if (z->img_comp[i].linebuf) {
+ STBI_FREE(z->img_comp[i].linebuf);
+ z->img_comp[i].linebuf = NULL;
+ }
+ }
+ return why;
+}
+
+static int stbi__process_frame_header(stbi__jpeg *z, int scan)
+{
+ stbi__context *s = z->s;
+ int Lf,p,i,q, h_max=1,v_max=1,c;
+ Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len","Corrupt JPEG"); // JPEG
+ p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline
+ s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG
+ s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires
+ if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
+ if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
+ c = stbi__get8(s);
+ if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count","Corrupt JPEG");
+ s->img_n = c;
+ for (i=0; i < c; ++i) {
+ z->img_comp[i].data = NULL;
+ z->img_comp[i].linebuf = NULL;
+ }
+
+ if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG");
+
+ z->rgb = 0;
+ for (i=0; i < s->img_n; ++i) {
+ static const unsigned char rgb[3] = { 'R', 'G', 'B' };
+ z->img_comp[i].id = stbi__get8(s);
+ if (s->img_n == 3 && z->img_comp[i].id == rgb[i])
+ ++z->rgb;
+ q = stbi__get8(s);
+ z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG");
+ z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG");
+ z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG");
+ }
+
+ if (scan != STBI__SCAN_load) return 1;
+
+ if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode");
+
+ for (i=0; i < s->img_n; ++i) {
+ if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h;
+ if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;
+ }
+
+ // check that plane subsampling factors are integer ratios; our resamplers can't deal with fractional ratios
+ // and I've never seen a non-corrupted JPEG file actually use them
+ for (i=0; i < s->img_n; ++i) {
+ if (h_max % z->img_comp[i].h != 0) return stbi__err("bad H","Corrupt JPEG");
+ if (v_max % z->img_comp[i].v != 0) return stbi__err("bad V","Corrupt JPEG");
+ }
+
+ // compute interleaved mcu info
+ z->img_h_max = h_max;
+ z->img_v_max = v_max;
+ z->img_mcu_w = h_max * 8;
+ z->img_mcu_h = v_max * 8;
+ // these sizes can't be more than 17 bits
+ z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w;
+ z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h;
+
+ for (i=0; i < s->img_n; ++i) {
+ // number of effective pixels (e.g. for non-interleaved MCU)
+ z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max;
+ z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max;
+ // to simplify generation, we'll allocate enough memory to decode
+ // the bogus oversized data from using interleaved MCUs and their
+ // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't
+ // discard the extra data until colorspace conversion
+ //
+ // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier)
+ // so these muls can't overflow with 32-bit ints (which we require)
+ z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8;
+ z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8;
+ z->img_comp[i].coeff = 0;
+ z->img_comp[i].raw_coeff = 0;
+ z->img_comp[i].linebuf = NULL;
+ z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15);
+ if (z->img_comp[i].raw_data == NULL)
+ return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory"));
+ // align blocks for idct using mmx/sse
+ z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15);
+ if (z->progressive) {
+ // w2, h2 are multiples of 8 (see above)
+ z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8;
+ z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8;
+ z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15);
+ if (z->img_comp[i].raw_coeff == NULL)
+ return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory"));
+ z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15);
+ }
+ }
+
+ return 1;
+}
+
+// use comparisons since in some cases we handle more than one case (e.g. SOF)
+#define stbi__DNL(x) ((x) == 0xdc)
+#define stbi__SOI(x) ((x) == 0xd8)
+#define stbi__EOI(x) ((x) == 0xd9)
+#define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2)
+#define stbi__SOS(x) ((x) == 0xda)
+
+#define stbi__SOF_progressive(x) ((x) == 0xc2)
+
+static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan)
+{
+ int m;
+ z->jfif = 0;
+ z->app14_color_transform = -1; // valid values are 0,1,2
+ z->marker = STBI__MARKER_none; // initialize cached marker to empty
+ m = stbi__get_marker(z);
+ if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG");
+ if (scan == STBI__SCAN_type) return 1;
+ m = stbi__get_marker(z);
+ while (!stbi__SOF(m)) {
+ if (!stbi__process_marker(z,m)) return 0;
+ m = stbi__get_marker(z);
+ while (m == STBI__MARKER_none) {
+ // some files have extra padding after their blocks, so ok, we'll scan
+ if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG");
+ m = stbi__get_marker(z);
+ }
+ }
+ z->progressive = stbi__SOF_progressive(m);
+ if (!stbi__process_frame_header(z, scan)) return 0;
+ return 1;
+}
+
+static stbi_uc stbi__skip_jpeg_junk_at_end(stbi__jpeg *j)
+{
+ // some JPEGs have junk at end, skip over it but if we find what looks
+ // like a valid marker, resume there
+ while (!stbi__at_eof(j->s)) {
+ stbi_uc x = stbi__get8(j->s);
+ while (x == 0xff) { // might be a marker
+ if (stbi__at_eof(j->s)) return STBI__MARKER_none;
+ x = stbi__get8(j->s);
+ if (x != 0x00 && x != 0xff) {
+ // not a stuffed zero or lead-in to another marker, looks
+ // like an actual marker, return it
+ return x;
+ }
+ // stuffed zero has x=0 now which ends the loop, meaning we go
+ // back to regular scan loop.
+ // repeated 0xff keeps trying to read the next byte of the marker.
+ }
+ }
+ return STBI__MARKER_none;
+}
+
+// decode image to YCbCr format
+static int stbi__decode_jpeg_image(stbi__jpeg *j)
+{
+ int m;
+ for (m = 0; m < 4; m++) {
+ j->img_comp[m].raw_data = NULL;
+ j->img_comp[m].raw_coeff = NULL;
+ }
+ j->restart_interval = 0;
+ if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0;
+ m = stbi__get_marker(j);
+ while (!stbi__EOI(m)) {
+ if (stbi__SOS(m)) {
+ if (!stbi__process_scan_header(j)) return 0;
+ if (!stbi__parse_entropy_coded_data(j)) return 0;
+ if (j->marker == STBI__MARKER_none ) {
+ j->marker = stbi__skip_jpeg_junk_at_end(j);
+ // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0
+ }
+ m = stbi__get_marker(j);
+ if (STBI__RESTART(m))
+ m = stbi__get_marker(j);
+ } else if (stbi__DNL(m)) {
+ int Ld = stbi__get16be(j->s);
+ stbi__uint32 NL = stbi__get16be(j->s);
+ if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG");
+ if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG");
+ m = stbi__get_marker(j);
+ } else {
+ if (!stbi__process_marker(j, m)) return 1;
+ m = stbi__get_marker(j);
+ }
+ }
+ if (j->progressive)
+ stbi__jpeg_finish(j);
+ return 1;
+}
+
+// static jfif-centered resampling (across block boundaries)
+
+typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1,
+ int w, int hs);
+
+#define stbi__div4(x) ((stbi_uc) ((x) >> 2))
+
+static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
+{
+ STBI_NOTUSED(out);
+ STBI_NOTUSED(in_far);
+ STBI_NOTUSED(w);
+ STBI_NOTUSED(hs);
+ return in_near;
+}
+
+static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
+{
+ // need to generate two samples vertically for every one in input
+ int i;
+ STBI_NOTUSED(hs);
+ for (i=0; i < w; ++i)
+ out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2);
+ return out;
+}
+
+static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
+{
+ // need to generate two samples horizontally for every one in input
+ int i;
+ stbi_uc *input = in_near;
+
+ if (w == 1) {
+ // if only one sample, can't do any interpolation
+ out[0] = out[1] = input[0];
+ return out;
+ }
+
+ out[0] = input[0];
+ out[1] = stbi__div4(input[0]*3 + input[1] + 2);
+ for (i=1; i < w-1; ++i) {
+ int n = 3*input[i]+2;
+ out[i*2+0] = stbi__div4(n+input[i-1]);
+ out[i*2+1] = stbi__div4(n+input[i+1]);
+ }
+ out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2);
+ out[i*2+1] = input[w-1];
+
+ STBI_NOTUSED(in_far);
+ STBI_NOTUSED(hs);
+
+ return out;
+}
+
+#define stbi__div16(x) ((stbi_uc) ((x) >> 4))
+
+static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
+{
+ // need to generate 2x2 samples for every one in input
+ int i,t0,t1;
+ if (w == 1) {
+ out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2);
+ return out;
+ }
+
+ t1 = 3*in_near[0] + in_far[0];
+ out[0] = stbi__div4(t1+2);
+ for (i=1; i < w; ++i) {
+ t0 = t1;
+ t1 = 3*in_near[i]+in_far[i];
+ out[i*2-1] = stbi__div16(3*t0 + t1 + 8);
+ out[i*2 ] = stbi__div16(3*t1 + t0 + 8);
+ }
+ out[w*2-1] = stbi__div4(t1+2);
+
+ STBI_NOTUSED(hs);
+
+ return out;
+}
+
+#if defined(STBI_SSE2) || defined(STBI_NEON)
+static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
+{
+ // need to generate 2x2 samples for every one in input
+ int i=0,t0,t1;
+
+ if (w == 1) {
+ out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2);
+ return out;
+ }
+
+ t1 = 3*in_near[0] + in_far[0];
+ // process groups of 8 pixels for as long as we can.
+ // note we can't handle the last pixel in a row in this loop
+ // because we need to handle the filter boundary conditions.
+ for (; i < ((w-1) & ~7); i += 8) {
+#if defined(STBI_SSE2)
+ // load and perform the vertical filtering pass
+ // this uses 3*x + y = 4*x + (y - x)
+ __m128i zero = _mm_setzero_si128();
+ __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i));
+ __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i));
+ __m128i farw = _mm_unpacklo_epi8(farb, zero);
+ __m128i nearw = _mm_unpacklo_epi8(nearb, zero);
+ __m128i diff = _mm_sub_epi16(farw, nearw);
+ __m128i nears = _mm_slli_epi16(nearw, 2);
+ __m128i curr = _mm_add_epi16(nears, diff); // current row
+
+ // horizontal filter works the same based on shifted vers of current
+ // row. "prev" is current row shifted right by 1 pixel; we need to
+ // insert the previous pixel value (from t1).
+ // "next" is current row shifted left by 1 pixel, with first pixel
+ // of next block of 8 pixels added in.
+ __m128i prv0 = _mm_slli_si128(curr, 2);
+ __m128i nxt0 = _mm_srli_si128(curr, 2);
+ __m128i prev = _mm_insert_epi16(prv0, t1, 0);
+ __m128i next = _mm_insert_epi16(nxt0, 3*in_near[i+8] + in_far[i+8], 7);
+
+ // horizontal filter, polyphase implementation since it's convenient:
+ // even pixels = 3*cur + prev = cur*4 + (prev - cur)
+ // odd pixels = 3*cur + next = cur*4 + (next - cur)
+ // note the shared term.
+ __m128i bias = _mm_set1_epi16(8);
+ __m128i curs = _mm_slli_epi16(curr, 2);
+ __m128i prvd = _mm_sub_epi16(prev, curr);
+ __m128i nxtd = _mm_sub_epi16(next, curr);
+ __m128i curb = _mm_add_epi16(curs, bias);
+ __m128i even = _mm_add_epi16(prvd, curb);
+ __m128i odd = _mm_add_epi16(nxtd, curb);
+
+ // interleave even and odd pixels, then undo scaling.
+ __m128i int0 = _mm_unpacklo_epi16(even, odd);
+ __m128i int1 = _mm_unpackhi_epi16(even, odd);
+ __m128i de0 = _mm_srli_epi16(int0, 4);
+ __m128i de1 = _mm_srli_epi16(int1, 4);
+
+ // pack and write output
+ __m128i outv = _mm_packus_epi16(de0, de1);
+ _mm_storeu_si128((__m128i *) (out + i*2), outv);
+#elif defined(STBI_NEON)
+ // load and perform the vertical filtering pass
+ // this uses 3*x + y = 4*x + (y - x)
+ uint8x8_t farb = vld1_u8(in_far + i);
+ uint8x8_t nearb = vld1_u8(in_near + i);
+ int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb));
+ int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2));
+ int16x8_t curr = vaddq_s16(nears, diff); // current row
+
+ // horizontal filter works the same based on shifted vers of current
+ // row. "prev" is current row shifted right by 1 pixel; we need to
+ // insert the previous pixel value (from t1).
+ // "next" is current row shifted left by 1 pixel, with first pixel
+ // of next block of 8 pixels added in.
+ int16x8_t prv0 = vextq_s16(curr, curr, 7);
+ int16x8_t nxt0 = vextq_s16(curr, curr, 1);
+ int16x8_t prev = vsetq_lane_s16(t1, prv0, 0);
+ int16x8_t next = vsetq_lane_s16(3*in_near[i+8] + in_far[i+8], nxt0, 7);
+
+ // horizontal filter, polyphase implementation since it's convenient:
+ // even pixels = 3*cur + prev = cur*4 + (prev - cur)
+ // odd pixels = 3*cur + next = cur*4 + (next - cur)
+ // note the shared term.
+ int16x8_t curs = vshlq_n_s16(curr, 2);
+ int16x8_t prvd = vsubq_s16(prev, curr);
+ int16x8_t nxtd = vsubq_s16(next, curr);
+ int16x8_t even = vaddq_s16(curs, prvd);
+ int16x8_t odd = vaddq_s16(curs, nxtd);
+
+ // undo scaling and round, then store with even/odd phases interleaved
+ uint8x8x2_t o;
+ o.val[0] = vqrshrun_n_s16(even, 4);
+ o.val[1] = vqrshrun_n_s16(odd, 4);
+ vst2_u8(out + i*2, o);
+#endif
+
+ // "previous" value for next iter
+ t1 = 3*in_near[i+7] + in_far[i+7];
+ }
+
+ t0 = t1;
+ t1 = 3*in_near[i] + in_far[i];
+ out[i*2] = stbi__div16(3*t1 + t0 + 8);
+
+ for (++i; i < w; ++i) {
+ t0 = t1;
+ t1 = 3*in_near[i]+in_far[i];
+ out[i*2-1] = stbi__div16(3*t0 + t1 + 8);
+ out[i*2 ] = stbi__div16(3*t1 + t0 + 8);
+ }
+ out[w*2-1] = stbi__div4(t1+2);
+
+ STBI_NOTUSED(hs);
+
+ return out;
+}
+#endif
+
+static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
+{
+ // resample with nearest-neighbor
+ int i,j;
+ STBI_NOTUSED(in_far);
+ for (i=0; i < w; ++i)
+ for (j=0; j < hs; ++j)
+ out[i*hs+j] = in_near[i];
+ return out;
+}
+
+// this is a reduced-precision calculation of YCbCr-to-RGB introduced
+// to make sure the code produces the same results in both SIMD and scalar
+#define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8)
+static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step)
+{
+ int i;
+ for (i=0; i < count; ++i) {
+ int y_fixed = (y[i] << 20) + (1<<19); // rounding
+ int r,g,b;
+ int cr = pcr[i] - 128;
+ int cb = pcb[i] - 128;
+ r = y_fixed + cr* stbi__float2fixed(1.40200f);
+ g = y_fixed + (cr*-stbi__float2fixed(0.71414f)) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000);
+ b = y_fixed + cb* stbi__float2fixed(1.77200f);
+ r >>= 20;
+ g >>= 20;
+ b >>= 20;
+ if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }
+ if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }
+ if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }
+ out[0] = (stbi_uc)r;
+ out[1] = (stbi_uc)g;
+ out[2] = (stbi_uc)b;
+ out[3] = 255;
+ out += step;
+ }
+}
+
+#if defined(STBI_SSE2) || defined(STBI_NEON)
+static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step)
+{
+ int i = 0;
+
+#ifdef STBI_SSE2
+ // step == 3 is pretty ugly on the final interleave, and i'm not convinced
+ // it's useful in practice (you wouldn't use it for textures, for example).
+ // so just accelerate step == 4 case.
+ if (step == 4) {
+ // this is a fairly straightforward implementation and not super-optimized.
+ __m128i signflip = _mm_set1_epi8(-0x80);
+ __m128i cr_const0 = _mm_set1_epi16( (short) ( 1.40200f*4096.0f+0.5f));
+ __m128i cr_const1 = _mm_set1_epi16( - (short) ( 0.71414f*4096.0f+0.5f));
+ __m128i cb_const0 = _mm_set1_epi16( - (short) ( 0.34414f*4096.0f+0.5f));
+ __m128i cb_const1 = _mm_set1_epi16( (short) ( 1.77200f*4096.0f+0.5f));
+ __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128);
+ __m128i xw = _mm_set1_epi16(255); // alpha channel
+
+ for (; i+7 < count; i += 8) {
+ // load
+ __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y+i));
+ __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr+i));
+ __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb+i));
+ __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128
+ __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128
+
+ // unpack to short (and left-shift cr, cb by 8)
+ __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes);
+ __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased);
+ __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased);
+
+ // color transform
+ __m128i yws = _mm_srli_epi16(yw, 4);
+ __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw);
+ __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw);
+ __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1);
+ __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1);
+ __m128i rws = _mm_add_epi16(cr0, yws);
+ __m128i gwt = _mm_add_epi16(cb0, yws);
+ __m128i bws = _mm_add_epi16(yws, cb1);
+ __m128i gws = _mm_add_epi16(gwt, cr1);
+
+ // descale
+ __m128i rw = _mm_srai_epi16(rws, 4);
+ __m128i bw = _mm_srai_epi16(bws, 4);
+ __m128i gw = _mm_srai_epi16(gws, 4);
+
+ // back to byte, set up for transpose
+ __m128i brb = _mm_packus_epi16(rw, bw);
+ __m128i gxb = _mm_packus_epi16(gw, xw);
+
+ // transpose to interleave channels
+ __m128i t0 = _mm_unpacklo_epi8(brb, gxb);
+ __m128i t1 = _mm_unpackhi_epi8(brb, gxb);
+ __m128i o0 = _mm_unpacklo_epi16(t0, t1);
+ __m128i o1 = _mm_unpackhi_epi16(t0, t1);
+
+ // store
+ _mm_storeu_si128((__m128i *) (out + 0), o0);
+ _mm_storeu_si128((__m128i *) (out + 16), o1);
+ out += 32;
+ }
+ }
+#endif
+
+#ifdef STBI_NEON
+ // in this version, step=3 support would be easy to add. but is there demand?
+ if (step == 4) {
+ // this is a fairly straightforward implementation and not super-optimized.
+ uint8x8_t signflip = vdup_n_u8(0x80);
+ int16x8_t cr_const0 = vdupq_n_s16( (short) ( 1.40200f*4096.0f+0.5f));
+ int16x8_t cr_const1 = vdupq_n_s16( - (short) ( 0.71414f*4096.0f+0.5f));
+ int16x8_t cb_const0 = vdupq_n_s16( - (short) ( 0.34414f*4096.0f+0.5f));
+ int16x8_t cb_const1 = vdupq_n_s16( (short) ( 1.77200f*4096.0f+0.5f));
+
+ for (; i+7 < count; i += 8) {
+ // load
+ uint8x8_t y_bytes = vld1_u8(y + i);
+ uint8x8_t cr_bytes = vld1_u8(pcr + i);
+ uint8x8_t cb_bytes = vld1_u8(pcb + i);
+ int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip));
+ int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip));
+
+ // expand to s16
+ int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4));
+ int16x8_t crw = vshll_n_s8(cr_biased, 7);
+ int16x8_t cbw = vshll_n_s8(cb_biased, 7);
+
+ // color transform
+ int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0);
+ int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0);
+ int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1);
+ int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1);
+ int16x8_t rws = vaddq_s16(yws, cr0);
+ int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1);
+ int16x8_t bws = vaddq_s16(yws, cb1);
+
+ // undo scaling, round, convert to byte
+ uint8x8x4_t o;
+ o.val[0] = vqrshrun_n_s16(rws, 4);
+ o.val[1] = vqrshrun_n_s16(gws, 4);
+ o.val[2] = vqrshrun_n_s16(bws, 4);
+ o.val[3] = vdup_n_u8(255);
+
+ // store, interleaving r/g/b/a
+ vst4_u8(out, o);
+ out += 8*4;
+ }
+ }
+#endif
+
+ for (; i < count; ++i) {
+ int y_fixed = (y[i] << 20) + (1<<19); // rounding
+ int r,g,b;
+ int cr = pcr[i] - 128;
+ int cb = pcb[i] - 128;
+ r = y_fixed + cr* stbi__float2fixed(1.40200f);
+ g = y_fixed + cr*-stbi__float2fixed(0.71414f) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000);
+ b = y_fixed + cb* stbi__float2fixed(1.77200f);
+ r >>= 20;
+ g >>= 20;
+ b >>= 20;
+ if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }
+ if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }
+ if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }
+ out[0] = (stbi_uc)r;
+ out[1] = (stbi_uc)g;
+ out[2] = (stbi_uc)b;
+ out[3] = 255;
+ out += step;
+ }
+}
+#endif
+
+// set up the kernels
+static void stbi__setup_jpeg(stbi__jpeg *j)
+{
+ j->idct_block_kernel = stbi__idct_block;
+ j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row;
+ j->resample_row_hv_2_kernel = stbi__resample_row_hv_2;
+
+#ifdef STBI_SSE2
+ if (stbi__sse2_available()) {
+ j->idct_block_kernel = stbi__idct_simd;
+ j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd;
+ j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd;
+ }
+#endif
+
+#ifdef STBI_NEON
+ j->idct_block_kernel = stbi__idct_simd;
+ j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd;
+ j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd;
+#endif
+}
+
+// clean up the temporary component buffers
+static void stbi__cleanup_jpeg(stbi__jpeg *j)
+{
+ stbi__free_jpeg_components(j, j->s->img_n, 0);
+}
+
+typedef struct
+{
+ resample_row_func resample;
+ stbi_uc *line0,*line1;
+ int hs,vs; // expansion factor in each axis
+ int w_lores; // horizontal pixels pre-expansion
+ int ystep; // how far through vertical expansion we are
+ int ypos; // which pre-expansion row we're on
+} stbi__resample;
+
+// fast 0..255 * 0..255 => 0..255 rounded multiplication
+static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y)
+{
+ unsigned int t = x*y + 128;
+ return (stbi_uc) ((t + (t >>8)) >> 8);
+}
+
+static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp)
+{
+ int n, decode_n, is_rgb;
+ z->s->img_n = 0; // make stbi__cleanup_jpeg safe
+
+ // validate req_comp
+ if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error");
+
+ // load a jpeg image from whichever source, but leave in YCbCr format
+ if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; }
+
+ // determine actual number of components to generate
+ n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1;
+
+ is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif));
+
+ if (z->s->img_n == 3 && n < 3 && !is_rgb)
+ decode_n = 1;
+ else
+ decode_n = z->s->img_n;
+
+ // nothing to do if no components requested; check this now to avoid
+ // accessing uninitialized coutput[0] later
+ if (decode_n <= 0) { stbi__cleanup_jpeg(z); return NULL; }
+
+ // resample and color-convert
+ {
+ int k;
+ unsigned int i,j;
+ stbi_uc *output;
+ stbi_uc *coutput[4] = { NULL, NULL, NULL, NULL };
+
+ stbi__resample res_comp[4];
+
+ for (k=0; k < decode_n; ++k) {
+ stbi__resample *r = &res_comp[k];
+
+ // allocate line buffer big enough for upsampling off the edges
+ // with upsample factor of 4
+ z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3);
+ if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); }
+
+ r->hs = z->img_h_max / z->img_comp[k].h;
+ r->vs = z->img_v_max / z->img_comp[k].v;
+ r->ystep = r->vs >> 1;
+ r->w_lores = (z->s->img_x + r->hs-1) / r->hs;
+ r->ypos = 0;
+ r->line0 = r->line1 = z->img_comp[k].data;
+
+ if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1;
+ else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2;
+ else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2;
+ else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel;
+ else r->resample = stbi__resample_row_generic;
+ }
+
+ // can't error after this so, this is safe
+ output = (stbi_uc *) stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1);
+ if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); }
+
+ // now go ahead and resample
+ for (j=0; j < z->s->img_y; ++j) {
+ stbi_uc *out = output + n * z->s->img_x * j;
+ for (k=0; k < decode_n; ++k) {
+ stbi__resample *r = &res_comp[k];
+ int y_bot = r->ystep >= (r->vs >> 1);
+ coutput[k] = r->resample(z->img_comp[k].linebuf,
+ y_bot ? r->line1 : r->line0,
+ y_bot ? r->line0 : r->line1,
+ r->w_lores, r->hs);
+ if (++r->ystep >= r->vs) {
+ r->ystep = 0;
+ r->line0 = r->line1;
+ if (++r->ypos < z->img_comp[k].y)
+ r->line1 += z->img_comp[k].w2;
+ }
+ }
+ if (n >= 3) {
+ stbi_uc *y = coutput[0];
+ if (z->s->img_n == 3) {
+ if (is_rgb) {
+ for (i=0; i < z->s->img_x; ++i) {
+ out[0] = y[i];
+ out[1] = coutput[1][i];
+ out[2] = coutput[2][i];
+ out[3] = 255;
+ out += n;
+ }
+ } else {
+ z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n);
+ }
+ } else if (z->s->img_n == 4) {
+ if (z->app14_color_transform == 0) { // CMYK
+ for (i=0; i < z->s->img_x; ++i) {
+ stbi_uc m = coutput[3][i];
+ out[0] = stbi__blinn_8x8(coutput[0][i], m);
+ out[1] = stbi__blinn_8x8(coutput[1][i], m);
+ out[2] = stbi__blinn_8x8(coutput[2][i], m);
+ out[3] = 255;
+ out += n;
+ }
+ } else if (z->app14_color_transform == 2) { // YCCK
+ z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n);
+ for (i=0; i < z->s->img_x; ++i) {
+ stbi_uc m = coutput[3][i];
+ out[0] = stbi__blinn_8x8(255 - out[0], m);
+ out[1] = stbi__blinn_8x8(255 - out[1], m);
+ out[2] = stbi__blinn_8x8(255 - out[2], m);
+ out += n;
+ }
+ } else { // YCbCr + alpha? Ignore the fourth channel for now
+ z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n);
+ }
+ } else
+ for (i=0; i < z->s->img_x; ++i) {
+ out[0] = out[1] = out[2] = y[i];
+ out[3] = 255; // not used if n==3
+ out += n;
+ }
+ } else {
+ if (is_rgb) {
+ if (n == 1)
+ for (i=0; i < z->s->img_x; ++i)
+ *out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]);
+ else {
+ for (i=0; i < z->s->img_x; ++i, out += 2) {
+ out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]);
+ out[1] = 255;
+ }
+ }
+ } else if (z->s->img_n == 4 && z->app14_color_transform == 0) {
+ for (i=0; i < z->s->img_x; ++i) {
+ stbi_uc m = coutput[3][i];
+ stbi_uc r = stbi__blinn_8x8(coutput[0][i], m);
+ stbi_uc g = stbi__blinn_8x8(coutput[1][i], m);
+ stbi_uc b = stbi__blinn_8x8(coutput[2][i], m);
+ out[0] = stbi__compute_y(r, g, b);
+ out[1] = 255;
+ out += n;
+ }
+ } else if (z->s->img_n == 4 && z->app14_color_transform == 2) {
+ for (i=0; i < z->s->img_x; ++i) {
+ out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]);
+ out[1] = 255;
+ out += n;
+ }
+ } else {
+ stbi_uc *y = coutput[0];
+ if (n == 1)
+ for (i=0; i < z->s->img_x; ++i) out[i] = y[i];
+ else
+ for (i=0; i < z->s->img_x; ++i) { *out++ = y[i]; *out++ = 255; }
+ }
+ }
+ }
+ stbi__cleanup_jpeg(z);
+ *out_x = z->s->img_x;
+ *out_y = z->s->img_y;
+ if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output
+ return output;
+ }
+}
+
+static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)
+{
+ unsigned char* result;
+ stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg));
+ if (!j) return stbi__errpuc("outofmem", "Out of memory");
+ memset(j, 0, sizeof(stbi__jpeg));
+ STBI_NOTUSED(ri);
+ j->s = s;
+ stbi__setup_jpeg(j);
+ result = load_jpeg_image(j, x,y,comp,req_comp);
+ STBI_FREE(j);
+ return result;
+}
+
+static int stbi__jpeg_test(stbi__context *s)
+{
+ int r;
+ stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg));
+ if (!j) return stbi__err("outofmem", "Out of memory");
+ memset(j, 0, sizeof(stbi__jpeg));
+ j->s = s;
+ stbi__setup_jpeg(j);
+ r = stbi__decode_jpeg_header(j, STBI__SCAN_type);
+ stbi__rewind(s);
+ STBI_FREE(j);
+ return r;
+}
+
+static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp)
+{
+ if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) {
+ stbi__rewind( j->s );
+ return 0;
+ }
+ if (x) *x = j->s->img_x;
+ if (y) *y = j->s->img_y;
+ if (comp) *comp = j->s->img_n >= 3 ? 3 : 1;
+ return 1;
+}
+
+static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ int result;
+ stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg)));
+ if (!j) return stbi__err("outofmem", "Out of memory");
+ memset(j, 0, sizeof(stbi__jpeg));
+ j->s = s;
+ result = stbi__jpeg_info_raw(j, x, y, comp);
+ STBI_FREE(j);
+ return result;
+}
+#endif
+
+// public domain zlib decode v0.2 Sean Barrett 2006-11-18
+// simple implementation
+// - all input must be provided in an upfront buffer
+// - all output is written to a single output buffer (can malloc/realloc)
+// performance
+// - fast huffman
+
+#ifndef STBI_NO_ZLIB
+
+// fast-way is faster to check than jpeg huffman, but slow way is slower
+#define STBI__ZFAST_BITS 9 // accelerate all cases in default tables
+#define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1)
+#define STBI__ZNSYMS 288 // number of symbols in literal/length alphabet
+
+// zlib-style huffman encoding
+// (jpegs packs from left, zlib from right, so can't share code)
+typedef struct
+{
+ stbi__uint16 fast[1 << STBI__ZFAST_BITS];
+ stbi__uint16 firstcode[16];
+ int maxcode[17];
+ stbi__uint16 firstsymbol[16];
+ stbi_uc size[STBI__ZNSYMS];
+ stbi__uint16 value[STBI__ZNSYMS];
+} stbi__zhuffman;
+
+stbi_inline static int stbi__bitreverse16(int n)
+{
+ n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1);
+ n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2);
+ n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4);
+ n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8);
+ return n;
+}
+
+stbi_inline static int stbi__bit_reverse(int v, int bits)
+{
+ STBI_ASSERT(bits <= 16);
+ // to bit reverse n bits, reverse 16 and shift
+ // e.g. 11 bits, bit reverse and shift away 5
+ return stbi__bitreverse16(v) >> (16-bits);
+}
+
+static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int num)
+{
+ int i,k=0;
+ int code, next_code[16], sizes[17];
+
+ // DEFLATE spec for generating codes
+ memset(sizes, 0, sizeof(sizes));
+ memset(z->fast, 0, sizeof(z->fast));
+ for (i=0; i < num; ++i)
+ ++sizes[sizelist[i]];
+ sizes[0] = 0;
+ for (i=1; i < 16; ++i)
+ if (sizes[i] > (1 << i))
+ return stbi__err("bad sizes", "Corrupt PNG");
+ code = 0;
+ for (i=1; i < 16; ++i) {
+ next_code[i] = code;
+ z->firstcode[i] = (stbi__uint16) code;
+ z->firstsymbol[i] = (stbi__uint16) k;
+ code = (code + sizes[i]);
+ if (sizes[i])
+ if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt PNG");
+ z->maxcode[i] = code << (16-i); // preshift for inner loop
+ code <<= 1;
+ k += sizes[i];
+ }
+ z->maxcode[16] = 0x10000; // sentinel
+ for (i=0; i < num; ++i) {
+ int s = sizelist[i];
+ if (s) {
+ int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];
+ stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i);
+ z->size [c] = (stbi_uc ) s;
+ z->value[c] = (stbi__uint16) i;
+ if (s <= STBI__ZFAST_BITS) {
+ int j = stbi__bit_reverse(next_code[s],s);
+ while (j < (1 << STBI__ZFAST_BITS)) {
+ z->fast[j] = fastv;
+ j += (1 << s);
+ }
+ }
+ ++next_code[s];
+ }
+ }
+ return 1;
+}
+
+// zlib-from-memory implementation for PNG reading
+// because PNG allows splitting the zlib stream arbitrarily,
+// and it's annoying structurally to have PNG call ZLIB call PNG,
+// we require PNG read all the IDATs and combine them into a single
+// memory buffer
+
+typedef struct
+{
+ stbi_uc *zbuffer, *zbuffer_end;
+ int num_bits;
+ int hit_zeof_once;
+ stbi__uint32 code_buffer;
+
+ char *zout;
+ char *zout_start;
+ char *zout_end;
+ int z_expandable;
+
+ stbi__zhuffman z_length, z_distance;
+} stbi__zbuf;
+
+stbi_inline static int stbi__zeof(stbi__zbuf *z)
+{
+ return (z->zbuffer >= z->zbuffer_end);
+}
+
+stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z)
+{
+ return stbi__zeof(z) ? 0 : *z->zbuffer++;
+}
+
+static void stbi__fill_bits(stbi__zbuf *z)
+{
+ do {
+ if (z->code_buffer >= (1U << z->num_bits)) {
+ z->zbuffer = z->zbuffer_end; /* treat this as EOF so we fail. */
+ return;
+ }
+ z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits;
+ z->num_bits += 8;
+ } while (z->num_bits <= 24);
+}
+
+stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n)
+{
+ unsigned int k;
+ if (z->num_bits < n) stbi__fill_bits(z);
+ k = z->code_buffer & ((1 << n) - 1);
+ z->code_buffer >>= n;
+ z->num_bits -= n;
+ return k;
+}
+
+static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z)
+{
+ int b,s,k;
+ // not resolved by fast table, so compute it the slow way
+ // use jpeg approach, which requires MSbits at top
+ k = stbi__bit_reverse(a->code_buffer, 16);
+ for (s=STBI__ZFAST_BITS+1; ; ++s)
+ if (k < z->maxcode[s])
+ break;
+ if (s >= 16) return -1; // invalid code!
+ // code size is s, so:
+ b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];
+ if (b >= STBI__ZNSYMS) return -1; // some data was corrupt somewhere!
+ if (z->size[b] != s) return -1; // was originally an assert, but report failure instead.
+ a->code_buffer >>= s;
+ a->num_bits -= s;
+ return z->value[b];
+}
+
+stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z)
+{
+ int b,s;
+ if (a->num_bits < 16) {
+ if (stbi__zeof(a)) {
+ if (!a->hit_zeof_once) {
+ // This is the first time we hit eof, insert 16 extra padding btis
+ // to allow us to keep going; if we actually consume any of them
+ // though, that is invalid data. This is caught later.
+ a->hit_zeof_once = 1;
+ a->num_bits += 16; // add 16 implicit zero bits
+ } else {
+ // We already inserted our extra 16 padding bits and are again
+ // out, this stream is actually prematurely terminated.
+ return -1;
+ }
+ } else {
+ stbi__fill_bits(a);
+ }
+ }
+ b = z->fast[a->code_buffer & STBI__ZFAST_MASK];
+ if (b) {
+ s = b >> 9;
+ a->code_buffer >>= s;
+ a->num_bits -= s;
+ return b & 511;
+ }
+ return stbi__zhuffman_decode_slowpath(a, z);
+}
+
+static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes
+{
+ char *q;
+ unsigned int cur, limit, old_limit;
+ z->zout = zout;
+ if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG");
+ cur = (unsigned int) (z->zout - z->zout_start);
+ limit = old_limit = (unsigned) (z->zout_end - z->zout_start);
+ if (UINT_MAX - cur < (unsigned) n) return stbi__err("outofmem", "Out of memory");
+ while (cur + n > limit) {
+ if(limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory");
+ limit *= 2;
+ }
+ q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit);
+ STBI_NOTUSED(old_limit);
+ if (q == NULL) return stbi__err("outofmem", "Out of memory");
+ z->zout_start = q;
+ z->zout = q + cur;
+ z->zout_end = q + limit;
+ return 1;
+}
+
+static const int stbi__zlength_base[31] = {
+ 3,4,5,6,7,8,9,10,11,13,
+ 15,17,19,23,27,31,35,43,51,59,
+ 67,83,99,115,131,163,195,227,258,0,0 };
+
+static const int stbi__zlength_extra[31]=
+{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 };
+
+static const int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,
+257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};
+
+static const int stbi__zdist_extra[32] =
+{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
+
+static int stbi__parse_huffman_block(stbi__zbuf *a)
+{
+ char *zout = a->zout;
+ for(;;) {
+ int z = stbi__zhuffman_decode(a, &a->z_length);
+ if (z < 256) {
+ if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes
+ if (zout >= a->zout_end) {
+ if (!stbi__zexpand(a, zout, 1)) return 0;
+ zout = a->zout;
+ }
+ *zout++ = (char) z;
+ } else {
+ stbi_uc *p;
+ int len,dist;
+ if (z == 256) {
+ a->zout = zout;
+ if (a->hit_zeof_once && a->num_bits < 16) {
+ // The first time we hit zeof, we inserted 16 extra zero bits into our bit
+ // buffer so the decoder can just do its speculative decoding. But if we
+ // actually consumed any of those bits (which is the case when num_bits < 16),
+ // the stream actually read past the end so it is malformed.
+ return stbi__err("unexpected end","Corrupt PNG");
+ }
+ return 1;
+ }
+ if (z >= 286) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, length codes 286 and 287 must not appear in compressed data
+ z -= 257;
+ len = stbi__zlength_base[z];
+ if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]);
+ z = stbi__zhuffman_decode(a, &a->z_distance);
+ if (z < 0 || z >= 30) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, distance codes 30 and 31 must not appear in compressed data
+ dist = stbi__zdist_base[z];
+ if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]);
+ if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG");
+ if (len > a->zout_end - zout) {
+ if (!stbi__zexpand(a, zout, len)) return 0;
+ zout = a->zout;
+ }
+ p = (stbi_uc *) (zout - dist);
+ if (dist == 1) { // run of one byte; common in images.
+ stbi_uc v = *p;
+ if (len) { do *zout++ = v; while (--len); }
+ } else {
+ if (len) { do *zout++ = *p++; while (--len); }
+ }
+ }
+ }
+}
+
+static int stbi__compute_huffman_codes(stbi__zbuf *a)
+{
+ static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };
+ stbi__zhuffman z_codelength;
+ stbi_uc lencodes[286+32+137];//padding for maximum single op
+ stbi_uc codelength_sizes[19];
+ int i,n;
+
+ int hlit = stbi__zreceive(a,5) + 257;
+ int hdist = stbi__zreceive(a,5) + 1;
+ int hclen = stbi__zreceive(a,4) + 4;
+ int ntot = hlit + hdist;
+
+ memset(codelength_sizes, 0, sizeof(codelength_sizes));
+ for (i=0; i < hclen; ++i) {
+ int s = stbi__zreceive(a,3);
+ codelength_sizes[length_dezigzag[i]] = (stbi_uc) s;
+ }
+ if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;
+
+ n = 0;
+ while (n < ntot) {
+ int c = stbi__zhuffman_decode(a, &z_codelength);
+ if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG");
+ if (c < 16)
+ lencodes[n++] = (stbi_uc) c;
+ else {
+ stbi_uc fill = 0;
+ if (c == 16) {
+ c = stbi__zreceive(a,2)+3;
+ if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG");
+ fill = lencodes[n-1];
+ } else if (c == 17) {
+ c = stbi__zreceive(a,3)+3;
+ } else if (c == 18) {
+ c = stbi__zreceive(a,7)+11;
+ } else {
+ return stbi__err("bad codelengths", "Corrupt PNG");
+ }
+ if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG");
+ memset(lencodes+n, fill, c);
+ n += c;
+ }
+ }
+ if (n != ntot) return stbi__err("bad codelengths","Corrupt PNG");
+ if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;
+ if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0;
+ return 1;
+}
+
+static int stbi__parse_uncompressed_block(stbi__zbuf *a)
+{
+ stbi_uc header[4];
+ int len,nlen,k;
+ if (a->num_bits & 7)
+ stbi__zreceive(a, a->num_bits & 7); // discard
+ // drain the bit-packed data into header
+ k = 0;
+ while (a->num_bits > 0) {
+ header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check
+ a->code_buffer >>= 8;
+ a->num_bits -= 8;
+ }
+ if (a->num_bits < 0) return stbi__err("zlib corrupt","Corrupt PNG");
+ // now fill header the normal way
+ while (k < 4)
+ header[k++] = stbi__zget8(a);
+ len = header[1] * 256 + header[0];
+ nlen = header[3] * 256 + header[2];
+ if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG");
+ if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG");
+ if (a->zout + len > a->zout_end)
+ if (!stbi__zexpand(a, a->zout, len)) return 0;
+ memcpy(a->zout, a->zbuffer, len);
+ a->zbuffer += len;
+ a->zout += len;
+ return 1;
+}
+
+static int stbi__parse_zlib_header(stbi__zbuf *a)
+{
+ int cmf = stbi__zget8(a);
+ int cm = cmf & 15;
+ /* int cinfo = cmf >> 4; */
+ int flg = stbi__zget8(a);
+ if (stbi__zeof(a)) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec
+ if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec
+ if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png
+ if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png
+ // window = 1 << (8 + cinfo)... but who cares, we fully buffer output
+ return 1;
+}
+
+static const stbi_uc stbi__zdefault_length[STBI__ZNSYMS] =
+{
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
+ 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
+ 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
+ 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8
+};
+static const stbi_uc stbi__zdefault_distance[32] =
+{
+ 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5
+};
+/*
+Init algorithm:
+{
+ int i; // use <= to match clearly with spec
+ for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8;
+ for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9;
+ for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7;
+ for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8;
+
+ for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5;
+}
+*/
+
+static int stbi__parse_zlib(stbi__zbuf *a, int parse_header)
+{
+ int final, type;
+ if (parse_header)
+ if (!stbi__parse_zlib_header(a)) return 0;
+ a->num_bits = 0;
+ a->code_buffer = 0;
+ a->hit_zeof_once = 0;
+ do {
+ final = stbi__zreceive(a,1);
+ type = stbi__zreceive(a,2);
+ if (type == 0) {
+ if (!stbi__parse_uncompressed_block(a)) return 0;
+ } else if (type == 3) {
+ return 0;
+ } else {
+ if (type == 1) {
+ // use fixed code lengths
+ if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , STBI__ZNSYMS)) return 0;
+ if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0;
+ } else {
+ if (!stbi__compute_huffman_codes(a)) return 0;
+ }
+ if (!stbi__parse_huffman_block(a)) return 0;
+ }
+ } while (!final);
+ return 1;
+}
+
+static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header)
+{
+ a->zout_start = obuf;
+ a->zout = obuf;
+ a->zout_end = obuf + olen;
+ a->z_expandable = exp;
+
+ return stbi__parse_zlib(a, parse_header);
+}
+
+STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen)
+{
+ stbi__zbuf a;
+ char *p = (char *) stbi__malloc(initial_size);
+ if (p == NULL) return NULL;
+ a.zbuffer = (stbi_uc *) buffer;
+ a.zbuffer_end = (stbi_uc *) buffer + len;
+ if (stbi__do_zlib(&a, p, initial_size, 1, 1)) {
+ if (outlen) *outlen = (int) (a.zout - a.zout_start);
+ return a.zout_start;
+ } else {
+ STBI_FREE(a.zout_start);
+ return NULL;
+ }
+}
+
+STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen)
+{
+ return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);
+}
+
+STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header)
+{
+ stbi__zbuf a;
+ char *p = (char *) stbi__malloc(initial_size);
+ if (p == NULL) return NULL;
+ a.zbuffer = (stbi_uc *) buffer;
+ a.zbuffer_end = (stbi_uc *) buffer + len;
+ if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) {
+ if (outlen) *outlen = (int) (a.zout - a.zout_start);
+ return a.zout_start;
+ } else {
+ STBI_FREE(a.zout_start);
+ return NULL;
+ }
+}
+
+STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen)
+{
+ stbi__zbuf a;
+ a.zbuffer = (stbi_uc *) ibuffer;
+ a.zbuffer_end = (stbi_uc *) ibuffer + ilen;
+ if (stbi__do_zlib(&a, obuffer, olen, 0, 1))
+ return (int) (a.zout - a.zout_start);
+ else
+ return -1;
+}
+
+STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen)
+{
+ stbi__zbuf a;
+ char *p = (char *) stbi__malloc(16384);
+ if (p == NULL) return NULL;
+ a.zbuffer = (stbi_uc *) buffer;
+ a.zbuffer_end = (stbi_uc *) buffer+len;
+ if (stbi__do_zlib(&a, p, 16384, 1, 0)) {
+ if (outlen) *outlen = (int) (a.zout - a.zout_start);
+ return a.zout_start;
+ } else {
+ STBI_FREE(a.zout_start);
+ return NULL;
+ }
+}
+
+STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen)
+{
+ stbi__zbuf a;
+ a.zbuffer = (stbi_uc *) ibuffer;
+ a.zbuffer_end = (stbi_uc *) ibuffer + ilen;
+ if (stbi__do_zlib(&a, obuffer, olen, 0, 0))
+ return (int) (a.zout - a.zout_start);
+ else
+ return -1;
+}
+#endif
+
+// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18
+// simple implementation
+// - only 8-bit samples
+// - no CRC checking
+// - allocates lots of intermediate memory
+// - avoids problem of streaming data between subsystems
+// - avoids explicit window management
+// performance
+// - uses stb_zlib, a PD zlib implementation with fast huffman decoding
+
+#ifndef STBI_NO_PNG
+typedef struct
+{
+ stbi__uint32 length;
+ stbi__uint32 type;
+} stbi__pngchunk;
+
+static stbi__pngchunk stbi__get_chunk_header(stbi__context *s)
+{
+ stbi__pngchunk c;
+ c.length = stbi__get32be(s);
+ c.type = stbi__get32be(s);
+ return c;
+}
+
+static int stbi__check_png_header(stbi__context *s)
+{
+ static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 };
+ int i;
+ for (i=0; i < 8; ++i)
+ if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG");
+ return 1;
+}
+
+typedef struct
+{
+ stbi__context *s;
+ stbi_uc *idata, *expanded, *out;
+ int depth;
+} stbi__png;
+
+
+enum {
+ STBI__F_none=0,
+ STBI__F_sub=1,
+ STBI__F_up=2,
+ STBI__F_avg=3,
+ STBI__F_paeth=4,
+ // synthetic filter used for first scanline to avoid needing a dummy row of 0s
+ STBI__F_avg_first
+};
+
+static stbi_uc first_row_filter[5] =
+{
+ STBI__F_none,
+ STBI__F_sub,
+ STBI__F_none,
+ STBI__F_avg_first,
+ STBI__F_sub // Paeth with b=c=0 turns out to be equivalent to sub
+};
+
+static int stbi__paeth(int a, int b, int c)
+{
+ // This formulation looks very different from the reference in the PNG spec, but is
+ // actually equivalent and has favorable data dependencies and admits straightforward
+ // generation of branch-free code, which helps performance significantly.
+ int thresh = c*3 - (a + b);
+ int lo = a < b ? a : b;
+ int hi = a < b ? b : a;
+ int t0 = (hi <= thresh) ? lo : c;
+ int t1 = (thresh <= lo) ? hi : t0;
+ return t1;
+}
+
+static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 };
+
+// adds an extra all-255 alpha channel
+// dest == src is legal
+// img_n must be 1 or 3
+static void stbi__create_png_alpha_expand8(stbi_uc *dest, stbi_uc *src, stbi__uint32 x, int img_n)
+{
+ int i;
+ // must process data backwards since we allow dest==src
+ if (img_n == 1) {
+ for (i=x-1; i >= 0; --i) {
+ dest[i*2+1] = 255;
+ dest[i*2+0] = src[i];
+ }
+ } else {
+ STBI_ASSERT(img_n == 3);
+ for (i=x-1; i >= 0; --i) {
+ dest[i*4+3] = 255;
+ dest[i*4+2] = src[i*3+2];
+ dest[i*4+1] = src[i*3+1];
+ dest[i*4+0] = src[i*3+0];
+ }
+ }
+}
+
+// create the png data from post-deflated data
+static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color)
+{
+ int bytes = (depth == 16 ? 2 : 1);
+ stbi__context *s = a->s;
+ stbi__uint32 i,j,stride = x*out_n*bytes;
+ stbi__uint32 img_len, img_width_bytes;
+ stbi_uc *filter_buf;
+ int all_ok = 1;
+ int k;
+ int img_n = s->img_n; // copy it into a local for later
+
+ int output_bytes = out_n*bytes;
+ int filter_bytes = img_n*bytes;
+ int width = x;
+
+ STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1);
+ a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into
+ if (!a->out) return stbi__err("outofmem", "Out of memory");
+
+ // note: error exits here don't need to clean up a->out individually,
+ // stbi__do_png always does on error.
+ if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG");
+ img_width_bytes = (((img_n * x * depth) + 7) >> 3);
+ if (!stbi__mad2sizes_valid(img_width_bytes, y, img_width_bytes)) return stbi__err("too large", "Corrupt PNG");
+ img_len = (img_width_bytes + 1) * y;
+
+ // we used to check for exact match between raw_len and img_len on non-interlaced PNGs,
+ // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros),
+ // so just check for raw_len < img_len always.
+ if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG");
+
+ // Allocate two scan lines worth of filter workspace buffer.
+ filter_buf = (stbi_uc *) stbi__malloc_mad2(img_width_bytes, 2, 0);
+ if (!filter_buf) return stbi__err("outofmem", "Out of memory");
+
+ // Filtering for low-bit-depth images
+ if (depth < 8) {
+ filter_bytes = 1;
+ width = img_width_bytes;
+ }
+
+ for (j=0; j < y; ++j) {
+ // cur/prior filter buffers alternate
+ stbi_uc *cur = filter_buf + (j & 1)*img_width_bytes;
+ stbi_uc *prior = filter_buf + (~j & 1)*img_width_bytes;
+ stbi_uc *dest = a->out + stride*j;
+ int nk = width * filter_bytes;
+ int filter = *raw++;
+
+ // check filter type
+ if (filter > 4) {
+ all_ok = stbi__err("invalid filter","Corrupt PNG");
+ break;
+ }
+
+ // if first row, use special filter that doesn't sample previous row
+ if (j == 0) filter = first_row_filter[filter];
+
+ // perform actual filtering
+ switch (filter) {
+ case STBI__F_none:
+ memcpy(cur, raw, nk);
+ break;
+ case STBI__F_sub:
+ memcpy(cur, raw, filter_bytes);
+ for (k = filter_bytes; k < nk; ++k)
+ cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]);
+ break;
+ case STBI__F_up:
+ for (k = 0; k < nk; ++k)
+ cur[k] = STBI__BYTECAST(raw[k] + prior[k]);
+ break;
+ case STBI__F_avg:
+ for (k = 0; k < filter_bytes; ++k)
+ cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1));
+ for (k = filter_bytes; k < nk; ++k)
+ cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1));
+ break;
+ case STBI__F_paeth:
+ for (k = 0; k < filter_bytes; ++k)
+ cur[k] = STBI__BYTECAST(raw[k] + prior[k]); // prior[k] == stbi__paeth(0,prior[k],0)
+ for (k = filter_bytes; k < nk; ++k)
+ cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes], prior[k], prior[k-filter_bytes]));
+ break;
+ case STBI__F_avg_first:
+ memcpy(cur, raw, filter_bytes);
+ for (k = filter_bytes; k < nk; ++k)
+ cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1));
+ break;
+ }
+
+ raw += nk;
+
+ // expand decoded bits in cur to dest, also adding an extra alpha channel if desired
+ if (depth < 8) {
+ stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range
+ stbi_uc *in = cur;
+ stbi_uc *out = dest;
+ stbi_uc inb = 0;
+ stbi__uint32 nsmp = x*img_n;
+
+ // expand bits to bytes first
+ if (depth == 4) {
+ for (i=0; i < nsmp; ++i) {
+ if ((i & 1) == 0) inb = *in++;
+ *out++ = scale * (inb >> 4);
+ inb <<= 4;
+ }
+ } else if (depth == 2) {
+ for (i=0; i < nsmp; ++i) {
+ if ((i & 3) == 0) inb = *in++;
+ *out++ = scale * (inb >> 6);
+ inb <<= 2;
+ }
+ } else {
+ STBI_ASSERT(depth == 1);
+ for (i=0; i < nsmp; ++i) {
+ if ((i & 7) == 0) inb = *in++;
+ *out++ = scale * (inb >> 7);
+ inb <<= 1;
+ }
+ }
+
+ // insert alpha=255 values if desired
+ if (img_n != out_n)
+ stbi__create_png_alpha_expand8(dest, dest, x, img_n);
+ } else if (depth == 8) {
+ if (img_n == out_n)
+ memcpy(dest, cur, x*img_n);
+ else
+ stbi__create_png_alpha_expand8(dest, cur, x, img_n);
+ } else if (depth == 16) {
+ // convert the image data from big-endian to platform-native
+ stbi__uint16 *dest16 = (stbi__uint16*)dest;
+ stbi__uint32 nsmp = x*img_n;
+
+ if (img_n == out_n) {
+ for (i = 0; i < nsmp; ++i, ++dest16, cur += 2)
+ *dest16 = (cur[0] << 8) | cur[1];
+ } else {
+ STBI_ASSERT(img_n+1 == out_n);
+ if (img_n == 1) {
+ for (i = 0; i < x; ++i, dest16 += 2, cur += 2) {
+ dest16[0] = (cur[0] << 8) | cur[1];
+ dest16[1] = 0xffff;
+ }
+ } else {
+ STBI_ASSERT(img_n == 3);
+ for (i = 0; i < x; ++i, dest16 += 4, cur += 6) {
+ dest16[0] = (cur[0] << 8) | cur[1];
+ dest16[1] = (cur[2] << 8) | cur[3];
+ dest16[2] = (cur[4] << 8) | cur[5];
+ dest16[3] = 0xffff;
+ }
+ }
+ }
+ }
+ }
+
+ STBI_FREE(filter_buf);
+ if (!all_ok) return 0;
+
+ return 1;
+}
+
+static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced)
+{
+ int bytes = (depth == 16 ? 2 : 1);
+ int out_bytes = out_n * bytes;
+ stbi_uc *final;
+ int p;
+ if (!interlaced)
+ return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color);
+
+ // de-interlacing
+ final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0);
+ if (!final) return stbi__err("outofmem", "Out of memory");
+ for (p=0; p < 7; ++p) {
+ int xorig[] = { 0,4,0,2,0,1,0 };
+ int yorig[] = { 0,0,4,0,2,0,1 };
+ int xspc[] = { 8,8,4,4,2,2,1 };
+ int yspc[] = { 8,8,8,4,4,2,2 };
+ int i,j,x,y;
+ // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1
+ x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p];
+ y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p];
+ if (x && y) {
+ stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y;
+ if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) {
+ STBI_FREE(final);
+ return 0;
+ }
+ for (j=0; j < y; ++j) {
+ for (i=0; i < x; ++i) {
+ int out_y = j*yspc[p]+yorig[p];
+ int out_x = i*xspc[p]+xorig[p];
+ memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes,
+ a->out + (j*x+i)*out_bytes, out_bytes);
+ }
+ }
+ STBI_FREE(a->out);
+ image_data += img_len;
+ image_data_len -= img_len;
+ }
+ }
+ a->out = final;
+
+ return 1;
+}
+
+static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n)
+{
+ stbi__context *s = z->s;
+ stbi__uint32 i, pixel_count = s->img_x * s->img_y;
+ stbi_uc *p = z->out;
+
+ // compute color-based transparency, assuming we've
+ // already got 255 as the alpha value in the output
+ STBI_ASSERT(out_n == 2 || out_n == 4);
+
+ if (out_n == 2) {
+ for (i=0; i < pixel_count; ++i) {
+ p[1] = (p[0] == tc[0] ? 0 : 255);
+ p += 2;
+ }
+ } else {
+ for (i=0; i < pixel_count; ++i) {
+ if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])
+ p[3] = 0;
+ p += 4;
+ }
+ }
+ return 1;
+}
+
+static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n)
+{
+ stbi__context *s = z->s;
+ stbi__uint32 i, pixel_count = s->img_x * s->img_y;
+ stbi__uint16 *p = (stbi__uint16*) z->out;
+
+ // compute color-based transparency, assuming we've
+ // already got 65535 as the alpha value in the output
+ STBI_ASSERT(out_n == 2 || out_n == 4);
+
+ if (out_n == 2) {
+ for (i = 0; i < pixel_count; ++i) {
+ p[1] = (p[0] == tc[0] ? 0 : 65535);
+ p += 2;
+ }
+ } else {
+ for (i = 0; i < pixel_count; ++i) {
+ if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])
+ p[3] = 0;
+ p += 4;
+ }
+ }
+ return 1;
+}
+
+static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n)
+{
+ stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y;
+ stbi_uc *p, *temp_out, *orig = a->out;
+
+ p = (stbi_uc *) stbi__malloc_mad2(pixel_count, pal_img_n, 0);
+ if (p == NULL) return stbi__err("outofmem", "Out of memory");
+
+ // between here and free(out) below, exitting would leak
+ temp_out = p;
+
+ if (pal_img_n == 3) {
+ for (i=0; i < pixel_count; ++i) {
+ int n = orig[i]*4;
+ p[0] = palette[n ];
+ p[1] = palette[n+1];
+ p[2] = palette[n+2];
+ p += 3;
+ }
+ } else {
+ for (i=0; i < pixel_count; ++i) {
+ int n = orig[i]*4;
+ p[0] = palette[n ];
+ p[1] = palette[n+1];
+ p[2] = palette[n+2];
+ p[3] = palette[n+3];
+ p += 4;
+ }
+ }
+ STBI_FREE(a->out);
+ a->out = temp_out;
+
+ STBI_NOTUSED(len);
+
+ return 1;
+}
+
+static int stbi__unpremultiply_on_load_global = 0;
+static int stbi__de_iphone_flag_global = 0;
+
+STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)
+{
+ stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply;
+}
+
+STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert)
+{
+ stbi__de_iphone_flag_global = flag_true_if_should_convert;
+}
+
+#ifndef STBI_THREAD_LOCAL
+#define stbi__unpremultiply_on_load stbi__unpremultiply_on_load_global
+#define stbi__de_iphone_flag stbi__de_iphone_flag_global
+#else
+static STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local, stbi__unpremultiply_on_load_set;
+static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, stbi__de_iphone_flag_set;
+
+STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply)
+{
+ stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply;
+ stbi__unpremultiply_on_load_set = 1;
+}
+
+STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert)
+{
+ stbi__de_iphone_flag_local = flag_true_if_should_convert;
+ stbi__de_iphone_flag_set = 1;
+}
+
+#define stbi__unpremultiply_on_load (stbi__unpremultiply_on_load_set \
+ ? stbi__unpremultiply_on_load_local \
+ : stbi__unpremultiply_on_load_global)
+#define stbi__de_iphone_flag (stbi__de_iphone_flag_set \
+ ? stbi__de_iphone_flag_local \
+ : stbi__de_iphone_flag_global)
+#endif // STBI_THREAD_LOCAL
+
+static void stbi__de_iphone(stbi__png *z)
+{
+ stbi__context *s = z->s;
+ stbi__uint32 i, pixel_count = s->img_x * s->img_y;
+ stbi_uc *p = z->out;
+
+ if (s->img_out_n == 3) { // convert bgr to rgb
+ for (i=0; i < pixel_count; ++i) {
+ stbi_uc t = p[0];
+ p[0] = p[2];
+ p[2] = t;
+ p += 3;
+ }
+ } else {
+ STBI_ASSERT(s->img_out_n == 4);
+ if (stbi__unpremultiply_on_load) {
+ // convert bgr to rgb and unpremultiply
+ for (i=0; i < pixel_count; ++i) {
+ stbi_uc a = p[3];
+ stbi_uc t = p[0];
+ if (a) {
+ stbi_uc half = a / 2;
+ p[0] = (p[2] * 255 + half) / a;
+ p[1] = (p[1] * 255 + half) / a;
+ p[2] = ( t * 255 + half) / a;
+ } else {
+ p[0] = p[2];
+ p[2] = t;
+ }
+ p += 4;
+ }
+ } else {
+ // convert bgr to rgb
+ for (i=0; i < pixel_count; ++i) {
+ stbi_uc t = p[0];
+ p[0] = p[2];
+ p[2] = t;
+ p += 4;
+ }
+ }
+ }
+}
+
+#define STBI__PNG_TYPE(a,b,c,d) (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d))
+
+static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp)
+{
+ stbi_uc palette[1024], pal_img_n=0;
+ stbi_uc has_trans=0, tc[3]={0};
+ stbi__uint16 tc16[3];
+ stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0;
+ int first=1,k,interlace=0, color=0, is_iphone=0;
+ stbi__context *s = z->s;
+
+ z->expanded = NULL;
+ z->idata = NULL;
+ z->out = NULL;
+
+ if (!stbi__check_png_header(s)) return 0;
+
+ if (scan == STBI__SCAN_type) return 1;
+
+ for (;;) {
+ stbi__pngchunk c = stbi__get_chunk_header(s);
+ switch (c.type) {
+ case STBI__PNG_TYPE('C','g','B','I'):
+ is_iphone = 1;
+ stbi__skip(s, c.length);
+ break;
+ case STBI__PNG_TYPE('I','H','D','R'): {
+ int comp,filter;
+ if (!first) return stbi__err("multiple IHDR","Corrupt PNG");
+ first = 0;
+ if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG");
+ s->img_x = stbi__get32be(s);
+ s->img_y = stbi__get32be(s);
+ if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
+ if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
+ z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only","PNG not supported: 1/2/4/8/16-bit only");
+ color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG");
+ if (color == 3 && z->depth == 16) return stbi__err("bad ctype","Corrupt PNG");
+ if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG");
+ comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG");
+ filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG");
+ interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG");
+ if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG");
+ if (!pal_img_n) {
+ s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);
+ if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode");
+ } else {
+ // if paletted, then pal_n is our final components, and
+ // img_n is # components to decompress/filter.
+ s->img_n = 1;
+ if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG");
+ }
+ // even with SCAN_header, have to scan to see if we have a tRNS
+ break;
+ }
+
+ case STBI__PNG_TYPE('P','L','T','E'): {
+ if (first) return stbi__err("first not IHDR", "Corrupt PNG");
+ if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG");
+ pal_len = c.length / 3;
+ if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG");
+ for (i=0; i < pal_len; ++i) {
+ palette[i*4+0] = stbi__get8(s);
+ palette[i*4+1] = stbi__get8(s);
+ palette[i*4+2] = stbi__get8(s);
+ palette[i*4+3] = 255;
+ }
+ break;
+ }
+
+ case STBI__PNG_TYPE('t','R','N','S'): {
+ if (first) return stbi__err("first not IHDR", "Corrupt PNG");
+ if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG");
+ if (pal_img_n) {
+ if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; }
+ if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG");
+ if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG");
+ pal_img_n = 4;
+ for (i=0; i < c.length; ++i)
+ palette[i*4+3] = stbi__get8(s);
+ } else {
+ if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG");
+ if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG");
+ has_trans = 1;
+ // non-paletted with tRNS = constant alpha. if header-scanning, we can stop now.
+ if (scan == STBI__SCAN_header) { ++s->img_n; return 1; }
+ if (z->depth == 16) {
+ for (k = 0; k < s->img_n && k < 3; ++k) // extra loop test to suppress false GCC warning
+ tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is
+ } else {
+ for (k = 0; k < s->img_n && k < 3; ++k)
+ tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger
+ }
+ }
+ break;
+ }
+
+ case STBI__PNG_TYPE('I','D','A','T'): {
+ if (first) return stbi__err("first not IHDR", "Corrupt PNG");
+ if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG");
+ if (scan == STBI__SCAN_header) {
+ // header scan definitely stops at first IDAT
+ if (pal_img_n)
+ s->img_n = pal_img_n;
+ return 1;
+ }
+ if (c.length > (1u << 30)) return stbi__err("IDAT size limit", "IDAT section larger than 2^30 bytes");
+ if ((int)(ioff + c.length) < (int)ioff) return 0;
+ if (ioff + c.length > idata_limit) {
+ stbi__uint32 idata_limit_old = idata_limit;
+ stbi_uc *p;
+ if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;
+ while (ioff + c.length > idata_limit)
+ idata_limit *= 2;
+ STBI_NOTUSED(idata_limit_old);
+ p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory");
+ z->idata = p;
+ }
+ if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG");
+ ioff += c.length;
+ break;
+ }
+
+ case STBI__PNG_TYPE('I','E','N','D'): {
+ stbi__uint32 raw_len, bpl;
+ if (first) return stbi__err("first not IHDR", "Corrupt PNG");
+ if (scan != STBI__SCAN_load) return 1;
+ if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG");
+ // initial guess for decoded data size to avoid unnecessary reallocs
+ bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component
+ raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */;
+ z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone);
+ if (z->expanded == NULL) return 0; // zlib should set error
+ STBI_FREE(z->idata); z->idata = NULL;
+ if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans)
+ s->img_out_n = s->img_n+1;
+ else
+ s->img_out_n = s->img_n;
+ if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0;
+ if (has_trans) {
+ if (z->depth == 16) {
+ if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0;
+ } else {
+ if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0;
+ }
+ }
+ if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2)
+ stbi__de_iphone(z);
+ if (pal_img_n) {
+ // pal_img_n == 3 or 4
+ s->img_n = pal_img_n; // record the actual colors we had
+ s->img_out_n = pal_img_n;
+ if (req_comp >= 3) s->img_out_n = req_comp;
+ if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n))
+ return 0;
+ } else if (has_trans) {
+ // non-paletted image with tRNS -> source image has (constant) alpha
+ ++s->img_n;
+ }
+ STBI_FREE(z->expanded); z->expanded = NULL;
+ // end of PNG chunk, read and skip CRC
+ stbi__get32be(s);
+ return 1;
+ }
+
+ default:
+ // if critical, fail
+ if (first) return stbi__err("first not IHDR", "Corrupt PNG");
+ if ((c.type & (1 << 29)) == 0) {
+ #ifndef STBI_NO_FAILURE_STRINGS
+ // not threadsafe
+ static char invalid_chunk[] = "XXXX PNG chunk not known";
+ invalid_chunk[0] = STBI__BYTECAST(c.type >> 24);
+ invalid_chunk[1] = STBI__BYTECAST(c.type >> 16);
+ invalid_chunk[2] = STBI__BYTECAST(c.type >> 8);
+ invalid_chunk[3] = STBI__BYTECAST(c.type >> 0);
+ #endif
+ return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type");
+ }
+ stbi__skip(s, c.length);
+ break;
+ }
+ // end of PNG chunk, read and skip CRC
+ stbi__get32be(s);
+ }
+}
+
+static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri)
+{
+ void *result=NULL;
+ if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error");
+ if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) {
+ if (p->depth <= 8)
+ ri->bits_per_channel = 8;
+ else if (p->depth == 16)
+ ri->bits_per_channel = 16;
+ else
+ return stbi__errpuc("bad bits_per_channel", "PNG not supported: unsupported color depth");
+ result = p->out;
+ p->out = NULL;
+ if (req_comp && req_comp != p->s->img_out_n) {
+ if (ri->bits_per_channel == 8)
+ result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);
+ else
+ result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);
+ p->s->img_out_n = req_comp;
+ if (result == NULL) return result;
+ }
+ *x = p->s->img_x;
+ *y = p->s->img_y;
+ if (n) *n = p->s->img_n;
+ }
+ STBI_FREE(p->out); p->out = NULL;
+ STBI_FREE(p->expanded); p->expanded = NULL;
+ STBI_FREE(p->idata); p->idata = NULL;
+
+ return result;
+}
+
+static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)
+{
+ stbi__png p;
+ p.s = s;
+ return stbi__do_png(&p, x,y,comp,req_comp, ri);
+}
+
+static int stbi__png_test(stbi__context *s)
+{
+ int r;
+ r = stbi__check_png_header(s);
+ stbi__rewind(s);
+ return r;
+}
+
+static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp)
+{
+ if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) {
+ stbi__rewind( p->s );
+ return 0;
+ }
+ if (x) *x = p->s->img_x;
+ if (y) *y = p->s->img_y;
+ if (comp) *comp = p->s->img_n;
+ return 1;
+}
+
+static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ stbi__png p;
+ p.s = s;
+ return stbi__png_info_raw(&p, x, y, comp);
+}
+
+static int stbi__png_is16(stbi__context *s)
+{
+ stbi__png p;
+ p.s = s;
+ if (!stbi__png_info_raw(&p, NULL, NULL, NULL))
+ return 0;
+ if (p.depth != 16) {
+ stbi__rewind(p.s);
+ return 0;
+ }
+ return 1;
+}
+#endif
+
+// Microsoft/Windows BMP image
+
+#ifndef STBI_NO_BMP
+static int stbi__bmp_test_raw(stbi__context *s)
+{
+ int r;
+ int sz;
+ if (stbi__get8(s) != 'B') return 0;
+ if (stbi__get8(s) != 'M') return 0;
+ stbi__get32le(s); // discard filesize
+ stbi__get16le(s); // discard reserved
+ stbi__get16le(s); // discard reserved
+ stbi__get32le(s); // discard data offset
+ sz = stbi__get32le(s);
+ r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124);
+ return r;
+}
+
+static int stbi__bmp_test(stbi__context *s)
+{
+ int r = stbi__bmp_test_raw(s);
+ stbi__rewind(s);
+ return r;
+}
+
+
+// returns 0..31 for the highest set bit
+static int stbi__high_bit(unsigned int z)
+{
+ int n=0;
+ if (z == 0) return -1;
+ if (z >= 0x10000) { n += 16; z >>= 16; }
+ if (z >= 0x00100) { n += 8; z >>= 8; }
+ if (z >= 0x00010) { n += 4; z >>= 4; }
+ if (z >= 0x00004) { n += 2; z >>= 2; }
+ if (z >= 0x00002) { n += 1;/* >>= 1;*/ }
+ return n;
+}
+
+static int stbi__bitcount(unsigned int a)
+{
+ a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2
+ a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4
+ a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits
+ a = (a + (a >> 8)); // max 16 per 8 bits
+ a = (a + (a >> 16)); // max 32 per 8 bits
+ return a & 0xff;
+}
+
+// extract an arbitrarily-aligned N-bit value (N=bits)
+// from v, and then make it 8-bits long and fractionally
+// extend it to full full range.
+static int stbi__shiftsigned(unsigned int v, int shift, int bits)
+{
+ static unsigned int mul_table[9] = {
+ 0,
+ 0xff/*0b11111111*/, 0x55/*0b01010101*/, 0x49/*0b01001001*/, 0x11/*0b00010001*/,
+ 0x21/*0b00100001*/, 0x41/*0b01000001*/, 0x81/*0b10000001*/, 0x01/*0b00000001*/,
+ };
+ static unsigned int shift_table[9] = {
+ 0, 0,0,1,0,2,4,6,0,
+ };
+ if (shift < 0)
+ v <<= -shift;
+ else
+ v >>= shift;
+ STBI_ASSERT(v < 256);
+ v >>= (8-bits);
+ STBI_ASSERT(bits >= 0 && bits <= 8);
+ return (int) ((unsigned) v * mul_table[bits]) >> shift_table[bits];
+}
+
+typedef struct
+{
+ int bpp, offset, hsz;
+ unsigned int mr,mg,mb,ma, all_a;
+ int extra_read;
+} stbi__bmp_data;
+
+static int stbi__bmp_set_mask_defaults(stbi__bmp_data *info, int compress)
+{
+ // BI_BITFIELDS specifies masks explicitly, don't override
+ if (compress == 3)
+ return 1;
+
+ if (compress == 0) {
+ if (info->bpp == 16) {
+ info->mr = 31u << 10;
+ info->mg = 31u << 5;
+ info->mb = 31u << 0;
+ } else if (info->bpp == 32) {
+ info->mr = 0xffu << 16;
+ info->mg = 0xffu << 8;
+ info->mb = 0xffu << 0;
+ info->ma = 0xffu << 24;
+ info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0
+ } else {
+ // otherwise, use defaults, which is all-0
+ info->mr = info->mg = info->mb = info->ma = 0;
+ }
+ return 1;
+ }
+ return 0; // error
+}
+
+static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info)
+{
+ int hsz;
+ if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP");
+ stbi__get32le(s); // discard filesize
+ stbi__get16le(s); // discard reserved
+ stbi__get16le(s); // discard reserved
+ info->offset = stbi__get32le(s);
+ info->hsz = hsz = stbi__get32le(s);
+ info->mr = info->mg = info->mb = info->ma = 0;
+ info->extra_read = 14;
+
+ if (info->offset < 0) return stbi__errpuc("bad BMP", "bad BMP");
+
+ if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown");
+ if (hsz == 12) {
+ s->img_x = stbi__get16le(s);
+ s->img_y = stbi__get16le(s);
+ } else {
+ s->img_x = stbi__get32le(s);
+ s->img_y = stbi__get32le(s);
+ }
+ if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP");
+ info->bpp = stbi__get16le(s);
+ if (hsz != 12) {
+ int compress = stbi__get32le(s);
+ if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE");
+ if (compress >= 4) return stbi__errpuc("BMP JPEG/PNG", "BMP type not supported: unsupported compression"); // this includes PNG/JPEG modes
+ if (compress == 3 && info->bpp != 16 && info->bpp != 32) return stbi__errpuc("bad BMP", "bad BMP"); // bitfields requires 16 or 32 bits/pixel
+ stbi__get32le(s); // discard sizeof
+ stbi__get32le(s); // discard hres
+ stbi__get32le(s); // discard vres
+ stbi__get32le(s); // discard colorsused
+ stbi__get32le(s); // discard max important
+ if (hsz == 40 || hsz == 56) {
+ if (hsz == 56) {
+ stbi__get32le(s);
+ stbi__get32le(s);
+ stbi__get32le(s);
+ stbi__get32le(s);
+ }
+ if (info->bpp == 16 || info->bpp == 32) {
+ if (compress == 0) {
+ stbi__bmp_set_mask_defaults(info, compress);
+ } else if (compress == 3) {
+ info->mr = stbi__get32le(s);
+ info->mg = stbi__get32le(s);
+ info->mb = stbi__get32le(s);
+ info->extra_read += 12;
+ // not documented, but generated by photoshop and handled by mspaint
+ if (info->mr == info->mg && info->mg == info->mb) {
+ // ?!?!?
+ return stbi__errpuc("bad BMP", "bad BMP");
+ }
+ } else
+ return stbi__errpuc("bad BMP", "bad BMP");
+ }
+ } else {
+ // V4/V5 header
+ int i;
+ if (hsz != 108 && hsz != 124)
+ return stbi__errpuc("bad BMP", "bad BMP");
+ info->mr = stbi__get32le(s);
+ info->mg = stbi__get32le(s);
+ info->mb = stbi__get32le(s);
+ info->ma = stbi__get32le(s);
+ if (compress != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs
+ stbi__bmp_set_mask_defaults(info, compress);
+ stbi__get32le(s); // discard color space
+ for (i=0; i < 12; ++i)
+ stbi__get32le(s); // discard color space parameters
+ if (hsz == 124) {
+ stbi__get32le(s); // discard rendering intent
+ stbi__get32le(s); // discard offset of profile data
+ stbi__get32le(s); // discard size of profile data
+ stbi__get32le(s); // discard reserved
+ }
+ }
+ }
+ return (void *) 1;
+}
+
+
+static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)
+{
+ stbi_uc *out;
+ unsigned int mr=0,mg=0,mb=0,ma=0, all_a;
+ stbi_uc pal[256][4];
+ int psize=0,i,j,width;
+ int flip_vertically, pad, target;
+ stbi__bmp_data info;
+ STBI_NOTUSED(ri);
+
+ info.all_a = 255;
+ if (stbi__bmp_parse_header(s, &info) == NULL)
+ return NULL; // error code already set
+
+ flip_vertically = ((int) s->img_y) > 0;
+ s->img_y = abs((int) s->img_y);
+
+ if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+ if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+
+ mr = info.mr;
+ mg = info.mg;
+ mb = info.mb;
+ ma = info.ma;
+ all_a = info.all_a;
+
+ if (info.hsz == 12) {
+ if (info.bpp < 24)
+ psize = (info.offset - info.extra_read - 24) / 3;
+ } else {
+ if (info.bpp < 16)
+ psize = (info.offset - info.extra_read - info.hsz) >> 2;
+ }
+ if (psize == 0) {
+ // accept some number of extra bytes after the header, but if the offset points either to before
+ // the header ends or implies a large amount of extra data, reject the file as malformed
+ int bytes_read_so_far = s->callback_already_read + (int)(s->img_buffer - s->img_buffer_original);
+ int header_limit = 1024; // max we actually read is below 256 bytes currently.
+ int extra_data_limit = 256*4; // what ordinarily goes here is a palette; 256 entries*4 bytes is its max size.
+ if (bytes_read_so_far <= 0 || bytes_read_so_far > header_limit) {
+ return stbi__errpuc("bad header", "Corrupt BMP");
+ }
+ // we established that bytes_read_so_far is positive and sensible.
+ // the first half of this test rejects offsets that are either too small positives, or
+ // negative, and guarantees that info.offset >= bytes_read_so_far > 0. this in turn
+ // ensures the number computed in the second half of the test can't overflow.
+ if (info.offset < bytes_read_so_far || info.offset - bytes_read_so_far > extra_data_limit) {
+ return stbi__errpuc("bad offset", "Corrupt BMP");
+ } else {
+ stbi__skip(s, info.offset - bytes_read_so_far);
+ }
+ }
+
+ if (info.bpp == 24 && ma == 0xff000000)
+ s->img_n = 3;
+ else
+ s->img_n = ma ? 4 : 3;
+ if (req_comp && req_comp >= 3) // we can directly decode 3 or 4
+ target = req_comp;
+ else
+ target = s->img_n; // if they want monochrome, we'll post-convert
+
+ // sanity-check size
+ if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0))
+ return stbi__errpuc("too large", "Corrupt BMP");
+
+ out = (stbi_uc *) stbi__malloc_mad3(target, s->img_x, s->img_y, 0);
+ if (!out) return stbi__errpuc("outofmem", "Out of memory");
+ if (info.bpp < 16) {
+ int z=0;
+ if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); }
+ for (i=0; i < psize; ++i) {
+ pal[i][2] = stbi__get8(s);
+ pal[i][1] = stbi__get8(s);
+ pal[i][0] = stbi__get8(s);
+ if (info.hsz != 12) stbi__get8(s);
+ pal[i][3] = 255;
+ }
+ stbi__skip(s, info.offset - info.extra_read - info.hsz - psize * (info.hsz == 12 ? 3 : 4));
+ if (info.bpp == 1) width = (s->img_x + 7) >> 3;
+ else if (info.bpp == 4) width = (s->img_x + 1) >> 1;
+ else if (info.bpp == 8) width = s->img_x;
+ else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); }
+ pad = (-width)&3;
+ if (info.bpp == 1) {
+ for (j=0; j < (int) s->img_y; ++j) {
+ int bit_offset = 7, v = stbi__get8(s);
+ for (i=0; i < (int) s->img_x; ++i) {
+ int color = (v>>bit_offset)&0x1;
+ out[z++] = pal[color][0];
+ out[z++] = pal[color][1];
+ out[z++] = pal[color][2];
+ if (target == 4) out[z++] = 255;
+ if (i+1 == (int) s->img_x) break;
+ if((--bit_offset) < 0) {
+ bit_offset = 7;
+ v = stbi__get8(s);
+ }
+ }
+ stbi__skip(s, pad);
+ }
+ } else {
+ for (j=0; j < (int) s->img_y; ++j) {
+ for (i=0; i < (int) s->img_x; i += 2) {
+ int v=stbi__get8(s),v2=0;
+ if (info.bpp == 4) {
+ v2 = v & 15;
+ v >>= 4;
+ }
+ out[z++] = pal[v][0];
+ out[z++] = pal[v][1];
+ out[z++] = pal[v][2];
+ if (target == 4) out[z++] = 255;
+ if (i+1 == (int) s->img_x) break;
+ v = (info.bpp == 8) ? stbi__get8(s) : v2;
+ out[z++] = pal[v][0];
+ out[z++] = pal[v][1];
+ out[z++] = pal[v][2];
+ if (target == 4) out[z++] = 255;
+ }
+ stbi__skip(s, pad);
+ }
+ }
+ } else {
+ int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0;
+ int z = 0;
+ int easy=0;
+ stbi__skip(s, info.offset - info.extra_read - info.hsz);
+ if (info.bpp == 24) width = 3 * s->img_x;
+ else if (info.bpp == 16) width = 2*s->img_x;
+ else /* bpp = 32 and pad = 0 */ width=0;
+ pad = (-width) & 3;
+ if (info.bpp == 24) {
+ easy = 1;
+ } else if (info.bpp == 32) {
+ if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000)
+ easy = 2;
+ }
+ if (!easy) {
+ if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); }
+ // right shift amt to put high bit in position #7
+ rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr);
+ gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg);
+ bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb);
+ ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma);
+ if (rcount > 8 || gcount > 8 || bcount > 8 || acount > 8) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); }
+ }
+ for (j=0; j < (int) s->img_y; ++j) {
+ if (easy) {
+ for (i=0; i < (int) s->img_x; ++i) {
+ unsigned char a;
+ out[z+2] = stbi__get8(s);
+ out[z+1] = stbi__get8(s);
+ out[z+0] = stbi__get8(s);
+ z += 3;
+ a = (easy == 2 ? stbi__get8(s) : 255);
+ all_a |= a;
+ if (target == 4) out[z++] = a;
+ }
+ } else {
+ int bpp = info.bpp;
+ for (i=0; i < (int) s->img_x; ++i) {
+ stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s));
+ unsigned int a;
+ out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount));
+ out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount));
+ out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount));
+ a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255);
+ all_a |= a;
+ if (target == 4) out[z++] = STBI__BYTECAST(a);
+ }
+ }
+ stbi__skip(s, pad);
+ }
+ }
+
+ // if alpha channel is all 0s, replace with all 255s
+ if (target == 4 && all_a == 0)
+ for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4)
+ out[i] = 255;
+
+ if (flip_vertically) {
+ stbi_uc t;
+ for (j=0; j < (int) s->img_y>>1; ++j) {
+ stbi_uc *p1 = out + j *s->img_x*target;
+ stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target;
+ for (i=0; i < (int) s->img_x*target; ++i) {
+ t = p1[i]; p1[i] = p2[i]; p2[i] = t;
+ }
+ }
+ }
+
+ if (req_comp && req_comp != target) {
+ out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y);
+ if (out == NULL) return out; // stbi__convert_format frees input on failure
+ }
+
+ *x = s->img_x;
+ *y = s->img_y;
+ if (comp) *comp = s->img_n;
+ return out;
+}
+#endif
+
+// Targa Truevision - TGA
+// by Jonathan Dummer
+#ifndef STBI_NO_TGA
+// returns STBI_rgb or whatever, 0 on error
+static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16)
+{
+ // only RGB or RGBA (incl. 16bit) or grey allowed
+ if (is_rgb16) *is_rgb16 = 0;
+ switch(bits_per_pixel) {
+ case 8: return STBI_grey;
+ case 16: if(is_grey) return STBI_grey_alpha;
+ // fallthrough
+ case 15: if(is_rgb16) *is_rgb16 = 1;
+ return STBI_rgb;
+ case 24: // fallthrough
+ case 32: return bits_per_pixel/8;
+ default: return 0;
+ }
+}
+
+static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp;
+ int sz, tga_colormap_type;
+ stbi__get8(s); // discard Offset
+ tga_colormap_type = stbi__get8(s); // colormap type
+ if( tga_colormap_type > 1 ) {
+ stbi__rewind(s);
+ return 0; // only RGB or indexed allowed
+ }
+ tga_image_type = stbi__get8(s); // image type
+ if ( tga_colormap_type == 1 ) { // colormapped (paletted) image
+ if (tga_image_type != 1 && tga_image_type != 9) {
+ stbi__rewind(s);
+ return 0;
+ }
+ stbi__skip(s,4); // skip index of first colormap entry and number of entries
+ sz = stbi__get8(s); // check bits per palette color entry
+ if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) {
+ stbi__rewind(s);
+ return 0;
+ }
+ stbi__skip(s,4); // skip image x and y origin
+ tga_colormap_bpp = sz;
+ } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE
+ if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) {
+ stbi__rewind(s);
+ return 0; // only RGB or grey allowed, +/- RLE
+ }
+ stbi__skip(s,9); // skip colormap specification and image x/y origin
+ tga_colormap_bpp = 0;
+ }
+ tga_w = stbi__get16le(s);
+ if( tga_w < 1 ) {
+ stbi__rewind(s);
+ return 0; // test width
+ }
+ tga_h = stbi__get16le(s);
+ if( tga_h < 1 ) {
+ stbi__rewind(s);
+ return 0; // test height
+ }
+ tga_bits_per_pixel = stbi__get8(s); // bits per pixel
+ stbi__get8(s); // ignore alpha bits
+ if (tga_colormap_bpp != 0) {
+ if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) {
+ // when using a colormap, tga_bits_per_pixel is the size of the indexes
+ // I don't think anything but 8 or 16bit indexes makes sense
+ stbi__rewind(s);
+ return 0;
+ }
+ tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL);
+ } else {
+ tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL);
+ }
+ if(!tga_comp) {
+ stbi__rewind(s);
+ return 0;
+ }
+ if (x) *x = tga_w;
+ if (y) *y = tga_h;
+ if (comp) *comp = tga_comp;
+ return 1; // seems to have passed everything
+}
+
+static int stbi__tga_test(stbi__context *s)
+{
+ int res = 0;
+ int sz, tga_color_type;
+ stbi__get8(s); // discard Offset
+ tga_color_type = stbi__get8(s); // color type
+ if ( tga_color_type > 1 ) goto errorEnd; // only RGB or indexed allowed
+ sz = stbi__get8(s); // image type
+ if ( tga_color_type == 1 ) { // colormapped (paletted) image
+ if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9
+ stbi__skip(s,4); // skip index of first colormap entry and number of entries
+ sz = stbi__get8(s); // check bits per palette color entry
+ if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd;
+ stbi__skip(s,4); // skip image x and y origin
+ } else { // "normal" image w/o colormap
+ if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE
+ stbi__skip(s,9); // skip colormap specification and image x/y origin
+ }
+ if ( stbi__get16le(s) < 1 ) goto errorEnd; // test width
+ if ( stbi__get16le(s) < 1 ) goto errorEnd; // test height
+ sz = stbi__get8(s); // bits per pixel
+ if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index
+ if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd;
+
+ res = 1; // if we got this far, everything's good and we can return 1 instead of 0
+
+errorEnd:
+ stbi__rewind(s);
+ return res;
+}
+
+// read 16bit value and convert to 24bit RGB
+static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out)
+{
+ stbi__uint16 px = (stbi__uint16)stbi__get16le(s);
+ stbi__uint16 fiveBitMask = 31;
+ // we have 3 channels with 5bits each
+ int r = (px >> 10) & fiveBitMask;
+ int g = (px >> 5) & fiveBitMask;
+ int b = px & fiveBitMask;
+ // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later
+ out[0] = (stbi_uc)((r * 255)/31);
+ out[1] = (stbi_uc)((g * 255)/31);
+ out[2] = (stbi_uc)((b * 255)/31);
+
+ // some people claim that the most significant bit might be used for alpha
+ // (possibly if an alpha-bit is set in the "image descriptor byte")
+ // but that only made 16bit test images completely translucent..
+ // so let's treat all 15 and 16bit TGAs as RGB with no alpha.
+}
+
+static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)
+{
+ // read in the TGA header stuff
+ int tga_offset = stbi__get8(s);
+ int tga_indexed = stbi__get8(s);
+ int tga_image_type = stbi__get8(s);
+ int tga_is_RLE = 0;
+ int tga_palette_start = stbi__get16le(s);
+ int tga_palette_len = stbi__get16le(s);
+ int tga_palette_bits = stbi__get8(s);
+ int tga_x_origin = stbi__get16le(s);
+ int tga_y_origin = stbi__get16le(s);
+ int tga_width = stbi__get16le(s);
+ int tga_height = stbi__get16le(s);
+ int tga_bits_per_pixel = stbi__get8(s);
+ int tga_comp, tga_rgb16=0;
+ int tga_inverted = stbi__get8(s);
+ // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?)
+ // image data
+ unsigned char *tga_data;
+ unsigned char *tga_palette = NULL;
+ int i, j;
+ unsigned char raw_data[4] = {0};
+ int RLE_count = 0;
+ int RLE_repeating = 0;
+ int read_next_pixel = 1;
+ STBI_NOTUSED(ri);
+ STBI_NOTUSED(tga_x_origin); // @TODO
+ STBI_NOTUSED(tga_y_origin); // @TODO
+
+ if (tga_height > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+ if (tga_width > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+
+ // do a tiny bit of precessing
+ if ( tga_image_type >= 8 )
+ {
+ tga_image_type -= 8;
+ tga_is_RLE = 1;
+ }
+ tga_inverted = 1 - ((tga_inverted >> 5) & 1);
+
+ // If I'm paletted, then I'll use the number of bits from the palette
+ if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16);
+ else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16);
+
+ if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency
+ return stbi__errpuc("bad format", "Can't find out TGA pixelformat");
+
+ // tga info
+ *x = tga_width;
+ *y = tga_height;
+ if (comp) *comp = tga_comp;
+
+ if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0))
+ return stbi__errpuc("too large", "Corrupt TGA");
+
+ tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0);
+ if (!tga_data) return stbi__errpuc("outofmem", "Out of memory");
+
+ // skip to the data's starting position (offset usually = 0)
+ stbi__skip(s, tga_offset );
+
+ if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) {
+ for (i=0; i < tga_height; ++i) {
+ int row = tga_inverted ? tga_height -i - 1 : i;
+ stbi_uc *tga_row = tga_data + row*tga_width*tga_comp;
+ stbi__getn(s, tga_row, tga_width * tga_comp);
+ }
+ } else {
+ // do I need to load a palette?
+ if ( tga_indexed)
+ {
+ if (tga_palette_len == 0) { /* you have to have at least one entry! */
+ STBI_FREE(tga_data);
+ return stbi__errpuc("bad palette", "Corrupt TGA");
+ }
+
+ // any data to skip? (offset usually = 0)
+ stbi__skip(s, tga_palette_start );
+ // load the palette
+ tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0);
+ if (!tga_palette) {
+ STBI_FREE(tga_data);
+ return stbi__errpuc("outofmem", "Out of memory");
+ }
+ if (tga_rgb16) {
+ stbi_uc *pal_entry = tga_palette;
+ STBI_ASSERT(tga_comp == STBI_rgb);
+ for (i=0; i < tga_palette_len; ++i) {
+ stbi__tga_read_rgb16(s, pal_entry);
+ pal_entry += tga_comp;
+ }
+ } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) {
+ STBI_FREE(tga_data);
+ STBI_FREE(tga_palette);
+ return stbi__errpuc("bad palette", "Corrupt TGA");
+ }
+ }
+ // load the data
+ for (i=0; i < tga_width * tga_height; ++i)
+ {
+ // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk?
+ if ( tga_is_RLE )
+ {
+ if ( RLE_count == 0 )
+ {
+ // yep, get the next byte as a RLE command
+ int RLE_cmd = stbi__get8(s);
+ RLE_count = 1 + (RLE_cmd & 127);
+ RLE_repeating = RLE_cmd >> 7;
+ read_next_pixel = 1;
+ } else if ( !RLE_repeating )
+ {
+ read_next_pixel = 1;
+ }
+ } else
+ {
+ read_next_pixel = 1;
+ }
+ // OK, if I need to read a pixel, do it now
+ if ( read_next_pixel )
+ {
+ // load however much data we did have
+ if ( tga_indexed )
+ {
+ // read in index, then perform the lookup
+ int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s);
+ if ( pal_idx >= tga_palette_len ) {
+ // invalid index
+ pal_idx = 0;
+ }
+ pal_idx *= tga_comp;
+ for (j = 0; j < tga_comp; ++j) {
+ raw_data[j] = tga_palette[pal_idx+j];
+ }
+ } else if(tga_rgb16) {
+ STBI_ASSERT(tga_comp == STBI_rgb);
+ stbi__tga_read_rgb16(s, raw_data);
+ } else {
+ // read in the data raw
+ for (j = 0; j < tga_comp; ++j) {
+ raw_data[j] = stbi__get8(s);
+ }
+ }
+ // clear the reading flag for the next pixel
+ read_next_pixel = 0;
+ } // end of reading a pixel
+
+ // copy data
+ for (j = 0; j < tga_comp; ++j)
+ tga_data[i*tga_comp+j] = raw_data[j];
+
+ // in case we're in RLE mode, keep counting down
+ --RLE_count;
+ }
+ // do I need to invert the image?
+ if ( tga_inverted )
+ {
+ for (j = 0; j*2 < tga_height; ++j)
+ {
+ int index1 = j * tga_width * tga_comp;
+ int index2 = (tga_height - 1 - j) * tga_width * tga_comp;
+ for (i = tga_width * tga_comp; i > 0; --i)
+ {
+ unsigned char temp = tga_data[index1];
+ tga_data[index1] = tga_data[index2];
+ tga_data[index2] = temp;
+ ++index1;
+ ++index2;
+ }
+ }
+ }
+ // clear my palette, if I had one
+ if ( tga_palette != NULL )
+ {
+ STBI_FREE( tga_palette );
+ }
+ }
+
+ // swap RGB - if the source data was RGB16, it already is in the right order
+ if (tga_comp >= 3 && !tga_rgb16)
+ {
+ unsigned char* tga_pixel = tga_data;
+ for (i=0; i < tga_width * tga_height; ++i)
+ {
+ unsigned char temp = tga_pixel[0];
+ tga_pixel[0] = tga_pixel[2];
+ tga_pixel[2] = temp;
+ tga_pixel += tga_comp;
+ }
+ }
+
+ // convert to target component count
+ if (req_comp && req_comp != tga_comp)
+ tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height);
+
+ // the things I do to get rid of an error message, and yet keep
+ // Microsoft's C compilers happy... [8^(
+ tga_palette_start = tga_palette_len = tga_palette_bits =
+ tga_x_origin = tga_y_origin = 0;
+ STBI_NOTUSED(tga_palette_start);
+ // OK, done
+ return tga_data;
+}
+#endif
+
+// *************************************************************************************************
+// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB
+
+#ifndef STBI_NO_PSD
+static int stbi__psd_test(stbi__context *s)
+{
+ int r = (stbi__get32be(s) == 0x38425053);
+ stbi__rewind(s);
+ return r;
+}
+
+static int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount)
+{
+ int count, nleft, len;
+
+ count = 0;
+ while ((nleft = pixelCount - count) > 0) {
+ len = stbi__get8(s);
+ if (len == 128) {
+ // No-op.
+ } else if (len < 128) {
+ // Copy next len+1 bytes literally.
+ len++;
+ if (len > nleft) return 0; // corrupt data
+ count += len;
+ while (len) {
+ *p = stbi__get8(s);
+ p += 4;
+ len--;
+ }
+ } else if (len > 128) {
+ stbi_uc val;
+ // Next -len+1 bytes in the dest are replicated from next source byte.
+ // (Interpret len as a negative 8-bit int.)
+ len = 257 - len;
+ if (len > nleft) return 0; // corrupt data
+ val = stbi__get8(s);
+ count += len;
+ while (len) {
+ *p = val;
+ p += 4;
+ len--;
+ }
+ }
+ }
+
+ return 1;
+}
+
+static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc)
+{
+ int pixelCount;
+ int channelCount, compression;
+ int channel, i;
+ int bitdepth;
+ int w,h;
+ stbi_uc *out;
+ STBI_NOTUSED(ri);
+
+ // Check identifier
+ if (stbi__get32be(s) != 0x38425053) // "8BPS"
+ return stbi__errpuc("not PSD", "Corrupt PSD image");
+
+ // Check file type version.
+ if (stbi__get16be(s) != 1)
+ return stbi__errpuc("wrong version", "Unsupported version of PSD image");
+
+ // Skip 6 reserved bytes.
+ stbi__skip(s, 6 );
+
+ // Read the number of channels (R, G, B, A, etc).
+ channelCount = stbi__get16be(s);
+ if (channelCount < 0 || channelCount > 16)
+ return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image");
+
+ // Read the rows and columns of the image.
+ h = stbi__get32be(s);
+ w = stbi__get32be(s);
+
+ if (h > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+ if (w > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+
+ // Make sure the depth is 8 bits.
+ bitdepth = stbi__get16be(s);
+ if (bitdepth != 8 && bitdepth != 16)
+ return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit");
+
+ // Make sure the color mode is RGB.
+ // Valid options are:
+ // 0: Bitmap
+ // 1: Grayscale
+ // 2: Indexed color
+ // 3: RGB color
+ // 4: CMYK color
+ // 7: Multichannel
+ // 8: Duotone
+ // 9: Lab color
+ if (stbi__get16be(s) != 3)
+ return stbi__errpuc("wrong color format", "PSD is not in RGB color format");
+
+ // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.)
+ stbi__skip(s,stbi__get32be(s) );
+
+ // Skip the image resources. (resolution, pen tool paths, etc)
+ stbi__skip(s, stbi__get32be(s) );
+
+ // Skip the reserved data.
+ stbi__skip(s, stbi__get32be(s) );
+
+ // Find out if the data is compressed.
+ // Known values:
+ // 0: no compression
+ // 1: RLE compressed
+ compression = stbi__get16be(s);
+ if (compression > 1)
+ return stbi__errpuc("bad compression", "PSD has an unknown compression format");
+
+ // Check size
+ if (!stbi__mad3sizes_valid(4, w, h, 0))
+ return stbi__errpuc("too large", "Corrupt PSD");
+
+ // Create the destination image.
+
+ if (!compression && bitdepth == 16 && bpc == 16) {
+ out = (stbi_uc *) stbi__malloc_mad3(8, w, h, 0);
+ ri->bits_per_channel = 16;
+ } else
+ out = (stbi_uc *) stbi__malloc(4 * w*h);
+
+ if (!out) return stbi__errpuc("outofmem", "Out of memory");
+ pixelCount = w*h;
+
+ // Initialize the data to zero.
+ //memset( out, 0, pixelCount * 4 );
+
+ // Finally, the image data.
+ if (compression) {
+ // RLE as used by .PSD and .TIFF
+ // Loop until you get the number of unpacked bytes you are expecting:
+ // Read the next source byte into n.
+ // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally.
+ // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times.
+ // Else if n is 128, noop.
+ // Endloop
+
+ // The RLE-compressed data is preceded by a 2-byte data count for each row in the data,
+ // which we're going to just skip.
+ stbi__skip(s, h * channelCount * 2 );
+
+ // Read the RLE data by channel.
+ for (channel = 0; channel < 4; channel++) {
+ stbi_uc *p;
+
+ p = out+channel;
+ if (channel >= channelCount) {
+ // Fill this channel with default data.
+ for (i = 0; i < pixelCount; i++, p += 4)
+ *p = (channel == 3 ? 255 : 0);
+ } else {
+ // Read the RLE data.
+ if (!stbi__psd_decode_rle(s, p, pixelCount)) {
+ STBI_FREE(out);
+ return stbi__errpuc("corrupt", "bad RLE data");
+ }
+ }
+ }
+
+ } else {
+ // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...)
+ // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image.
+
+ // Read the data by channel.
+ for (channel = 0; channel < 4; channel++) {
+ if (channel >= channelCount) {
+ // Fill this channel with default data.
+ if (bitdepth == 16 && bpc == 16) {
+ stbi__uint16 *q = ((stbi__uint16 *) out) + channel;
+ stbi__uint16 val = channel == 3 ? 65535 : 0;
+ for (i = 0; i < pixelCount; i++, q += 4)
+ *q = val;
+ } else {
+ stbi_uc *p = out+channel;
+ stbi_uc val = channel == 3 ? 255 : 0;
+ for (i = 0; i < pixelCount; i++, p += 4)
+ *p = val;
+ }
+ } else {
+ if (ri->bits_per_channel == 16) { // output bpc
+ stbi__uint16 *q = ((stbi__uint16 *) out) + channel;
+ for (i = 0; i < pixelCount; i++, q += 4)
+ *q = (stbi__uint16) stbi__get16be(s);
+ } else {
+ stbi_uc *p = out+channel;
+ if (bitdepth == 16) { // input bpc
+ for (i = 0; i < pixelCount; i++, p += 4)
+ *p = (stbi_uc) (stbi__get16be(s) >> 8);
+ } else {
+ for (i = 0; i < pixelCount; i++, p += 4)
+ *p = stbi__get8(s);
+ }
+ }
+ }
+ }
+ }
+
+ // remove weird white matte from PSD
+ if (channelCount >= 4) {
+ if (ri->bits_per_channel == 16) {
+ for (i=0; i < w*h; ++i) {
+ stbi__uint16 *pixel = (stbi__uint16 *) out + 4*i;
+ if (pixel[3] != 0 && pixel[3] != 65535) {
+ float a = pixel[3] / 65535.0f;
+ float ra = 1.0f / a;
+ float inv_a = 65535.0f * (1 - ra);
+ pixel[0] = (stbi__uint16) (pixel[0]*ra + inv_a);
+ pixel[1] = (stbi__uint16) (pixel[1]*ra + inv_a);
+ pixel[2] = (stbi__uint16) (pixel[2]*ra + inv_a);
+ }
+ }
+ } else {
+ for (i=0; i < w*h; ++i) {
+ unsigned char *pixel = out + 4*i;
+ if (pixel[3] != 0 && pixel[3] != 255) {
+ float a = pixel[3] / 255.0f;
+ float ra = 1.0f / a;
+ float inv_a = 255.0f * (1 - ra);
+ pixel[0] = (unsigned char) (pixel[0]*ra + inv_a);
+ pixel[1] = (unsigned char) (pixel[1]*ra + inv_a);
+ pixel[2] = (unsigned char) (pixel[2]*ra + inv_a);
+ }
+ }
+ }
+ }
+
+ // convert to desired output format
+ if (req_comp && req_comp != 4) {
+ if (ri->bits_per_channel == 16)
+ out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h);
+ else
+ out = stbi__convert_format(out, 4, req_comp, w, h);
+ if (out == NULL) return out; // stbi__convert_format frees input on failure
+ }
+
+ if (comp) *comp = 4;
+ *y = h;
+ *x = w;
+
+ return out;
+}
+#endif
+
+// *************************************************************************************************
+// Softimage PIC loader
+// by Tom Seddon
+//
+// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format
+// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/
+
+#ifndef STBI_NO_PIC
+static int stbi__pic_is4(stbi__context *s,const char *str)
+{
+ int i;
+ for (i=0; i<4; ++i)
+ if (stbi__get8(s) != (stbi_uc)str[i])
+ return 0;
+
+ return 1;
+}
+
+static int stbi__pic_test_core(stbi__context *s)
+{
+ int i;
+
+ if (!stbi__pic_is4(s,"\x53\x80\xF6\x34"))
+ return 0;
+
+ for(i=0;i<84;++i)
+ stbi__get8(s);
+
+ if (!stbi__pic_is4(s,"PICT"))
+ return 0;
+
+ return 1;
+}
+
+typedef struct
+{
+ stbi_uc size,type,channel;
+} stbi__pic_packet;
+
+static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest)
+{
+ int mask=0x80, i;
+
+ for (i=0; i<4; ++i, mask>>=1) {
+ if (channel & mask) {
+ if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short");
+ dest[i]=stbi__get8(s);
+ }
+ }
+
+ return dest;
+}
+
+static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src)
+{
+ int mask=0x80,i;
+
+ for (i=0;i<4; ++i, mask>>=1)
+ if (channel&mask)
+ dest[i]=src[i];
+}
+
+static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result)
+{
+ int act_comp=0,num_packets=0,y,chained;
+ stbi__pic_packet packets[10];
+
+ // this will (should...) cater for even some bizarre stuff like having data
+ // for the same channel in multiple packets.
+ do {
+ stbi__pic_packet *packet;
+
+ if (num_packets==sizeof(packets)/sizeof(packets[0]))
+ return stbi__errpuc("bad format","too many packets");
+
+ packet = &packets[num_packets++];
+
+ chained = stbi__get8(s);
+ packet->size = stbi__get8(s);
+ packet->type = stbi__get8(s);
+ packet->channel = stbi__get8(s);
+
+ act_comp |= packet->channel;
+
+ if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)");
+ if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp");
+ } while (chained);
+
+ *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel?
+
+ for(y=0; y<height; ++y) {
+ int packet_idx;
+
+ for(packet_idx=0; packet_idx < num_packets; ++packet_idx) {
+ stbi__pic_packet *packet = &packets[packet_idx];
+ stbi_uc *dest = result+y*width*4;
+
+ switch (packet->type) {
+ default:
+ return stbi__errpuc("bad format","packet has bad compression type");
+
+ case 0: {//uncompressed
+ int x;
+
+ for(x=0;x<width;++x, dest+=4)
+ if (!stbi__readval(s,packet->channel,dest))
+ return 0;
+ break;
+ }
+
+ case 1://Pure RLE
+ {
+ int left=width, i;
+
+ while (left>0) {
+ stbi_uc count,value[4];
+
+ count=stbi__get8(s);
+ if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)");
+
+ if (count > left)
+ count = (stbi_uc) left;
+
+ if (!stbi__readval(s,packet->channel,value)) return 0;
+
+ for(i=0; i<count; ++i,dest+=4)
+ stbi__copyval(packet->channel,dest,value);
+ left -= count;
+ }
+ }
+ break;
+
+ case 2: {//Mixed RLE
+ int left=width;
+ while (left>0) {
+ int count = stbi__get8(s), i;
+ if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)");
+
+ if (count >= 128) { // Repeated
+ stbi_uc value[4];
+
+ if (count==128)
+ count = stbi__get16be(s);
+ else
+ count -= 127;
+ if (count > left)
+ return stbi__errpuc("bad file","scanline overrun");
+
+ if (!stbi__readval(s,packet->channel,value))
+ return 0;
+
+ for(i=0;i<count;++i, dest += 4)
+ stbi__copyval(packet->channel,dest,value);
+ } else { // Raw
+ ++count;
+ if (count>left) return stbi__errpuc("bad file","scanline overrun");
+
+ for(i=0;i<count;++i, dest+=4)
+ if (!stbi__readval(s,packet->channel,dest))
+ return 0;
+ }
+ left-=count;
+ }
+ break;
+ }
+ }
+ }
+ }
+
+ return result;
+}
+
+static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp, stbi__result_info *ri)
+{
+ stbi_uc *result;
+ int i, x,y, internal_comp;
+ STBI_NOTUSED(ri);
+
+ if (!comp) comp = &internal_comp;
+
+ for (i=0; i<92; ++i)
+ stbi__get8(s);
+
+ x = stbi__get16be(s);
+ y = stbi__get16be(s);
+
+ if (y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+ if (x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+
+ if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)");
+ if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode");
+
+ stbi__get32be(s); //skip `ratio'
+ stbi__get16be(s); //skip `fields'
+ stbi__get16be(s); //skip `pad'
+
+ // intermediate buffer is RGBA
+ result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0);
+ if (!result) return stbi__errpuc("outofmem", "Out of memory");
+ memset(result, 0xff, x*y*4);
+
+ if (!stbi__pic_load_core(s,x,y,comp, result)) {
+ STBI_FREE(result);
+ result=0;
+ }
+ *px = x;
+ *py = y;
+ if (req_comp == 0) req_comp = *comp;
+ result=stbi__convert_format(result,4,req_comp,x,y);
+
+ return result;
+}
+
+static int stbi__pic_test(stbi__context *s)
+{
+ int r = stbi__pic_test_core(s);
+ stbi__rewind(s);
+ return r;
+}
+#endif
+
+// *************************************************************************************************
+// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb
+
+#ifndef STBI_NO_GIF
+typedef struct
+{
+ stbi__int16 prefix;
+ stbi_uc first;
+ stbi_uc suffix;
+} stbi__gif_lzw;
+
+typedef struct
+{
+ int w,h;
+ stbi_uc *out; // output buffer (always 4 components)
+ stbi_uc *background; // The current "background" as far as a gif is concerned
+ stbi_uc *history;
+ int flags, bgindex, ratio, transparent, eflags;
+ stbi_uc pal[256][4];
+ stbi_uc lpal[256][4];
+ stbi__gif_lzw codes[8192];
+ stbi_uc *color_table;
+ int parse, step;
+ int lflags;
+ int start_x, start_y;
+ int max_x, max_y;
+ int cur_x, cur_y;
+ int line_size;
+ int delay;
+} stbi__gif;
+
+static int stbi__gif_test_raw(stbi__context *s)
+{
+ int sz;
+ if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0;
+ sz = stbi__get8(s);
+ if (sz != '9' && sz != '7') return 0;
+ if (stbi__get8(s) != 'a') return 0;
+ return 1;
+}
+
+static int stbi__gif_test(stbi__context *s)
+{
+ int r = stbi__gif_test_raw(s);
+ stbi__rewind(s);
+ return r;
+}
+
+static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp)
+{
+ int i;
+ for (i=0; i < num_entries; ++i) {
+ pal[i][2] = stbi__get8(s);
+ pal[i][1] = stbi__get8(s);
+ pal[i][0] = stbi__get8(s);
+ pal[i][3] = transp == i ? 0 : 255;
+ }
+}
+
+static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info)
+{
+ stbi_uc version;
+ if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8')
+ return stbi__err("not GIF", "Corrupt GIF");
+
+ version = stbi__get8(s);
+ if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF");
+ if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF");
+
+ stbi__g_failure_reason = "";
+ g->w = stbi__get16le(s);
+ g->h = stbi__get16le(s);
+ g->flags = stbi__get8(s);
+ g->bgindex = stbi__get8(s);
+ g->ratio = stbi__get8(s);
+ g->transparent = -1;
+
+ if (g->w > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
+ if (g->h > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
+
+ if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments
+
+ if (is_info) return 1;
+
+ if (g->flags & 0x80)
+ stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1);
+
+ return 1;
+}
+
+static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp)
+{
+ stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif));
+ if (!g) return stbi__err("outofmem", "Out of memory");
+ if (!stbi__gif_header(s, g, comp, 1)) {
+ STBI_FREE(g);
+ stbi__rewind( s );
+ return 0;
+ }
+ if (x) *x = g->w;
+ if (y) *y = g->h;
+ STBI_FREE(g);
+ return 1;
+}
+
+static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code)
+{
+ stbi_uc *p, *c;
+ int idx;
+
+ // recurse to decode the prefixes, since the linked-list is backwards,
+ // and working backwards through an interleaved image would be nasty
+ if (g->codes[code].prefix >= 0)
+ stbi__out_gif_code(g, g->codes[code].prefix);
+
+ if (g->cur_y >= g->max_y) return;
+
+ idx = g->cur_x + g->cur_y;
+ p = &g->out[idx];
+ g->history[idx / 4] = 1;
+
+ c = &g->color_table[g->codes[code].suffix * 4];
+ if (c[3] > 128) { // don't render transparent pixels;
+ p[0] = c[2];
+ p[1] = c[1];
+ p[2] = c[0];
+ p[3] = c[3];
+ }
+ g->cur_x += 4;
+
+ if (g->cur_x >= g->max_x) {
+ g->cur_x = g->start_x;
+ g->cur_y += g->step;
+
+ while (g->cur_y >= g->max_y && g->parse > 0) {
+ g->step = (1 << g->parse) * g->line_size;
+ g->cur_y = g->start_y + (g->step >> 1);
+ --g->parse;
+ }
+ }
+}
+
+static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g)
+{
+ stbi_uc lzw_cs;
+ stbi__int32 len, init_code;
+ stbi__uint32 first;
+ stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear;
+ stbi__gif_lzw *p;
+
+ lzw_cs = stbi__get8(s);
+ if (lzw_cs > 12) return NULL;
+ clear = 1 << lzw_cs;
+ first = 1;
+ codesize = lzw_cs + 1;
+ codemask = (1 << codesize) - 1;
+ bits = 0;
+ valid_bits = 0;
+ for (init_code = 0; init_code < clear; init_code++) {
+ g->codes[init_code].prefix = -1;
+ g->codes[init_code].first = (stbi_uc) init_code;
+ g->codes[init_code].suffix = (stbi_uc) init_code;
+ }
+
+ // support no starting clear code
+ avail = clear+2;
+ oldcode = -1;
+
+ len = 0;
+ for(;;) {
+ if (valid_bits < codesize) {
+ if (len == 0) {
+ len = stbi__get8(s); // start new block
+ if (len == 0)
+ return g->out;
+ }
+ --len;
+ bits |= (stbi__int32) stbi__get8(s) << valid_bits;
+ valid_bits += 8;
+ } else {
+ stbi__int32 code = bits & codemask;
+ bits >>= codesize;
+ valid_bits -= codesize;
+ // @OPTIMIZE: is there some way we can accelerate the non-clear path?
+ if (code == clear) { // clear code
+ codesize = lzw_cs + 1;
+ codemask = (1 << codesize) - 1;
+ avail = clear + 2;
+ oldcode = -1;
+ first = 0;
+ } else if (code == clear + 1) { // end of stream code
+ stbi__skip(s, len);
+ while ((len = stbi__get8(s)) > 0)
+ stbi__skip(s,len);
+ return g->out;
+ } else if (code <= avail) {
+ if (first) {
+ return stbi__errpuc("no clear code", "Corrupt GIF");
+ }
+
+ if (oldcode >= 0) {
+ p = &g->codes[avail++];
+ if (avail > 8192) {
+ return stbi__errpuc("too many codes", "Corrupt GIF");
+ }
+
+ p->prefix = (stbi__int16) oldcode;
+ p->first = g->codes[oldcode].first;
+ p->suffix = (code == avail) ? p->first : g->codes[code].first;
+ } else if (code == avail)
+ return stbi__errpuc("illegal code in raster", "Corrupt GIF");
+
+ stbi__out_gif_code(g, (stbi__uint16) code);
+
+ if ((avail & codemask) == 0 && avail <= 0x0FFF) {
+ codesize++;
+ codemask = (1 << codesize) - 1;
+ }
+
+ oldcode = code;
+ } else {
+ return stbi__errpuc("illegal code in raster", "Corrupt GIF");
+ }
+ }
+ }
+}
+
+// this function is designed to support animated gifs, although stb_image doesn't support it
+// two back is the image from two frames ago, used for a very specific disposal format
+static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp, stbi_uc *two_back)
+{
+ int dispose;
+ int first_frame;
+ int pi;
+ int pcount;
+ STBI_NOTUSED(req_comp);
+
+ // on first frame, any non-written pixels get the background colour (non-transparent)
+ first_frame = 0;
+ if (g->out == 0) {
+ if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header
+ if (!stbi__mad3sizes_valid(4, g->w, g->h, 0))
+ return stbi__errpuc("too large", "GIF image is too large");
+ pcount = g->w * g->h;
+ g->out = (stbi_uc *) stbi__malloc(4 * pcount);
+ g->background = (stbi_uc *) stbi__malloc(4 * pcount);
+ g->history = (stbi_uc *) stbi__malloc(pcount);
+ if (!g->out || !g->background || !g->history)
+ return stbi__errpuc("outofmem", "Out of memory");
+
+ // image is treated as "transparent" at the start - ie, nothing overwrites the current background;
+ // background colour is only used for pixels that are not rendered first frame, after that "background"
+ // color refers to the color that was there the previous frame.
+ memset(g->out, 0x00, 4 * pcount);
+ memset(g->background, 0x00, 4 * pcount); // state of the background (starts transparent)
+ memset(g->history, 0x00, pcount); // pixels that were affected previous frame
+ first_frame = 1;
+ } else {
+ // second frame - how do we dispose of the previous one?
+ dispose = (g->eflags & 0x1C) >> 2;
+ pcount = g->w * g->h;
+
+ if ((dispose == 3) && (two_back == 0)) {
+ dispose = 2; // if I don't have an image to revert back to, default to the old background
+ }
+
+ if (dispose == 3) { // use previous graphic
+ for (pi = 0; pi < pcount; ++pi) {
+ if (g->history[pi]) {
+ memcpy( &g->out[pi * 4], &two_back[pi * 4], 4 );
+ }
+ }
+ } else if (dispose == 2) {
+ // restore what was changed last frame to background before that frame;
+ for (pi = 0; pi < pcount; ++pi) {
+ if (g->history[pi]) {
+ memcpy( &g->out[pi * 4], &g->background[pi * 4], 4 );
+ }
+ }
+ } else {
+ // This is a non-disposal case eithe way, so just
+ // leave the pixels as is, and they will become the new background
+ // 1: do not dispose
+ // 0: not specified.
+ }
+
+ // background is what out is after the undoing of the previou frame;
+ memcpy( g->background, g->out, 4 * g->w * g->h );
+ }
+
+ // clear my history;
+ memset( g->history, 0x00, g->w * g->h ); // pixels that were affected previous frame
+
+ for (;;) {
+ int tag = stbi__get8(s);
+ switch (tag) {
+ case 0x2C: /* Image Descriptor */
+ {
+ stbi__int32 x, y, w, h;
+ stbi_uc *o;
+
+ x = stbi__get16le(s);
+ y = stbi__get16le(s);
+ w = stbi__get16le(s);
+ h = stbi__get16le(s);
+ if (((x + w) > (g->w)) || ((y + h) > (g->h)))
+ return stbi__errpuc("bad Image Descriptor", "Corrupt GIF");
+
+ g->line_size = g->w * 4;
+ g->start_x = x * 4;
+ g->start_y = y * g->line_size;
+ g->max_x = g->start_x + w * 4;
+ g->max_y = g->start_y + h * g->line_size;
+ g->cur_x = g->start_x;
+ g->cur_y = g->start_y;
+
+ // if the width of the specified rectangle is 0, that means
+ // we may not see *any* pixels or the image is malformed;
+ // to make sure this is caught, move the current y down to
+ // max_y (which is what out_gif_code checks).
+ if (w == 0)
+ g->cur_y = g->max_y;
+
+ g->lflags = stbi__get8(s);
+
+ if (g->lflags & 0x40) {
+ g->step = 8 * g->line_size; // first interlaced spacing
+ g->parse = 3;
+ } else {
+ g->step = g->line_size;
+ g->parse = 0;
+ }
+
+ if (g->lflags & 0x80) {
+ stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1);
+ g->color_table = (stbi_uc *) g->lpal;
+ } else if (g->flags & 0x80) {
+ g->color_table = (stbi_uc *) g->pal;
+ } else
+ return stbi__errpuc("missing color table", "Corrupt GIF");
+
+ o = stbi__process_gif_raster(s, g);
+ if (!o) return NULL;
+
+ // if this was the first frame,
+ pcount = g->w * g->h;
+ if (first_frame && (g->bgindex > 0)) {
+ // if first frame, any pixel not drawn to gets the background color
+ for (pi = 0; pi < pcount; ++pi) {
+ if (g->history[pi] == 0) {
+ g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be;
+ memcpy( &g->out[pi * 4], &g->pal[g->bgindex], 4 );
+ }
+ }
+ }
+
+ return o;
+ }
+
+ case 0x21: // Comment Extension.
+ {
+ int len;
+ int ext = stbi__get8(s);
+ if (ext == 0xF9) { // Graphic Control Extension.
+ len = stbi__get8(s);
+ if (len == 4) {
+ g->eflags = stbi__get8(s);
+ g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths.
+
+ // unset old transparent
+ if (g->transparent >= 0) {
+ g->pal[g->transparent][3] = 255;
+ }
+ if (g->eflags & 0x01) {
+ g->transparent = stbi__get8(s);
+ if (g->transparent >= 0) {
+ g->pal[g->transparent][3] = 0;
+ }
+ } else {
+ // don't need transparent
+ stbi__skip(s, 1);
+ g->transparent = -1;
+ }
+ } else {
+ stbi__skip(s, len);
+ break;
+ }
+ }
+ while ((len = stbi__get8(s)) != 0) {
+ stbi__skip(s, len);
+ }
+ break;
+ }
+
+ case 0x3B: // gif stream termination code
+ return (stbi_uc *) s; // using '1' causes warning on some compilers
+
+ default:
+ return stbi__errpuc("unknown code", "Corrupt GIF");
+ }
+ }
+}
+
+static void *stbi__load_gif_main_outofmem(stbi__gif *g, stbi_uc *out, int **delays)
+{
+ STBI_FREE(g->out);
+ STBI_FREE(g->history);
+ STBI_FREE(g->background);
+
+ if (out) STBI_FREE(out);
+ if (delays && *delays) STBI_FREE(*delays);
+ return stbi__errpuc("outofmem", "Out of memory");
+}
+
+static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp)
+{
+ if (stbi__gif_test(s)) {
+ int layers = 0;
+ stbi_uc *u = 0;
+ stbi_uc *out = 0;
+ stbi_uc *two_back = 0;
+ stbi__gif g;
+ int stride;
+ int out_size = 0;
+ int delays_size = 0;
+
+ STBI_NOTUSED(out_size);
+ STBI_NOTUSED(delays_size);
+
+ memset(&g, 0, sizeof(g));
+ if (delays) {
+ *delays = 0;
+ }
+
+ do {
+ u = stbi__gif_load_next(s, &g, comp, req_comp, two_back);
+ if (u == (stbi_uc *) s) u = 0; // end of animated gif marker
+
+ if (u) {
+ *x = g.w;
+ *y = g.h;
+ ++layers;
+ stride = g.w * g.h * 4;
+
+ if (out) {
+ void *tmp = (stbi_uc*) STBI_REALLOC_SIZED( out, out_size, layers * stride );
+ if (!tmp)
+ return stbi__load_gif_main_outofmem(&g, out, delays);
+ else {
+ out = (stbi_uc*) tmp;
+ out_size = layers * stride;
+ }
+
+ if (delays) {
+ int *new_delays = (int*) STBI_REALLOC_SIZED( *delays, delays_size, sizeof(int) * layers );
+ if (!new_delays)
+ return stbi__load_gif_main_outofmem(&g, out, delays);
+ *delays = new_delays;
+ delays_size = layers * sizeof(int);
+ }
+ } else {
+ out = (stbi_uc*)stbi__malloc( layers * stride );
+ if (!out)
+ return stbi__load_gif_main_outofmem(&g, out, delays);
+ out_size = layers * stride;
+ if (delays) {
+ *delays = (int*) stbi__malloc( layers * sizeof(int) );
+ if (!*delays)
+ return stbi__load_gif_main_outofmem(&g, out, delays);
+ delays_size = layers * sizeof(int);
+ }
+ }
+ memcpy( out + ((layers - 1) * stride), u, stride );
+ if (layers >= 2) {
+ two_back = out - 2 * stride;
+ }
+
+ if (delays) {
+ (*delays)[layers - 1U] = g.delay;
+ }
+ }
+ } while (u != 0);
+
+ // free temp buffer;
+ STBI_FREE(g.out);
+ STBI_FREE(g.history);
+ STBI_FREE(g.background);
+
+ // do the final conversion after loading everything;
+ if (req_comp && req_comp != 4)
+ out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h);
+
+ *z = layers;
+ return out;
+ } else {
+ return stbi__errpuc("not GIF", "Image was not as a gif type.");
+ }
+}
+
+static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)
+{
+ stbi_uc *u = 0;
+ stbi__gif g;
+ memset(&g, 0, sizeof(g));
+ STBI_NOTUSED(ri);
+
+ u = stbi__gif_load_next(s, &g, comp, req_comp, 0);
+ if (u == (stbi_uc *) s) u = 0; // end of animated gif marker
+ if (u) {
+ *x = g.w;
+ *y = g.h;
+
+ // moved conversion to after successful load so that the same
+ // can be done for multiple frames.
+ if (req_comp && req_comp != 4)
+ u = stbi__convert_format(u, 4, req_comp, g.w, g.h);
+ } else if (g.out) {
+ // if there was an error and we allocated an image buffer, free it!
+ STBI_FREE(g.out);
+ }
+
+ // free buffers needed for multiple frame loading;
+ STBI_FREE(g.history);
+ STBI_FREE(g.background);
+
+ return u;
+}
+
+static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ return stbi__gif_info_raw(s,x,y,comp);
+}
+#endif
+
+// *************************************************************************************************
+// Radiance RGBE HDR loader
+// originally by Nicolas Schulz
+#ifndef STBI_NO_HDR
+static int stbi__hdr_test_core(stbi__context *s, const char *signature)
+{
+ int i;
+ for (i=0; signature[i]; ++i)
+ if (stbi__get8(s) != signature[i])
+ return 0;
+ stbi__rewind(s);
+ return 1;
+}
+
+static int stbi__hdr_test(stbi__context* s)
+{
+ int r = stbi__hdr_test_core(s, "#?RADIANCE\n");
+ stbi__rewind(s);
+ if(!r) {
+ r = stbi__hdr_test_core(s, "#?RGBE\n");
+ stbi__rewind(s);
+ }
+ return r;
+}
+
+#define STBI__HDR_BUFLEN 1024
+static char *stbi__hdr_gettoken(stbi__context *z, char *buffer)
+{
+ int len=0;
+ char c = '\0';
+
+ c = (char) stbi__get8(z);
+
+ while (!stbi__at_eof(z) && c != '\n') {
+ buffer[len++] = c;
+ if (len == STBI__HDR_BUFLEN-1) {
+ // flush to end of line
+ while (!stbi__at_eof(z) && stbi__get8(z) != '\n')
+ ;
+ break;
+ }
+ c = (char) stbi__get8(z);
+ }
+
+ buffer[len] = 0;
+ return buffer;
+}
+
+static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp)
+{
+ if ( input[3] != 0 ) {
+ float f1;
+ // Exponent
+ f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8));
+ if (req_comp <= 2)
+ output[0] = (input[0] + input[1] + input[2]) * f1 / 3;
+ else {
+ output[0] = input[0] * f1;
+ output[1] = input[1] * f1;
+ output[2] = input[2] * f1;
+ }
+ if (req_comp == 2) output[1] = 1;
+ if (req_comp == 4) output[3] = 1;
+ } else {
+ switch (req_comp) {
+ case 4: output[3] = 1; /* fallthrough */
+ case 3: output[0] = output[1] = output[2] = 0;
+ break;
+ case 2: output[1] = 1; /* fallthrough */
+ case 1: output[0] = 0;
+ break;
+ }
+ }
+}
+
+static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)
+{
+ char buffer[STBI__HDR_BUFLEN];
+ char *token;
+ int valid = 0;
+ int width, height;
+ stbi_uc *scanline;
+ float *hdr_data;
+ int len;
+ unsigned char count, value;
+ int i, j, k, c1,c2, z;
+ const char *headerToken;
+ STBI_NOTUSED(ri);
+
+ // Check identifier
+ headerToken = stbi__hdr_gettoken(s,buffer);
+ if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0)
+ return stbi__errpf("not HDR", "Corrupt HDR image");
+
+ // Parse header
+ for(;;) {
+ token = stbi__hdr_gettoken(s,buffer);
+ if (token[0] == 0) break;
+ if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
+ }
+
+ if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format");
+
+ // Parse width and height
+ // can't use sscanf() if we're not using stdio!
+ token = stbi__hdr_gettoken(s,buffer);
+ if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format");
+ token += 3;
+ height = (int) strtol(token, &token, 10);
+ while (*token == ' ') ++token;
+ if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format");
+ token += 3;
+ width = (int) strtol(token, NULL, 10);
+
+ if (height > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)");
+ if (width > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)");
+
+ *x = width;
+ *y = height;
+
+ if (comp) *comp = 3;
+ if (req_comp == 0) req_comp = 3;
+
+ if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0))
+ return stbi__errpf("too large", "HDR image is too large");
+
+ // Read data
+ hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0);
+ if (!hdr_data)
+ return stbi__errpf("outofmem", "Out of memory");
+
+ // Load image data
+ // image data is stored as some number of sca
+ if ( width < 8 || width >= 32768) {
+ // Read flat data
+ for (j=0; j < height; ++j) {
+ for (i=0; i < width; ++i) {
+ stbi_uc rgbe[4];
+ main_decode_loop:
+ stbi__getn(s, rgbe, 4);
+ stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp);
+ }
+ }
+ } else {
+ // Read RLE-encoded data
+ scanline = NULL;
+
+ for (j = 0; j < height; ++j) {
+ c1 = stbi__get8(s);
+ c2 = stbi__get8(s);
+ len = stbi__get8(s);
+ if (c1 != 2 || c2 != 2 || (len & 0x80)) {
+ // not run-length encoded, so we have to actually use THIS data as a decoded
+ // pixel (note this can't be a valid pixel--one of RGB must be >= 128)
+ stbi_uc rgbe[4];
+ rgbe[0] = (stbi_uc) c1;
+ rgbe[1] = (stbi_uc) c2;
+ rgbe[2] = (stbi_uc) len;
+ rgbe[3] = (stbi_uc) stbi__get8(s);
+ stbi__hdr_convert(hdr_data, rgbe, req_comp);
+ i = 1;
+ j = 0;
+ STBI_FREE(scanline);
+ goto main_decode_loop; // yes, this makes no sense
+ }
+ len <<= 8;
+ len |= stbi__get8(s);
+ if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); }
+ if (scanline == NULL) {
+ scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0);
+ if (!scanline) {
+ STBI_FREE(hdr_data);
+ return stbi__errpf("outofmem", "Out of memory");
+ }
+ }
+
+ for (k = 0; k < 4; ++k) {
+ int nleft;
+ i = 0;
+ while ((nleft = width - i) > 0) {
+ count = stbi__get8(s);
+ if (count > 128) {
+ // Run
+ value = stbi__get8(s);
+ count -= 128;
+ if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); }
+ for (z = 0; z < count; ++z)
+ scanline[i++ * 4 + k] = value;
+ } else {
+ // Dump
+ if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); }
+ for (z = 0; z < count; ++z)
+ scanline[i++ * 4 + k] = stbi__get8(s);
+ }
+ }
+ }
+ for (i=0; i < width; ++i)
+ stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp);
+ }
+ if (scanline)
+ STBI_FREE(scanline);
+ }
+
+ return hdr_data;
+}
+
+static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ char buffer[STBI__HDR_BUFLEN];
+ char *token;
+ int valid = 0;
+ int dummy;
+
+ if (!x) x = &dummy;
+ if (!y) y = &dummy;
+ if (!comp) comp = &dummy;
+
+ if (stbi__hdr_test(s) == 0) {
+ stbi__rewind( s );
+ return 0;
+ }
+
+ for(;;) {
+ token = stbi__hdr_gettoken(s,buffer);
+ if (token[0] == 0) break;
+ if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
+ }
+
+ if (!valid) {
+ stbi__rewind( s );
+ return 0;
+ }
+ token = stbi__hdr_gettoken(s,buffer);
+ if (strncmp(token, "-Y ", 3)) {
+ stbi__rewind( s );
+ return 0;
+ }
+ token += 3;
+ *y = (int) strtol(token, &token, 10);
+ while (*token == ' ') ++token;
+ if (strncmp(token, "+X ", 3)) {
+ stbi__rewind( s );
+ return 0;
+ }
+ token += 3;
+ *x = (int) strtol(token, NULL, 10);
+ *comp = 3;
+ return 1;
+}
+#endif // STBI_NO_HDR
+
+#ifndef STBI_NO_BMP
+static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ void *p;
+ stbi__bmp_data info;
+
+ info.all_a = 255;
+ p = stbi__bmp_parse_header(s, &info);
+ if (p == NULL) {
+ stbi__rewind( s );
+ return 0;
+ }
+ if (x) *x = s->img_x;
+ if (y) *y = s->img_y;
+ if (comp) {
+ if (info.bpp == 24 && info.ma == 0xff000000)
+ *comp = 3;
+ else
+ *comp = info.ma ? 4 : 3;
+ }
+ return 1;
+}
+#endif
+
+#ifndef STBI_NO_PSD
+static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ int channelCount, dummy, depth;
+ if (!x) x = &dummy;
+ if (!y) y = &dummy;
+ if (!comp) comp = &dummy;
+ if (stbi__get32be(s) != 0x38425053) {
+ stbi__rewind( s );
+ return 0;
+ }
+ if (stbi__get16be(s) != 1) {
+ stbi__rewind( s );
+ return 0;
+ }
+ stbi__skip(s, 6);
+ channelCount = stbi__get16be(s);
+ if (channelCount < 0 || channelCount > 16) {
+ stbi__rewind( s );
+ return 0;
+ }
+ *y = stbi__get32be(s);
+ *x = stbi__get32be(s);
+ depth = stbi__get16be(s);
+ if (depth != 8 && depth != 16) {
+ stbi__rewind( s );
+ return 0;
+ }
+ if (stbi__get16be(s) != 3) {
+ stbi__rewind( s );
+ return 0;
+ }
+ *comp = 4;
+ return 1;
+}
+
+static int stbi__psd_is16(stbi__context *s)
+{
+ int channelCount, depth;
+ if (stbi__get32be(s) != 0x38425053) {
+ stbi__rewind( s );
+ return 0;
+ }
+ if (stbi__get16be(s) != 1) {
+ stbi__rewind( s );
+ return 0;
+ }
+ stbi__skip(s, 6);
+ channelCount = stbi__get16be(s);
+ if (channelCount < 0 || channelCount > 16) {
+ stbi__rewind( s );
+ return 0;
+ }
+ STBI_NOTUSED(stbi__get32be(s));
+ STBI_NOTUSED(stbi__get32be(s));
+ depth = stbi__get16be(s);
+ if (depth != 16) {
+ stbi__rewind( s );
+ return 0;
+ }
+ return 1;
+}
+#endif
+
+#ifndef STBI_NO_PIC
+static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ int act_comp=0,num_packets=0,chained,dummy;
+ stbi__pic_packet packets[10];
+
+ if (!x) x = &dummy;
+ if (!y) y = &dummy;
+ if (!comp) comp = &dummy;
+
+ if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) {
+ stbi__rewind(s);
+ return 0;
+ }
+
+ stbi__skip(s, 88);
+
+ *x = stbi__get16be(s);
+ *y = stbi__get16be(s);
+ if (stbi__at_eof(s)) {
+ stbi__rewind( s);
+ return 0;
+ }
+ if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) {
+ stbi__rewind( s );
+ return 0;
+ }
+
+ stbi__skip(s, 8);
+
+ do {
+ stbi__pic_packet *packet;
+
+ if (num_packets==sizeof(packets)/sizeof(packets[0]))
+ return 0;
+
+ packet = &packets[num_packets++];
+ chained = stbi__get8(s);
+ packet->size = stbi__get8(s);
+ packet->type = stbi__get8(s);
+ packet->channel = stbi__get8(s);
+ act_comp |= packet->channel;
+
+ if (stbi__at_eof(s)) {
+ stbi__rewind( s );
+ return 0;
+ }
+ if (packet->size != 8) {
+ stbi__rewind( s );
+ return 0;
+ }
+ } while (chained);
+
+ *comp = (act_comp & 0x10 ? 4 : 3);
+
+ return 1;
+}
+#endif
+
+// *************************************************************************************************
+// Portable Gray Map and Portable Pixel Map loader
+// by Ken Miller
+//
+// PGM: http://netpbm.sourceforge.net/doc/pgm.html
+// PPM: http://netpbm.sourceforge.net/doc/ppm.html
+//
+// Known limitations:
+// Does not support comments in the header section
+// Does not support ASCII image data (formats P2 and P3)
+
+#ifndef STBI_NO_PNM
+
+static int stbi__pnm_test(stbi__context *s)
+{
+ char p, t;
+ p = (char) stbi__get8(s);
+ t = (char) stbi__get8(s);
+ if (p != 'P' || (t != '5' && t != '6')) {
+ stbi__rewind( s );
+ return 0;
+ }
+ return 1;
+}
+
+static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)
+{
+ stbi_uc *out;
+ STBI_NOTUSED(ri);
+
+ ri->bits_per_channel = stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n);
+ if (ri->bits_per_channel == 0)
+ return 0;
+
+ if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+ if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+
+ *x = s->img_x;
+ *y = s->img_y;
+ if (comp) *comp = s->img_n;
+
+ if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0))
+ return stbi__errpuc("too large", "PNM too large");
+
+ out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0);
+ if (!out) return stbi__errpuc("outofmem", "Out of memory");
+ if (!stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8))) {
+ STBI_FREE(out);
+ return stbi__errpuc("bad PNM", "PNM file truncated");
+ }
+
+ if (req_comp && req_comp != s->img_n) {
+ if (ri->bits_per_channel == 16) {
+ out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, s->img_n, req_comp, s->img_x, s->img_y);
+ } else {
+ out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y);
+ }
+ if (out == NULL) return out; // stbi__convert_format frees input on failure
+ }
+ return out;
+}
+
+static int stbi__pnm_isspace(char c)
+{
+ return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r';
+}
+
+static void stbi__pnm_skip_whitespace(stbi__context *s, char *c)
+{
+ for (;;) {
+ while (!stbi__at_eof(s) && stbi__pnm_isspace(*c))
+ *c = (char) stbi__get8(s);
+
+ if (stbi__at_eof(s) || *c != '#')
+ break;
+
+ while (!stbi__at_eof(s) && *c != '\n' && *c != '\r' )
+ *c = (char) stbi__get8(s);
+ }
+}
+
+static int stbi__pnm_isdigit(char c)
+{
+ return c >= '0' && c <= '9';
+}
+
+static int stbi__pnm_getinteger(stbi__context *s, char *c)
+{
+ int value = 0;
+
+ while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) {
+ value = value*10 + (*c - '0');
+ *c = (char) stbi__get8(s);
+ if((value > 214748364) || (value == 214748364 && *c > '7'))
+ return stbi__err("integer parse overflow", "Parsing an integer in the PPM header overflowed a 32-bit int");
+ }
+
+ return value;
+}
+
+static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ int maxv, dummy;
+ char c, p, t;
+
+ if (!x) x = &dummy;
+ if (!y) y = &dummy;
+ if (!comp) comp = &dummy;
+
+ stbi__rewind(s);
+
+ // Get identifier
+ p = (char) stbi__get8(s);
+ t = (char) stbi__get8(s);
+ if (p != 'P' || (t != '5' && t != '6')) {
+ stbi__rewind(s);
+ return 0;
+ }
+
+ *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm
+
+ c = (char) stbi__get8(s);
+ stbi__pnm_skip_whitespace(s, &c);
+
+ *x = stbi__pnm_getinteger(s, &c); // read width
+ if(*x == 0)
+ return stbi__err("invalid width", "PPM image header had zero or overflowing width");
+ stbi__pnm_skip_whitespace(s, &c);
+
+ *y = stbi__pnm_getinteger(s, &c); // read height
+ if (*y == 0)
+ return stbi__err("invalid width", "PPM image header had zero or overflowing width");
+ stbi__pnm_skip_whitespace(s, &c);
+
+ maxv = stbi__pnm_getinteger(s, &c); // read max value
+ if (maxv > 65535)
+ return stbi__err("max value > 65535", "PPM image supports only 8-bit and 16-bit images");
+ else if (maxv > 255)
+ return 16;
+ else
+ return 8;
+}
+
+static int stbi__pnm_is16(stbi__context *s)
+{
+ if (stbi__pnm_info(s, NULL, NULL, NULL) == 16)
+ return 1;
+ return 0;
+}
+#endif
+
+static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp)
+{
+ #ifndef STBI_NO_JPEG
+ if (stbi__jpeg_info(s, x, y, comp)) return 1;
+ #endif
+
+ #ifndef STBI_NO_PNG
+ if (stbi__png_info(s, x, y, comp)) return 1;
+ #endif
+
+ #ifndef STBI_NO_GIF
+ if (stbi__gif_info(s, x, y, comp)) return 1;
+ #endif
+
+ #ifndef STBI_NO_BMP
+ if (stbi__bmp_info(s, x, y, comp)) return 1;
+ #endif
+
+ #ifndef STBI_NO_PSD
+ if (stbi__psd_info(s, x, y, comp)) return 1;
+ #endif
+
+ #ifndef STBI_NO_PIC
+ if (stbi__pic_info(s, x, y, comp)) return 1;
+ #endif
+
+ #ifndef STBI_NO_PNM
+ if (stbi__pnm_info(s, x, y, comp)) return 1;
+ #endif
+
+ #ifndef STBI_NO_HDR
+ if (stbi__hdr_info(s, x, y, comp)) return 1;
+ #endif
+
+ // test tga last because it's a crappy test!
+ #ifndef STBI_NO_TGA
+ if (stbi__tga_info(s, x, y, comp))
+ return 1;
+ #endif
+ return stbi__err("unknown image type", "Image not of any known type, or corrupt");
+}
+
+static int stbi__is_16_main(stbi__context *s)
+{
+ #ifndef STBI_NO_PNG
+ if (stbi__png_is16(s)) return 1;
+ #endif
+
+ #ifndef STBI_NO_PSD
+ if (stbi__psd_is16(s)) return 1;
+ #endif
+
+ #ifndef STBI_NO_PNM
+ if (stbi__pnm_is16(s)) return 1;
+ #endif
+ return 0;
+}
+
+#ifndef STBI_NO_STDIO
+STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp)
+{
+ FILE *f = stbi__fopen(filename, "rb");
+ int result;
+ if (!f) return stbi__err("can't fopen", "Unable to open file");
+ result = stbi_info_from_file(f, x, y, comp);
+ fclose(f);
+ return result;
+}
+
+STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp)
+{
+ int r;
+ stbi__context s;
+ long pos = ftell(f);
+ stbi__start_file(&s, f);
+ r = stbi__info_main(&s,x,y,comp);
+ fseek(f,pos,SEEK_SET);
+ return r;
+}
+
+STBIDEF int stbi_is_16_bit(char const *filename)
+{
+ FILE *f = stbi__fopen(filename, "rb");
+ int result;
+ if (!f) return stbi__err("can't fopen", "Unable to open file");
+ result = stbi_is_16_bit_from_file(f);
+ fclose(f);
+ return result;
+}
+
+STBIDEF int stbi_is_16_bit_from_file(FILE *f)
+{
+ int r;
+ stbi__context s;
+ long pos = ftell(f);
+ stbi__start_file(&s, f);
+ r = stbi__is_16_main(&s);
+ fseek(f,pos,SEEK_SET);
+ return r;
+}
+#endif // !STBI_NO_STDIO
+
+STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp)
+{
+ stbi__context s;
+ stbi__start_mem(&s,buffer,len);
+ return stbi__info_main(&s,x,y,comp);
+}
+
+STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp)
+{
+ stbi__context s;
+ stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user);
+ return stbi__info_main(&s,x,y,comp);
+}
+
+STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len)
+{
+ stbi__context s;
+ stbi__start_mem(&s,buffer,len);
+ return stbi__is_16_main(&s);
+}
+
+STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user)
+{
+ stbi__context s;
+ stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user);
+ return stbi__is_16_main(&s);
+}
+
+#endif // STB_IMAGE_IMPLEMENTATION
+
+/*
+ revision history:
+ 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs
+ 2.19 (2018-02-11) fix warning
+ 2.18 (2018-01-30) fix warnings
+ 2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug
+ 1-bit BMP
+ *_is_16_bit api
+ avoid warnings
+ 2.16 (2017-07-23) all functions have 16-bit variants;
+ STBI_NO_STDIO works again;
+ compilation fixes;
+ fix rounding in unpremultiply;
+ optimize vertical flip;
+ disable raw_len validation;
+ documentation fixes
+ 2.15 (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode;
+ warning fixes; disable run-time SSE detection on gcc;
+ uniform handling of optional "return" values;
+ thread-safe initialization of zlib tables
+ 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs
+ 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now
+ 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes
+ 2.11 (2016-04-02) allocate large structures on the stack
+ remove white matting for transparent PSD
+ fix reported channel count for PNG & BMP
+ re-enable SSE2 in non-gcc 64-bit
+ support RGB-formatted JPEG
+ read 16-bit PNGs (only as 8-bit)
+ 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED
+ 2.09 (2016-01-16) allow comments in PNM files
+ 16-bit-per-pixel TGA (not bit-per-component)
+ info() for TGA could break due to .hdr handling
+ info() for BMP to shares code instead of sloppy parse
+ can use STBI_REALLOC_SIZED if allocator doesn't support realloc
+ code cleanup
+ 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA
+ 2.07 (2015-09-13) fix compiler warnings
+ partial animated GIF support
+ limited 16-bpc PSD support
+ #ifdef unused functions
+ bug with < 92 byte PIC,PNM,HDR,TGA
+ 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value
+ 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning
+ 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit
+ 2.03 (2015-04-12) extra corruption checking (mmozeiko)
+ stbi_set_flip_vertically_on_load (nguillemot)
+ fix NEON support; fix mingw support
+ 2.02 (2015-01-19) fix incorrect assert, fix warning
+ 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2
+ 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG
+ 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg)
+ progressive JPEG (stb)
+ PGM/PPM support (Ken Miller)
+ STBI_MALLOC,STBI_REALLOC,STBI_FREE
+ GIF bugfix -- seemingly never worked
+ STBI_NO_*, STBI_ONLY_*
+ 1.48 (2014-12-14) fix incorrectly-named assert()
+ 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb)
+ optimize PNG (ryg)
+ fix bug in interlaced PNG with user-specified channel count (stb)
+ 1.46 (2014-08-26)
+ fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG
+ 1.45 (2014-08-16)
+ fix MSVC-ARM internal compiler error by wrapping malloc
+ 1.44 (2014-08-07)
+ various warning fixes from Ronny Chevalier
+ 1.43 (2014-07-15)
+ fix MSVC-only compiler problem in code changed in 1.42
+ 1.42 (2014-07-09)
+ don't define _CRT_SECURE_NO_WARNINGS (affects user code)
+ fixes to stbi__cleanup_jpeg path
+ added STBI_ASSERT to avoid requiring assert.h
+ 1.41 (2014-06-25)
+ fix search&replace from 1.36 that messed up comments/error messages
+ 1.40 (2014-06-22)
+ fix gcc struct-initialization warning
+ 1.39 (2014-06-15)
+ fix to TGA optimization when req_comp != number of components in TGA;
+ fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite)
+ add support for BMP version 5 (more ignored fields)
+ 1.38 (2014-06-06)
+ suppress MSVC warnings on integer casts truncating values
+ fix accidental rename of 'skip' field of I/O
+ 1.37 (2014-06-04)
+ remove duplicate typedef
+ 1.36 (2014-06-03)
+ convert to header file single-file library
+ if de-iphone isn't set, load iphone images color-swapped instead of returning NULL
+ 1.35 (2014-05-27)
+ various warnings
+ fix broken STBI_SIMD path
+ fix bug where stbi_load_from_file no longer left file pointer in correct place
+ fix broken non-easy path for 32-bit BMP (possibly never used)
+ TGA optimization by Arseny Kapoulkine
+ 1.34 (unknown)
+ use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case
+ 1.33 (2011-07-14)
+ make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements
+ 1.32 (2011-07-13)
+ support for "info" function for all supported filetypes (SpartanJ)
+ 1.31 (2011-06-20)
+ a few more leak fixes, bug in PNG handling (SpartanJ)
+ 1.30 (2011-06-11)
+ added ability to load files via callbacks to accomidate custom input streams (Ben Wenger)
+ removed deprecated format-specific test/load functions
+ removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway
+ error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha)
+ fix inefficiency in decoding 32-bit BMP (David Woo)
+ 1.29 (2010-08-16)
+ various warning fixes from Aurelien Pocheville
+ 1.28 (2010-08-01)
+ fix bug in GIF palette transparency (SpartanJ)
+ 1.27 (2010-08-01)
+ cast-to-stbi_uc to fix warnings
+ 1.26 (2010-07-24)
+ fix bug in file buffering for PNG reported by SpartanJ
+ 1.25 (2010-07-17)
+ refix trans_data warning (Won Chun)
+ 1.24 (2010-07-12)
+ perf improvements reading from files on platforms with lock-heavy fgetc()
+ minor perf improvements for jpeg
+ deprecated type-specific functions so we'll get feedback if they're needed
+ attempt to fix trans_data warning (Won Chun)
+ 1.23 fixed bug in iPhone support
+ 1.22 (2010-07-10)
+ removed image *writing* support
+ stbi_info support from Jetro Lauha
+ GIF support from Jean-Marc Lienher
+ iPhone PNG-extensions from James Brown
+ warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva)
+ 1.21 fix use of 'stbi_uc' in header (reported by jon blow)
+ 1.20 added support for Softimage PIC, by Tom Seddon
+ 1.19 bug in interlaced PNG corruption check (found by ryg)
+ 1.18 (2008-08-02)
+ fix a threading bug (local mutable static)
+ 1.17 support interlaced PNG
+ 1.16 major bugfix - stbi__convert_format converted one too many pixels
+ 1.15 initialize some fields for thread safety
+ 1.14 fix threadsafe conversion bug
+ header-file-only version (#define STBI_HEADER_FILE_ONLY before including)
+ 1.13 threadsafe
+ 1.12 const qualifiers in the API
+ 1.11 Support installable IDCT, colorspace conversion routines
+ 1.10 Fixes for 64-bit (don't use "unsigned long")
+ optimized upsampling by Fabian "ryg" Giesen
+ 1.09 Fix format-conversion for PSD code (bad global variables!)
+ 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz
+ 1.07 attempt to fix C++ warning/errors again
+ 1.06 attempt to fix C++ warning/errors again
+ 1.05 fix TGA loading to return correct *comp and use good luminance calc
+ 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free
+ 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR
+ 1.02 support for (subset of) HDR files, float interface for preferred access to them
+ 1.01 fix bug: possible bug in handling right-side up bmps... not sure
+ fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all
+ 1.00 interface to zlib that skips zlib header
+ 0.99 correct handling of alpha in palette
+ 0.98 TGA loader by lonesock; dynamically add loaders (untested)
+ 0.97 jpeg errors on too large a file; also catch another malloc failure
+ 0.96 fix detection of invalid v value - particleman@mollyrocket forum
+ 0.95 during header scan, seek to markers in case of padding
+ 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same
+ 0.93 handle jpegtran output; verbose errors
+ 0.92 read 4,8,16,24,32-bit BMP files of several formats
+ 0.91 output 24-bit Windows 3.0 BMP files
+ 0.90 fix a few more warnings; bump version number to approach 1.0
+ 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd
+ 0.60 fix compiling as c++
+ 0.59 fix warnings: merge Dave Moore's -Wall fixes
+ 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian
+ 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available
+ 0.56 fix bug: zlib uncompressed mode len vs. nlen
+ 0.55 fix bug: restart_interval not initialized to 0
+ 0.54 allow NULL for 'int *comp'
+ 0.53 fix bug in png 3->4; speedup png decoding
+ 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments
+ 0.51 obey req_comp requests, 1-component jpegs return as 1-component,
+ on 'test' only check type, not whether we support this variant
+ 0.50 (2006-11-19)
+ first released version
+*/
+
+
+/*
+------------------------------------------------------------------------------
+This software is available under 2 licenses -- choose whichever you prefer.
+------------------------------------------------------------------------------
+ALTERNATIVE A - MIT License
+Copyright (c) 2017 Sean Barrett
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+------------------------------------------------------------------------------
+ALTERNATIVE B - Public Domain (www.unlicense.org)
+This is free and unencumbered software released into the public domain.
+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
+software, either in source code form or as a compiled binary, for any purpose,
+commercial or non-commercial, and by any means.
+In jurisdictions that recognize copyright laws, the author or authors of this
+software dedicate any and all copyright interest in the software to the public
+domain. We make this dedication for the benefit of the public at large and to
+the detriment of our heirs and successors. We intend this dedication to be an
+overt act of relinquishment in perpetuity of all present and future rights to
+this software under copyright law.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+------------------------------------------------------------------------------
+*/
diff --git a/nn2/src/stb_image_write.h b/nn2/src/stb_image_write.h
new file mode 100644
index 0000000..e4b32ed
--- /dev/null
+++ b/nn2/src/stb_image_write.h
@@ -0,0 +1,1724 @@
+/* stb_image_write - v1.16 - public domain - http://nothings.org/stb
+ writes out PNG/BMP/TGA/JPEG/HDR images to C stdio - Sean Barrett 2010-2015
+ no warranty implied; use at your own risk
+
+ Before #including,
+
+ #define STB_IMAGE_WRITE_IMPLEMENTATION
+
+ in the file that you want to have the implementation.
+
+ Will probably not work correctly with strict-aliasing optimizations.
+
+ABOUT:
+
+ This header file is a library for writing images to C stdio or a callback.
+
+ The PNG output is not optimal; it is 20-50% larger than the file
+ written by a decent optimizing implementation; though providing a custom
+ zlib compress function (see STBIW_ZLIB_COMPRESS) can mitigate that.
+ This library is designed for source code compactness and simplicity,
+ not optimal image file size or run-time performance.
+
+BUILDING:
+
+ You can #define STBIW_ASSERT(x) before the #include to avoid using assert.h.
+ You can #define STBIW_MALLOC(), STBIW_REALLOC(), and STBIW_FREE() to replace
+ malloc,realloc,free.
+ You can #define STBIW_MEMMOVE() to replace memmove()
+ You can #define STBIW_ZLIB_COMPRESS to use a custom zlib-style compress function
+ for PNG compression (instead of the builtin one), it must have the following signature:
+ unsigned char * my_compress(unsigned char *data, int data_len, int *out_len, int quality);
+ The returned data will be freed with STBIW_FREE() (free() by default),
+ so it must be heap allocated with STBIW_MALLOC() (malloc() by default),
+
+UNICODE:
+
+ If compiling for Windows and you wish to use Unicode filenames, compile
+ with
+ #define STBIW_WINDOWS_UTF8
+ and pass utf8-encoded filenames. Call stbiw_convert_wchar_to_utf8 to convert
+ Windows wchar_t filenames to utf8.
+
+USAGE:
+
+ There are five functions, one for each image file format:
+
+ int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes);
+ int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data);
+ int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data);
+ int stbi_write_jpg(char const *filename, int w, int h, int comp, const void *data, int quality);
+ int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data);
+
+ void stbi_flip_vertically_on_write(int flag); // flag is non-zero to flip data vertically
+
+ There are also five equivalent functions that use an arbitrary write function. You are
+ expected to open/close your file-equivalent before and after calling these:
+
+ int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes);
+ int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data);
+ int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data);
+ int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data);
+ int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality);
+
+ where the callback is:
+ void stbi_write_func(void *context, void *data, int size);
+
+ You can configure it with these global variables:
+ int stbi_write_tga_with_rle; // defaults to true; set to 0 to disable RLE
+ int stbi_write_png_compression_level; // defaults to 8; set to higher for more compression
+ int stbi_write_force_png_filter; // defaults to -1; set to 0..5 to force a filter mode
+
+
+ You can define STBI_WRITE_NO_STDIO to disable the file variant of these
+ functions, so the library will not use stdio.h at all. However, this will
+ also disable HDR writing, because it requires stdio for formatted output.
+
+ Each function returns 0 on failure and non-0 on success.
+
+ The functions create an image file defined by the parameters. The image
+ is a rectangle of pixels stored from left-to-right, top-to-bottom.
+ Each pixel contains 'comp' channels of data stored interleaved with 8-bits
+ per channel, in the following order: 1=Y, 2=YA, 3=RGB, 4=RGBA. (Y is
+ monochrome color.) The rectangle is 'w' pixels wide and 'h' pixels tall.
+ The *data pointer points to the first byte of the top-left-most pixel.
+ For PNG, "stride_in_bytes" is the distance in bytes from the first byte of
+ a row of pixels to the first byte of the next row of pixels.
+
+ PNG creates output files with the same number of components as the input.
+ The BMP format expands Y to RGB in the file format and does not
+ output alpha.
+
+ PNG supports writing rectangles of data even when the bytes storing rows of
+ data are not consecutive in memory (e.g. sub-rectangles of a larger image),
+ by supplying the stride between the beginning of adjacent rows. The other
+ formats do not. (Thus you cannot write a native-format BMP through the BMP
+ writer, both because it is in BGR order and because it may have padding
+ at the end of the line.)
+
+ PNG allows you to set the deflate compression level by setting the global
+ variable 'stbi_write_png_compression_level' (it defaults to 8).
+
+ HDR expects linear float data. Since the format is always 32-bit rgb(e)
+ data, alpha (if provided) is discarded, and for monochrome data it is
+ replicated across all three channels.
+
+ TGA supports RLE or non-RLE compressed data. To use non-RLE-compressed
+ data, set the global variable 'stbi_write_tga_with_rle' to 0.
+
+ JPEG does ignore alpha channels in input data; quality is between 1 and 100.
+ Higher quality looks better but results in a bigger image.
+ JPEG baseline (no JPEG progressive).
+
+CREDITS:
+
+
+ Sean Barrett - PNG/BMP/TGA
+ Baldur Karlsson - HDR
+ Jean-Sebastien Guay - TGA monochrome
+ Tim Kelsey - misc enhancements
+ Alan Hickman - TGA RLE
+ Emmanuel Julien - initial file IO callback implementation
+ Jon Olick - original jo_jpeg.cpp code
+ Daniel Gibson - integrate JPEG, allow external zlib
+ Aarni Koskela - allow choosing PNG filter
+
+ bugfixes:
+ github:Chribba
+ Guillaume Chereau
+ github:jry2
+ github:romigrou
+ Sergio Gonzalez
+ Jonas Karlsson
+ Filip Wasil
+ Thatcher Ulrich
+ github:poppolopoppo
+ Patrick Boettcher
+ github:xeekworx
+ Cap Petschulat
+ Simon Rodriguez
+ Ivan Tikhonov
+ github:ignotion
+ Adam Schackart
+ Andrew Kensler
+
+LICENSE
+
+ See end of file for license information.
+
+*/
+
+#ifndef INCLUDE_STB_IMAGE_WRITE_H
+#define INCLUDE_STB_IMAGE_WRITE_H
+
+#include <stdlib.h>
+
+// if STB_IMAGE_WRITE_STATIC causes problems, try defining STBIWDEF to 'inline' or 'static inline'
+#ifndef STBIWDEF
+#ifdef STB_IMAGE_WRITE_STATIC
+#define STBIWDEF static
+#else
+#ifdef __cplusplus
+#define STBIWDEF extern "C"
+#else
+#define STBIWDEF extern
+#endif
+#endif
+#endif
+
+#ifndef STB_IMAGE_WRITE_STATIC // C++ forbids static forward declarations
+STBIWDEF int stbi_write_tga_with_rle;
+STBIWDEF int stbi_write_png_compression_level;
+STBIWDEF int stbi_write_force_png_filter;
+#endif
+
+#ifndef STBI_WRITE_NO_STDIO
+STBIWDEF int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes);
+STBIWDEF int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data);
+STBIWDEF int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data);
+STBIWDEF int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data);
+STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality);
+
+#ifdef STBIW_WINDOWS_UTF8
+STBIWDEF int stbiw_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input);
+#endif
+#endif
+
+typedef void stbi_write_func(void *context, void *data, int size);
+
+STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes);
+STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data);
+STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data);
+STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data);
+STBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality);
+
+STBIWDEF void stbi_flip_vertically_on_write(int flip_boolean);
+
+#endif//INCLUDE_STB_IMAGE_WRITE_H
+
+#ifdef STB_IMAGE_WRITE_IMPLEMENTATION
+
+#ifdef _WIN32
+ #ifndef _CRT_SECURE_NO_WARNINGS
+ #define _CRT_SECURE_NO_WARNINGS
+ #endif
+ #ifndef _CRT_NONSTDC_NO_DEPRECATE
+ #define _CRT_NONSTDC_NO_DEPRECATE
+ #endif
+#endif
+
+#ifndef STBI_WRITE_NO_STDIO
+#include <stdio.h>
+#endif // STBI_WRITE_NO_STDIO
+
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+
+#if defined(STBIW_MALLOC) && defined(STBIW_FREE) && (defined(STBIW_REALLOC) || defined(STBIW_REALLOC_SIZED))
+// ok
+#elif !defined(STBIW_MALLOC) && !defined(STBIW_FREE) && !defined(STBIW_REALLOC) && !defined(STBIW_REALLOC_SIZED)
+// ok
+#else
+#error "Must define all or none of STBIW_MALLOC, STBIW_FREE, and STBIW_REALLOC (or STBIW_REALLOC_SIZED)."
+#endif
+
+#ifndef STBIW_MALLOC
+#define STBIW_MALLOC(sz) malloc(sz)
+#define STBIW_REALLOC(p,newsz) realloc(p,newsz)
+#define STBIW_FREE(p) free(p)
+#endif
+
+#ifndef STBIW_REALLOC_SIZED
+#define STBIW_REALLOC_SIZED(p,oldsz,newsz) STBIW_REALLOC(p,newsz)
+#endif
+
+
+#ifndef STBIW_MEMMOVE
+#define STBIW_MEMMOVE(a,b,sz) memmove(a,b,sz)
+#endif
+
+
+#ifndef STBIW_ASSERT
+#include <assert.h>
+#define STBIW_ASSERT(x) assert(x)
+#endif
+
+#define STBIW_UCHAR(x) (unsigned char) ((x) & 0xff)
+
+#ifdef STB_IMAGE_WRITE_STATIC
+static int stbi_write_png_compression_level = 8;
+static int stbi_write_tga_with_rle = 1;
+static int stbi_write_force_png_filter = -1;
+#else
+int stbi_write_png_compression_level = 8;
+int stbi_write_tga_with_rle = 1;
+int stbi_write_force_png_filter = -1;
+#endif
+
+static int stbi__flip_vertically_on_write = 0;
+
+STBIWDEF void stbi_flip_vertically_on_write(int flag)
+{
+ stbi__flip_vertically_on_write = flag;
+}
+
+typedef struct
+{
+ stbi_write_func *func;
+ void *context;
+ unsigned char buffer[64];
+ int buf_used;
+} stbi__write_context;
+
+// initialize a callback-based context
+static void stbi__start_write_callbacks(stbi__write_context *s, stbi_write_func *c, void *context)
+{
+ s->func = c;
+ s->context = context;
+}
+
+#ifndef STBI_WRITE_NO_STDIO
+
+static void stbi__stdio_write(void *context, void *data, int size)
+{
+ fwrite(data,1,size,(FILE*) context);
+}
+
+#if defined(_WIN32) && defined(STBIW_WINDOWS_UTF8)
+#ifdef __cplusplus
+#define STBIW_EXTERN extern "C"
+#else
+#define STBIW_EXTERN extern
+#endif
+STBIW_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide);
+STBIW_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default);
+
+STBIWDEF int stbiw_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input)
+{
+ return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL);
+}
+#endif
+
+static FILE *stbiw__fopen(char const *filename, char const *mode)
+{
+ FILE *f;
+#if defined(_WIN32) && defined(STBIW_WINDOWS_UTF8)
+ wchar_t wMode[64];
+ wchar_t wFilename[1024];
+ if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename)))
+ return 0;
+
+ if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode)))
+ return 0;
+
+#if defined(_MSC_VER) && _MSC_VER >= 1400
+ if (0 != _wfopen_s(&f, wFilename, wMode))
+ f = 0;
+#else
+ f = _wfopen(wFilename, wMode);
+#endif
+
+#elif defined(_MSC_VER) && _MSC_VER >= 1400
+ if (0 != fopen_s(&f, filename, mode))
+ f=0;
+#else
+ f = fopen(filename, mode);
+#endif
+ return f;
+}
+
+static int stbi__start_write_file(stbi__write_context *s, const char *filename)
+{
+ FILE *f = stbiw__fopen(filename, "wb");
+ stbi__start_write_callbacks(s, stbi__stdio_write, (void *) f);
+ return f != NULL;
+}
+
+static void stbi__end_write_file(stbi__write_context *s)
+{
+ fclose((FILE *)s->context);
+}
+
+#endif // !STBI_WRITE_NO_STDIO
+
+typedef unsigned int stbiw_uint32;
+typedef int stb_image_write_test[sizeof(stbiw_uint32)==4 ? 1 : -1];
+
+static void stbiw__writefv(stbi__write_context *s, const char *fmt, va_list v)
+{
+ while (*fmt) {
+ switch (*fmt++) {
+ case ' ': break;
+ case '1': { unsigned char x = STBIW_UCHAR(va_arg(v, int));
+ s->func(s->context,&x,1);
+ break; }
+ case '2': { int x = va_arg(v,int);
+ unsigned char b[2];
+ b[0] = STBIW_UCHAR(x);
+ b[1] = STBIW_UCHAR(x>>8);
+ s->func(s->context,b,2);
+ break; }
+ case '4': { stbiw_uint32 x = va_arg(v,int);
+ unsigned char b[4];
+ b[0]=STBIW_UCHAR(x);
+ b[1]=STBIW_UCHAR(x>>8);
+ b[2]=STBIW_UCHAR(x>>16);
+ b[3]=STBIW_UCHAR(x>>24);
+ s->func(s->context,b,4);
+ break; }
+ default:
+ STBIW_ASSERT(0);
+ return;
+ }
+ }
+}
+
+static void stbiw__writef(stbi__write_context *s, const char *fmt, ...)
+{
+ va_list v;
+ va_start(v, fmt);
+ stbiw__writefv(s, fmt, v);
+ va_end(v);
+}
+
+static void stbiw__write_flush(stbi__write_context *s)
+{
+ if (s->buf_used) {
+ s->func(s->context, &s->buffer, s->buf_used);
+ s->buf_used = 0;
+ }
+}
+
+static void stbiw__putc(stbi__write_context *s, unsigned char c)
+{
+ s->func(s->context, &c, 1);
+}
+
+static void stbiw__write1(stbi__write_context *s, unsigned char a)
+{
+ if ((size_t)s->buf_used + 1 > sizeof(s->buffer))
+ stbiw__write_flush(s);
+ s->buffer[s->buf_used++] = a;
+}
+
+static void stbiw__write3(stbi__write_context *s, unsigned char a, unsigned char b, unsigned char c)
+{
+ int n;
+ if ((size_t)s->buf_used + 3 > sizeof(s->buffer))
+ stbiw__write_flush(s);
+ n = s->buf_used;
+ s->buf_used = n+3;
+ s->buffer[n+0] = a;
+ s->buffer[n+1] = b;
+ s->buffer[n+2] = c;
+}
+
+static void stbiw__write_pixel(stbi__write_context *s, int rgb_dir, int comp, int write_alpha, int expand_mono, unsigned char *d)
+{
+ unsigned char bg[3] = { 255, 0, 255}, px[3];
+ int k;
+
+ if (write_alpha < 0)
+ stbiw__write1(s, d[comp - 1]);
+
+ switch (comp) {
+ case 2: // 2 pixels = mono + alpha, alpha is written separately, so same as 1-channel case
+ case 1:
+ if (expand_mono)
+ stbiw__write3(s, d[0], d[0], d[0]); // monochrome bmp
+ else
+ stbiw__write1(s, d[0]); // monochrome TGA
+ break;
+ case 4:
+ if (!write_alpha) {
+ // composite against pink background
+ for (k = 0; k < 3; ++k)
+ px[k] = bg[k] + ((d[k] - bg[k]) * d[3]) / 255;
+ stbiw__write3(s, px[1 - rgb_dir], px[1], px[1 + rgb_dir]);
+ break;
+ }
+ /* FALLTHROUGH */
+ case 3:
+ stbiw__write3(s, d[1 - rgb_dir], d[1], d[1 + rgb_dir]);
+ break;
+ }
+ if (write_alpha > 0)
+ stbiw__write1(s, d[comp - 1]);
+}
+
+static void stbiw__write_pixels(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad, int expand_mono)
+{
+ stbiw_uint32 zero = 0;
+ int i,j, j_end;
+
+ if (y <= 0)
+ return;
+
+ if (stbi__flip_vertically_on_write)
+ vdir *= -1;
+
+ if (vdir < 0) {
+ j_end = -1; j = y-1;
+ } else {
+ j_end = y; j = 0;
+ }
+
+ for (; j != j_end; j += vdir) {
+ for (i=0; i < x; ++i) {
+ unsigned char *d = (unsigned char *) data + (j*x+i)*comp;
+ stbiw__write_pixel(s, rgb_dir, comp, write_alpha, expand_mono, d);
+ }
+ stbiw__write_flush(s);
+ s->func(s->context, &zero, scanline_pad);
+ }
+}
+
+static int stbiw__outfile(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, int expand_mono, void *data, int alpha, int pad, const char *fmt, ...)
+{
+ if (y < 0 || x < 0) {
+ return 0;
+ } else {
+ va_list v;
+ va_start(v, fmt);
+ stbiw__writefv(s, fmt, v);
+ va_end(v);
+ stbiw__write_pixels(s,rgb_dir,vdir,x,y,comp,data,alpha,pad, expand_mono);
+ return 1;
+ }
+}
+
+static int stbi_write_bmp_core(stbi__write_context *s, int x, int y, int comp, const void *data)
+{
+ if (comp != 4) {
+ // write RGB bitmap
+ int pad = (-x*3) & 3;
+ return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *) data,0,pad,
+ "11 4 22 4" "4 44 22 444444",
+ 'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40, // file header
+ 40, x,y, 1,24, 0,0,0,0,0,0); // bitmap header
+ } else {
+ // RGBA bitmaps need a v4 header
+ // use BI_BITFIELDS mode with 32bpp and alpha mask
+ // (straight BI_RGB with alpha mask doesn't work in most readers)
+ return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *)data,1,0,
+ "11 4 22 4" "4 44 22 444444 4444 4 444 444 444 444",
+ 'B', 'M', 14+108+x*y*4, 0, 0, 14+108, // file header
+ 108, x,y, 1,32, 3,0,0,0,0,0, 0xff0000,0xff00,0xff,0xff000000u, 0, 0,0,0, 0,0,0, 0,0,0, 0,0,0); // bitmap V4 header
+ }
+}
+
+STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data)
+{
+ stbi__write_context s = { 0 };
+ stbi__start_write_callbacks(&s, func, context);
+ return stbi_write_bmp_core(&s, x, y, comp, data);
+}
+
+#ifndef STBI_WRITE_NO_STDIO
+STBIWDEF int stbi_write_bmp(char const *filename, int x, int y, int comp, const void *data)
+{
+ stbi__write_context s = { 0 };
+ if (stbi__start_write_file(&s,filename)) {
+ int r = stbi_write_bmp_core(&s, x, y, comp, data);
+ stbi__end_write_file(&s);
+ return r;
+ } else
+ return 0;
+}
+#endif //!STBI_WRITE_NO_STDIO
+
+static int stbi_write_tga_core(stbi__write_context *s, int x, int y, int comp, void *data)
+{
+ int has_alpha = (comp == 2 || comp == 4);
+ int colorbytes = has_alpha ? comp-1 : comp;
+ int format = colorbytes < 2 ? 3 : 2; // 3 color channels (RGB/RGBA) = 2, 1 color channel (Y/YA) = 3
+
+ if (y < 0 || x < 0)
+ return 0;
+
+ if (!stbi_write_tga_with_rle) {
+ return stbiw__outfile(s, -1, -1, x, y, comp, 0, (void *) data, has_alpha, 0,
+ "111 221 2222 11", 0, 0, format, 0, 0, 0, 0, 0, x, y, (colorbytes + has_alpha) * 8, has_alpha * 8);
+ } else {
+ int i,j,k;
+ int jend, jdir;
+
+ stbiw__writef(s, "111 221 2222 11", 0,0,format+8, 0,0,0, 0,0,x,y, (colorbytes + has_alpha) * 8, has_alpha * 8);
+
+ if (stbi__flip_vertically_on_write) {
+ j = 0;
+ jend = y;
+ jdir = 1;
+ } else {
+ j = y-1;
+ jend = -1;
+ jdir = -1;
+ }
+ for (; j != jend; j += jdir) {
+ unsigned char *row = (unsigned char *) data + j * x * comp;
+ int len;
+
+ for (i = 0; i < x; i += len) {
+ unsigned char *begin = row + i * comp;
+ int diff = 1;
+ len = 1;
+
+ if (i < x - 1) {
+ ++len;
+ diff = memcmp(begin, row + (i + 1) * comp, comp);
+ if (diff) {
+ const unsigned char *prev = begin;
+ for (k = i + 2; k < x && len < 128; ++k) {
+ if (memcmp(prev, row + k * comp, comp)) {
+ prev += comp;
+ ++len;
+ } else {
+ --len;
+ break;
+ }
+ }
+ } else {
+ for (k = i + 2; k < x && len < 128; ++k) {
+ if (!memcmp(begin, row + k * comp, comp)) {
+ ++len;
+ } else {
+ break;
+ }
+ }
+ }
+ }
+
+ if (diff) {
+ unsigned char header = STBIW_UCHAR(len - 1);
+ stbiw__write1(s, header);
+ for (k = 0; k < len; ++k) {
+ stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin + k * comp);
+ }
+ } else {
+ unsigned char header = STBIW_UCHAR(len - 129);
+ stbiw__write1(s, header);
+ stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin);
+ }
+ }
+ }
+ stbiw__write_flush(s);
+ }
+ return 1;
+}
+
+STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data)
+{
+ stbi__write_context s = { 0 };
+ stbi__start_write_callbacks(&s, func, context);
+ return stbi_write_tga_core(&s, x, y, comp, (void *) data);
+}
+
+#ifndef STBI_WRITE_NO_STDIO
+STBIWDEF int stbi_write_tga(char const *filename, int x, int y, int comp, const void *data)
+{
+ stbi__write_context s = { 0 };
+ if (stbi__start_write_file(&s,filename)) {
+ int r = stbi_write_tga_core(&s, x, y, comp, (void *) data);
+ stbi__end_write_file(&s);
+ return r;
+ } else
+ return 0;
+}
+#endif
+
+// *************************************************************************************************
+// Radiance RGBE HDR writer
+// by Baldur Karlsson
+
+#define stbiw__max(a, b) ((a) > (b) ? (a) : (b))
+
+#ifndef STBI_WRITE_NO_STDIO
+
+static void stbiw__linear_to_rgbe(unsigned char *rgbe, float *linear)
+{
+ int exponent;
+ float maxcomp = stbiw__max(linear[0], stbiw__max(linear[1], linear[2]));
+
+ if (maxcomp < 1e-32f) {
+ rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0;
+ } else {
+ float normalize = (float) frexp(maxcomp, &exponent) * 256.0f/maxcomp;
+
+ rgbe[0] = (unsigned char)(linear[0] * normalize);
+ rgbe[1] = (unsigned char)(linear[1] * normalize);
+ rgbe[2] = (unsigned char)(linear[2] * normalize);
+ rgbe[3] = (unsigned char)(exponent + 128);
+ }
+}
+
+static void stbiw__write_run_data(stbi__write_context *s, int length, unsigned char databyte)
+{
+ unsigned char lengthbyte = STBIW_UCHAR(length+128);
+ STBIW_ASSERT(length+128 <= 255);
+ s->func(s->context, &lengthbyte, 1);
+ s->func(s->context, &databyte, 1);
+}
+
+static void stbiw__write_dump_data(stbi__write_context *s, int length, unsigned char *data)
+{
+ unsigned char lengthbyte = STBIW_UCHAR(length);
+ STBIW_ASSERT(length <= 128); // inconsistent with spec but consistent with official code
+ s->func(s->context, &lengthbyte, 1);
+ s->func(s->context, data, length);
+}
+
+static void stbiw__write_hdr_scanline(stbi__write_context *s, int width, int ncomp, unsigned char *scratch, float *scanline)
+{
+ unsigned char scanlineheader[4] = { 2, 2, 0, 0 };
+ unsigned char rgbe[4];
+ float linear[3];
+ int x;
+
+ scanlineheader[2] = (width&0xff00)>>8;
+ scanlineheader[3] = (width&0x00ff);
+
+ /* skip RLE for images too small or large */
+ if (width < 8 || width >= 32768) {
+ for (x=0; x < width; x++) {
+ switch (ncomp) {
+ case 4: /* fallthrough */
+ case 3: linear[2] = scanline[x*ncomp + 2];
+ linear[1] = scanline[x*ncomp + 1];
+ linear[0] = scanline[x*ncomp + 0];
+ break;
+ default:
+ linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0];
+ break;
+ }
+ stbiw__linear_to_rgbe(rgbe, linear);
+ s->func(s->context, rgbe, 4);
+ }
+ } else {
+ int c,r;
+ /* encode into scratch buffer */
+ for (x=0; x < width; x++) {
+ switch(ncomp) {
+ case 4: /* fallthrough */
+ case 3: linear[2] = scanline[x*ncomp + 2];
+ linear[1] = scanline[x*ncomp + 1];
+ linear[0] = scanline[x*ncomp + 0];
+ break;
+ default:
+ linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0];
+ break;
+ }
+ stbiw__linear_to_rgbe(rgbe, linear);
+ scratch[x + width*0] = rgbe[0];
+ scratch[x + width*1] = rgbe[1];
+ scratch[x + width*2] = rgbe[2];
+ scratch[x + width*3] = rgbe[3];
+ }
+
+ s->func(s->context, scanlineheader, 4);
+
+ /* RLE each component separately */
+ for (c=0; c < 4; c++) {
+ unsigned char *comp = &scratch[width*c];
+
+ x = 0;
+ while (x < width) {
+ // find first run
+ r = x;
+ while (r+2 < width) {
+ if (comp[r] == comp[r+1] && comp[r] == comp[r+2])
+ break;
+ ++r;
+ }
+ if (r+2 >= width)
+ r = width;
+ // dump up to first run
+ while (x < r) {
+ int len = r-x;
+ if (len > 128) len = 128;
+ stbiw__write_dump_data(s, len, &comp[x]);
+ x += len;
+ }
+ // if there's a run, output it
+ if (r+2 < width) { // same test as what we break out of in search loop, so only true if we break'd
+ // find next byte after run
+ while (r < width && comp[r] == comp[x])
+ ++r;
+ // output run up to r
+ while (x < r) {
+ int len = r-x;
+ if (len > 127) len = 127;
+ stbiw__write_run_data(s, len, comp[x]);
+ x += len;
+ }
+ }
+ }
+ }
+ }
+}
+
+static int stbi_write_hdr_core(stbi__write_context *s, int x, int y, int comp, float *data)
+{
+ if (y <= 0 || x <= 0 || data == NULL)
+ return 0;
+ else {
+ // Each component is stored separately. Allocate scratch space for full output scanline.
+ unsigned char *scratch = (unsigned char *) STBIW_MALLOC(x*4);
+ int i, len;
+ char buffer[128];
+ char header[] = "#?RADIANCE\n# Written by stb_image_write.h\nFORMAT=32-bit_rle_rgbe\n";
+ s->func(s->context, header, sizeof(header)-1);
+
+#ifdef __STDC_LIB_EXT1__
+ len = sprintf_s(buffer, sizeof(buffer), "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x);
+#else
+ len = sprintf(buffer, "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x);
+#endif
+ s->func(s->context, buffer, len);
+
+ for(i=0; i < y; i++)
+ stbiw__write_hdr_scanline(s, x, comp, scratch, data + comp*x*(stbi__flip_vertically_on_write ? y-1-i : i));
+ STBIW_FREE(scratch);
+ return 1;
+ }
+}
+
+STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const float *data)
+{
+ stbi__write_context s = { 0 };
+ stbi__start_write_callbacks(&s, func, context);
+ return stbi_write_hdr_core(&s, x, y, comp, (float *) data);
+}
+
+STBIWDEF int stbi_write_hdr(char const *filename, int x, int y, int comp, const float *data)
+{
+ stbi__write_context s = { 0 };
+ if (stbi__start_write_file(&s,filename)) {
+ int r = stbi_write_hdr_core(&s, x, y, comp, (float *) data);
+ stbi__end_write_file(&s);
+ return r;
+ } else
+ return 0;
+}
+#endif // STBI_WRITE_NO_STDIO
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// PNG writer
+//
+
+#ifndef STBIW_ZLIB_COMPRESS
+// stretchy buffer; stbiw__sbpush() == vector<>::push_back() -- stbiw__sbcount() == vector<>::size()
+#define stbiw__sbraw(a) ((int *) (void *) (a) - 2)
+#define stbiw__sbm(a) stbiw__sbraw(a)[0]
+#define stbiw__sbn(a) stbiw__sbraw(a)[1]
+
+#define stbiw__sbneedgrow(a,n) ((a)==0 || stbiw__sbn(a)+n >= stbiw__sbm(a))
+#define stbiw__sbmaybegrow(a,n) (stbiw__sbneedgrow(a,(n)) ? stbiw__sbgrow(a,n) : 0)
+#define stbiw__sbgrow(a,n) stbiw__sbgrowf((void **) &(a), (n), sizeof(*(a)))
+
+#define stbiw__sbpush(a, v) (stbiw__sbmaybegrow(a,1), (a)[stbiw__sbn(a)++] = (v))
+#define stbiw__sbcount(a) ((a) ? stbiw__sbn(a) : 0)
+#define stbiw__sbfree(a) ((a) ? STBIW_FREE(stbiw__sbraw(a)),0 : 0)
+
+static void *stbiw__sbgrowf(void **arr, int increment, int itemsize)
+{
+ int m = *arr ? 2*stbiw__sbm(*arr)+increment : increment+1;
+ void *p = STBIW_REALLOC_SIZED(*arr ? stbiw__sbraw(*arr) : 0, *arr ? (stbiw__sbm(*arr)*itemsize + sizeof(int)*2) : 0, itemsize * m + sizeof(int)*2);
+ STBIW_ASSERT(p);
+ if (p) {
+ if (!*arr) ((int *) p)[1] = 0;
+ *arr = (void *) ((int *) p + 2);
+ stbiw__sbm(*arr) = m;
+ }
+ return *arr;
+}
+
+static unsigned char *stbiw__zlib_flushf(unsigned char *data, unsigned int *bitbuffer, int *bitcount)
+{
+ while (*bitcount >= 8) {
+ stbiw__sbpush(data, STBIW_UCHAR(*bitbuffer));
+ *bitbuffer >>= 8;
+ *bitcount -= 8;
+ }
+ return data;
+}
+
+static int stbiw__zlib_bitrev(int code, int codebits)
+{
+ int res=0;
+ while (codebits--) {
+ res = (res << 1) | (code & 1);
+ code >>= 1;
+ }
+ return res;
+}
+
+static unsigned int stbiw__zlib_countm(unsigned char *a, unsigned char *b, int limit)
+{
+ int i;
+ for (i=0; i < limit && i < 258; ++i)
+ if (a[i] != b[i]) break;
+ return i;
+}
+
+static unsigned int stbiw__zhash(unsigned char *data)
+{
+ stbiw_uint32 hash = data[0] + (data[1] << 8) + (data[2] << 16);
+ hash ^= hash << 3;
+ hash += hash >> 5;
+ hash ^= hash << 4;
+ hash += hash >> 17;
+ hash ^= hash << 25;
+ hash += hash >> 6;
+ return hash;
+}
+
+#define stbiw__zlib_flush() (out = stbiw__zlib_flushf(out, &bitbuf, &bitcount))
+#define stbiw__zlib_add(code,codebits) \
+ (bitbuf |= (code) << bitcount, bitcount += (codebits), stbiw__zlib_flush())
+#define stbiw__zlib_huffa(b,c) stbiw__zlib_add(stbiw__zlib_bitrev(b,c),c)
+// default huffman tables
+#define stbiw__zlib_huff1(n) stbiw__zlib_huffa(0x30 + (n), 8)
+#define stbiw__zlib_huff2(n) stbiw__zlib_huffa(0x190 + (n)-144, 9)
+#define stbiw__zlib_huff3(n) stbiw__zlib_huffa(0 + (n)-256,7)
+#define stbiw__zlib_huff4(n) stbiw__zlib_huffa(0xc0 + (n)-280,8)
+#define stbiw__zlib_huff(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : (n) <= 255 ? stbiw__zlib_huff2(n) : (n) <= 279 ? stbiw__zlib_huff3(n) : stbiw__zlib_huff4(n))
+#define stbiw__zlib_huffb(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : stbiw__zlib_huff2(n))
+
+#define stbiw__ZHASH 16384
+
+#endif // STBIW_ZLIB_COMPRESS
+
+STBIWDEF unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality)
+{
+#ifdef STBIW_ZLIB_COMPRESS
+ // user provided a zlib compress implementation, use that
+ return STBIW_ZLIB_COMPRESS(data, data_len, out_len, quality);
+#else // use builtin
+ static unsigned short lengthc[] = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258, 259 };
+ static unsigned char lengtheb[]= { 0,0,0,0,0,0,0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 };
+ static unsigned short distc[] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577, 32768 };
+ static unsigned char disteb[] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 };
+ unsigned int bitbuf=0;
+ int i,j, bitcount=0;
+ unsigned char *out = NULL;
+ unsigned char ***hash_table = (unsigned char***) STBIW_MALLOC(stbiw__ZHASH * sizeof(unsigned char**));
+ if (hash_table == NULL)
+ return NULL;
+ if (quality < 5) quality = 5;
+
+ stbiw__sbpush(out, 0x78); // DEFLATE 32K window
+ stbiw__sbpush(out, 0x5e); // FLEVEL = 1
+ stbiw__zlib_add(1,1); // BFINAL = 1
+ stbiw__zlib_add(1,2); // BTYPE = 1 -- fixed huffman
+
+ for (i=0; i < stbiw__ZHASH; ++i)
+ hash_table[i] = NULL;
+
+ i=0;
+ while (i < data_len-3) {
+ // hash next 3 bytes of data to be compressed
+ int h = stbiw__zhash(data+i)&(stbiw__ZHASH-1), best=3;
+ unsigned char *bestloc = 0;
+ unsigned char **hlist = hash_table[h];
+ int n = stbiw__sbcount(hlist);
+ for (j=0; j < n; ++j) {
+ if (hlist[j]-data > i-32768) { // if entry lies within window
+ int d = stbiw__zlib_countm(hlist[j], data+i, data_len-i);
+ if (d >= best) { best=d; bestloc=hlist[j]; }
+ }
+ }
+ // when hash table entry is too long, delete half the entries
+ if (hash_table[h] && stbiw__sbn(hash_table[h]) == 2*quality) {
+ STBIW_MEMMOVE(hash_table[h], hash_table[h]+quality, sizeof(hash_table[h][0])*quality);
+ stbiw__sbn(hash_table[h]) = quality;
+ }
+ stbiw__sbpush(hash_table[h],data+i);
+
+ if (bestloc) {
+ // "lazy matching" - check match at *next* byte, and if it's better, do cur byte as literal
+ h = stbiw__zhash(data+i+1)&(stbiw__ZHASH-1);
+ hlist = hash_table[h];
+ n = stbiw__sbcount(hlist);
+ for (j=0; j < n; ++j) {
+ if (hlist[j]-data > i-32767) {
+ int e = stbiw__zlib_countm(hlist[j], data+i+1, data_len-i-1);
+ if (e > best) { // if next match is better, bail on current match
+ bestloc = NULL;
+ break;
+ }
+ }
+ }
+ }
+
+ if (bestloc) {
+ int d = (int) (data+i - bestloc); // distance back
+ STBIW_ASSERT(d <= 32767 && best <= 258);
+ for (j=0; best > lengthc[j+1]-1; ++j);
+ stbiw__zlib_huff(j+257);
+ if (lengtheb[j]) stbiw__zlib_add(best - lengthc[j], lengtheb[j]);
+ for (j=0; d > distc[j+1]-1; ++j);
+ stbiw__zlib_add(stbiw__zlib_bitrev(j,5),5);
+ if (disteb[j]) stbiw__zlib_add(d - distc[j], disteb[j]);
+ i += best;
+ } else {
+ stbiw__zlib_huffb(data[i]);
+ ++i;
+ }
+ }
+ // write out final bytes
+ for (;i < data_len; ++i)
+ stbiw__zlib_huffb(data[i]);
+ stbiw__zlib_huff(256); // end of block
+ // pad with 0 bits to byte boundary
+ while (bitcount)
+ stbiw__zlib_add(0,1);
+
+ for (i=0; i < stbiw__ZHASH; ++i)
+ (void) stbiw__sbfree(hash_table[i]);
+ STBIW_FREE(hash_table);
+
+ // store uncompressed instead if compression was worse
+ if (stbiw__sbn(out) > data_len + 2 + ((data_len+32766)/32767)*5) {
+ stbiw__sbn(out) = 2; // truncate to DEFLATE 32K window and FLEVEL = 1
+ for (j = 0; j < data_len;) {
+ int blocklen = data_len - j;
+ if (blocklen > 32767) blocklen = 32767;
+ stbiw__sbpush(out, data_len - j == blocklen); // BFINAL = ?, BTYPE = 0 -- no compression
+ stbiw__sbpush(out, STBIW_UCHAR(blocklen)); // LEN
+ stbiw__sbpush(out, STBIW_UCHAR(blocklen >> 8));
+ stbiw__sbpush(out, STBIW_UCHAR(~blocklen)); // NLEN
+ stbiw__sbpush(out, STBIW_UCHAR(~blocklen >> 8));
+ memcpy(out+stbiw__sbn(out), data+j, blocklen);
+ stbiw__sbn(out) += blocklen;
+ j += blocklen;
+ }
+ }
+
+ {
+ // compute adler32 on input
+ unsigned int s1=1, s2=0;
+ int blocklen = (int) (data_len % 5552);
+ j=0;
+ while (j < data_len) {
+ for (i=0; i < blocklen; ++i) { s1 += data[j+i]; s2 += s1; }
+ s1 %= 65521; s2 %= 65521;
+ j += blocklen;
+ blocklen = 5552;
+ }
+ stbiw__sbpush(out, STBIW_UCHAR(s2 >> 8));
+ stbiw__sbpush(out, STBIW_UCHAR(s2));
+ stbiw__sbpush(out, STBIW_UCHAR(s1 >> 8));
+ stbiw__sbpush(out, STBIW_UCHAR(s1));
+ }
+ *out_len = stbiw__sbn(out);
+ // make returned pointer freeable
+ STBIW_MEMMOVE(stbiw__sbraw(out), out, *out_len);
+ return (unsigned char *) stbiw__sbraw(out);
+#endif // STBIW_ZLIB_COMPRESS
+}
+
+static unsigned int stbiw__crc32(unsigned char *buffer, int len)
+{
+#ifdef STBIW_CRC32
+ return STBIW_CRC32(buffer, len);
+#else
+ static unsigned int crc_table[256] =
+ {
+ 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
+ 0x0eDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
+ 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
+ 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
+ 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
+ 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
+ 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
+ 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
+ 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
+ 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
+ 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
+ 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
+ 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
+ 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
+ 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
+ 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
+ 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
+ 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
+ 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
+ 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
+ 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
+ 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
+ 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
+ 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
+ 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
+ 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
+ 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
+ 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
+ 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
+ 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
+ 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
+ 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
+ };
+
+ unsigned int crc = ~0u;
+ int i;
+ for (i=0; i < len; ++i)
+ crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)];
+ return ~crc;
+#endif
+}
+
+#define stbiw__wpng4(o,a,b,c,d) ((o)[0]=STBIW_UCHAR(a),(o)[1]=STBIW_UCHAR(b),(o)[2]=STBIW_UCHAR(c),(o)[3]=STBIW_UCHAR(d),(o)+=4)
+#define stbiw__wp32(data,v) stbiw__wpng4(data, (v)>>24,(v)>>16,(v)>>8,(v));
+#define stbiw__wptag(data,s) stbiw__wpng4(data, s[0],s[1],s[2],s[3])
+
+static void stbiw__wpcrc(unsigned char **data, int len)
+{
+ unsigned int crc = stbiw__crc32(*data - len - 4, len+4);
+ stbiw__wp32(*data, crc);
+}
+
+static unsigned char stbiw__paeth(int a, int b, int c)
+{
+ int p = a + b - c, pa = abs(p-a), pb = abs(p-b), pc = abs(p-c);
+ if (pa <= pb && pa <= pc) return STBIW_UCHAR(a);
+ if (pb <= pc) return STBIW_UCHAR(b);
+ return STBIW_UCHAR(c);
+}
+
+// @OPTIMIZE: provide an option that always forces left-predict or paeth predict
+static void stbiw__encode_png_line(unsigned char *pixels, int stride_bytes, int width, int height, int y, int n, int filter_type, signed char *line_buffer)
+{
+ static int mapping[] = { 0,1,2,3,4 };
+ static int firstmap[] = { 0,1,0,5,6 };
+ int *mymap = (y != 0) ? mapping : firstmap;
+ int i;
+ int type = mymap[filter_type];
+ unsigned char *z = pixels + stride_bytes * (stbi__flip_vertically_on_write ? height-1-y : y);
+ int signed_stride = stbi__flip_vertically_on_write ? -stride_bytes : stride_bytes;
+
+ if (type==0) {
+ memcpy(line_buffer, z, width*n);
+ return;
+ }
+
+ // first loop isn't optimized since it's just one pixel
+ for (i = 0; i < n; ++i) {
+ switch (type) {
+ case 1: line_buffer[i] = z[i]; break;
+ case 2: line_buffer[i] = z[i] - z[i-signed_stride]; break;
+ case 3: line_buffer[i] = z[i] - (z[i-signed_stride]>>1); break;
+ case 4: line_buffer[i] = (signed char) (z[i] - stbiw__paeth(0,z[i-signed_stride],0)); break;
+ case 5: line_buffer[i] = z[i]; break;
+ case 6: line_buffer[i] = z[i]; break;
+ }
+ }
+ switch (type) {
+ case 1: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-n]; break;
+ case 2: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-signed_stride]; break;
+ case 3: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - ((z[i-n] + z[i-signed_stride])>>1); break;
+ case 4: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], z[i-signed_stride], z[i-signed_stride-n]); break;
+ case 5: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - (z[i-n]>>1); break;
+ case 6: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], 0,0); break;
+ }
+}
+
+STBIWDEF unsigned char *stbi_write_png_to_mem(const unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len)
+{
+ int force_filter = stbi_write_force_png_filter;
+ int ctype[5] = { -1, 0, 4, 2, 6 };
+ unsigned char sig[8] = { 137,80,78,71,13,10,26,10 };
+ unsigned char *out,*o, *filt, *zlib;
+ signed char *line_buffer;
+ int j,zlen;
+
+ if (stride_bytes == 0)
+ stride_bytes = x * n;
+
+ if (force_filter >= 5) {
+ force_filter = -1;
+ }
+
+ filt = (unsigned char *) STBIW_MALLOC((x*n+1) * y); if (!filt) return 0;
+ line_buffer = (signed char *) STBIW_MALLOC(x * n); if (!line_buffer) { STBIW_FREE(filt); return 0; }
+ for (j=0; j < y; ++j) {
+ int filter_type;
+ if (force_filter > -1) {
+ filter_type = force_filter;
+ stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, force_filter, line_buffer);
+ } else { // Estimate the best filter by running through all of them:
+ int best_filter = 0, best_filter_val = 0x7fffffff, est, i;
+ for (filter_type = 0; filter_type < 5; filter_type++) {
+ stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, filter_type, line_buffer);
+
+ // Estimate the entropy of the line using this filter; the less, the better.
+ est = 0;
+ for (i = 0; i < x*n; ++i) {
+ est += abs((signed char) line_buffer[i]);
+ }
+ if (est < best_filter_val) {
+ best_filter_val = est;
+ best_filter = filter_type;
+ }
+ }
+ if (filter_type != best_filter) { // If the last iteration already got us the best filter, don't redo it
+ stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, best_filter, line_buffer);
+ filter_type = best_filter;
+ }
+ }
+ // when we get here, filter_type contains the filter type, and line_buffer contains the data
+ filt[j*(x*n+1)] = (unsigned char) filter_type;
+ STBIW_MEMMOVE(filt+j*(x*n+1)+1, line_buffer, x*n);
+ }
+ STBIW_FREE(line_buffer);
+ zlib = stbi_zlib_compress(filt, y*( x*n+1), &zlen, stbi_write_png_compression_level);
+ STBIW_FREE(filt);
+ if (!zlib) return 0;
+
+ // each tag requires 12 bytes of overhead
+ out = (unsigned char *) STBIW_MALLOC(8 + 12+13 + 12+zlen + 12);
+ if (!out) return 0;
+ *out_len = 8 + 12+13 + 12+zlen + 12;
+
+ o=out;
+ STBIW_MEMMOVE(o,sig,8); o+= 8;
+ stbiw__wp32(o, 13); // header length
+ stbiw__wptag(o, "IHDR");
+ stbiw__wp32(o, x);
+ stbiw__wp32(o, y);
+ *o++ = 8;
+ *o++ = STBIW_UCHAR(ctype[n]);
+ *o++ = 0;
+ *o++ = 0;
+ *o++ = 0;
+ stbiw__wpcrc(&o,13);
+
+ stbiw__wp32(o, zlen);
+ stbiw__wptag(o, "IDAT");
+ STBIW_MEMMOVE(o, zlib, zlen);
+ o += zlen;
+ STBIW_FREE(zlib);
+ stbiw__wpcrc(&o, zlen);
+
+ stbiw__wp32(o,0);
+ stbiw__wptag(o, "IEND");
+ stbiw__wpcrc(&o,0);
+
+ STBIW_ASSERT(o == out + *out_len);
+
+ return out;
+}
+
+#ifndef STBI_WRITE_NO_STDIO
+STBIWDEF int stbi_write_png(char const *filename, int x, int y, int comp, const void *data, int stride_bytes)
+{
+ FILE *f;
+ int len;
+ unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len);
+ if (png == NULL) return 0;
+
+ f = stbiw__fopen(filename, "wb");
+ if (!f) { STBIW_FREE(png); return 0; }
+ fwrite(png, 1, len, f);
+ fclose(f);
+ STBIW_FREE(png);
+ return 1;
+}
+#endif
+
+STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int stride_bytes)
+{
+ int len;
+ unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len);
+ if (png == NULL) return 0;
+ func(context, png, len);
+ STBIW_FREE(png);
+ return 1;
+}
+
+
+/* ***************************************************************************
+ *
+ * JPEG writer
+ *
+ * This is based on Jon Olick's jo_jpeg.cpp:
+ * public domain Simple, Minimalistic JPEG writer - http://www.jonolick.com/code.html
+ */
+
+static const unsigned char stbiw__jpg_ZigZag[] = { 0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,
+ 24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63 };
+
+static void stbiw__jpg_writeBits(stbi__write_context *s, int *bitBufP, int *bitCntP, const unsigned short *bs) {
+ int bitBuf = *bitBufP, bitCnt = *bitCntP;
+ bitCnt += bs[1];
+ bitBuf |= bs[0] << (24 - bitCnt);
+ while(bitCnt >= 8) {
+ unsigned char c = (bitBuf >> 16) & 255;
+ stbiw__putc(s, c);
+ if(c == 255) {
+ stbiw__putc(s, 0);
+ }
+ bitBuf <<= 8;
+ bitCnt -= 8;
+ }
+ *bitBufP = bitBuf;
+ *bitCntP = bitCnt;
+}
+
+static void stbiw__jpg_DCT(float *d0p, float *d1p, float *d2p, float *d3p, float *d4p, float *d5p, float *d6p, float *d7p) {
+ float d0 = *d0p, d1 = *d1p, d2 = *d2p, d3 = *d3p, d4 = *d4p, d5 = *d5p, d6 = *d6p, d7 = *d7p;
+ float z1, z2, z3, z4, z5, z11, z13;
+
+ float tmp0 = d0 + d7;
+ float tmp7 = d0 - d7;
+ float tmp1 = d1 + d6;
+ float tmp6 = d1 - d6;
+ float tmp2 = d2 + d5;
+ float tmp5 = d2 - d5;
+ float tmp3 = d3 + d4;
+ float tmp4 = d3 - d4;
+
+ // Even part
+ float tmp10 = tmp0 + tmp3; // phase 2
+ float tmp13 = tmp0 - tmp3;
+ float tmp11 = tmp1 + tmp2;
+ float tmp12 = tmp1 - tmp2;
+
+ d0 = tmp10 + tmp11; // phase 3
+ d4 = tmp10 - tmp11;
+
+ z1 = (tmp12 + tmp13) * 0.707106781f; // c4
+ d2 = tmp13 + z1; // phase 5
+ d6 = tmp13 - z1;
+
+ // Odd part
+ tmp10 = tmp4 + tmp5; // phase 2
+ tmp11 = tmp5 + tmp6;
+ tmp12 = tmp6 + tmp7;
+
+ // The rotator is modified from fig 4-8 to avoid extra negations.
+ z5 = (tmp10 - tmp12) * 0.382683433f; // c6
+ z2 = tmp10 * 0.541196100f + z5; // c2-c6
+ z4 = tmp12 * 1.306562965f + z5; // c2+c6
+ z3 = tmp11 * 0.707106781f; // c4
+
+ z11 = tmp7 + z3; // phase 5
+ z13 = tmp7 - z3;
+
+ *d5p = z13 + z2; // phase 6
+ *d3p = z13 - z2;
+ *d1p = z11 + z4;
+ *d7p = z11 - z4;
+
+ *d0p = d0; *d2p = d2; *d4p = d4; *d6p = d6;
+}
+
+static void stbiw__jpg_calcBits(int val, unsigned short bits[2]) {
+ int tmp1 = val < 0 ? -val : val;
+ val = val < 0 ? val-1 : val;
+ bits[1] = 1;
+ while(tmp1 >>= 1) {
+ ++bits[1];
+ }
+ bits[0] = val & ((1<<bits[1])-1);
+}
+
+static int stbiw__jpg_processDU(stbi__write_context *s, int *bitBuf, int *bitCnt, float *CDU, int du_stride, float *fdtbl, int DC, const unsigned short HTDC[256][2], const unsigned short HTAC[256][2]) {
+ const unsigned short EOB[2] = { HTAC[0x00][0], HTAC[0x00][1] };
+ const unsigned short M16zeroes[2] = { HTAC[0xF0][0], HTAC[0xF0][1] };
+ int dataOff, i, j, n, diff, end0pos, x, y;
+ int DU[64];
+
+ // DCT rows
+ for(dataOff=0, n=du_stride*8; dataOff<n; dataOff+=du_stride) {
+ stbiw__jpg_DCT(&CDU[dataOff], &CDU[dataOff+1], &CDU[dataOff+2], &CDU[dataOff+3], &CDU[dataOff+4], &CDU[dataOff+5], &CDU[dataOff+6], &CDU[dataOff+7]);
+ }
+ // DCT columns
+ for(dataOff=0; dataOff<8; ++dataOff) {
+ stbiw__jpg_DCT(&CDU[dataOff], &CDU[dataOff+du_stride], &CDU[dataOff+du_stride*2], &CDU[dataOff+du_stride*3], &CDU[dataOff+du_stride*4],
+ &CDU[dataOff+du_stride*5], &CDU[dataOff+du_stride*6], &CDU[dataOff+du_stride*7]);
+ }
+ // Quantize/descale/zigzag the coefficients
+ for(y = 0, j=0; y < 8; ++y) {
+ for(x = 0; x < 8; ++x,++j) {
+ float v;
+ i = y*du_stride+x;
+ v = CDU[i]*fdtbl[j];
+ // DU[stbiw__jpg_ZigZag[j]] = (int)(v < 0 ? ceilf(v - 0.5f) : floorf(v + 0.5f));
+ // ceilf() and floorf() are C99, not C89, but I /think/ they're not needed here anyway?
+ DU[stbiw__jpg_ZigZag[j]] = (int)(v < 0 ? v - 0.5f : v + 0.5f);
+ }
+ }
+
+ // Encode DC
+ diff = DU[0] - DC;
+ if (diff == 0) {
+ stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTDC[0]);
+ } else {
+ unsigned short bits[2];
+ stbiw__jpg_calcBits(diff, bits);
+ stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTDC[bits[1]]);
+ stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits);
+ }
+ // Encode ACs
+ end0pos = 63;
+ for(; (end0pos>0)&&(DU[end0pos]==0); --end0pos) {
+ }
+ // end0pos = first element in reverse order !=0
+ if(end0pos == 0) {
+ stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB);
+ return DU[0];
+ }
+ for(i = 1; i <= end0pos; ++i) {
+ int startpos = i;
+ int nrzeroes;
+ unsigned short bits[2];
+ for (; DU[i]==0 && i<=end0pos; ++i) {
+ }
+ nrzeroes = i-startpos;
+ if ( nrzeroes >= 16 ) {
+ int lng = nrzeroes>>4;
+ int nrmarker;
+ for (nrmarker=1; nrmarker <= lng; ++nrmarker)
+ stbiw__jpg_writeBits(s, bitBuf, bitCnt, M16zeroes);
+ nrzeroes &= 15;
+ }
+ stbiw__jpg_calcBits(DU[i], bits);
+ stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTAC[(nrzeroes<<4)+bits[1]]);
+ stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits);
+ }
+ if(end0pos != 63) {
+ stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB);
+ }
+ return DU[0];
+}
+
+static int stbi_write_jpg_core(stbi__write_context *s, int width, int height, int comp, const void* data, int quality) {
+ // Constants that don't pollute global namespace
+ static const unsigned char std_dc_luminance_nrcodes[] = {0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0};
+ static const unsigned char std_dc_luminance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11};
+ static const unsigned char std_ac_luminance_nrcodes[] = {0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d};
+ static const unsigned char std_ac_luminance_values[] = {
+ 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,
+ 0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,
+ 0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,
+ 0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
+ 0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,
+ 0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,
+ 0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa
+ };
+ static const unsigned char std_dc_chrominance_nrcodes[] = {0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0};
+ static const unsigned char std_dc_chrominance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11};
+ static const unsigned char std_ac_chrominance_nrcodes[] = {0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77};
+ static const unsigned char std_ac_chrominance_values[] = {
+ 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,
+ 0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,
+ 0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,
+ 0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
+ 0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,
+ 0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,
+ 0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa
+ };
+ // Huffman tables
+ static const unsigned short YDC_HT[256][2] = { {0,2},{2,3},{3,3},{4,3},{5,3},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9}};
+ static const unsigned short UVDC_HT[256][2] = { {0,2},{1,2},{2,2},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9},{1022,10},{2046,11}};
+ static const unsigned short YAC_HT[256][2] = {
+ {10,4},{0,2},{1,2},{4,3},{11,4},{26,5},{120,7},{248,8},{1014,10},{65410,16},{65411,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {12,4},{27,5},{121,7},{502,9},{2038,11},{65412,16},{65413,16},{65414,16},{65415,16},{65416,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {28,5},{249,8},{1015,10},{4084,12},{65417,16},{65418,16},{65419,16},{65420,16},{65421,16},{65422,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {58,6},{503,9},{4085,12},{65423,16},{65424,16},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {59,6},{1016,10},{65430,16},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {122,7},{2039,11},{65438,16},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {123,7},{4086,12},{65446,16},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {250,8},{4087,12},{65454,16},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {504,9},{32704,15},{65462,16},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {505,9},{65470,16},{65471,16},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {506,9},{65479,16},{65480,16},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {1017,10},{65488,16},{65489,16},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {1018,10},{65497,16},{65498,16},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {2040,11},{65506,16},{65507,16},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {65515,16},{65516,16},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {2041,11},{65525,16},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0}
+ };
+ static const unsigned short UVAC_HT[256][2] = {
+ {0,2},{1,2},{4,3},{10,4},{24,5},{25,5},{56,6},{120,7},{500,9},{1014,10},{4084,12},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {11,4},{57,6},{246,8},{501,9},{2038,11},{4085,12},{65416,16},{65417,16},{65418,16},{65419,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {26,5},{247,8},{1015,10},{4086,12},{32706,15},{65420,16},{65421,16},{65422,16},{65423,16},{65424,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {27,5},{248,8},{1016,10},{4087,12},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{65430,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {58,6},{502,9},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{65438,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {59,6},{1017,10},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{65446,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {121,7},{2039,11},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{65454,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {122,7},{2040,11},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{65462,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {249,8},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{65470,16},{65471,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {503,9},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{65479,16},{65480,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {504,9},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{65488,16},{65489,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {505,9},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{65497,16},{65498,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {506,9},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{65506,16},{65507,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {2041,11},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{65515,16},{65516,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {16352,14},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{65525,16},{0,0},{0,0},{0,0},{0,0},{0,0},
+ {1018,10},{32707,15},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0}
+ };
+ static const int YQT[] = {16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,
+ 37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99};
+ static const int UVQT[] = {17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,
+ 99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99};
+ static const float aasf[] = { 1.0f * 2.828427125f, 1.387039845f * 2.828427125f, 1.306562965f * 2.828427125f, 1.175875602f * 2.828427125f,
+ 1.0f * 2.828427125f, 0.785694958f * 2.828427125f, 0.541196100f * 2.828427125f, 0.275899379f * 2.828427125f };
+
+ int row, col, i, k, subsample;
+ float fdtbl_Y[64], fdtbl_UV[64];
+ unsigned char YTable[64], UVTable[64];
+
+ if(!data || !width || !height || comp > 4 || comp < 1) {
+ return 0;
+ }
+
+ quality = quality ? quality : 90;
+ subsample = quality <= 90 ? 1 : 0;
+ quality = quality < 1 ? 1 : quality > 100 ? 100 : quality;
+ quality = quality < 50 ? 5000 / quality : 200 - quality * 2;
+
+ for(i = 0; i < 64; ++i) {
+ int uvti, yti = (YQT[i]*quality+50)/100;
+ YTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (yti < 1 ? 1 : yti > 255 ? 255 : yti);
+ uvti = (UVQT[i]*quality+50)/100;
+ UVTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (uvti < 1 ? 1 : uvti > 255 ? 255 : uvti);
+ }
+
+ for(row = 0, k = 0; row < 8; ++row) {
+ for(col = 0; col < 8; ++col, ++k) {
+ fdtbl_Y[k] = 1 / (YTable [stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]);
+ fdtbl_UV[k] = 1 / (UVTable[stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]);
+ }
+ }
+
+ // Write Headers
+ {
+ static const unsigned char head0[] = { 0xFF,0xD8,0xFF,0xE0,0,0x10,'J','F','I','F',0,1,1,0,0,1,0,1,0,0,0xFF,0xDB,0,0x84,0 };
+ static const unsigned char head2[] = { 0xFF,0xDA,0,0xC,3,1,0,2,0x11,3,0x11,0,0x3F,0 };
+ const unsigned char head1[] = { 0xFF,0xC0,0,0x11,8,(unsigned char)(height>>8),STBIW_UCHAR(height),(unsigned char)(width>>8),STBIW_UCHAR(width),
+ 3,1,(unsigned char)(subsample?0x22:0x11),0,2,0x11,1,3,0x11,1,0xFF,0xC4,0x01,0xA2,0 };
+ s->func(s->context, (void*)head0, sizeof(head0));
+ s->func(s->context, (void*)YTable, sizeof(YTable));
+ stbiw__putc(s, 1);
+ s->func(s->context, UVTable, sizeof(UVTable));
+ s->func(s->context, (void*)head1, sizeof(head1));
+ s->func(s->context, (void*)(std_dc_luminance_nrcodes+1), sizeof(std_dc_luminance_nrcodes)-1);
+ s->func(s->context, (void*)std_dc_luminance_values, sizeof(std_dc_luminance_values));
+ stbiw__putc(s, 0x10); // HTYACinfo
+ s->func(s->context, (void*)(std_ac_luminance_nrcodes+1), sizeof(std_ac_luminance_nrcodes)-1);
+ s->func(s->context, (void*)std_ac_luminance_values, sizeof(std_ac_luminance_values));
+ stbiw__putc(s, 1); // HTUDCinfo
+ s->func(s->context, (void*)(std_dc_chrominance_nrcodes+1), sizeof(std_dc_chrominance_nrcodes)-1);
+ s->func(s->context, (void*)std_dc_chrominance_values, sizeof(std_dc_chrominance_values));
+ stbiw__putc(s, 0x11); // HTUACinfo
+ s->func(s->context, (void*)(std_ac_chrominance_nrcodes+1), sizeof(std_ac_chrominance_nrcodes)-1);
+ s->func(s->context, (void*)std_ac_chrominance_values, sizeof(std_ac_chrominance_values));
+ s->func(s->context, (void*)head2, sizeof(head2));
+ }
+
+ // Encode 8x8 macroblocks
+ {
+ static const unsigned short fillBits[] = {0x7F, 7};
+ int DCY=0, DCU=0, DCV=0;
+ int bitBuf=0, bitCnt=0;
+ // comp == 2 is grey+alpha (alpha is ignored)
+ int ofsG = comp > 2 ? 1 : 0, ofsB = comp > 2 ? 2 : 0;
+ const unsigned char *dataR = (const unsigned char *)data;
+ const unsigned char *dataG = dataR + ofsG;
+ const unsigned char *dataB = dataR + ofsB;
+ int x, y, pos;
+ if(subsample) {
+ for(y = 0; y < height; y += 16) {
+ for(x = 0; x < width; x += 16) {
+ float Y[256], U[256], V[256];
+ for(row = y, pos = 0; row < y+16; ++row) {
+ // row >= height => use last input row
+ int clamped_row = (row < height) ? row : height - 1;
+ int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp;
+ for(col = x; col < x+16; ++col, ++pos) {
+ // if col >= width => use pixel from last input column
+ int p = base_p + ((col < width) ? col : (width-1))*comp;
+ float r = dataR[p], g = dataG[p], b = dataB[p];
+ Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128;
+ U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b;
+ V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b;
+ }
+ }
+ DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+0, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT);
+ DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+8, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT);
+ DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+128, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT);
+ DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+136, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT);
+
+ // subsample U,V
+ {
+ float subU[64], subV[64];
+ int yy, xx;
+ for(yy = 0, pos = 0; yy < 8; ++yy) {
+ for(xx = 0; xx < 8; ++xx, ++pos) {
+ int j = yy*32+xx*2;
+ subU[pos] = (U[j+0] + U[j+1] + U[j+16] + U[j+17]) * 0.25f;
+ subV[pos] = (V[j+0] + V[j+1] + V[j+16] + V[j+17]) * 0.25f;
+ }
+ }
+ DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subU, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
+ DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subV, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
+ }
+ }
+ }
+ } else {
+ for(y = 0; y < height; y += 8) {
+ for(x = 0; x < width; x += 8) {
+ float Y[64], U[64], V[64];
+ for(row = y, pos = 0; row < y+8; ++row) {
+ // row >= height => use last input row
+ int clamped_row = (row < height) ? row : height - 1;
+ int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp;
+ for(col = x; col < x+8; ++col, ++pos) {
+ // if col >= width => use pixel from last input column
+ int p = base_p + ((col < width) ? col : (width-1))*comp;
+ float r = dataR[p], g = dataG[p], b = dataB[p];
+ Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128;
+ U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b;
+ V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b;
+ }
+ }
+
+ DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y, 8, fdtbl_Y, DCY, YDC_HT, YAC_HT);
+ DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, U, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
+ DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, V, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
+ }
+ }
+ }
+
+ // Do the bit alignment of the EOI marker
+ stbiw__jpg_writeBits(s, &bitBuf, &bitCnt, fillBits);
+ }
+
+ // EOI
+ stbiw__putc(s, 0xFF);
+ stbiw__putc(s, 0xD9);
+
+ return 1;
+}
+
+STBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality)
+{
+ stbi__write_context s = { 0 };
+ stbi__start_write_callbacks(&s, func, context);
+ return stbi_write_jpg_core(&s, x, y, comp, (void *) data, quality);
+}
+
+
+#ifndef STBI_WRITE_NO_STDIO
+STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality)
+{
+ stbi__write_context s = { 0 };
+ if (stbi__start_write_file(&s,filename)) {
+ int r = stbi_write_jpg_core(&s, x, y, comp, data, quality);
+ stbi__end_write_file(&s);
+ return r;
+ } else
+ return 0;
+}
+#endif
+
+#endif // STB_IMAGE_WRITE_IMPLEMENTATION
+
+/* Revision history
+ 1.16 (2021-07-11)
+ make Deflate code emit uncompressed blocks when it would otherwise expand
+ support writing BMPs with alpha channel
+ 1.15 (2020-07-13) unknown
+ 1.14 (2020-02-02) updated JPEG writer to downsample chroma channels
+ 1.13
+ 1.12
+ 1.11 (2019-08-11)
+
+ 1.10 (2019-02-07)
+ support utf8 filenames in Windows; fix warnings and platform ifdefs
+ 1.09 (2018-02-11)
+ fix typo in zlib quality API, improve STB_I_W_STATIC in C++
+ 1.08 (2018-01-29)
+ add stbi__flip_vertically_on_write, external zlib, zlib quality, choose PNG filter
+ 1.07 (2017-07-24)
+ doc fix
+ 1.06 (2017-07-23)
+ writing JPEG (using Jon Olick's code)
+ 1.05 ???
+ 1.04 (2017-03-03)
+ monochrome BMP expansion
+ 1.03 ???
+ 1.02 (2016-04-02)
+ avoid allocating large structures on the stack
+ 1.01 (2016-01-16)
+ STBIW_REALLOC_SIZED: support allocators with no realloc support
+ avoid race-condition in crc initialization
+ minor compile issues
+ 1.00 (2015-09-14)
+ installable file IO function
+ 0.99 (2015-09-13)
+ warning fixes; TGA rle support
+ 0.98 (2015-04-08)
+ added STBIW_MALLOC, STBIW_ASSERT etc
+ 0.97 (2015-01-18)
+ fixed HDR asserts, rewrote HDR rle logic
+ 0.96 (2015-01-17)
+ add HDR output
+ fix monochrome BMP
+ 0.95 (2014-08-17)
+ add monochrome TGA output
+ 0.94 (2014-05-31)
+ rename private functions to avoid conflicts with stb_image.h
+ 0.93 (2014-05-27)
+ warning fixes
+ 0.92 (2010-08-01)
+ casts to unsigned char to fix warnings
+ 0.91 (2010-07-17)
+ first public release
+ 0.90 first internal release
+*/
+
+/*
+------------------------------------------------------------------------------
+This software is available under 2 licenses -- choose whichever you prefer.
+------------------------------------------------------------------------------
+ALTERNATIVE A - MIT License
+Copyright (c) 2017 Sean Barrett
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+------------------------------------------------------------------------------
+ALTERNATIVE B - Public Domain (www.unlicense.org)
+This is free and unencumbered software released into the public domain.
+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
+software, either in source code form or as a compiled binary, for any purpose,
+commercial or non-commercial, and by any means.
+In jurisdictions that recognize copyright laws, the author or authors of this
+software dedicate any and all copyright interest in the software to the public
+domain. We make this dedication for the benefit of the public at large and to
+the detriment of our heirs and successors. We intend this dedication to be an
+overt act of relinquishment in perpetuity of all present and future rights to
+this software under copyright law.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+------------------------------------------------------------------------------
+*/
diff --git a/nn2/src/tensor_column.c b/nn2/src/tensor_column.c
new file mode 100644
index 0000000..0e40ae0
--- /dev/null
+++ b/nn2/src/tensor_column.c
@@ -0,0 +1,261 @@
+/*
+ * tensor_column.c — Tensor Column execution engine.
+ *
+ * Instead of processing the full network layer-by-layer (writing huge
+ * intermediate tensors to main memory), process VERTICAL STRIPS of the
+ * network that fit entirely in L2 cache.
+ *
+ * A "tensor column" is a vertical slice of width W_col pixels through
+ * all layers of the network. Each layer's activations for that slice
+ * fit in L2, so data flows through multiple layers without touching RAM.
+ *
+ * For conv layers with receptive field expansion, each layer needs a
+ * slightly wider input than output (halo). We compute the halo widths
+ * bottom-up and process overlapping strips.
+ *
+ * Example for 3 conv layers (3x3, pad=1, stride=1):
+ * Output strip width: W_col = 32
+ * Layer 3 input: 32 + 2 = 34 (1 pixel halo each side)
+ * Layer 2 input: 34 + 2 = 36
+ * Layer 1 input: 36 + 2 = 38
+ *
+ * For stride-2 layers, the input width doubles:
+ * Layer with stride 2: output 32 → input 64 + halo
+ *
+ * Memory per column: sum of (channels × height × strip_width) per layer
+ * Target: fit in L2 cache (~256KB per core)
+ *
+ * Performance gain: activations stay in L2 (200 GB/s) instead of
+ * main memory (40 GB/s) → 3-5x bandwidth improvement.
+ */
+
+#include "nn2_internal.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+/* ============ Halo computation ============ */
+
+typedef struct {
+ int w_in; /* input strip width needed (including halo) */
+ int w_out; /* output strip width produced */
+ int halo_l; /* left halo pixels */
+ int halo_r; /* right halo pixels */
+ int stride;
+ int channels_in;
+ int channels_out;
+} ColumnLayerInfo;
+
+/*
+ * Compute required input widths for each layer, working backwards from
+ * the desired output strip width.
+ *
+ * Returns array of ColumnLayerInfo for each layer.
+ */
+ColumnLayerInfo* nn2_tc_compute_halos(
+ int n_layers,
+ const int* kernel_sizes, /* [n_layers] */
+ const int* strides, /* [n_layers] */
+ const int* paddings, /* [n_layers] */
+ const int* channels_in, /* [n_layers] */
+ const int* channels_out, /* [n_layers] */
+ int output_strip_width) /* desired output W */
+{
+ ColumnLayerInfo* info = (ColumnLayerInfo*)calloc(n_layers, sizeof(ColumnLayerInfo));
+
+ /* Work backwards: start from output strip width */
+ int w = output_strip_width;
+ for (int i = n_layers - 1; i >= 0; i--) {
+ info[i].w_out = w;
+ info[i].stride = strides[i];
+ info[i].channels_in = channels_in[i];
+ info[i].channels_out = channels_out[i];
+
+ /* For conv with kernel k, stride s, pad p:
+ * w_in = (w_out - 1) * stride + kernel - 2*pad
+ * But for tensor columns, we need the actual input pixels: */
+ int k = kernel_sizes[i];
+ int s = strides[i];
+ int p = paddings[i];
+ int w_in = (w - 1) * s + k; /* without padding, the raw input width */
+ info[i].halo_l = k / 2; /* halo needed on left */
+ info[i].halo_r = k / 2; /* halo needed on right */
+ info[i].w_in = w_in;
+
+ /* Next layer's output is this layer's input */
+ w = w_in;
+ }
+
+ return info;
+}
+
+/*
+ * Estimate memory needed for one tensor column.
+ * Returns bytes needed for all intermediate activations.
+ */
+size_t nn2_tc_memory_estimate(const ColumnLayerInfo* info, int n_layers,
+ int max_height)
+{
+ size_t total = 0;
+ for (int i = 0; i < n_layers; i++) {
+ /* Height at this layer depends on strides of preceding layers */
+ int h = max_height;
+ for (int j = 0; j < i; j++)
+ h = (h + 1) / info[j].stride; /* approximate */
+
+ size_t layer_size = (size_t)info[i].channels_out * h * info[i].w_out * sizeof(float);
+ total += layer_size;
+ }
+ return total;
+}
+
+/*
+ * Find optimal strip width that fits in target cache size.
+ */
+int nn2_tc_optimal_width(
+ int n_layers,
+ const int* kernel_sizes,
+ const int* strides,
+ const int* paddings,
+ const int* channels_in,
+ const int* channels_out,
+ int input_height,
+ size_t target_cache_bytes) /* e.g. 256*1024 for L2 */
+{
+ /* Binary search for the largest strip width that fits */
+ int lo = 4, hi = 128;
+ int best = lo;
+
+ while (lo <= hi) {
+ int mid = (lo + hi) / 2;
+ ColumnLayerInfo* info = nn2_tc_compute_halos(
+ n_layers, kernel_sizes, strides, paddings,
+ channels_in, channels_out, mid);
+ size_t mem = nn2_tc_memory_estimate(info, n_layers, input_height);
+ free(info);
+
+ if (mem <= target_cache_bytes) {
+ best = mid;
+ lo = mid + 1;
+ } else {
+ hi = mid - 1;
+ }
+ }
+
+ return best;
+}
+
+/* ============ Column execution for a sequence of convolutions ============ */
+
+/*
+ * Process a vertical strip through a sequence of conv layers.
+ * All intermediate data stays in the provided buffer (should be L2-sized).
+ *
+ * input: full input tensor [Cin, H, W] (read only the strip region)
+ * output: strip of final output [Cout, Hout, strip_w_out]
+ * strip_x: starting x position in the output
+ */
+void nn2_tc_execute_strip(
+ const ConvLayer* layers, int n_layers,
+ const float* input, int H, int W,
+ float* output, int Hout, int Wout,
+ int strip_x, int strip_w,
+ float* work_buf) /* L2-sized work buffer */
+{
+ /* Compute halo requirements */
+ int w = strip_w;
+ int x_starts[32], x_widths[32]; /* max 32 layers */
+ int heights[32];
+
+ /* Backward pass: compute required input widths */
+ x_widths[n_layers] = strip_w;
+ x_starts[n_layers] = strip_x;
+ heights[n_layers] = Hout;
+
+ for (int i = n_layers - 1; i >= 0; i--) {
+ int k = layers[i].k;
+ int s = layers[i].stride;
+ int p = layers[i].pad;
+
+ /* Output width at layer i+1 needs input width at layer i */
+ int w_out = x_widths[i + 1];
+ int x_out = x_starts[i + 1];
+
+ /* Compute input range */
+ int x_in = x_out * s - p;
+ int w_in = (w_out - 1) * s + k;
+
+ /* Clamp to valid range */
+ if (x_in < 0) x_in = 0;
+ int h_in = (i == 0) ? H : heights[i]; /* approximate */
+
+ x_starts[i] = x_in;
+ x_widths[i] = w_in;
+ heights[i] = (i == 0) ? H : (heights[i + 1] - 1) * s + k;
+ if (heights[i] > H) heights[i] = H;
+ }
+
+ /* Forward pass: process each layer on the strip */
+ const float* cur_input = input;
+ float* ping = work_buf;
+ float* pong = work_buf + 256 * 256 * 64; /* half of work buffer */
+ int cur_x = x_starts[0];
+ int cur_w = x_widths[0];
+ int cur_h = H;
+
+ for (int i = 0; i < n_layers; i++) {
+ const ConvLayer* L = &layers[i];
+ int out_h = (cur_h + 2 * L->pad - L->k) / L->stride + 1;
+ int out_w = x_widths[i + 1];
+ int out_x = x_starts[i + 1];
+
+ /* Extract strip from input and run conv */
+ /* For simplicity, use full conv on the strip region */
+ /* TODO: implement strip-aware conv that reads only the needed region */
+
+ /* For now, just demonstrate the concept with a simple per-strip conv */
+ /* This would need a specialized conv that operates on sub-regions */
+
+ cur_h = out_h;
+ cur_w = out_w;
+ cur_x = out_x;
+
+ /* Swap buffers */
+ float* tmp = ping; ping = pong; pong = tmp;
+ }
+}
+
+/* ============ Print info ============ */
+
+void nn2_tc_print_info(int input_size)
+{
+ /* YOLOv8n backbone layer params */
+ int ks[] = {3, 3, 3, 3, 3}; /* kernel sizes */
+ int ss[] = {2, 2, 2, 2, 2}; /* strides */
+ int ps[] = {1, 1, 1, 1, 1}; /* paddings */
+ int ci[] = {3, 16, 32, 64, 128}; /* channels in */
+ int co[] = {16, 32, 64, 128, 256}; /* channels out */
+ int n = 5;
+
+ printf("=== Tensor Column Analysis for YOLOv8n (input=%d) ===\n\n", input_size);
+
+ for (size_t cache_kb = 128; cache_kb <= 512; cache_kb *= 2) {
+ int opt_w = nn2_tc_optimal_width(n, ks, ss, ps, ci, co,
+ input_size, cache_kb * 1024);
+ ColumnLayerInfo* info = nn2_tc_compute_halos(n, ks, ss, ps, ci, co, opt_w);
+ size_t mem = nn2_tc_memory_estimate(info, n, input_size);
+
+ printf("L2 = %zuKB → strip_width = %d\n", cache_kb, opt_w);
+ printf(" Input strip: %d pixels wide (with halos)\n", info[0].w_in);
+ printf(" Memory per column: %.1f KB\n", mem / 1024.0);
+ printf(" Strips needed: %d\n", (input_size + opt_w - 1) / opt_w);
+
+ int total_strips = (input_size + opt_w - 1) / opt_w;
+ /* Estimate: if data stays in L2 (200GB/s) vs DRAM (40GB/s) */
+ float bw_ratio = 200.0f / 40.0f;
+ printf(" Expected speedup from L2 residency: %.1fx\n", bw_ratio);
+ printf(" (assuming memory-bound execution)\n\n");
+
+ free(info);
+ }
+}
diff --git a/nn2/src/test_wino.c b/nn2/src/test_wino.c
new file mode 100644
index 0000000..fd185fb
--- /dev/null
+++ b/nn2/src/test_wino.c
@@ -0,0 +1,39 @@
+#include "nn2_internal.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+int nn2_load_weights(NN2* ctx, const char* path);
+int main(void) {
+ NN2 c; memset(&c, 0, sizeof(c));
+ nn2_tp_init(1);
+ if (nn2_load_weights(&c, "weights/yolov8n.bin")) return 1;
+ printf("Loaded OK\n");
+
+ /* Test Winograd on c2f0 bottleneck: 16->16, 3x3, s=1 at 160x160 */
+ ConvLayer* L = &c.bb_c2f[0].m[0].cv1;
+ printf("Layer: cout=%d cin=%d k=%d s=%d p=%d\n", L->cout, L->cin, L->k, L->stride, L->pad);
+
+ nn2_prepare_winograd(L);
+ printf("Winograd prepared: w_wino=%p\n", (void*)L->w_wino);
+
+ int H = 160, W = 160;
+ int h_tiles = (H+1)/2, w_tiles = (W+1)/2, n_tiles = h_tiles*w_tiles;
+ printf("Tiles: %d x %d = %d\n", h_tiles, w_tiles, n_tiles);
+
+ size_t v_size = 16 * L->cin * n_tiles;
+ size_t m_size = 16 * L->cout * n_tiles;
+ printf("V size: %zu, M size: %zu, total: %zu floats\n", v_size, m_size, v_size + m_size);
+
+ float* in = (float*)calloc(L->cin * H * W, sizeof(float));
+ float* out = (float*)malloc(L->cout * H * W * sizeof(float));
+ float* work = (float*)malloc((v_size + m_size) * sizeof(float));
+
+ printf("Buffers allocated, running Winograd...\n");
+ fflush(stdout);
+ nn2_conv2d(L, in, H, W, out, work);
+ printf("Winograd OK! out[0]=%.6f\n", out[0]);
+
+ free(in); free(out); free(work);
+ nn2_tp_destroy();
+ return 0;
+}
diff --git a/nn2/src/track.c b/nn2/src/track.c
new file mode 100644
index 0000000..a01a05d
--- /dev/null
+++ b/nn2/src/track.c
@@ -0,0 +1,210 @@
+/*
+ * track.c — SORT tracker (Simple Online and Realtime Tracking).
+ *
+ * Kalman filter: constant velocity model on bbox [cx, cy, s, r, dx, dy, ds].
+ * Matching: IoU between predicted and detected bboxes, greedy assignment.
+ * (Full Hungarian is overkill for <50 objects — greedy is 100x simpler and fast enough.)
+ */
+
+#include "nn2_track.h"
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+
+#define MAX_TRACKS 128
+
+/* Kalman state: [cx, cy, s, r, vx, vy, vs] where s=area, r=aspect ratio */
+typedef struct {
+ float x[7]; /* state: cx, cy, s, r, vx, vy, vs */
+ float P[7]; /* diagonal of covariance (simplified) */
+ int id;
+ int cls;
+ float score;
+ int age;
+ int hits;
+ int time_since_update;
+ int active;
+} KalmanTrack;
+
+struct NN2Tracker {
+ KalmanTrack tracks[MAX_TRACKS];
+ int n_tracks;
+ int next_id;
+ int max_age;
+ int min_hits;
+};
+
+/* Convert bbox to [cx, cy, s, r] */
+static void bbox_to_z(float x1, float y1, float x2, float y2, float z[4])
+{
+ float w = x2 - x1, h = y2 - y1;
+ z[0] = x1 + w * 0.5f; /* cx */
+ z[1] = y1 + h * 0.5f; /* cy */
+ z[2] = w * h; /* s (area) */
+ z[3] = w / (h + 1e-6f); /* r (aspect ratio) */
+}
+
+/* Convert [cx, cy, s, r] back to bbox */
+static void z_to_bbox(const float z[4], float* x1, float* y1, float* x2, float* y2)
+{
+ float w = sqrtf(z[2] * z[3]);
+ float h = z[2] / (w + 1e-6f);
+ *x1 = z[0] - w * 0.5f;
+ *y1 = z[1] - h * 0.5f;
+ *x2 = z[0] + w * 0.5f;
+ *y2 = z[1] + h * 0.5f;
+}
+
+/* Kalman predict */
+static void kf_predict(KalmanTrack* t)
+{
+ t->x[0] += t->x[4]; /* cx += vx */
+ t->x[1] += t->x[5]; /* cy += vy */
+ t->x[2] += t->x[6]; /* s += vs */
+ if (t->x[2] < 0) t->x[2] = 0;
+ /* Increase uncertainty */
+ for (int i = 0; i < 7; i++) t->P[i] += 10.0f;
+ t->age++;
+ t->time_since_update++;
+}
+
+/* Kalman update with measurement z[4] = [cx, cy, s, r] */
+static void kf_update(KalmanTrack* t, const float z[4])
+{
+ /* Simplified Kalman gain: K = P / (P + R) */
+ float R = 10.0f; /* measurement noise */
+ for (int i = 0; i < 4; i++) {
+ float K = t->P[i] / (t->P[i] + R);
+ t->x[i] += K * (z[i] - t->x[i]);
+ t->P[i] *= (1.0f - K);
+ }
+ /* Update velocities: exponential moving average of residuals */
+ float alpha = 0.3f;
+ t->x[4] = (1-alpha) * t->x[4] + alpha * (z[0] - t->x[0]);
+ t->x[5] = (1-alpha) * t->x[5] + alpha * (z[1] - t->x[1]);
+ t->x[6] = (1-alpha) * t->x[6] + alpha * (z[2] - t->x[2]);
+
+ t->time_since_update = 0;
+ t->hits++;
+}
+
+/* IoU between two bboxes */
+static float iou(float ax1, float ay1, float ax2, float ay2,
+ float bx1, float by1, float bx2, float by2)
+{
+ float ix1 = ax1 > bx1 ? ax1 : bx1;
+ float iy1 = ay1 > by1 ? ay1 : by1;
+ float ix2 = ax2 < bx2 ? ax2 : bx2;
+ float iy2 = ay2 < by2 ? ay2 : by2;
+ float inter = (ix2-ix1 > 0 ? ix2-ix1 : 0) * (iy2-iy1 > 0 ? iy2-iy1 : 0);
+ float a_area = (ax2-ax1) * (ay2-ay1);
+ float b_area = (bx2-bx1) * (by2-by1);
+ return inter / (a_area + b_area - inter + 1e-6f);
+}
+
+NN2Tracker* nn2_tracker_create(int max_age, int min_hits)
+{
+ NN2Tracker* tr = (NN2Tracker*)calloc(1, sizeof(NN2Tracker));
+ tr->max_age = max_age > 0 ? max_age : 30;
+ tr->min_hits = min_hits > 0 ? min_hits : 3;
+ tr->next_id = 1;
+ return tr;
+}
+
+int nn2_tracker_update(NN2Tracker* tr, const NN2Det* dets, int n_dets,
+ NN2Track* out_tracks, int max_tracks)
+{
+ /* 1. Predict all existing tracks */
+ for (int i = 0; i < tr->n_tracks; i++)
+ if (tr->tracks[i].active)
+ kf_predict(&tr->tracks[i]);
+
+ /* 2. Greedy IoU matching: for each detection, find best matching track */
+ int* det_matched = (int*)calloc(n_dets, sizeof(int)); /* -1 = unmatched */
+ int* trk_matched = (int*)calloc(tr->n_tracks, sizeof(int));
+ for (int i = 0; i < n_dets; i++) det_matched[i] = -1;
+
+ float iou_thresh = 0.1f; /* lowered from 0.3 for fast-moving objects */
+
+ for (int d = 0; d < n_dets; d++) {
+ float best_iou = iou_thresh;
+ int best_t = -1;
+
+ for (int t = 0; t < tr->n_tracks; t++) {
+ if (!tr->tracks[t].active || trk_matched[t]) continue;
+
+ float tx1, ty1, tx2, ty2;
+ z_to_bbox(tr->tracks[t].x, &tx1, &ty1, &tx2, &ty2);
+
+ float v = iou(dets[d].x1, dets[d].y1, dets[d].x2, dets[d].y2,
+ tx1, ty1, tx2, ty2);
+ if (v > best_iou) { best_iou = v; best_t = t; }
+ }
+
+ if (best_t >= 0) {
+ det_matched[d] = best_t;
+ trk_matched[best_t] = 1;
+ }
+ }
+
+ /* 3. Update matched tracks */
+ for (int d = 0; d < n_dets; d++) {
+ if (det_matched[d] >= 0) {
+ KalmanTrack* t = &tr->tracks[det_matched[d]];
+ float z[4];
+ bbox_to_z(dets[d].x1, dets[d].y1, dets[d].x2, dets[d].y2, z);
+ kf_update(t, z);
+ t->cls = dets[d].cls;
+ t->score = dets[d].score;
+ }
+ }
+
+ /* 4. Create new tracks for unmatched detections */
+ for (int d = 0; d < n_dets; d++) {
+ if (det_matched[d] >= 0) continue;
+ if (tr->n_tracks >= MAX_TRACKS) break;
+
+ KalmanTrack* t = &tr->tracks[tr->n_tracks++];
+ memset(t, 0, sizeof(*t));
+ float z[4];
+ bbox_to_z(dets[d].x1, dets[d].y1, dets[d].x2, dets[d].y2, z);
+ for (int i = 0; i < 4; i++) t->x[i] = z[i];
+ for (int i = 0; i < 7; i++) t->P[i] = 100.0f;
+ t->id = tr->next_id++;
+ t->cls = dets[d].cls;
+ t->score = dets[d].score;
+ t->active = 1;
+ t->hits = 1;
+ }
+
+ /* 5. Deactivate old tracks */
+ for (int t = 0; t < tr->n_tracks; t++) {
+ if (tr->tracks[t].active && tr->tracks[t].time_since_update > tr->max_age)
+ tr->tracks[t].active = 0;
+ }
+
+ /* 6. Output active tracks with enough hits */
+ int n_out = 0;
+ for (int t = 0; t < tr->n_tracks && n_out < max_tracks; t++) {
+ KalmanTrack* tk = &tr->tracks[t];
+ if (!tk->active) continue;
+ if (tk->hits < tr->min_hits && tk->time_since_update > 0) continue;
+
+ NN2Track* out = &out_tracks[n_out++];
+ out->id = tk->id;
+ out->cls = tk->cls;
+ out->score = tk->score;
+ z_to_bbox(tk->x, &out->x1, &out->y1, &out->x2, &out->y2);
+ out->age = tk->age;
+ out->hits = tk->hits;
+ out->time_since_update = tk->time_since_update;
+ }
+
+ free(det_matched);
+ free(trk_matched);
+ return n_out;
+}
+
+int nn2_tracker_total_ids(const NN2Tracker* tr) { return tr->next_id - 1; }
+
+void nn2_tracker_free(NN2Tracker* tr) { free(tr); }
diff --git a/nn2/src/winograd.c b/nn2/src/winograd.c
new file mode 100644
index 0000000..0d11fa5
--- /dev/null
+++ b/nn2/src/winograd.c
@@ -0,0 +1,194 @@
+/*
+ * winograd.c — Winograd F(2,3) for 3x3 stride-1 convolutions.
+ *
+ * Reduces multiplications by 2.25x (9→4 per output element).
+ * All transforms are AVX-512 vectorized — process full rows at once.
+ *
+ * Algorithm:
+ * 1. Transform input tiles: V = B^T × d × B (per channel, per 2-row strip)
+ * 2. Batched GEMM: M = U × V (16 independent [Cout,Cin]×[Cin,tiles] GEMMs)
+ * 3. Transform output: y = A^T × m × A (per channel, per 2-row strip)
+ *
+ * Key insight: B^T operates on ROWS (element-wise across full width),
+ * then B operates on COLUMNS (stride-2 shifts). Both are vectorizable.
+ */
+
+#include "nn2_internal.h"
+#include <string.h>
+#include <stdlib.h>
+#include <math.h>
+#include <immintrin.h>
+
+/* Pre-transform weights: U[16][Cout][Cin] from W[Cout][Cin*9] */
+void nn2_winograd_transform_weights(const float* W, int Cout, int Cin, float* U)
+{
+ for (int oc = 0; oc < Cout; oc++) {
+ for (int ic = 0; ic < Cin; ic++) {
+ const float* g = W + oc * Cin * 9 + ic * 9;
+ /* G × g (4×3): rows */
+ float t[4][3];
+ t[0][0]=g[0]; t[0][1]=g[1]; t[0][2]=g[2];
+ t[1][0]=(g[0]+g[3]+g[6])*.5f; t[1][1]=(g[1]+g[4]+g[7])*.5f; t[1][2]=(g[2]+g[5]+g[8])*.5f;
+ t[2][0]=(g[0]-g[3]+g[6])*.5f; t[2][1]=(g[1]-g[4]+g[7])*.5f; t[2][2]=(g[2]-g[5]+g[8])*.5f;
+ t[3][0]=g[6]; t[3][1]=g[7]; t[3][2]=g[8];
+ /* × G^T (4×4): columns */
+ for (int i = 0; i < 4; i++) {
+ float u0 = t[i][0];
+ float u1 = (t[i][0]+t[i][1]+t[i][2])*.5f;
+ float u2 = (t[i][0]-t[i][1]+t[i][2])*.5f;
+ float u3 = t[i][2];
+ U[(i*4+0)*Cout*Cin + oc*Cin + ic] = u0;
+ U[(i*4+1)*Cout*Cin + oc*Cin + ic] = u1;
+ U[(i*4+2)*Cout*Cin + oc*Cin + ic] = u2;
+ U[(i*4+3)*Cout*Cin + oc*Cin + ic] = u3;
+ }
+ }
+ }
+}
+
+/* Winograd F(2,3) convolution: 3x3 stride-1 pad-1 */
+void nn2_winograd_conv3x3(
+ const float* input, int Cin, int H, int W,
+ const float* U, /* [16][Cout][Cin] pre-transformed weights */
+ const float* bias, int Cout, int act,
+ float* output,
+ float* workspace) /* needs: 16*Cin*tiles + 16*Cout*tiles floats */
+{
+ int Htiles = (H + 1) / 2;
+ int Wtiles = (W + 1) / 2;
+ int ntiles = Htiles * Wtiles;
+
+ float* V = workspace; /* [16][Cin][ntiles] */
+ float* M = V + 16 * Cin * ntiles; /* [16][Cout][ntiles] + [Cout][ntiles][16] transposed */
+ /* Total workspace: 16*Cin*ntiles + 2*16*Cout*ntiles */
+
+ /* ============ Input transform ============
+ * For each channel, for each tile-row th:
+ * Load 4 input rows (with padding)
+ * Apply B^T on rows (element-wise across full width)
+ * Apply B on columns (extract stride-2 shifted values)
+ * Store to V[alpha][c][tile_idx] */
+
+ for (int c = 0; c < Cin; c++) {
+ const float* src = input + c * H * W;
+
+ for (int th = 0; th < Htiles; th++) {
+ /* 4 input rows for this tile row */
+ int r0 = th*2 - 1, r1 = th*2, r2 = th*2 + 1, r3 = th*2 + 2;
+ const float* d0 = (r0 >= 0 && r0 < H) ? src + r0*W : NULL;
+ const float* d1 = (r1 >= 0 && r1 < H) ? src + r1*W : NULL;
+ const float* d2 = (r2 >= 0 && r2 < H) ? src + r2*W : NULL;
+ const float* d3 = (r3 >= 0 && r3 < H) ? src + r3*W : NULL;
+
+ /* B^T on rows: t0=d0-d2, t1=d1+d2, t2=-d1+d2, t3=d1-d3
+ * Process full width with AVX-512 */
+ float t0[324], t1[324], t2[324], t3[324]; /* max W+4 */
+
+#ifdef __AVX512F__
+ int j = 0;
+ for (; j + 16 <= W; j += 16) {
+ __m512 vd0 = d0 ? _mm512_loadu_ps(d0+j) : _mm512_setzero_ps();
+ __m512 vd1 = d1 ? _mm512_loadu_ps(d1+j) : _mm512_setzero_ps();
+ __m512 vd2 = d2 ? _mm512_loadu_ps(d2+j) : _mm512_setzero_ps();
+ __m512 vd3 = d3 ? _mm512_loadu_ps(d3+j) : _mm512_setzero_ps();
+ _mm512_storeu_ps(t0+j, _mm512_sub_ps(vd0, vd2));
+ _mm512_storeu_ps(t1+j, _mm512_add_ps(vd1, vd2));
+ _mm512_storeu_ps(t2+j, _mm512_sub_ps(vd2, vd1));
+ _mm512_storeu_ps(t3+j, _mm512_sub_ps(vd1, vd3));
+ }
+ for (; j < W; j++) {
+ float v0=d0?d0[j]:0, v1=d1?d1[j]:0, v2=d2?d2[j]:0, v3=d3?d3[j]:0;
+ t0[j]=v0-v2; t1[j]=v1+v2; t2[j]=v2-v1; t3[j]=v1-v3;
+ }
+#else
+ for (int j = 0; j < W; j++) {
+ float v0=d0?d0[j]:0, v1=d1?d1[j]:0, v2=d2?d2[j]:0, v3=d3?d3[j]:0;
+ t0[j]=v0-v2; t1[j]=v1+v2; t2[j]=v2-v1; t3[j]=v1-v3;
+ }
+#endif
+
+ /* B on columns: for each tile tw, extract columns at tw*2-1, tw*2, tw*2+1, tw*2+2
+ * V[i*4+0] = t[i][tw*2-1] - t[i][tw*2+1]
+ * V[i*4+1] = t[i][tw*2] + t[i][tw*2+1]
+ * V[i*4+2] = t[i][tw*2+1] - t[i][tw*2]
+ * V[i*4+3] = t[i][tw*2] - t[i][tw*2+2] */
+ float* trows[4] = {t0, t1, t2, t3};
+ for (int i = 0; i < 4; i++) {
+ float* tr = trows[i];
+ for (int tw = 0; tw < Wtiles; tw++) {
+ int tile_idx = th * Wtiles + tw;
+ int c0 = tw*2 - 1, c1 = tw*2, c2 = tw*2 + 1, c3 = tw*2 + 2;
+ float v0 = (c0>=0&&c0<W) ? tr[c0] : 0;
+ float v1 = (c1>=0&&c1<W) ? tr[c1] : 0;
+ float v2 = (c2>=0&&c2<W) ? tr[c2] : 0;
+ float v3 = (c3>=0&&c3<W) ? tr[c3] : 0;
+ V[(i*4+0)*Cin*ntiles + c*ntiles + tile_idx] = v0 - v2;
+ V[(i*4+1)*Cin*ntiles + c*ntiles + tile_idx] = v1 + v2;
+ V[(i*4+2)*Cin*ntiles + c*ntiles + tile_idx] = v2 - v1;
+ V[(i*4+3)*Cin*ntiles + c*ntiles + tile_idx] = v1 - v3;
+ }
+ }
+ }
+ }
+
+ /* ============ 16 GEMMs + transpose to tile-major ============
+ * GEMM into M_raw[16][Cout][ntiles], then transpose to Mt[Cout][ntiles][16]
+ * so output transform has contiguous access (1 cache line per tile). */
+ float* M_raw = M;
+ float* Mt = M_raw + 16 * Cout * ntiles; /* need extra space for transposed */
+
+ for (int a = 0; a < 16; a++) {
+ nn2_sgemm(Cout, Cin, ntiles,
+ U + a * Cout * Cin, Cin,
+ V + a * Cin * ntiles, ntiles,
+ M_raw + a * Cout * ntiles, ntiles);
+ }
+
+ /* Transpose: M_raw[a][oc][t] → Mt[oc][t][a] (16 floats contiguous per tile) */
+ for (int oc = 0; oc < Cout; oc++) {
+ for (int t = 0; t < ntiles; t++) {
+ float* dst = Mt + (oc * ntiles + t) * 16;
+ for (int a = 0; a < 16; a++)
+ dst[a] = M_raw[a * Cout * ntiles + oc * ntiles + t];
+ }
+ }
+
+ /* ============ Output transform (cache-friendly) ============
+ * Mt[oc][t][16] — all 16 components for one tile are contiguous.
+ * m[i][j] = Mt[oc][t][i*4+j] for i=0..3, j=0..3 */
+ for (int oc = 0; oc < Cout; oc++) {
+ float b = bias[oc];
+ float* dst = output + oc * H * W;
+
+ for (int th = 0; th < Htiles; th++) {
+ for (int tw = 0; tw < Wtiles; tw++) {
+ int tidx = th * Wtiles + tw;
+ int oh = th * 2, ow = tw * 2;
+
+ const float* m = Mt + (oc * ntiles + tidx) * 16; /* contiguous! */
+
+ /* A^T × m × A → 2×2 output */
+ float r00 = m[0]+m[4]+m[8], r01 = m[1]+m[5]+m[9];
+ float r02 = m[2]+m[6]+m[10], r03 = m[3]+m[7]+m[11];
+ float r10 = m[4]-m[8]-m[12], r11 = m[5]-m[9]-m[13];
+ float r12 = m[6]-m[10]-m[14],r13 = m[7]-m[11]-m[15];
+
+ float y00 = r00+r01+r02 + b;
+ float y01 = r01-r02-r03 + b;
+ float y10 = r10+r11+r12 + b;
+ float y11 = r11-r12-r13 + b;
+
+ if (act == 1) {
+ #define S(x) ((x)*(0.5f+0.5f*(x)/(1.0f+fabsf(x))))
+ y00=S(y00); y01=S(y01); y10=S(y10); y11=S(y11);
+ #undef S
+ }
+
+ if (oh<H && ow<W) dst[oh*W+ow] = y00;
+ if (oh<H && ow+1<W) dst[oh*W+ow+1] = y01;
+ if (oh+1<H && ow<W) dst[(oh+1)*W+ow] = y10;
+ if (oh+1<H && ow+1<W) dst[(oh+1)*W+ow+1] = y11;
+ }
+ }
+ }
+}
diff --git a/nn2/test_dets.jsonl b/nn2/test_dets.jsonl
new file mode 100644
index 0000000..976c6fd
--- /dev/null
+++ b/nn2/test_dets.jsonl
@@ -0,0 +1,20 @@
+{"camera":0,"timestamp":16.1,"inference_ms":14.7,"detections":[{"class":"book","class_id":73,"confidence":0.992,"bbox":[-39.7,-151.0,745.9,554.2]}]}
+{"camera":0,"timestamp":29.1,"inference_ms":12.1,"detections":[{"class":"book","class_id":73,"confidence":0.997,"bbox":[-70.8,-251.0,746.9,520.6]}]}
+{"camera":0,"timestamp":43.1,"inference_ms":13.0,"detections":[{"class":"book","class_id":73,"confidence":0.995,"bbox":[-46.8,-138.7,735.3,557.3]}]}
+{"camera":0,"timestamp":57.9,"inference_ms":12.6,"detections":[{"class":"book","class_id":73,"confidence":0.996,"bbox":[-52.9,-244.0,742.3,529.0]}]}
+{"camera":0,"timestamp":70.9,"inference_ms":12.1,"detections":[{"class":"book","class_id":73,"confidence":0.995,"bbox":[-53.1,-249.1,743.6,522.5]}]}
+{"camera":0,"timestamp":97.7,"inference_ms":11.8,"detections":[{"class":"book","class_id":73,"confidence":0.998,"bbox":[-59.5,-250.6,736.8,535.3]}]}
+{"camera":0,"timestamp":110.1,"inference_ms":11.2,"detections":[{"class":"book","class_id":73,"confidence":0.998,"bbox":[-54.0,-135.1,726.4,535.7]}]}
+{"camera":0,"timestamp":124.5,"inference_ms":13.3,"detections":[{"class":"book","class_id":73,"confidence":0.995,"bbox":[-64.8,-256.4,740.6,533.1]}]}
+{"camera":0,"timestamp":136.9,"inference_ms":11.2,"detections":[{"class":"book","class_id":73,"confidence":0.999,"bbox":[-90.5,-255.0,738.5,524.5]}]}
+{"camera":0,"timestamp":148.8,"inference_ms":10.8,"detections":[{"class":"book","class_id":73,"confidence":0.998,"bbox":[-77.1,-257.1,738.5,529.4]}]}
+{"camera":0,"timestamp":160.9,"inference_ms":10.9,"detections":[{"class":"book","class_id":73,"confidence":0.997,"bbox":[-59.3,-257.5,737.0,523.9]}]}
+{"camera":0,"timestamp":174.2,"inference_ms":12.4,"detections":[{"class":"book","class_id":73,"confidence":0.997,"bbox":[-46.5,-256.3,742.5,514.2]}]}
+{"camera":0,"timestamp":184.6,"inference_ms":9.6,"detections":[{"class":"book","class_id":73,"confidence":0.991,"bbox":[-38.5,-140.6,748.4,534.4]}]}
+{"camera":0,"timestamp":196.7,"inference_ms":11.1,"detections":[{"class":"book","class_id":73,"confidence":0.995,"bbox":[-52.0,-151.5,746.5,561.6]}]}
+{"camera":0,"timestamp":209.3,"inference_ms":11.8,"detections":[{"class":"book","class_id":73,"confidence":0.996,"bbox":[-44.3,-145.8,740.6,542.6]}]}
+{"camera":0,"timestamp":220.7,"inference_ms":10.4,"detections":[{"class":"book","class_id":73,"confidence":0.994,"bbox":[-55.9,-259.0,742.5,535.6]}]}
+{"camera":0,"timestamp":234.3,"inference_ms":12.6,"detections":[{"class":"book","class_id":73,"confidence":0.996,"bbox":[-43.2,-252.4,742.2,522.7]}]}
+{"camera":0,"timestamp":246.2,"inference_ms":10.9,"detections":[{"class":"book","class_id":73,"confidence":0.994,"bbox":[-43.7,-249.1,739.4,526.2]}]}
+{"camera":0,"timestamp":258.8,"inference_ms":11.8,"detections":[{"class":"book","class_id":73,"confidence":0.997,"bbox":[-69.5,-254.9,742.8,526.7]}]}
+{"camera":0,"timestamp":273.3,"inference_ms":12.8,"detections":[{"class":"book","class_id":73,"confidence":0.996,"bbox":[-59.1,-255.6,742.3,528.8]}]}
diff --git a/nn2/tests/bench_onnx.py b/nn2/tests/bench_onnx.py
new file mode 100644
index 0000000..f16d0f0
--- /dev/null
+++ b/nn2/tests/bench_onnx.py
@@ -0,0 +1,24 @@
+import sys, time, numpy as np, onnxruntime as ort
+WEIGHTS_V2 = "tests/minifasnet_v2_27.onnx"
+WEIGHTS_V1SE = "tests/minifasnet_v1se_40.onnx"
+T_V2 = "tests/test_27.bin"
+T_V1SE = "tests/test_40.bin"
+
+def bench(weights_path, test_path, name, iters=100):
+ # ONNX Runtime — try AVX-512 BLAS via default CPU EP first.
+ s = ort.InferenceSession(weights_path, providers=["CPUExecutionProvider"])
+ bgr = np.frombuffer(open(test_path, "rb").read(), dtype=np.uint8).reshape(80, 80, 3)
+ x = bgr.astype(np.float32).transpose(2, 0, 1)[None]
+ # Warmup
+ for _ in range(10): _ = s.run(None, {"input": x})
+ # Measure
+ t0 = time.perf_counter()
+ for _ in range(iters):
+ p = s.run(None, {"input": x})[0][0]
+ dt = (time.perf_counter() - t0) * 1000 / iters
+ print(f"ONNX {name}: probs=[{p[0]:.6f}, {p[1]:.6f}, {p[2]:.6f}] P(live)={p[1]:.4f} {dt:.3f} ms/iter ({iters} iters)")
+ return dt
+
+dt27 = bench(WEIGHTS_V2, T_V2, "v2 @ 2.7")
+dt40 = bench(WEIGHTS_V1SE, T_V1SE, "v1se @ 4.0")
+print(f"ENSEMBLE (sum) = {(dt27+dt40):.3f} ms")
diff --git a/nn2/tools/bench_compare.py b/nn2/tools/bench_compare.py
new file mode 100644
index 0000000..4f0a743
--- /dev/null
+++ b/nn2/tools/bench_compare.py
@@ -0,0 +1,52 @@
+"""Direct comparison: nn2 vs ONNX Runtime at 320x320."""
+import time
+import subprocess
+import numpy as np
+import onnxruntime as ort
+
+RUNS = 50
+WARMUP = 10
+
+print("=" * 55)
+print(" nn2 vs ONNX Runtime — YOLOv8n @ 320x320")
+print("=" * 55)
+
+# --- ONNX Runtime ---
+sess = ort.InferenceSession("yolov8n_320.onnx", providers=["CPUExecutionProvider"])
+inp = sess.get_inputs()[0]
+dummy = np.random.rand(1, 3, 320, 320).astype(np.float32)
+
+for _ in range(WARMUP):
+ sess.run(None, {inp.name: dummy})
+
+times = []
+for _ in range(RUNS):
+ t0 = time.perf_counter()
+ sess.run(None, {inp.name: dummy})
+ t1 = time.perf_counter()
+ times.append((t1 - t0) * 1000)
+
+times.sort()
+onnx_avg = sum(times) / len(times)
+onnx_med = times[len(times) // 2]
+onnx_best = times[0]
+
+print(f"\nONNX Runtime {ort.__version__} (CPU):")
+print(f" Average: {onnx_avg:.1f} ms ({1000/onnx_avg:.0f} FPS)")
+print(f" Median: {onnx_med:.1f} ms")
+print(f" Best: {onnx_best:.1f} ms")
+
+# --- nn2 (from last benchmark) ---
+nn2_avg = 8.8 # from nn2.exe benchmark
+print(f"\nnn2 (pure C, AVX-512):")
+print(f" Average: {nn2_avg:.1f} ms ({1000/nn2_avg:.0f} FPS)")
+
+# --- Comparison ---
+ratio = onnx_avg / nn2_avg
+print(f"\n{'=' * 55}")
+if ratio > 1:
+ print(f" nn2 is {ratio:.2f}x FASTER than ONNX Runtime")
+else:
+ print(f" ONNX Runtime is {1/ratio:.2f}x faster than nn2")
+print(f" nn2: {nn2_avg:.1f}ms vs ONNX RT: {onnx_avg:.1f}ms")
+print(f"{'=' * 55}")
diff --git a/nn2/tools/bench_onnx.py b/nn2/tools/bench_onnx.py
new file mode 100644
index 0000000..1c38075
--- /dev/null
+++ b/nn2/tools/bench_onnx.py
@@ -0,0 +1,48 @@
+"""Benchmark ONNX Runtime YOLOv8n at 320x320 for comparison with nn2."""
+import time
+import numpy as np
+import onnxruntime as ort
+
+MODEL = "yolov8n.onnx"
+SIZE = 320
+WARMUP = 5
+RUNS = 50
+
+print(f"ONNX Runtime {ort.__version__}")
+print(f"Providers: {ort.get_available_providers()}")
+
+sess = ort.InferenceSession(MODEL, providers=["CPUExecutionProvider"])
+inp = sess.get_inputs()[0]
+print(f"Input: {inp.name} {inp.shape} {inp.type}")
+
+# Check if model expects 640 — if so, use 640
+h, w = inp.shape[2], inp.shape[3]
+if isinstance(h, int):
+ SIZE = h
+ print(f"Model expects {SIZE}x{SIZE}")
+
+dummy = np.random.rand(1, 3, SIZE, SIZE).astype(np.float32)
+
+# Warmup
+for _ in range(WARMUP):
+ sess.run(None, {inp.name: dummy})
+
+# Benchmark
+times = []
+for _ in range(RUNS):
+ t0 = time.perf_counter()
+ sess.run(None, {inp.name: dummy})
+ t1 = time.perf_counter()
+ times.append((t1 - t0) * 1000)
+
+times.sort()
+avg = sum(times) / len(times)
+med = times[len(times) // 2]
+best = times[0]
+p95 = times[int(len(times) * 0.95)]
+
+print(f"\nONNX Runtime @ {SIZE}x{SIZE} ({RUNS} runs):")
+print(f" Average: {avg:.1f} ms ({1000/avg:.1f} FPS)")
+print(f" Median: {med:.1f} ms")
+print(f" Best: {best:.1f} ms")
+print(f" P95: {p95:.1f} ms")
diff --git a/nn2/tools/bench_onnx_320.py b/nn2/tools/bench_onnx_320.py
new file mode 100644
index 0000000..126d746
--- /dev/null
+++ b/nn2/tools/bench_onnx_320.py
@@ -0,0 +1,44 @@
+"""Benchmark ONNX Runtime YOLOv8n at 320x320 — resize input to match nn2."""
+import time
+import numpy as np
+import onnxruntime as ort
+
+MODEL = "yolov8n.onnx"
+WARMUP = 5
+RUNS = 50
+
+print(f"ONNX Runtime {ort.__version__}")
+
+# Use 320x320 input regardless of model's expected size
+# ONNX RT supports dynamic shapes for YOLOv8
+sess_opts = ort.SessionOptions()
+sess_opts.intra_op_num_threads = 0 # auto
+sess = ort.InferenceSession(MODEL, sess_opts, providers=["CPUExecutionProvider"])
+inp = sess.get_inputs()[0]
+print(f"Input: {inp.name} {inp.shape}")
+
+# Test both 320 and 640
+for SIZE in [320, 640]:
+ dummy = np.random.rand(1, 3, SIZE, SIZE).astype(np.float32)
+
+ # Warmup
+ for _ in range(WARMUP):
+ sess.run(None, {inp.name: dummy})
+
+ # Benchmark
+ times = []
+ for _ in range(RUNS):
+ t0 = time.perf_counter()
+ sess.run(None, {inp.name: dummy})
+ t1 = time.perf_counter()
+ times.append((t1 - t0) * 1000)
+
+ times.sort()
+ avg = sum(times) / len(times)
+ med = times[len(times) // 2]
+ best = times[0]
+
+ print(f"\n=== ONNX Runtime @ {SIZE}x{SIZE} ({RUNS} runs) ===")
+ print(f" Average: {avg:.1f} ms ({1000/avg:.1f} FPS)")
+ print(f" Median: {med:.1f} ms")
+ print(f" Best: {best:.1f} ms")
diff --git a/nn2/tools/export_minifasnet.py b/nn2/tools/export_minifasnet.py
new file mode 100644
index 0000000..103a881
--- /dev/null
+++ b/nn2/tools/export_minifasnet.py
@@ -0,0 +1,184 @@
+#!/usr/bin/env python3
+"""
+export_minifasnet.py — Convert MinivisionAI Silent-Face MiniFASNet PyTorch
+weights (.pth) to nn2 binary format (.bin) for the antispoof port.
+
+Layer write order MUST match `src/minifasnet.c` loader. Each Conv_block
+folds its BatchNorm into [weight, bias]; PReLU.weight is appended when
+the block uses activation. Project conv has no activation. Final Linear
+folds BN1d into [w, b].
+"""
+
+import argparse, struct, sys
+from collections import OrderedDict
+from pathlib import Path
+
+import numpy as np
+import torch
+import torch.nn as nn
+
+
+def fold_bn_conv(conv, bn):
+ """Fold BN(running_mean, running_var, weight, bias, eps) into conv weights/bias."""
+ w = conv.weight.data.clone()
+ if conv.bias is not None:
+ b = conv.bias.data.clone()
+ else:
+ b = torch.zeros(w.shape[0], device=w.device)
+ mean = bn.running_mean
+ var = bn.running_var
+ gamma = bn.weight
+ beta = bn.bias
+ eps = bn.eps
+ std = torch.sqrt(var + eps)
+ scale = gamma / std
+ if w.dim() == 4:
+ w_new = w * scale.reshape(-1, 1, 1, 1)
+ else:
+ w_new = w * scale.reshape(-1, 1)
+ b_new = (b - mean) * scale + beta
+ return w_new.cpu().numpy(), b_new.cpu().numpy()
+
+
+def fold_bn1d_linear(lin, bn1d):
+ """Fold BN1d into Linear: y = (W*x+b - μ)/√(v+ε)*γ + β = (γ/√(v+ε))*W*x + (γ/√(v+ε))*(b-μ) + β"""
+ W = lin.weight.data.clone()
+ if lin.bias is not None:
+ b = lin.bias.data.clone()
+ else:
+ b = torch.zeros(W.shape[0], device=W.device)
+ mean = bn1d.running_mean
+ var = bn1d.running_var
+ gamma = bn1d.weight
+ beta = bn1d.bias
+ eps = bn1d.eps
+ std = torch.sqrt(var + eps)
+ scale = gamma / std
+ W_new = W * scale.reshape(-1, 1)
+ b_new = (b - mean) * scale + beta
+ return W_new.cpu().numpy(), b_new.cpu().numpy()
+
+
+def write_tensor(f, arr, tag=""):
+ flat = np.ascontiguousarray(arr).astype(np.float32).ravel()
+ f.write(struct.pack("<I", len(flat)))
+ f.write(flat.tobytes())
+ return len(flat)
+
+
+def write_conv_block(f, cb, has_prelu, tag):
+ """Conv_block: conv + bn + prelu(optional). Writes [w, b, prelu_alpha?]."""
+ w, b = fold_bn_conv(cb.conv, cb.bn)
+ write_tensor(f, w, f"{tag}.w")
+ write_tensor(f, b, f"{tag}.b")
+ if has_prelu:
+ write_tensor(f, cb.prelu.weight.data.cpu().numpy(), f"{tag}.prelu")
+
+
+def write_linear_block(f, cb, tag):
+ """Linear_block: conv + bn, NO activation."""
+ w, b = fold_bn_conv(cb.conv, cb.bn)
+ write_tensor(f, w, f"{tag}.w")
+ write_tensor(f, b, f"{tag}.b")
+
+
+def write_dw_block(f, dw, has_se, tag):
+ """Depth_Wise: expand (Conv_block) + dw (Conv_block) + project (Linear_block) + optional SE."""
+ write_conv_block(f, dw.conv, True, f"{tag}.expand")
+ write_conv_block(f, dw.conv_dw, True, f"{tag}.dw")
+ write_linear_block(f, dw.project, f"{tag}.project")
+ if has_se:
+ se = dw.se_module
+ # fc1: Conv2d 1x1 + BN1 + ReLU + Conv2d 1x1 + BN2 + sigmoid; fuse BN into bias
+ # Treat the Conv2d like a 1x1 conv with BN — same fold_bn_conv works.
+ w1, b1 = fold_bn_conv(se.fc1, se.bn1)
+ w2, b2 = fold_bn_conv(se.fc2, se.bn2)
+ # The fc1/fc2 are Conv2d 1x1; weights shape is [out, in, 1, 1] → write as [out*in].
+ write_tensor(f, w1, f"{tag}.se.fc1.w")
+ write_tensor(f, b1, f"{tag}.se.fc1.b")
+ write_tensor(f, w2, f"{tag}.se.fc2.w")
+ write_tensor(f, b2, f"{tag}.se.fc2.b")
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--repo", default="D:/apps/facex/training/Silent-Face-Anti-Spoofing",
+ help="path to MinivisionAI repo (for src.model_lib.MiniFASNet)")
+ ap.add_argument("--ckpt", required=True, help="path to .pth")
+ ap.add_argument("--variant", choices=["v2", "v1se"], required=True)
+ ap.add_argument("--output", required=True)
+ args = ap.parse_args()
+
+ sys.path.insert(0, args.repo)
+ from src.model_lib.MiniFASNet import MiniFASNetV2, MiniFASNetV1SE
+
+ ctor = MiniFASNetV2 if args.variant == "v2" else MiniFASNetV1SE
+ variant_id = 0 if args.variant == "v2" else 1
+ has_se = (args.variant == "v1se")
+
+ net = ctor(conv6_kernel=(5, 5)).eval()
+ sd = torch.load(args.ckpt, map_location="cpu", weights_only=False)
+ # strip module. prefix if needed
+ if next(iter(sd)).startswith("module."):
+ sd = OrderedDict((k[7:], v) for k, v in sd.items())
+ net.load_state_dict(sd)
+ print(f"loaded {args.variant} from {args.ckpt}")
+
+ Path(args.output).parent.mkdir(parents=True, exist_ok=True)
+ with open(args.output, "wb") as f:
+ f.write(b"MFN1")
+ f.write(struct.pack("<III", variant_id, 80, 0)) # num_tensors placeholder
+ tensors_before = f.tell()
+
+ # === Backbone Conv_blocks ===
+ write_conv_block(f, net.conv1, True, "conv1")
+ write_conv_block(f, net.conv2_dw, True, "conv2_dw")
+
+ # === Depth_Wise / Residual stages ===
+ # conv_23
+ write_dw_block(f, net.conv_23, False, "conv_23")
+ # conv_3 = Residual of 4 Depth_Wise (last has SE if V1SE)
+ for i, dw in enumerate(net.conv_3.model):
+ write_dw_block(f, dw, has_se and i == len(net.conv_3.model) - 1, f"conv_3[{i}]")
+ write_dw_block(f, net.conv_34, False, "conv_34")
+ for i, dw in enumerate(net.conv_4.model):
+ write_dw_block(f, dw, has_se and i == len(net.conv_4.model) - 1, f"conv_4[{i}]")
+ write_dw_block(f, net.conv_45, False, "conv_45")
+ for i, dw in enumerate(net.conv_5.model):
+ write_dw_block(f, dw, has_se and i == len(net.conv_5.model) - 1, f"conv_5[{i}]")
+
+ # === Head ===
+ write_conv_block(f, net.conv_6_sep, True, "conv_6_sep")
+ write_linear_block(f, net.conv_6_dw, "conv_6_dw")
+
+ # Linear 512→128 + BN1d (folded), then Linear 128→3 (no bias)
+ w_lin, b_lin = fold_bn1d_linear(net.linear, net.bn)
+ write_tensor(f, w_lin, "linear.w")
+ write_tensor(f, b_lin, "linear.b")
+ # prob: 128→3, no bias
+ write_tensor(f, net.prob.weight.data.cpu().numpy(), "prob.w")
+
+ # Patch num_tensors: count how many [size, data] records were written
+ end = f.tell()
+ # We don't track tensor count individually; rewind and count.
+ # Simpler: read back by scanning. But to avoid that, track tensor writes inline.
+
+ # Re-read to count tensors and patch
+ with open(args.output, "rb") as f:
+ f.seek(16)
+ n = 0
+ while True:
+ head = f.read(4)
+ if len(head) < 4: break
+ sz = struct.unpack("<I", head)[0]
+ f.seek(sz * 4, 1)
+ n += 1
+ with open(args.output, "r+b") as f:
+ f.seek(12)
+ f.write(struct.pack("<I", n))
+ size = Path(args.output).stat().st_size
+ print(f"wrote {args.output} {n} tensors {size/1024:.1f} KB")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/nn2/tools/export_nanodet.py b/nn2/tools/export_nanodet.py
new file mode 100644
index 0000000..2def5db
--- /dev/null
+++ b/nn2/tools/export_nanodet.py
@@ -0,0 +1,108 @@
+#!/usr/bin/env python3
+"""
+export_nanodet.py — Export NanoDet-Plus-m ONNX weights to nn2 binary format.
+
+Reads the ONNX model graph, extracts all Conv weights (with fused BN),
+and writes them sequentially in nn2 format.
+
+Weight file format:
+ [4] magic "NN2N" (NanoDet)
+ [4] uint32 num_classes (80)
+ [4] uint32 input_size (320)
+ [4] uint32 num_conv_layers
+ For each conv layer:
+ [4] uint32 cout
+ [4] uint32 cin (cin_per_group for DW)
+ [4] uint32 k
+ [4] uint32 stride
+ [4] uint32 pad
+ [4] uint32 groups (1=regular, cout=depthwise)
+ [4] uint32 act (0=none, 3=LeakyReLU)
+ [cout*4] float32 bias
+ [cout*cin_per_group*k*k*4] float32 weights
+"""
+
+import struct
+import numpy as np
+import onnx
+
+
+def main():
+ import argparse
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--onnx', default='weights/nanodet_plus_m_320.onnx')
+ parser.add_argument('--output', default='weights/nanodet_plus_m_320.bin')
+ parser.add_argument('--size', type=int, default=320)
+ args = parser.parse_args()
+
+ model = onnx.load(args.onnx)
+
+ # Build initializer lookup
+ inits = {}
+ for init in model.graph.initializer:
+ from onnx.numpy_helper import to_array
+ inits[init.name] = to_array(init).copy()
+
+ # Extract conv layers in order
+ convs = []
+ for node in model.graph.node:
+ if node.op_type != 'Conv':
+ continue
+
+ attrs = {a.name: a for a in node.attribute}
+ group = attrs['group'].i if 'group' in attrs else 1
+ ks = list(attrs['kernel_shape'].ints) if 'kernel_shape' in attrs else [1, 1]
+ stride = list(attrs['strides'].ints) if 'strides' in attrs else [1, 1]
+ pad = list(attrs['pads'].ints) if 'pads' in attrs else [0, 0, 0, 0]
+
+ w_name = node.input[1]
+ b_name = node.input[2] if len(node.input) > 2 else None
+
+ w = inits[w_name]
+ b = inits[b_name] if b_name and b_name in inits else np.zeros(w.shape[0], dtype=np.float32)
+
+ cout = w.shape[0]
+ cin_per_g = w.shape[1]
+
+ # Determine activation from the next node
+ act = 0 # default none
+ # Find output name and check if next node is LeakyRelu
+ out_name = node.output[0]
+ for next_node in model.graph.node:
+ if next_node.op_type == 'LeakyRelu' and out_name in next_node.input:
+ act = 3 # LeakyReLU
+ break
+
+ convs.append({
+ 'cout': cout, 'cin_per_g': cin_per_g,
+ 'k': ks[0], 's': stride[0], 'p': pad[0],
+ 'group': group, 'act': act,
+ 'w': w, 'b': b,
+ 'name': w_name
+ })
+
+ nc = 80 # COCO classes
+ print(f'NanoDet-Plus-m: {len(convs)} conv layers, input={args.size}')
+
+ with open(args.output, 'wb') as f:
+ f.write(b'NN2N')
+ f.write(struct.pack('<III', nc, args.size, len(convs)))
+
+ for i, c in enumerate(convs):
+ f.write(struct.pack('<IIIIIII',
+ c['cout'], c['cin_per_g'], c['k'], c['s'], c['p'],
+ c['group'], c['act']))
+ c['b'].astype(np.float32).tofile(f)
+ c['w'].astype(np.float32).tofile(f)
+
+ dw = ' [DW]' if c['group'] > 1 else ''
+ act_str = ' LeakyReLU' if c['act'] == 3 else ''
+ if i < 10 or i >= len(convs) - 5 or i % 20 == 0:
+ print(f' {i:3d} {c["cout"]:4d}x{c["cin_per_g"]:4d} k={c["k"]} s={c["s"]} g={c["group"]:3d}{dw}{act_str}')
+
+ fsize = open(args.output, 'rb').seek(0, 2)
+ print(f'\nExported: {args.output} ({len(convs)} layers, {fsize:,} bytes, {fsize/1024/1024:.1f} MB)')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/nn2/tools/export_onnx_320.py b/nn2/tools/export_onnx_320.py
new file mode 100644
index 0000000..1915fc6
--- /dev/null
+++ b/nn2/tools/export_onnx_320.py
@@ -0,0 +1,21 @@
+"""Export YOLOv8n ONNX at 320x320 for fair comparison."""
+try:
+ from ultralytics import YOLO
+ model = YOLO("yolov8n.pt")
+ model.export(format="onnx", imgsz=320, simplify=True)
+ import shutil
+ shutil.move("yolov8n.onnx", "yolov8n_320.onnx")
+ print("Exported yolov8n_320.onnx")
+except ImportError:
+ # Try onnx shape inference to resize
+ import onnx
+ from onnx import shape_inference
+ print("ultralytics not available, trying onnx resize...")
+ model = onnx.load("yolov8n.onnx")
+ # Change input shape
+ for inp in model.graph.input:
+ for dim in inp.type.tensor_type.shape.dim:
+ if dim.dim_value == 640:
+ dim.dim_value = 320
+ onnx.save(model, "yolov8n_320.onnx")
+ print("Saved yolov8n_320.onnx (input resized, intermediate shapes may be wrong)")
diff --git a/nn2/tools/export_yolov8n.py b/nn2/tools/export_yolov8n.py
new file mode 100644
index 0000000..0bba27c
--- /dev/null
+++ b/nn2/tools/export_yolov8n.py
@@ -0,0 +1,161 @@
+#!/usr/bin/env python3
+"""
+export_yolov8n.py — Export YOLOv8n weights to nn2 binary format.
+
+Usage:
+ pip install ultralytics
+ python tools/export_yolov8n.py [--model yolov8n.pt] [--size 640] [--output weights/yolov8n.bin]
+
+Weight file format:
+ [4] magic "NN2W"
+ [4] uint32 num_classes
+ [4] uint32 input_size
+ [4] uint32 num_tensors
+ For each tensor:
+ [4] uint32 size_in_floats
+ [N*4] float32 data
+
+Tensors are written in the exact order expected by nn2_load_weights():
+ backbone convs → backbone c2f blocks → sppf → neck c2f → neck convs → head
+Each conv = [weight_tensor, bias_tensor] (bias includes folded BN).
+"""
+
+import struct
+import argparse
+import numpy as np
+import torch
+
+
+def fold_bn(conv, bn):
+ """Fold BatchNorm into Conv weights: w_new, b_new."""
+ w = conv.weight.data.clone()
+ if conv.bias is not None:
+ b = conv.bias.data.clone()
+ else:
+ b = torch.zeros(w.shape[0])
+
+ mean = bn.running_mean
+ var = bn.running_var
+ gamma = bn.weight
+ beta = bn.bias
+ eps = bn.eps
+
+ std = torch.sqrt(var + eps)
+ scale = gamma / std
+
+ # Fold: w_new = w * scale, b_new = (b - mean) * scale + beta
+ w_new = w * scale.reshape(-1, 1, 1, 1) if w.dim() == 4 else w * scale.reshape(-1, 1)
+ b_new = (b - mean) * scale + beta
+
+ return w_new.numpy(), b_new.numpy()
+
+
+def write_tensor(f, data):
+ """Write a single tensor: [size_in_floats][float32 data]."""
+ flat = data.flatten().astype(np.float32)
+ f.write(struct.pack('<I', len(flat)))
+ f.write(flat.tobytes())
+
+
+def write_conv(f, conv_module, tensors_count):
+ """Write a Conv (with fused BN) or raw Conv2d."""
+ if hasattr(conv_module, 'conv') and hasattr(conv_module, 'bn'):
+ # ultralytics Conv = conv + bn + act
+ w, b = fold_bn(conv_module.conv, conv_module.bn)
+ elif hasattr(conv_module, 'weight'):
+ # raw nn.Conv2d (no BN, used in detection head output)
+ w = conv_module.weight.data.numpy()
+ b = conv_module.bias.data.numpy() if conv_module.bias is not None else np.zeros(w.shape[0], dtype=np.float32)
+ else:
+ raise ValueError(f"Unknown conv type: {type(conv_module)}")
+
+ # Reshape to [cout, cin*k*k] for GEMM
+ cout = w.shape[0]
+ w_flat = w.reshape(cout, -1)
+
+ write_tensor(f, w_flat)
+ write_tensor(f, b)
+ return tensors_count + 2
+
+
+def write_c2f(f, c2f, tc):
+ """Write a C2f block: cv1 + n*bottleneck + cv2."""
+ tc = write_conv(f, c2f.cv1, tc)
+ for bn in c2f.m:
+ tc = write_conv(f, bn.cv1, tc)
+ tc = write_conv(f, bn.cv2, tc)
+ tc = write_conv(f, c2f.cv2, tc)
+ return tc
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--model', default='yolov8n.pt', help='YOLOv8 model path')
+ parser.add_argument('--size', type=int, default=640, help='Input size')
+ parser.add_argument('--output', default='weights/yolov8n.bin', help='Output path')
+ args = parser.parse_args()
+
+ from ultralytics import YOLO
+ model = YOLO(args.model)
+ m = model.model.model # nn.Sequential of layers
+
+ nc = model.model.nc
+ print(f"Model: {args.model}, classes={nc}, input_size={args.size}")
+
+ with open(args.output, 'wb') as f:
+ # Header
+ f.write(b'NN2W')
+ f.write(struct.pack('<III', nc, args.size, 0)) # num_tensors placeholder
+ tc = 0
+
+ # Backbone convs (layers 0, 1, 3, 5, 7 in YOLOv8n)
+ backbone_conv_indices = [0, 1, 3, 5, 7]
+ for idx in backbone_conv_indices:
+ tc = write_conv(f, m[idx], tc)
+ print(f" backbone conv {idx}: {m[idx].conv.weight.shape}")
+
+ # Backbone C2f (layers 2, 4, 6, 8)
+ c2f_indices = [2, 4, 6, 8]
+ for idx in c2f_indices:
+ tc = write_c2f(f, m[idx], tc)
+ print(f" backbone c2f {idx}: n={len(m[idx].m)}")
+
+ # SPPF (layer 9)
+ sppf = m[9]
+ tc = write_conv(f, sppf.cv1, tc)
+ tc = write_conv(f, sppf.cv2, tc)
+ print(f" sppf: cv1={sppf.cv1.conv.weight.shape}, cv2={sppf.cv2.conv.weight.shape}")
+
+ # Neck C2f blocks (layers 12, 15, 18, 21)
+ neck_c2f_indices = [12, 15, 18, 21]
+ for idx in neck_c2f_indices:
+ tc = write_c2f(f, m[idx], tc)
+ print(f" neck c2f {idx}: n={len(m[idx].m)}")
+
+ # Neck convs (layers 16, 19) — downsample
+ neck_conv_indices = [16, 19]
+ for idx in neck_conv_indices:
+ tc = write_conv(f, m[idx], tc)
+ print(f" neck conv {idx}: {m[idx].conv.weight.shape}")
+
+ # Head (layer 22 = Detect)
+ detect = m[22]
+ for s in range(3):
+ # bbox branch: cv2[s] = Sequential(Conv, Conv, Conv2d)
+ for layer in detect.cv2[s]:
+ tc = write_conv(f, layer, tc)
+ # cls branch: cv3[s] = Sequential(Conv, Conv, Conv2d)
+ for layer in detect.cv3[s]:
+ tc = write_conv(f, layer, tc)
+ print(f" head scale {s}: bbox={[l for l in detect.cv2[s]]}, cls={[l for l in detect.cv3[s]]}")
+
+ # Patch num_tensors in header
+ f.seek(12)
+ f.write(struct.pack('<I', tc))
+
+ file_size = open(args.output, 'rb').seek(0, 2)
+ print(f"\nExported: {args.output} ({tc} tensors, {file_size} bytes)")
+
+
+if __name__ == '__main__':
+ main()
diff --git a/nn2/tools/fuse_normalize.py b/nn2/tools/fuse_normalize.py
new file mode 100644
index 0000000..e13c70c
--- /dev/null
+++ b/nn2/tools/fuse_normalize.py
@@ -0,0 +1,35 @@
+#!/usr/bin/env python3
+"""Fuse 1/255 normalization into first conv weights of nn2 .bin model."""
+import sys, struct, numpy as np
+
+def fuse(inp, out):
+ with open(inp, 'rb') as f:
+ magic = f.read(4)
+ assert magic == b'NN2W', f"Bad magic: {magic}"
+ nc, isz, nt = struct.unpack('III', f.read(12))
+ print(f"Model: nc={nc}, input={isz}, tensors={nt}")
+
+ header = magic + struct.pack('III', nc, isz, nt)
+ tensors = []
+ for i in range(nt):
+ sz = struct.unpack('I', f.read(4))[0]
+ data = np.frombuffer(f.read(sz * 4), dtype=np.float32).copy()
+ tensors.append(data)
+
+ print(f"Loaded {len(tensors)} tensors")
+ # First tensor = conv0 weights [16, 27] (16 filters, 3*3*3)
+ # Second tensor = conv0 bias [16]
+ w = tensors[0]
+ print(f"conv0 weights: {w.shape[0]} values, range [{w.min():.4f}, {w.max():.4f}]")
+ tensors[0] = w / 255.0
+ print(f"After /255: range [{tensors[0].min():.6f}, {tensors[0].max():.6f}]")
+
+ with open(out, 'wb') as f:
+ f.write(header)
+ for t in tensors:
+ f.write(struct.pack('I', len(t)))
+ f.write(t.astype(np.float32).tobytes())
+ print(f"Saved {out}")
+
+if __name__ == '__main__':
+ fuse(sys.argv[1], sys.argv[2])
diff --git a/nn2/tools/prune_channels.py b/nn2/tools/prune_channels.py
new file mode 100644
index 0000000..c957b03
--- /dev/null
+++ b/nn2/tools/prune_channels.py
@@ -0,0 +1,119 @@
+#!/usr/bin/env python3
+"""
+Channel-prune YOLOv8n: reduce all channel widths by a factor.
+Creates a new, narrower model that runs faster.
+
+Width multipliers:
+ 1.00 = original (16,32,64,128,256) — 3.1M params, 8.5ms
+ 0.75 = pruned (12,24,48,96,192) — 1.7M params, ~5ms target
+ 0.50 = tiny (8,16,32,64,128) — 0.8M params, ~3ms target
+
+For NVR with 3 classes (person,car,bicycle): 0.75 should have minimal quality impact.
+"""
+
+import struct
+import numpy as np
+import sys
+
+try:
+ from ultralytics import YOLO
+except ImportError:
+ print("Need ultralytics: pip install ultralytics")
+ sys.exit(1)
+
+def export_pruned(width_mult=0.75, num_classes=80, imgsz=320):
+ """Export a width-scaled YOLOv8n."""
+ import yaml, tempfile, os
+
+ # YOLOv8n architecture with scaled channels
+ # Original channels: [16, 32, 64, 128, 256] (after first conv)
+ # Scale factor applied to all
+ base = [16, 32, 64, 128, 256]
+ scaled = [max(8, int(c * width_mult / 8) * 8) for c in base] # round to 8
+ print(f"Channel widths: {base} → {scaled}")
+
+ # Train a scaled model from scratch? No — that requires training data.
+ # Instead: load pretrained YOLOv8n and prune channels by importance (L1 norm).
+
+ model = YOLO("yolov8n.pt")
+
+ # Export standard model first (we'll measure the baseline)
+ print(f"\nExporting standard YOLOv8n@{imgsz}...")
+ model.export(format="onnx", imgsz=imgsz, simplify=True)
+
+ # For actual pruning, we need torch-pruning library
+ try:
+ import torch_pruning as tp
+ import torch
+
+ print(f"\nPruning with width_mult={width_mult}...")
+ pruning_model = YOLO("yolov8n.pt").model
+
+ # Setup pruner
+ example_input = torch.randn(1, 3, imgsz, imgsz)
+ imp = tp.importance.MagnitudeImportance(p=2) # L2 norm
+ ignored_layers = []
+
+ # Don't prune detection head outputs
+ for m in pruning_model.modules():
+ if hasattr(m, 'cv2') and hasattr(m, 'cv3'): # Detect head
+ ignored_layers.append(m)
+
+ pruner = tp.pruner.MagnitudePruner(
+ pruning_model,
+ example_input,
+ importance=imp,
+ pruning_ratio=1.0 - width_mult,
+ ignored_layers=ignored_layers,
+ )
+
+ pruner.step()
+
+ # Count params
+ n_params = sum(p.numel() for p in pruning_model.parameters())
+ print(f"Pruned model: {n_params/1e6:.2f}M params")
+
+ # Export pruned ONNX
+ torch.onnx.export(pruning_model, example_input,
+ f"yolov8n_pruned_{int(width_mult*100)}.onnx",
+ opset_version=13)
+ print(f"Exported yolov8n_pruned_{int(width_mult*100)}.onnx")
+
+ except ImportError:
+ print("\ntorch-pruning not available. Using width-scaled YOLOv8 instead.")
+ print("Install: pip install torch-pruning")
+ print("\nAlternative: use ultralytics YOLOv8-nano with custom yaml...")
+
+ # Create custom yaml with scaled channels
+ custom_yaml = {
+ 'nc': num_classes,
+ 'scales': {
+ 'n': [0.33 * width_mult, 0.25 * width_mult, 1024]
+ },
+ 'backbone': [
+ [[-1, 1, 'Conv', [64, 3, 2]]],
+ [[-1, 1, 'Conv', [128, 3, 2]]],
+ [[-1, 3, 'C2f', [128, True]]],
+ [[-1, 1, 'Conv', [256, 3, 2]]],
+ [[-1, 6, 'C2f', [256, True]]],
+ [[-1, 1, 'Conv', [512, 3, 2]]],
+ [[-1, 6, 'C2f', [512, True]]],
+ [[-1, 1, 'Conv', [1024, 3, 2]]],
+ [[-1, 3, 'C2f', [1024, True]]],
+ [[-1, 1, 'SPPF', [1024, 5]]],
+ ]
+ }
+ print(f"\nTo create a {width_mult:.0%} width model:")
+ print(f" yolo train model=yolov8n.yaml data=coco.yaml epochs=100 \\")
+ print(f" scale={width_mult}")
+
+ # Also benchmark different input sizes
+ print(f"\n=== Input size comparison ===")
+ for size in [320, 256, 224, 192]:
+ gflops = 2.04 * (size/320)**2 # approximate
+ est_ms = 8.5 * (size/320)**2 # linear scaling estimate
+ print(f" {size}×{size}: ~{gflops:.1f} GFLOPs, ~{est_ms:.1f}ms estimated")
+
+if __name__ == "__main__":
+ wm = float(sys.argv[1]) if len(sys.argv) > 1 else 0.75
+ export_pruned(width_mult=wm)
diff --git a/nn2/tools/quantize_weights.py b/nn2/tools/quantize_weights.py
new file mode 100644
index 0000000..c92ee4f
--- /dev/null
+++ b/nn2/tools/quantize_weights.py
@@ -0,0 +1,104 @@
+#!/usr/bin/env python3
+"""
+quantize_weights.py — Quantize YOLOv8n FP32 weights to INT8 for nn2.
+
+Per-channel symmetric quantization for weights.
+Activation scales determined by calibration on sample images.
+
+Usage:
+ python tools/quantize_weights.py --fp32 weights/yolov8n.bin --output weights/yolov8n_int8.bin [--calib-dir images/]
+
+Weight file format (INT8):
+ [4] magic "NN2Q"
+ [4] uint32 num_classes
+ [4] uint32 input_size
+ [4] uint32 num_layers
+ For each conv layer:
+ [4] uint32 cout, cin, k, stride, pad, act
+ [cout*4] float32 bias (fused BN, FP32)
+ [cout*4] float32 w_scale (per-channel weight scale)
+ [cout*cin*k*k] int8 quantized weights
+ [4] float32 input_act_scale (per-tensor, from calibration)
+ [4] float32 output_act_scale (per-tensor, from calibration)
+"""
+
+import struct
+import argparse
+import numpy as np
+
+
+def quantize_per_channel(weights_fp32, bits=8):
+ """Symmetric per-channel quantization.
+ weights_fp32: [Cout, K] float32
+ Returns: (weights_int8, scales)
+ """
+ max_abs = np.abs(weights_fp32).max(axis=1, keepdims=True)
+ max_abs = np.maximum(max_abs, 1e-8) # avoid div by zero
+ qmax = 127.0
+ scales = max_abs.flatten() / qmax # [Cout]
+ weights_q = np.round(weights_fp32 / scales.reshape(-1, 1)).astype(np.int8)
+ return weights_q, scales.astype(np.float32)
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--fp32', required=True, help='FP32 weight file (NN2W format)')
+ parser.add_argument('--output', required=True, help='Output INT8 weight file')
+ parser.add_argument('--act-scale', type=float, default=0.05,
+ help='Default activation scale (calibrate for better accuracy)')
+ args = parser.parse_args()
+
+ # Read FP32 weights
+ with open(args.fp32, 'rb') as f:
+ magic = f.read(4)
+ assert magic == b'NN2W', f'Expected NN2W, got {magic}'
+ nc, isz, ntensors = struct.unpack('<III', f.read(12))
+ print(f'FP32 model: {nc} classes, {isz} input, {ntensors} tensors')
+
+ # Read all tensor pairs (weight, bias)
+ layers = []
+ for i in range(ntensors // 2):
+ # Weight
+ wsz = struct.unpack('<I', f.read(4))[0]
+ w = np.frombuffer(f.read(wsz * 4), dtype=np.float32).copy()
+ # Bias
+ bsz = struct.unpack('<I', f.read(4))[0]
+ b = np.frombuffer(f.read(bsz * 4), dtype=np.float32).copy()
+ layers.append((w, b))
+
+ # Quantize weights
+ print(f'\nQuantizing {len(layers)} layers...')
+ with open(args.output, 'wb') as f:
+ f.write(b'NN2Q')
+ f.write(struct.pack('<III', nc, isz, len(layers)))
+
+ for i, (w, b) in enumerate(layers):
+ cout = b.shape[0]
+ kin = w.shape[0] // cout # cin*k*k
+ w_2d = w.reshape(cout, kin)
+
+ # Per-channel quantization
+ w_int8, w_scales = quantize_per_channel(w_2d)
+
+ # Write layer
+ f.write(struct.pack('<I', cout))
+ f.write(struct.pack('<I', kin))
+ b.tofile(f) # FP32 bias
+ w_scales.tofile(f) # FP32 per-channel scale
+ w_int8.tobytes() # INT8 weights
+ f.write(w_int8.tobytes())
+ # Activation scales (default, should be calibrated)
+ f.write(struct.pack('<ff', args.act_scale, args.act_scale))
+
+ if i < 5 or i % 10 == 0:
+ w_range = np.abs(w_2d).max()
+ print(f' layer {i:3d}: {cout:4d}x{kin:5d} '
+ f'w_range={w_range:.4f} scale_mean={w_scales.mean():.6f}')
+
+ fsize = open(args.output, 'rb').seek(0, 2)
+ print(f'\nQuantized: {args.output} ({fsize:,} bytes, '
+ f'{fsize / open(args.fp32, "rb").seek(0, 2) * 100:.0f}% of FP32)')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/nn2/weights/calibration.json b/nn2/weights/calibration.json
new file mode 100644
index 0000000..ea96940
--- /dev/null
+++ b/nn2/weights/calibration.json
@@ -0,0 +1,90 @@
+{
+ "layer_0": {
+ "absmax": 50.24422836303711,
+ "scale": 2.5276535059328893
+ },
+ "layer_1": {
+ "absmax": 97.81292724609375,
+ "scale": 1.2983968843656901
+ },
+ "layer_2": {
+ "absmax": 11.134185791015625,
+ "scale": 11.40631225934953
+ },
+ "layer_3": {
+ "absmax": 7.2413740158081055,
+ "scale": 17.538108036869062
+ },
+ "layer_4": {
+ "absmax": 4.88383150100708,
+ "scale": 26.004173099290995
+ },
+ "layer_5": {
+ "absmax": 5.760451793670654,
+ "scale": 22.0468817947706
+ },
+ "layer_6": {
+ "absmax": 4.79788875579834,
+ "scale": 26.469975899674274
+ },
+ "layer_7": {
+ "absmax": 5.999900817871094,
+ "scale": 21.167016529681973
+ },
+ "layer_8": {
+ "absmax": 5.168757438659668,
+ "scale": 24.57070219708857
+ },
+ "layer_9": {
+ "absmax": 3.2495365142822266,
+ "scale": 39.08249655019723
+ },
+ "layer_10": {
+ "absmax": 3.2495365142822266,
+ "scale": 39.08249655019723
+ },
+ "layer_11": {
+ "absmax": 4.79788875579834,
+ "scale": 26.469975899674274
+ },
+ "layer_12": {
+ "absmax": 4.789520263671875,
+ "scale": 26.51622558069594
+ },
+ "layer_13": {
+ "absmax": 4.789520263671875,
+ "scale": 26.51622558069594
+ },
+ "layer_14": {
+ "absmax": 4.88383150100708,
+ "scale": 26.004173099290995
+ },
+ "layer_15": {
+ "absmax": 5.08205509185791,
+ "scale": 24.98989039956907
+ },
+ "layer_16": {
+ "absmax": 4.314272880554199,
+ "scale": 29.4371735914197
+ },
+ "layer_17": {
+ "absmax": 4.789520263671875,
+ "scale": 26.51622558069594
+ },
+ "layer_18": {
+ "absmax": 4.831411838531494,
+ "scale": 26.28631215502806
+ },
+ "layer_19": {
+ "absmax": 4.746646881103516,
+ "scale": 26.755729447250843
+ },
+ "layer_20": {
+ "absmax": 4.746646881103516,
+ "scale": 26.755729447250843
+ },
+ "layer_21": {
+ "absmax": 4.54713249206543,
+ "scale": 27.929689742340518
+ }
+}
\ No newline at end of file
diff --git a/training/antispoof/scripts/ssh_check_devices.py b/training/antispoof/scripts/ssh_check_devices.py
new file mode 100644
index 0000000..554a1d2
--- /dev/null
+++ b/training/antispoof/scripts/ssh_check_devices.py
@@ -0,0 +1,21 @@
+"""Check device-specific code paths in nn (decoder) and nn2."""
+import paramiko
+c = paramiko.SSHClient()
+c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
+c.connect("10.0.0.3", port=22, username="admin", password="1235", timeout=15)
+
+cmds = [
+ 'powershell -Command "Get-ChildItem e:/aidos/nn/src -ErrorAction SilentlyContinue | Where-Object {$_.Name -match \\"neon|arm|sse|avx|simd|cpu\\"} | Select Name,Length"',
+ 'powershell -Command "Get-ChildItem e:/aidos/nn -Filter Makefile* -ErrorAction SilentlyContinue | Select Name"',
+ 'powershell -Command "Get-Content e:/aidos/nn/Makefile -ErrorAction SilentlyContinue | Select -First 60"',
+ 'powershell -Command "Select-String -Path e:/aidos/nn/src/*.c,e:/aidos/nn/src/*.h -Pattern \\"__aarch64__|__arm__|__ARM_NEON|__riscv|esp32|raspberry\\" -ErrorAction SilentlyContinue | Select Path,Line -First 20"',
+ 'powershell -Command "Get-Content e:/aidos/nn/README.md -ErrorAction SilentlyContinue | Select -Skip 100 -First 40"',
+]
+for cmd in cmds:
+ print(f"\n$ {cmd[:120]}")
+ _, out, err = c.exec_command(cmd, timeout=30)
+ o = out.read().decode("utf-8", errors="replace")
+ print(o[:3000] if o.strip() else "(empty)")
+ e = err.read().decode("utf-8", errors="replace")
+ if e.strip(): print("ERR:", e[:200])
+c.close()