Raw ↗
+ +
a18b27f fix(windows): resolve Win32 Winsock, signal, and CLI test compatibility
saifmukhtar · 2026-11-24
1 /*
2 * SPDX-License-Identifier: AGPL-3.0-or-later WITH Classpath-exception-2.0
3 * Copyright (c) 2026 Saif Mukhtar
4 *
5 * OpenAVX - Open Audio-Video eXchange
6 * src/avx_web.c - Embedded HTTP and fragmented MP4 preview server
7 */
8  
9 #define _POSIX_C_SOURCE 200809L
10 #define _DEFAULT_SOURCE
11  
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <stdint.h>
15 #include <stdbool.h>
16 #include <string.h>
17 #include <errno.h>
18  
19 #include "openavx.h"
20 #include "avx_web.h"
21 #include "avx_rtsp.h"
22 #include "avx_platform.h"
23  
24 #if defined(AVX_OS_POSIX)
25 #include <sys/socket.h>
26 #include <sys/uio.h>
27 #include <netinet/in.h>
28 #include <netinet/tcp.h>
29 #include <arpa/inet.h>
30 #include <unistd.h>
31 #include <fcntl.h>
32 #include <strings.h>
33 #endif
34  
35 /* Embedded HTML5 Low-Latency Media Source Extensions Player */
36 static const char *k_player_html =
37 "<!DOCTYPE html>\n"
38 "<html>\n"
39 "<head>\n"
40 "<meta charset=\"utf-8\">\n"
41 "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no\">\n"
42 "<title>OpenAVX Web Preview</title>\n"
43 "<style>\n"
44 " * { margin:0; padding:0; box-sizing:border-box; background:#080808; }\n"
45 " html, body { width:100%; height:100%; overflow:hidden; font-family:-apple-system,BlinkMacSystemFont,\"Segoe UI\",Roboto,sans-serif; }\n"
46 " #wrap { position:relative; width:100%; height:100%; display:flex; align-items:center; justify-content:center; }\n"
47 " video { width:100%; height:100%; object-fit:contain; }\n"
48 " #hud { position:absolute; top:12px; left:12px; display:flex; align-items:center; gap:8px; background:rgba(12,12,12,0.75); backdrop-filter:blur(6px); -webkit-backdrop-filter:blur(6px); padding:6px 12px; border-radius:6px; border:1px solid #222; font-size:12px; color:#eee; pointer-events:none; box-shadow:0 4px 12px rgba(0,0,0,0.5); }\n"
49 " .dot { width:8px; height:8px; border-radius:50%; background:#00ff66; box-shadow:0 0 8px #00ff66; transition:all 0.3s; }\n"
50 " .dot.offline { background:#ff3333; box-shadow:0 0 8px #ff3333; }\n"
51 " #title { font-weight:600; letter-spacing:0.5px; }\n"
52 " #stats { color:#888; font-family:monospace; }\n"
53 "</style>\n"
54 "</head>\n"
55 "<body>\n"
56 "<div id=\"wrap\">\n"
57 " <video id=\"v\" autoplay muted playsinline></video>\n"
58 " <div id=\"hud\">\n"
59 " <div id=\"dot\" class=\"dot\"></div>\n"
60 " <span id=\"title\">OPENAVX LIVE</span>\n"
61 " <span id=\"stats\">Connecting...</span>\n"
62 " </div>\n"
63 "</div>\n"
64 "<script>\n"
65 "(function(){\n"
66 " const v = document.getElementById('v');\n"
67 " const dot = document.getElementById('dot');\n"
68 " const stats = document.getElementById('stats');\n"
69 " let ms, sb, queue = [], frames = 0, lastTime = performance.now();\n"
70 "\n"
71 " setInterval(() => {\n"
72 " const now = performance.now();\n"
73 " const fps = ((frames * 1000) / (now - lastTime)).toFixed(1);\n"
74 " frames = 0;\n"
75 " lastTime = now;\n"
76 " if (sb && !v.paused) stats.textContent = fps + ' fps | <100ms';\n"
77 " }, 1000);\n"
78 "\n"
79 " async function connect() {\n"
80 " if (!window.MediaSource) {\n"
81 " stats.textContent = 'MediaSource not supported';\n"
82 " dot.className = 'dot offline';\n"
83 " return;\n"
84 " }\n"
85 " ms = new MediaSource();\n"
86 " v.src = URL.createObjectURL(ms);\n"
87 " ms.onsourceopen = async () => {\n"
88 " try {\n"
89 " const res = await fetch('/live.mp4');\n"
90 " if (!res.ok) throw new Error('HTTP ' + res.status);\n"
91 " const mime = res.headers.get('Content-Type') || 'video/mp4; codecs=\"avc1.640028\"';\n"
92 " sb = ms.addSourceBuffer(mime);\n"
93 " sb.mode = 'segments';\n"
94 " sb.onupdateend = () => {\n"
95 " if (queue.length > 0 && !sb.updating) sb.appendBuffer(queue.shift());\n"
96 " if (v.buffered.length > 0) {\n"
97 " const end = v.buffered.end(v.buffered.length - 1);\n"
98 " if (end - v.currentTime > 0.25) v.currentTime = end - 0.05;\n"
99 " }\n"
100 " };\n"
101 " v.play().catch(()=>{});\n"
102 " dot.className = 'dot';\n"
103 " stats.textContent = 'Streaming';\n"
104 " const reader = res.body.getReader();\n"
105 " while (true) {\n"
106 " const {done, value} = await reader.read();\n"
107 " if (done) break;\n"
108 " frames++;\n"
109 " if (!sb.updating && queue.length === 0) sb.appendBuffer(value);\n"
110 " else queue.push(value);\n"
111 " }\n"
112 " } catch (e) {\n"
113 " dot.className = 'dot offline';\n"
114 " stats.textContent = 'Offline (retrying...)';\n"
115 " setTimeout(connect, 1500);\n"
116 " }\n"
117 " };\n"
118 " }\n"
119 " connect();\n"
120 "})();\n"
121 "</script>\n"
122 "</body>\n"
123 "</html>\n";
124  
125 /* Embedded Smartphone Camera Ingress Web App */
126 static const char *k_camera_html =
127 "<!DOCTYPE html>\n"
128 "<html lang=\"en\">\n"
129 "<head>\n"
130 "<meta charset=\"utf-8\">\n"
131 "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover\">\n"
132 "<title>OpenAVX Mobile Camera</title>\n"
133 "<style>\n"
134 " * { margin:0; padding:0; box-sizing:border-box; user-select:none; -webkit-user-select:none; }\n"
135 " html, body { width:100%; height:100%; overflow:hidden; background:#08080a; font-family:-apple-system,BlinkMacSystemFont,\"Segoe UI\",Roboto,sans-serif; color:#eee; }\n"
136 " #wrap { position:relative; width:100%; height:100%; display:flex; align-items:center; justify-content:center; }\n"
137 " video { width:100%; height:100%; object-fit:cover; }\n"
138 " #hud { position:absolute; top:env(safe-area-inset-top, 16px); left:16px; right:16px; display:flex; align-items:center; justify-content:space-between; pointer-events:none; z-index:10; }\n"
139 " .badge { display:inline-flex; align-items:center; gap:8px; background:rgba(15,15,18,0.78); backdrop-filter:blur(10px); -webkit-backdrop-filter:blur(10px); border:1px solid rgba(255,255,255,0.12); border-radius:20px; padding:6px 14px; font-size:12px; font-weight:600; box-shadow:0 4px 16px rgba(0,0,0,0.6); }\n"
140 " .dot { width:8px; height:8px; border-radius:50%; background:#888; transition:all 0.3s; }\n"
141 " .dot.live { background:#00ff66; box-shadow:0 0 10px #00ff66; }\n"
142 " .dot.warn { background:#ffaa00; box-shadow:0 0 10px #ffaa00; }\n"
143 " .dot.err { background:#ff3333; box-shadow:0 0 10px #ff3333; }\n"
144 " #stats { font-family:monospace; font-size:11px; color:#aaa; }\n"
145 " #controls { position:absolute; bottom:calc(env(safe-area-inset-bottom, 20px) + 12px); left:50%; transform:translateX(-50%); display:flex; align-items:center; gap:12px; background:rgba(18,18,22,0.85); backdrop-filter:blur(16px); -webkit-backdrop-filter:blur(16px); border:1px solid rgba(255,255,255,0.15); border-radius:32px; padding:8px 16px; box-shadow:0 8px 32px rgba(0,0,0,0.7); z-index:10; max-width:calc(100% - 32px); }\n"
146 " .btn { background:rgba(255,255,255,0.08); color:#fff; border:1px solid rgba(255,255,255,0.12); border-radius:24px; padding:10px 16px; font-size:13px; font-weight:600; cursor:pointer; display:flex; align-items:center; gap:6px; transition:all 0.2s; white-space:nowrap; }\n"
147 " .btn:active { transform:scale(0.96); background:rgba(255,255,255,0.18); }\n"
148 " .btn-stream { background:#0070f3; border-color:#0070f3; color:#fff; min-width:110px; justify-content:center; }\n"
149 " .btn-stream.active { background:#e00; border-color:#e00; }\n"
150 " select { background:rgba(255,255,255,0.08); color:#fff; border:1px solid rgba(255,255,255,0.12); border-radius:24px; padding:10px 14px; font-size:12px; font-weight:600; outline:none; }\n"
151 " select option { background:#16161a; color:#fff; }\n"
152 " #secWarn { position:absolute; top:70px; left:16px; right:16px; background:rgba(30,20,10,0.92); border:1px solid #d97706; border-radius:12px; padding:14px 18px; font-size:12px; line-height:1.5; color:#fef3c7; z-index:20; display:none; box-shadow:0 6px 20px rgba(0,0,0,0.6); }\n"
153 " #secWarn b { color:#f59e0b; font-size:13px; }\n"
154 " #secWarn code { background:rgba(0,0,0,0.4); padding:2px 6px; border-radius:4px; font-family:monospace; color:#fff; }\n"
155 " #tallyBorder { position:fixed; top:0; left:0; right:0; bottom:0; border:10px solid transparent; pointer-events:none; z-index:90; box-sizing:border-box; transition:border-color 0.2s ease, box-shadow 0.2s ease; }\n"
156 " body.tally-program #tallyBorder { border-color:#ff1133; box-shadow:inset 0 0 50px rgba(255,17,51,0.85); }\n"
157 " body.tally-preview #tallyBorder { border-color:#00e64d; box-shadow:inset 0 0 50px rgba(0,230,77,0.85); }\n"
158 " body.tally-recording #tallyBorder { border-color:#f59e0b; box-shadow:inset 0 0 50px rgba(245,158,11,0.85); }\n"
159 " body.tally-program.tally-recording #tallyBorder { border-color:#ff1133; box-shadow:inset 0 0 50px rgba(255,17,51,0.85), inset 0 0 100px rgba(245,158,11,0.6); }\n"
160 " body.tally-preview.tally-recording #tallyBorder { border-color:#00e64d; box-shadow:inset 0 0 50px rgba(0,230,77,0.85), inset 0 0 100px rgba(245,158,11,0.6); }\n"
161 " body.tally-program #dot { background:#ff1133 !important; box-shadow:0 0 16px #ff1133 !important; }\n"
162 " body.tally-preview #dot { background:#00e64d !important; box-shadow:0 0 16px #00e64d !important; }\n"
163 " body.tally-recording #dot { background:#f59e0b !important; box-shadow:0 0 16px #f59e0b !important; }\n"
164 " #recPill { display:none; align-items:center; gap:4px; background:#b91c1c; color:#fff; font-weight:700; font-size:11px; padding:2px 8px; border-radius:12px; margin-left:6px; animation:blinkRec 1.2s infinite; }\n"
165 " @keyframes blinkRec { 0%, 100% { opacity:1; } 50% { opacity:0.3; } }\n"
166 "</style>\n"
167 "</head>\n"
168 "<body>\n"
169 "<div id=\"wrap\">\n"
170 " <div id=\"tallyBorder\"></div>\n"
171 " <video id=\"v\" autoplay playsinline muted></video>\n"
172 " <div id=\"hud\">\n"
173 " <div class=\"badge\">\n"
174 " <div id=\"dot\" class=\"dot\"></div>\n"
175 " <span id=\"title\">OPENAVX CAM</span>\n"
176 " <span id=\"recPill\">&#x25cf; REC</span>\n"
177 " <span id=\"stats\">Ready</span>\n"
178 " </div>\n"
179 " </div>\n"
180 " <div id=\"secWarn\">\n"
181 " <b>Secure Context Required</b><br>\n"
182 " Mobile browsers require HTTPS or localhost to access camera.<br>\n"
183 " &bull; <b>USB (Recommended &bull; 0 latency):</b> Run on laptop: <code>adb reverse tcp:8080 tcp:8080</code> then open <code>http://localhost:8080/camera</code><br>\n"
184 " &bull; <b>Wi-Fi (Chrome Android):</b> Open <code>chrome://flags/#unsafely-treat-insecure-origin-as-secure</code>, add this URL and restart Chrome.\n"
185 " </div>\n"
186 " <div id=\"controls\">\n"
187 " <button id=\"btnFlip\" class=\"btn\" title=\"Flip Camera\">&#x21bb; Flip</button>\n"
188 " <select id=\"selRes\">\n"
189 " <option value=\"1080\" selected>1080p</option>\n"
190 " <option value=\"720\">720p</option>\n"
191 " <option value=\"2160\">4K</option>\n"
192 " <option value=\"480\">480p</option>\n"
193 " </select>\n"
194 " <button id=\"btnStream\" class=\"btn btn-stream\">Start Cam</button>\n"
195 " </div>\n"
196 "</div>\n"
197 "<canvas id=\"cvs\" style=\"display:none\"></canvas>\n"
198 "<script>\n"
199 "(function(){\n"
200 " const v = document.getElementById('v');\n"
201 " const dot = document.getElementById('dot');\n"
202 " const stats = document.getElementById('stats');\n"
203 " const btnStream = document.getElementById('btnStream');\n"
204 " const btnFlip = document.getElementById('btnFlip');\n"
205 " const selRes = document.getElementById('selRes');\n"
206 " const secWarn = document.getElementById('secWarn');\n"
207 " const cvs = document.getElementById('cvs');\n"
208 " const ctx = cvs.getContext('2d');\n"
209 "\n"
210 " let ws = null, stream = null, enc = null, isStreaming = false;\n"
211 " let facingMode = 'environment', curW = 1920, curH = 1080;\n"
212 " let frames = 0, bytes = 0, lastTime = performance.now(), frameIdx = 0;\n"
213 " let lastFrameTime = 0;\n"
214 " const frameIntervalMs = 1000 / 30;\n"
215 " let codecName = 'Detecting...';\n"
216 " let wakeLock = null;\n"
217 "\n"
218 " async function acquireWakeLock() {\n"
219 " if ('wakeLock' in navigator) {\n"
220 " try { wakeLock = await navigator.wakeLock.request('screen'); } catch(e){}\n"
221 " }\n"
222 " }\n"
223 " function releaseWakeLock() {\n"
224 " if (wakeLock) {\n"
225 " try { wakeLock.release(); } catch(e){}\n"
226 " wakeLock = null;\n"
227 " }\n"
228 " }\n"
229 "\n"
230 " if (!window.isSecureContext && location.hostname !== 'localhost' && location.hostname !== '127.0.0.1') {\n"
231 " secWarn.style.display = 'block';\n"
232 " }\n"
233 "\n"
234 " setInterval(() => {\n"
235 " if (!isStreaming) return;\n"
236 " const now = performance.now();\n"
237 " const dt = (now - lastTime) / 1000;\n"
238 " const fps = (frames / dt).toFixed(1);\n"
239 " const mbps = ((bytes * 8) / (dt * 1000000)).toFixed(2);\n"
240 " frames = 0; bytes = 0; lastTime = now;\n"
241 " stats.textContent = `${curW}x${curH} | ${fps} fps | ${mbps} Mb/s | ${codecName}`;\n"
242 " }, 1000);\n"
243 "\n"
244 " function connectWS() {\n"
245 " const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';\n"
246 " ws = new WebSocket(`${proto}//${location.host}/camera/ws`);\n"
247 " ws.binaryType = 'arraybuffer';\n"
248 " ws.onopen = () => {\n"
249 " dot.className = isStreaming ? 'dot live' : 'dot warn';\n"
250 " };\n"
251 " ws.onmessage = (evt) => {\n"
252 " try {\n"
253 " const msg = JSON.parse(evt.data);\n"
254 " if (msg.type === 'tally') {\n"
255 " document.body.classList.remove('tally-program', 'tally-preview', 'tally-recording');\n"
256 " const title = document.getElementById('title');\n"
257 " const recPill = document.getElementById('recPill');\n"
258 " if (recPill) recPill.style.display = msg.recording ? 'inline-flex' : 'none';\n"
259 " if (msg.recording) document.body.classList.add('tally-recording');\n"
260 " if (msg.program) {\n"
261 " document.body.classList.add('tally-program');\n"
262 " if (title) title.textContent = msg.recording ? 'LIVE + REC' : 'ON AIR (LIVE)';\n"
263 " } else if (msg.preview) {\n"
264 " document.body.classList.add('tally-preview');\n"
265 " if (title) title.textContent = msg.recording ? 'CUED + REC' : 'PREVIEW (CUED)';\n"
266 " } else if (msg.recording) {\n"
267 " if (title) title.textContent = 'RECORDING';\n"
268 " } else {\n"
269 " if (title) title.textContent = 'OPENAVX CAM';\n"
270 " }\n"
271 " }\n"
272 " } catch(e) {}\n"
273 " };\n"
274 " ws.onclose = () => {\n"
275 " dot.className = 'dot err';\n"
276 " document.body.classList.remove('tally-program', 'tally-preview', 'tally-recording');\n"
277 " const recPill = document.getElementById('recPill');\n"
278 " if (recPill) recPill.style.display = 'none';\n"
279 " if (isStreaming) setTimeout(connectWS, 1500);\n"
280 " };\n"
281 " ws.onerror = () => { dot.className = 'dot err'; };\n"
282 " }\n"
283 "\n"
284 " async function startCapture() {\n"
285 " const resVal = parseInt(selRes.value) || 1080;\n"
286 " if (resVal === 2160) { curW = 3840; curH = 2160; }\n"
287 " else if (resVal === 720) { curW = 1280; curH = 720; }\n"
288 " else if (resVal === 480) { curW = 854; curH = 480; }\n"
289 " else { curW = 1920; curH = 1080; }\n"
290 "\n"
291 " try {\n"
292 " if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {\n"
293 " secWarn.style.display = 'block';\n"
294 " throw new Error('getUserMedia unavailable in this context');\n"
295 " }\n"
296 " stream = await navigator.mediaDevices.getUserMedia({\n"
297 " video: { facingMode: { ideal: facingMode }, width: { ideal: curW }, height: { ideal: curH }, frameRate: { ideal: 30 } },\n"
298 " audio: false\n"
299 " });\n"
300 " v.srcObject = stream;\n"
301 " await v.play();\n"
302 " curW = v.videoWidth || curW;\n"
303 " curH = v.videoHeight || curH;\n"
304 " if (facingMode === 'user') v.style.transform = 'scaleX(-1)';\n"
305 " else v.style.transform = 'scaleX(1)';\n"
306 "\n"
307 " await acquireWakeLock();\n"
308 " if (!ws || ws.readyState !== 1) connectWS();\n"
309 "\n"
310 " /* Setup Hardware H.264 Encoder if WebCodecs supported */\n"
311 " if (window.VideoEncoder) {\n"
312 " try {\n"
313 " enc = new VideoEncoder({\n"
314 " output: (chunk) => {\n"
315 " if (!ws || ws.readyState !== 1) return;\n"
316 " const chunkLen = chunk.byteLength;\n"
317 " const pkt = new Uint8Array(16 + chunkLen);\n"
318 " const dv = new DataView(pkt.buffer);\n"
319 " dv.setUint32(0, 0x5856414F, true); /* 'OAVX' Little Endian */\n"
320 " dv.setUint32(4, 0x34363248, true); /* 'H264' Little Endian */\n"
321 " dv.setUint16(8, curW, true);\n"
322 " dv.setUint16(10, curH, true);\n"
323 " dv.setUint32(12, chunk.type === 'key' ? 1 : 0, true);\n"
324 " chunk.copyTo(new Uint8Array(pkt.buffer, 16, chunkLen));\n"
325 " ws.send(pkt.buffer);\n"
326 " frames++; bytes += pkt.byteLength;\n"
327 " },\n"
328 " error: (e) => { console.warn('VideoEncoder error', e); enc = null; }\n"
329 " });\n"
330 " const safeW = Math.max(320, Math.floor(curW / 16) * 16);\n"
331 " const safeH = Math.max(240, Math.floor(curH / 16) * 16);\n"
332 " const candProfiles = (safeW > 1280 || safeH > 720)\n"
333 " ? ['avc1.420028', 'avc1.42e028', 'avc1.4d0028', 'avc1.42001f']\n"
334 " : ['avc1.42001f', 'avc1.42e01f', 'avc1.42001e', 'avc1.4d001f'];\n"
335 " let confOk = false;\n"
336 " for (const p of candProfiles) {\n"
337 " try {\n"
338 " enc.configure({\n"
339 " codec: p,\n"
340 " width: safeW,\n"
341 " height: safeH,\n"
342 " bitrate: 3500000,\n"
343 " framerate: 30,\n"
344 " latencyMode: 'realtime',\n"
345 " avc: { format: 'annexb' }\n"
346 " });\n"
347 " confOk = true;\n"
348 " break;\n"
349 " } catch(ce) {}\n"
350 " }\n"
351 " if (!confOk) throw new Error('No profile supported');\n"
352 " codecName = 'H.264 HW';\n"
353 " } catch (e) {\n"
354 " enc = null;\n"
355 " codecName = 'JPEG';\n"
356 " }\n"
357 " } else {\n"
358 " codecName = 'JPEG';\n"
359 " }\n"
360 "\n"
361 " isStreaming = true;\n"
362 " btnStream.textContent = 'Stop Cam';\n"
363 " btnStream.className = 'btn btn-stream active';\n"
364 " dot.className = 'dot live';\n"
365 " lastFrameTime = performance.now();\n"
366 " pumpFrames();\n"
367 " } catch (err) {\n"
368 " alert('Camera error: ' + err.message);\n"
369 " stopCapture();\n"
370 " }\n"
371 " }\n"
372 "\n"
373 " function stopCapture() {\n"
374 " isStreaming = false;\n"
375 " releaseWakeLock();\n"
376 " if (stream) {\n"
377 " stream.getTracks().forEach(t => t.stop());\n"
378 " stream = null;\n"
379 " }\n"
380 " if (enc) { try { enc.close(); } catch(e){} enc = null; }\n"
381 " v.srcObject = null;\n"
382 " btnStream.textContent = 'Start Cam';\n"
383 " btnStream.className = 'btn btn-stream';\n"
384 " dot.className = (ws && ws.readyState === 1) ? 'dot warn' : 'dot err';\n"
385 " stats.textContent = 'Stopped';\n"
386 " }\n"
387 "\n"
388 " async function pumpFrames(now) {\n"
389 " if (!isStreaming) return;\n"
390 " if (!now) now = performance.now();\n"
391 " if (now - lastFrameTime >= frameIntervalMs) {\n"
392 " lastFrameTime = now;\n"
393 " if (enc && enc.state === 'configured') {\n"
394 " if (enc.encodeQueueSize <= 2 && (!ws || ws.bufferedAmount < 512 * 1024)) {\n"
395 " try {\n"
396 " const vf = new VideoFrame(v, { timestamp: Math.round(now * 1000) });\n"
397 " const needKey = (frameIdx++ % 60 === 0);\n"
398 " enc.encode(vf, { keyFrame: needKey });\n"
399 " vf.close();\n"
400 " } catch(e) {}\n"
401 " }\n"
402 " } else {\n"
403 " if (!ws || ws.bufferedAmount < 512 * 1024) {\n"
404 " cvs.width = curW;\n"
405 " cvs.height = curH;\n"
406 " ctx.drawImage(v, 0, 0, curW, curH);\n"
407 " cvs.toBlob((blob) => {\n"
408 " if (!blob || !ws || ws.readyState !== 1 || !isStreaming) return;\n"
409 " blob.arrayBuffer().then((ab) => {\n"
410 " const pkt = new Uint8Array(16 + ab.byteLength);\n"
411 " const dv = new DataView(pkt.buffer);\n"
412 " dv.setUint32(0, 0x5856414F, true); /* 'OAVX' */\n"
413 " dv.setUint32(4, 0x47504A4D, true); /* 'MJPG' */\n"
414 " dv.setUint16(8, curW, true);\n"
415 " dv.setUint16(10, curH, true);\n"
416 " dv.setUint32(12, 1, true);\n"
417 " pkt.set(new Uint8Array(ab), 16);\n"
418 " ws.send(pkt.buffer);\n"
419 " frames++; bytes += pkt.byteLength;\n"
420 " });\n"
421 " }, 'image/jpeg', 0.80);\n"
422 " }\n"
423 " }\n"
424 " }\n"
425 " if (isStreaming) requestAnimationFrame(pumpFrames);\n"
426 " }\n"
427 "\n"
428 " btnStream.onclick = () => {\n"
429 " if (isStreaming) stopCapture();\n"
430 " else startCapture();\n"
431 " };\n"
432 "\n"
433 " btnFlip.onclick = () => {\n"
434 " facingMode = (facingMode === 'environment') ? 'user' : 'environment';\n"
435 " if (isStreaming) {\n"
436 " stopCapture();\n"
437 " startCapture();\n"
438 " }\n"
439 " };\n"
440 "\n"
441 " connectWS();\n"
442 "})();\n"
443 "</script>\n"
444 "</body>\n"
445 "</html>\n";
446  
447 /* ========================================================================= */
448 /* 1. ISOBMFF BOX WRITING HELPERS */
449 /* ========================================================================= */
450  
451 static inline void avx_put_u32(uint8_t **p, uint32_t val) {
452 (*p)[0] = (uint8_t)(val >> 24);
453 (*p)[1] = (uint8_t)(val >> 16);
454 (*p)[2] = (uint8_t)(val >> 8);
455 (*p)[3] = (uint8_t)(val);
456 *p += 4;
457 }
458  
459 static inline void avx_put_u16(uint8_t **p, uint16_t val) {
460 (*p)[0] = (uint8_t)(val >> 8);
461 (*p)[1] = (uint8_t)(val);
462 *p += 2;
463 }
464  
465 static inline void avx_put_u8(uint8_t **p, uint8_t val) {
466 (*p)[0] = val;
467 *p += 1;
468 }
469  
470 static inline void avx_put_fourcc(uint8_t **p, const char *fourcc) {
471 memcpy(*p, fourcc, 4);
472 *p += 4;
473 }
474  
475 static inline void avx_put_u64(uint8_t **p, uint64_t val) {
476 avx_put_u32(p, (uint32_t)(val >> 32));
477 avx_put_u32(p, (uint32_t)(val & 0xFFFFFFFFULL));
478 }
479  
480 static inline void avx_box_patch_size(uint8_t *box_start, uint8_t *box_end) {
481 uint32_t sz = (uint32_t)(box_end - box_start);
482 box_start[0] = (uint8_t)(sz >> 24);
483 box_start[1] = (uint8_t)(sz >> 16);
484 box_start[2] = (uint8_t)(sz >> 8);
485 box_start[3] = (uint8_t)(sz);
486 }
487  
488 /* ========================================================================= */
489 /* 2. PURE C99 fMP4 GENERATION (ftyp, moov, moof, mdat) */
490 /* ========================================================================= */
491  
492 /*
493 * Generates ISO/IEC 14496-12 fMP4 initialization segment (ftyp and moov boxes)
494 * containing track metadata and avcC/hvcC codec configuration records.
495 */
496 OPENAVX_API size_t avx_fmp4_generate_init_segment(
497 avx_rtsp_codec_e codec,
498 uint32_t width,
499 uint32_t height,
500 const uint8_t *sps,
501 size_t sps_len,
502 const uint8_t *pps,
503 size_t pps_len,
504 const uint8_t *vps,
505 size_t vps_len,
506 uint8_t *out_buf,
507 size_t out_max
508 ) {
509 if (!out_buf || out_max < 1024) return 0;
510 if (width == 0) width = 1920;
511 if (height == 0) height = 1080;
512  
513 /* Strip leading Annex B start code from SPS/PPS if present */
514 if (sps && sps_len >= 4) {
515 if (sps[0] == 0 && sps[1] == 0 && sps[2] == 1) {
516 sps += 3; sps_len -= 3;
517 } else if (sps[0] == 0 && sps[1] == 0 && sps[2] == 0 && sps[3] == 1) {
518 sps += 4; sps_len -= 4;
519 }
520 }
521 if (pps && pps_len >= 4) {
522 if (pps[0] == 0 && pps[1] == 0 && pps[2] == 1) {
523 pps += 3; pps_len -= 3;
524 } else if (pps[0] == 0 && pps[1] == 0 && pps[2] == 0 && pps[3] == 1) {
525 pps += 4; pps_len -= 4;
526 }
527 }
528 if (vps && vps_len >= 4) {
529 if (vps[0] == 0 && vps[1] == 0 && vps[2] == 1) {
530 vps += 3; vps_len -= 3;
531 } else if (vps[0] == 0 && vps[1] == 0 && vps[2] == 0 && vps[3] == 1) {
532 vps += 4; vps_len -= 4;
533 }
534 }
535  
536 uint8_t *p = out_buf;
537  
538 /* 1. ftyp Box (32 bytes) */
539 uint8_t *b_ftyp = p;
540 avx_put_u32(&p, 0); /* size */
541 avx_put_fourcc(&p, "ftyp");
542 avx_put_fourcc(&p, "isom"); /* major brand */
543 avx_put_u32(&p, 0x00000200); /* minor version */
544 avx_put_fourcc(&p, "isom");
545 avx_put_fourcc(&p, "iso2");
546 avx_put_fourcc(&p, (codec == AVX_RTSP_CODEC_HEVC) ? "hvc1" : ((codec == AVX_RTSP_CODEC_AV1) ? "av01" : "avc1"));
547 avx_put_fourcc(&p, "mp41");
548 avx_box_patch_size(b_ftyp, p);
549  
550 /* 2. moov Box */
551 uint8_t *b_moov = p;
552 avx_put_u32(&p, 0);
553 avx_put_fourcc(&p, "moov");
554  
555 /* 2.1. mvhd Box (108 bytes) */
556 uint8_t *b_mvhd = p;
557 avx_put_u32(&p, 0);
558 avx_put_fourcc(&p, "mvhd");
559 avx_put_u8(&p, 0); /* version = 0 */
560 avx_put_u8(&p, 0); avx_put_u8(&p, 0); avx_put_u8(&p, 0); /* flags = 0 */
561 avx_put_u32(&p, 0); /* creation_time */
562 avx_put_u32(&p, 0); /* modification_time */
563 avx_put_u32(&p, 90000); /* timescale = 90kHz */
564 avx_put_u32(&p, 0); /* duration = 0 (live fragment) */
565 avx_put_u32(&p, 0x00010000); /* rate = 1.0 */
566 avx_put_u16(&p, 0x0100); /* volume = 1.0 */
567 memset(p, 0, 10); p += 10; /* reserved */
568 /* Identity matrix (36 bytes) */
569 avx_put_u32(&p, 0x00010000); avx_put_u32(&p, 0); avx_put_u32(&p, 0);
570 avx_put_u32(&p, 0); avx_put_u32(&p, 0x00010000); avx_put_u32(&p, 0);
571 avx_put_u32(&p, 0); avx_put_u32(&p, 0); avx_put_u32(&p, 0x40000000);
572 memset(p, 0, 24); p += 24; /* pre_defined */
573 avx_put_u32(&p, 2); /* next_track_ID = 2 */
574 avx_box_patch_size(b_mvhd, p);
575  
576 /* 2.2. trak Box */
577 uint8_t *b_trak = p;
578 avx_put_u32(&p, 0);
579 avx_put_fourcc(&p, "trak");
580  
581 /* 2.2.1. tkhd Box (92 bytes) */
582 uint8_t *b_tkhd = p;
583 avx_put_u32(&p, 0);
584 avx_put_fourcc(&p, "tkhd");
585 avx_put_u8(&p, 0); /* version = 0 */
586 avx_put_u8(&p, 0); avx_put_u8(&p, 0); avx_put_u8(&p, 7); /* flags = TrackEnabled | InMovie | InPreview */
587 avx_put_u32(&p, 0); /* creation_time */
588 avx_put_u32(&p, 0); /* modification_time */
589 avx_put_u32(&p, 1); /* track_id = 1 */
590 avx_put_u32(&p, 0); /* reserved */
591 avx_put_u32(&p, 0); /* duration */
592 memset(p, 0, 8); p += 8; /* reserved */
593 avx_put_u16(&p, 0); /* layer */
594 avx_put_u16(&p, 0); /* alternate_group */
595 avx_put_u16(&p, 0); /* volume (video = 0) */
596 avx_put_u16(&p, 0); /* reserved */
597 /* Matrix (36 bytes) */
598 avx_put_u32(&p, 0x00010000); avx_put_u32(&p, 0); avx_put_u32(&p, 0);
599 avx_put_u32(&p, 0); avx_put_u32(&p, 0x00010000); avx_put_u32(&p, 0);
600 avx_put_u32(&p, 0); avx_put_u32(&p, 0); avx_put_u32(&p, 0x40000000);
601 avx_put_u32(&p, width << 16); /* width (16.16 fixed) */
602 avx_put_u32(&p, height << 16); /* height (16.16 fixed) */
603 avx_box_patch_size(b_tkhd, p);
604  
605 /* 2.2.2. mdia Box */
606 uint8_t *b_mdia = p;
607 avx_put_u32(&p, 0);
608 avx_put_fourcc(&p, "mdia");
609  
610 /* mdhd (32 bytes) */
611 uint8_t *b_mdhd = p;
612 avx_put_u32(&p, 0);
613 avx_put_fourcc(&p, "mdhd");
614 avx_put_u8(&p, 0); avx_put_u8(&p, 0); avx_put_u8(&p, 0); avx_put_u8(&p, 0);
615 avx_put_u32(&p, 0); /* creation_time */
616 avx_put_u32(&p, 0); /* modification_time */
617 avx_put_u32(&p, 90000); /* timescale */
618 avx_put_u32(&p, 0); /* duration */
619 avx_put_u16(&p, 0x55C4); /* language = 'und' */
620 avx_put_u16(&p, 0);
621 avx_box_patch_size(b_mdhd, p);
622  
623 /* hdlr (45 bytes) */
624 uint8_t *b_hdlr = p;
625 avx_put_u32(&p, 0);
626 avx_put_fourcc(&p, "hdlr");
627 avx_put_u32(&p, 0); /* ver/flags */
628 avx_put_u32(&p, 0); /* pre_defined */
629 avx_put_fourcc(&p, "vide"); /* handler_type = video */
630 memset(p, 0, 12); p += 12; /* reserved */
631 const char *hdlr_name = "VideoHandler";
632 memcpy(p, hdlr_name, strlen(hdlr_name) + 1);
633 p += strlen(hdlr_name) + 1;
634 avx_box_patch_size(b_hdlr, p);
635  
636 /* minf Box */
637 uint8_t *b_minf = p;
638 avx_put_u32(&p, 0);
639 avx_put_fourcc(&p, "minf");
640  
641 /* vmhd Box (20 bytes) */
642 uint8_t *b_vmhd = p;
643 avx_put_u32(&p, 0);
644 avx_put_fourcc(&p, "vmhd");
645 avx_put_u8(&p, 0); avx_put_u8(&p, 0); avx_put_u8(&p, 0); avx_put_u8(&p, 1);
646 avx_put_u16(&p, 0); /* graphicsmode */
647 memset(p, 0, 6); p += 6; /* opcolor */
648 avx_box_patch_size(b_vmhd, p);
649  
650 /* dinf Box (36 bytes) */
651 uint8_t *b_dinf = p;
652 avx_put_u32(&p, 0);
653 avx_put_fourcc(&p, "dinf");
654 /* dref */
655 uint8_t *b_dref = p;
656 avx_put_u32(&p, 0);
657 avx_put_fourcc(&p, "dref");
658 avx_put_u32(&p, 0); /* ver/flags */
659 avx_put_u32(&p, 1); /* entry_count = 1 */
660 /* url */
661 uint8_t *b_url = p;
662 avx_put_u32(&p, 0);
663 avx_put_fourcc(&p, "url ");
664 avx_put_u8(&p, 0); avx_put_u8(&p, 0); avx_put_u8(&p, 0); avx_put_u8(&p, 1); /* self-contained */
665 avx_box_patch_size(b_url, p);
666 avx_box_patch_size(b_dref, p);
667 avx_box_patch_size(b_dinf, p);
668  
669 /* stbl Box */
670 uint8_t *b_stbl = p;
671 avx_put_u32(&p, 0);
672 avx_put_fourcc(&p, "stbl");
673  
674 /* stsd Box */
675 uint8_t *b_stsd = p;
676 avx_put_u32(&p, 0);
677 avx_put_fourcc(&p, "stsd");
678 avx_put_u32(&p, 0); /* ver/flags */
679 avx_put_u32(&p, 1); /* entry_count = 1 */
680  
681 if (codec == AVX_RTSP_CODEC_H264) {
682 /* avc1 Box */
683 uint8_t *b_avc1 = p;
684 avx_put_u32(&p, 0);
685 avx_put_fourcc(&p, "avc1");
686 memset(p, 0, 6); p += 6; /* reserved */
687 avx_put_u16(&p, 1); /* data_reference_index */
688 avx_put_u16(&p, 0); avx_put_u16(&p, 0); /* pre_defined / reserved */
689 memset(p, 0, 12); p += 12; /* pre_defined */
690 avx_put_u16(&p, (uint16_t)width);
691 avx_put_u16(&p, (uint16_t)height);
692 avx_put_u32(&p, 0x00480000); /* 72 dpi horiz */
693 avx_put_u32(&p, 0x00480000); /* 72 dpi vert */
694 avx_put_u32(&p, 0); /* reserved */
695 avx_put_u16(&p, 1); /* frame_count */
696 /* compressorname (32 bytes) */
697 p[0] = 7;
698 memcpy(p + 1, "OpenAVX", 7);
699 memset(p + 8, 0, 24);
700 p += 32;
701 avx_put_u16(&p, 0x0018); /* depth = 24 */
702 avx_put_u16(&p, 0xFFFF); /* pre_defined = -1 */
703  
704 /* avcC Box */
705 uint8_t *b_avcC = p;
706 avx_put_u32(&p, 0);
707 avx_put_fourcc(&p, "avcC");
708 avx_put_u8(&p, 1); /* configurationVersion = 1 */
709 avx_put_u8(&p, (sps && sps_len > 1) ? sps[1] : 0x64); /* AVCProfileIndication (High = 100) */
710 avx_put_u8(&p, (sps && sps_len > 2) ? sps[2] : 0x00); /* profile_compatibility */
711 avx_put_u8(&p, (sps && sps_len > 3) ? sps[3] : 0x28); /* AVCLevelIndication (Level 4.0 = 40) */
712 avx_put_u8(&p, 0xFF); /* lengthSizeMinusOne = 3 (4 bytes) | 0xFC */
713 avx_put_u8(&p, (sps && sps_len > 0) ? 0xE1 : 0xE0); /* numOfSequenceParameterSets = 1 | 0xE0 */
714 if (sps && sps_len > 0) {
715 avx_put_u16(&p, (uint16_t)sps_len);
716 memcpy(p, sps, sps_len);
717 p += sps_len;
718 }
719 avx_put_u8(&p, (pps && pps_len > 0) ? 1 : 0); /* numOfPictureParameterSets */
720 if (pps && pps_len > 0) {
721 avx_put_u16(&p, (uint16_t)pps_len);
722 memcpy(p, pps, pps_len);
723 p += pps_len;
724 }
725 avx_box_patch_size(b_avcC, p);
726 avx_box_patch_size(b_avc1, p);
727 } else if (codec == AVX_RTSP_CODEC_HEVC) {
728 /* hvc1 Box */
729 uint8_t *b_hvc1 = p;
730 avx_put_u32(&p, 0);
731 avx_put_fourcc(&p, "hvc1");
732 memset(p, 0, 6); p += 6;
733 avx_put_u16(&p, 1);
734 avx_put_u16(&p, 0); avx_put_u16(&p, 0);
735 memset(p, 0, 12); p += 12;
736 avx_put_u16(&p, (uint16_t)width);
737 avx_put_u16(&p, (uint16_t)height);
738 avx_put_u32(&p, 0x00480000);
739 avx_put_u32(&p, 0x00480000);
740 avx_put_u32(&p, 0);
741 avx_put_u16(&p, 1);
742 p[0] = 7;
743 memcpy(p + 1, "OpenAVX", 7);
744 memset(p + 8, 0, 24);
745 p += 32;
746 avx_put_u16(&p, 0x0018);
747 avx_put_u16(&p, 0xFFFF);
748  
749 /* hvcC Box */
750 uint8_t *b_hvcC = p;
751 avx_put_u32(&p, 0);
752 avx_put_fourcc(&p, "hvcC");
753 avx_put_u8(&p, 1); /* configurationVersion */
754 avx_put_u8(&p, 0x01); /* general_profile_space(0) | general_tier_flag(0) | Main profile(1) */
755 avx_put_u32(&p, 0x60000000); /* general_profile_compatibility_flags */
756 memset(p, 0, 6); p += 6; /* general_constraint_indicator_flags */
757 avx_put_u8(&p, 93); /* general_level_idc = 93 (Level 3.1) */
758 avx_put_u16(&p, 0xF000); /* min_spatial_segmentation_idc */
759 avx_put_u8(&p, 0xFC); /* parallelismType */
760 avx_put_u8(&p, 0xFD); /* chromaFormat = 4:2:0 */
761 avx_put_u8(&p, 0xF8); /* bitDepthLumaMinus8 = 0 */
762 avx_put_u8(&p, 0xF8); /* bitDepthChromaMinus8 = 0 */
763 avx_put_u16(&p, 0); /* avgFrameRate */
764 avx_put_u8(&p, 0x0F); /* constantFrameRate=0, numTemporalLayers=1, temporalIdNested=1, lengthSizeMinusOne=3 */
765  
766 uint8_t num_arrays = 0;
767 if (vps && vps_len > 0) num_arrays++;
768 if (sps && sps_len > 0) num_arrays++;
769 if (pps && pps_len > 0) num_arrays++;
770 avx_put_u8(&p, num_arrays);
771  
772 if (vps && vps_len > 0) {
773 avx_put_u8(&p, 0x80 | 32); /* completeness=1, type=32 (VPS) */
774 avx_put_u16(&p, 1); /* count=1 */
775 avx_put_u16(&p, (uint16_t)vps_len);
776 memcpy(p, vps, vps_len);
777 p += vps_len;
778 }
779 if (sps && sps_len > 0) {
780 avx_put_u8(&p, 0x80 | 33); /* completeness=1, type=33 (SPS) */
781 avx_put_u16(&p, 1);
782 avx_put_u16(&p, (uint16_t)sps_len);
783 memcpy(p, sps, sps_len);
784 p += sps_len;
785 }
786 if (pps && pps_len > 0) {
787 avx_put_u8(&p, 0x80 | 34); /* completeness=1, type=34 (PPS) */
788 avx_put_u16(&p, 1);
789 avx_put_u16(&p, (uint16_t)pps_len);
790 memcpy(p, pps, pps_len);
791 p += pps_len;
792 }
793 avx_box_patch_size(b_hvcC, p);
794 avx_box_patch_size(b_hvc1, p);
795 } else {
796 /* av01 Box for AV1 */
797 uint8_t *b_av01 = p;
798 avx_put_u32(&p, 0);
799 avx_put_fourcc(&p, "av01");
800 memset(p, 0, 6); p += 6;
801 avx_put_u16(&p, 1);
802 avx_put_u16(&p, 0); avx_put_u16(&p, 0);
803 memset(p, 0, 12); p += 12;
804 avx_put_u16(&p, (uint16_t)width);
805 avx_put_u16(&p, (uint16_t)height);
806 avx_put_u32(&p, 0x00480000);
807 avx_put_u32(&p, 0x00480000);
808 avx_put_u32(&p, 0);
809 avx_put_u16(&p, 1);
810 p[0] = 7;
811 memcpy(p + 1, "OpenAVX", 7);
812 memset(p + 8, 0, 24);
813 p += 32;
814 avx_put_u16(&p, 0x0018);
815 avx_put_u16(&p, 0xFFFF);
816  
817 /* av1C Box (4 bytes header + config) */
818 uint8_t *b_av1C = p;
819 avx_put_u32(&p, 0);
820 avx_put_fourcc(&p, "av1C");
821 avx_put_u8(&p, 0x81); /* marker=1, version=1 */
822 avx_put_u8(&p, 0x00); /* seq_profile=0, seq_level_idx_0=0 */
823 avx_put_u8(&p, 0x00); /* tier=0, depth=8bit, mono=0, 4:2:0 */
824 avx_put_u8(&p, 0x00);
825 if (sps && sps_len > 0) {
826 memcpy(p, sps, sps_len);
827 p += sps_len;
828 }
829 avx_box_patch_size(b_av1C, p);
830 avx_box_patch_size(b_av01, p);
831 }
832  
833 avx_box_patch_size(b_stsd, p);
834  
835 /* Empty table boxes required by ISOBMFF specification */
836 /* stts (16 bytes) */
837 uint8_t *b_stts = p;
838 avx_put_u32(&p, 0); avx_put_fourcc(&p, "stts");
839 avx_put_u32(&p, 0); avx_put_u32(&p, 0);
840 avx_box_patch_size(b_stts, p);
841  
842 /* stsc (16 bytes) */
843 uint8_t *b_stsc = p;
844 avx_put_u32(&p, 0); avx_put_fourcc(&p, "stsc");
845 avx_put_u32(&p, 0); avx_put_u32(&p, 0);
846 avx_box_patch_size(b_stsc, p);
847  
848 /* stsz (20 bytes) */
849 uint8_t *b_stsz = p;
850 avx_put_u32(&p, 0); avx_put_fourcc(&p, "stsz");
851 avx_put_u32(&p, 0); avx_put_u32(&p, 0); avx_put_u32(&p, 0);
852 avx_box_patch_size(b_stsz, p);
853  
854 /* stco (16 bytes) */
855 uint8_t *b_stco = p;
856 avx_put_u32(&p, 0); avx_put_fourcc(&p, "stco");
857 avx_put_u32(&p, 0); avx_put_u32(&p, 0);
858 avx_box_patch_size(b_stco, p);
859  
860 avx_box_patch_size(b_stbl, p);
861 avx_box_patch_size(b_minf, p);
862 avx_box_patch_size(b_mdia, p);
863 avx_box_patch_size(b_trak, p);
864  
865 /* 2.3. mvex Box (Movie Extends Box) */
866 uint8_t *b_mvex = p;
867 avx_put_u32(&p, 0);
868 avx_put_fourcc(&p, "mvex");
869  
870 /* trex Box (32 bytes) */
871 uint8_t *b_trex = p;
872 avx_put_u32(&p, 0);
873 avx_put_fourcc(&p, "trex");
874 avx_put_u32(&p, 0); /* ver/flags */
875 avx_put_u32(&p, 1); /* track_id = 1 */
876 avx_put_u32(&p, 1); /* default_sample_description_index = 1 */
877 avx_put_u32(&p, 0); /* default_sample_duration = 0 */
878 avx_put_u32(&p, 0); /* default_sample_size = 0 */
879 avx_put_u32(&p, 0); /* default_sample_flags = 0 */
880 avx_box_patch_size(b_trex, p);
881  
882 avx_box_patch_size(b_mvex, p);
883 avx_box_patch_size(b_moov, p);
884  
885 return (size_t)(p - out_buf);
886 }
887  
888 /*
889 * Generates fMP4 movie fragment (moof and mdat boxes) wrapping single video Access Unit
890 * with sample duration, size, flags, and decode timestamp (tfdt).
891 */
892 OPENAVX_API size_t avx_fmp4_generate_media_fragment(
893 uint32_t sequence_number,
894 uint64_t base_decode_time_90khz,
895 uint32_t sample_duration_90khz,
896 bool is_keyframe,
897 const uint8_t *sample_avcc_data,
898 size_t sample_avcc_len,
899 uint8_t *out_buf,
900 size_t out_max
901 ) {
902 if (!out_buf || !sample_avcc_data || sample_avcc_len == 0) return 0;
903 if (out_max < (128 + sample_avcc_len)) return 0;
904 if (sample_duration_90khz == 0) sample_duration_90khz = 1500; /* 60fps default */
905  
906 uint8_t *p = out_buf;
907  
908 /* 1. moof Box (Movie Fragment Box) */
909 uint8_t *b_moof = p;
910 avx_put_u32(&p, 0);
911 avx_put_fourcc(&p, "moof");
912  
913 /* 1.1. mfhd Box (Movie Fragment Header, 16 bytes) */
914 uint8_t *b_mfhd = p;
915 avx_put_u32(&p, 0);
916 avx_put_fourcc(&p, "mfhd");
917 avx_put_u32(&p, 0); /* ver/flags */
918 avx_put_u32(&p, sequence_number);
919 avx_box_patch_size(b_mfhd, p);
920  
921 /* 1.2. traf Box (Track Fragment Box) */
922 uint8_t *b_traf = p;
923 avx_put_u32(&p, 0);
924 avx_put_fourcc(&p, "traf");
925  
926 /* 1.2.1. tfhd Box (Track Fragment Header, 16 bytes) */
927 uint8_t *b_tfhd = p;
928 avx_put_u32(&p, 0);
929 avx_put_fourcc(&p, "tfhd");
930 /* flags: 0x020000 = default-base-is-moof */
931 avx_put_u8(&p, 0); avx_put_u8(&p, 0x02); avx_put_u8(&p, 0); avx_put_u8(&p, 0);
932 avx_put_u32(&p, 1); /* track_id = 1 */
933 avx_box_patch_size(b_tfhd, p);
934  
935 /* 1.2.2. tfdt Box (Base Media Decode Time, 20 bytes) */
936 uint8_t *b_tfdt = p;
937 avx_put_u32(&p, 0);
938 avx_put_fourcc(&p, "tfdt");
939 avx_put_u8(&p, 1); /* version = 1 (64-bit timestamp) */
940 avx_put_u8(&p, 0); avx_put_u8(&p, 0); avx_put_u8(&p, 0);
941 avx_put_u64(&p, base_decode_time_90khz);
942 avx_box_patch_size(b_tfdt, p);
943  
944 /* 1.2.3. trun Box (Track Fragment Run) */
945 uint8_t *b_trun = p;
946 avx_put_u32(&p, 0);
947 avx_put_fourcc(&p, "trun");
948 /* flags: data-offset(0x01) | duration(0x100) | size(0x200) | flags(0x400) = 0x000701 */
949 avx_put_u8(&p, 0); avx_put_u8(&p, 0x00); avx_put_u8(&p, 0x07); avx_put_u8(&p, 0x01);
950 avx_put_u32(&p, 1); /* sample_count = 1 */
951  
952 /* Placeholder for data_offset */
953 uint8_t *p_data_offset = p;
954 avx_put_u32(&p, 0);
955  
956 /* Sample 0 description */
957 avx_put_u32(&p, sample_duration_90khz);
958 avx_put_u32(&p, (uint32_t)sample_avcc_len);
959 /* sample_flags: sync sample (keyframe) vs non-sync sample */
960 uint32_t sample_flags = is_keyframe ? 0x02000000 : 0x01010000;
961 avx_put_u32(&p, sample_flags);
962  
963 avx_box_patch_size(b_trun, p);
964 avx_box_patch_size(b_traf, p);
965 avx_box_patch_size(b_moof, p);
966  
967 /* Patch data_offset in trun: distance from moof start to mdat payload */
968 uint32_t moof_size = (uint32_t)(p - b_moof);
969 uint32_t data_offset = moof_size + 8; /* +8 for mdat header */
970 p_data_offset[0] = (uint8_t)(data_offset >> 24);
971 p_data_offset[1] = (uint8_t)(data_offset >> 16);
972 p_data_offset[2] = (uint8_t)(data_offset >> 8);
973 p_data_offset[3] = (uint8_t)(data_offset);
974  
975 /* 2. mdat Box (Media Data Box) */
976 avx_put_u32(&p, (uint32_t)(8 + sample_avcc_len));
977 avx_put_fourcc(&p, "mdat");
978 memcpy(p, sample_avcc_data, sample_avcc_len);
979 p += sample_avcc_len;
980  
981 return (size_t)(p - out_buf);
982 }
983  
984 /* ========================================================================= */
985 /* RFC 3174 FIPS 180-1 SHA-1 ENGINE & RFC 6455 WEBSOCKET ACCEPT KEY GENERATOR */
986 /* ========================================================================= */
987  
988 typedef struct {
989 uint32_t state[5];
990 uint32_t count[2];
991 uint8_t buffer[64];
992 } avx_sha1_ctx_t;
993  
994 static void avx_sha1_transform(uint32_t state[5], const uint8_t buffer[64]) {
995 uint32_t a = state[0], b = state[1], c = state[2], d = state[3], e = state[4];
996 uint32_t w[80];
997 for (int i = 0; i < 16; ++i) {
998 w[i] = ((uint32_t)buffer[i * 4] << 24) |
999 ((uint32_t)buffer[i * 4 + 1] << 16) |
1000 ((uint32_t)buffer[i * 4 + 2] << 8) |
1001 ((uint32_t)buffer[i * 4 + 3]);
1002 }
1003 for (int i = 16; i < 80; ++i) {
1004 uint32_t v = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16];
1005 w[i] = (v << 1) | (v >> 31);
1006 }
1007 for (int i = 0; i < 80; ++i) {
1008 uint32_t f, k;
1009 if (i < 20) {
1010 f = (b & c) | ((~b) & d);
1011 k = 0x5A827999U;
1012 } else if (i < 40) {
1013 f = b ^ c ^ d;
1014 k = 0x6ED9EBA1U;
1015 } else if (i < 60) {
1016 f = (b & c) | (b & d) | (c & d);
1017 k = 0x8F1BBCDCU;
1018 } else {
1019 f = b ^ c ^ d;
1020 k = 0xCA62C1D6U;
1021 }
1022 uint32_t temp = ((a << 5) | (a >> 27)) + f + e + k + w[i];
1023 e = d;
1024 d = c;
1025 c = (b << 30) | (b >> 2);
1026 b = a;
1027 a = temp;
1028 }
1029 state[0] += a;
1030 state[1] += b;
1031 state[2] += c;
1032 state[3] += d;
1033 state[4] += e;
1034 }
1035  
1036 static void avx_sha1_init(avx_sha1_ctx_t *ctx) {
1037 ctx->state[0] = 0x67452301U;
1038 ctx->state[1] = 0xEFCDAB89U;
1039 ctx->state[2] = 0x98BADCFEU;
1040 ctx->state[3] = 0x10325476U;
1041 ctx->state[4] = 0xC3D2E1F0U;
1042 ctx->count[0] = ctx->count[1] = 0;
1043 }
1044  
1045 static void avx_sha1_update(avx_sha1_ctx_t *ctx, const uint8_t *data, size_t len) {
1046 size_t i, j = (ctx->count[0] >> 3) & 63;
1047 if ((ctx->count[0] += (uint32_t)(len << 3)) < (uint32_t)(len << 3)) {
1048 ctx->count[1]++;
1049 }
1050 ctx->count[1] += (uint32_t)(len >> 29);
1051 if ((j + len) > 63) {
1052 i = 64 - j;
1053 memcpy(&ctx->buffer[j], data, i);
1054 avx_sha1_transform(ctx->state, ctx->buffer);
1055 for (; i + 63 < len; i += 64) {
1056 avx_sha1_transform(ctx->state, &data[i]);
1057 }
1058 j = 0;
1059 } else {
1060 i = 0;
1061 }
1062 memcpy(&ctx->buffer[j], &data[i], len - i);
1063 }
1064  
1065 static void avx_sha1_final(avx_sha1_ctx_t *ctx, uint8_t digest[20]) {
1066 uint8_t finalcount[8];
1067 for (int i = 0; i < 8; ++i) {
1068 finalcount[i] = (uint8_t)((ctx->count[(i >= 4 ? 0 : 1)] >> ((3 - (i & 3)) * 8)) & 255);
1069 }
1070 uint8_t c = 0x80;
1071 avx_sha1_update(ctx, &c, 1);
1072 while ((ctx->count[0] & 504) != 448) {
1073 c = 0x00;
1074 avx_sha1_update(ctx, &c, 1);
1075 }
1076 avx_sha1_update(ctx, finalcount, 8);
1077 for (int i = 0; i < 20; ++i) {
1078 digest[i] = (uint8_t)((ctx->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
1079 }
1080 }
1081  
1082 OPENAVX_API void avx_sha1_hash(const uint8_t *data, size_t len, uint8_t digest[20]) {
1083 avx_sha1_ctx_t ctx;
1084 avx_sha1_init(&ctx);
1085 if (data && len > 0) {
1086 avx_sha1_update(&ctx, data, len);
1087 }
1088 avx_sha1_final(&ctx, digest);
1089 }
1090  
1091 /* Computes RFC 6455 Sec-WebSocket-Accept response key via SHA-1 and Base64 encoding. */
1092 OPENAVX_API size_t avx_websocket_compute_accept(const char *client_key, char *out_accept, size_t out_max) {
1093 if (!client_key || !out_accept || out_max < 30) return 0;
1094 const char *guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
1095 char combined[128];
1096 snprintf(combined, sizeof(combined), "%s%s", client_key, guid);
1097  
1098 uint8_t digest[20];
1099 avx_sha1_hash((const uint8_t*)combined, strlen(combined), digest);
1100  
1101 return avx_base64_encode(digest, sizeof(digest), out_accept, out_max);
1102 }
1103  
1104 /* ========================================================================= */
1105 /* 3. HTTP / fMP4 SERVER ENGINE IMPLEMENTATION */
1106 /* ========================================================================= */
1107  
1108 typedef struct avx_web_client_t {
1109 avx_socket_t fd;
1110 bool active;
1111 bool streaming;
1112 bool received_keyframe;
1113 bool is_websocket;
1114 bool is_sse;
1115 uint8_t *ws_buf;
1116 size_t ws_cap;
1117 size_t ws_len;
1118 char req_buf[16384];
1119 size_t req_len;
1120 } avx_web_client_t;
1121  
1122 struct avx_web_server_t {
1123 avx_socket_t listen_fd;
1124 uint16_t port;
1125 char stream_name[128];
1126 avx_rtsp_codec_e codec;
1127 void (*on_keyframe_request)(void *user_ctx);
1128 avx_web_ingress_frame_cb on_ingress_frame;
1129 void (*on_tally_change)(void *user_ctx, const oavx_tally_t *tally);
1130 void *user_ctx;
1131  
1132 oavx_tally_t current_tally;
1133  
1134 avx_thread_t thread;
1135 avx_mutex_t lock;
1136 volatile bool running;
1137  
1138 avx_web_client_t clients[AVX_WEB_MAX_CLIENTS];
1139  
1140 /* Parameter cache */
1141 uint8_t *sps;
1142 size_t sps_len;
1143 uint8_t *pps;
1144 size_t pps_len;
1145 uint8_t *vps;
1146 size_t vps_len;
1147 uint32_t width;
1148 uint32_t height;
1149 uint8_t profile;
1150 uint8_t level;
1151  
1152 /* Pre-generated Init Segment */
1153 uint8_t init_segment[4096];
1154 size_t init_segment_len;
1155  
1156 /* Frame Sequence & Timestamp tracking */
1157 uint32_t seq_num;
1158 uint64_t last_pts_90k;
1159  
1160 /* Reusable Scratch Buffers */
1161 uint8_t *avcc_buf;
1162 size_t avcc_cap;
1163 uint8_t *frag_buf;
1164 size_t frag_cap;
1165 };
1166  
1167 static void close_client_locked(avx_web_client_t *c) {
1168 if (!c->active) return;
1169 if (avx_socket_is_valid(c->fd)) {
1170 avx_socket_close(c->fd);
1171 c->fd = AVX_INVALID_SOCKET;
1172 }
1173 c->active = false;
1174 c->streaming = false;
1175 c->received_keyframe = false;
1176 c->is_websocket = false;
1177 c->is_sse = false;
1178 if (c->ws_buf) {
1179 free(c->ws_buf);
1180 c->ws_buf = NULL;
1181 }
1182 c->ws_cap = 0;
1183 c->ws_len = 0;
1184 c->req_len = 0;
1185 }
1186  
1187 static void send_ws_text_frame_locked(avx_socket_t fd, const char *text) {
1188 if (!avx_socket_is_valid(fd) || !text) return;
1189 size_t len = strlen(text);
1190 uint8_t hdr[10];
1191 size_t hdr_len = 2;
1192 hdr[0] = 0x81; /* FIN + Text frame (opcode 0x1) */
1193 if (len < 126) {
1194 hdr[1] = (uint8_t)len;
1195 } else if (len <= 65535) {
1196 hdr[1] = 126;
1197 hdr[2] = (uint8_t)(len >> 8);
1198 hdr[3] = (uint8_t)(len & 0xFF);
1199 hdr_len = 4;
1200 } else {
1201 hdr[1] = 127;
1202 for (int k = 0; k < 8; ++k) {
1203 hdr[2 + k] = (uint8_t)((len >> (56 - k * 8)) & 0xFF);
1204 }
1205 hdr_len = 10;
1206 }
1207 send(fd, (const char*)hdr, hdr_len, MSG_NOSIGNAL);
1208 if (len > 0) {
1209 send(fd, text, len, MSG_NOSIGNAL);
1210 }
1211 }
1212  
1213 static const char* avx_strcasestr(const char *haystack, const char *needle) {
1214 if (!haystack || !needle) return NULL;
1215 if (*needle == '\0') return haystack;
1216 size_t nlen = strlen(needle);
1217 for (; *haystack != '\0'; ++haystack) {
1218 if (strncasecmp(haystack, needle, nlen) == 0) {
1219 return haystack;
1220 }
1221 }
1222 return NULL;
1223 }
1224  
1225 static uint8_t parse_tally_flags_from_str(const char *str, uint8_t current_flags) {
1226 if (!str) return current_flags;
1227 if (strstr(str, "off") || strstr(str, "none") || strstr(str, "clear")) {
1228 return OAVX_TALLY_NONE;
1229 }
1230 uint8_t flags = 0;
1231 if (strstr(str, "program") || strstr(str, "pgm") || strstr(str, "\"program\":true") || strstr(str, "\"program\": true")) {
1232 flags |= OAVX_TALLY_PROGRAM;
1233 }
1234 if (strstr(str, "preview") || strstr(str, "pvw") || strstr(str, "\"preview\":true") || strstr(str, "\"preview\": true")) {
1235 flags |= OAVX_TALLY_PREVIEW;
1236 }
1237 if (strstr(str, "recording") || strstr(str, "rec") || strstr(str, "\"recording\":true") || strstr(str, "\"recording\": true")) {
1238 flags |= OAVX_TALLY_RECORDING;
1239 }
1240 const char *f = strstr(str, "flags=");
1241 if (!f) f = strstr(str, "\"flags\":");
1242 if (f) {
1243 while (*f && (*f < '0' || *f > '9')) f++;
1244 if (*f >= '0' && *f <= '9') {
1245 flags = (uint8_t)atoi(f);
1246 }
1247 }
1248 return flags;
1249 }
1250  
1251 static void broadcast_tally_locked(avx_web_server_t *server, const oavx_tally_t *tally) {
1252 if (!server) return;
1253 if (tally) {
1254 server->current_tally = *tally;
1255 }
1256 bool prog = (server->current_tally.flags & OAVX_TALLY_PROGRAM) != 0;
1257 bool prev = (server->current_tally.flags & OAVX_TALLY_PREVIEW) != 0;
1258 bool rec = (server->current_tally.flags & OAVX_TALLY_RECORDING) != 0;
1259 char json[160];
1260 snprintf(json, sizeof(json),
1261 "{\"type\":\"tally\",\"program\":%s,\"preview\":%s,\"recording\":%s,\"flags\":%u}",
1262 prog ? "true" : "false",
1263 prev ? "true" : "false",
1264 rec ? "true" : "false",
1265 server->current_tally.flags);
1266  
1267 char sse_data[256];
1268 snprintf(sse_data, sizeof(sse_data),
1269 "data: {\"type\":\"tally\",\"program\":%s,\"preview\":%s,\"recording\":%s,\"flags\":%u}\n\n",
1270 prog ? "true" : "false",
1271 prev ? "true" : "false",
1272 rec ? "true" : "false",
1273 server->current_tally.flags);
1274  
1275 for (int i = 0; i < AVX_WEB_MAX_CLIENTS; ++i) {
1276 if (!server->clients[i].active || !avx_socket_is_valid(server->clients[i].fd)) continue;
1277 if (server->clients[i].is_websocket) {
1278 send_ws_text_frame_locked(server->clients[i].fd, json);
1279 } else if (server->clients[i].is_sse) {
1280 send(server->clients[i].fd, sse_data, strlen(sse_data), MSG_NOSIGNAL);
1281 }
1282 }
1283 }
1284  
1285 /* HTTP router servicing low-latency player UI, fMP4 live streaming, and WebSocket upgrades. */
1286 static void handle_client_http_request(avx_web_server_t *srv, avx_web_client_t *c) {
1287 c->req_buf[c->req_len] = '\0';
1288 char method[16] = {0};
1289 char path[2048] = {0};
1290  
1291 if (sscanf(c->req_buf, "%15s %2047s", method, path) < 2) {
1292 close_client_locked(c);
1293 return;
1294 }
1295  
1296 if (strcmp(method, "OPTIONS") == 0) {
1297 const char *resp =
1298 "HTTP/1.1 204 No Content\r\n"
1299 "Access-Control-Allow-Origin: *\r\n"
1300 "Access-Control-Allow-Methods: GET, POST, OPTIONS\r\n"
1301 "Access-Control-Allow-Headers: *\r\n"
1302 "Connection: close\r\n\r\n";
1303 send(c->fd, resp, strlen(resp), MSG_NOSIGNAL);
1304 close_client_locked(c);
1305 } else if (strcmp(method, "GET") == 0) {
1306 /* Check for WebSocket upgrade (RFC 6455) */
1307 const char *upgrade_hdr = avx_strcasestr(c->req_buf, "Upgrade:");
1308 bool is_ws_upgrade = false;
1309 if (upgrade_hdr) {
1310 const char *eol = strstr(upgrade_hdr, "\r\n");
1311 if (!eol) eol = strchr(upgrade_hdr, '\n');
1312 if (eol) {
1313 char uval[128] = {0};
1314 size_t ulen = (size_t)(eol - upgrade_hdr);
1315 if (ulen < sizeof(uval)) {
1316 memcpy(uval, upgrade_hdr, ulen);
1317 if (avx_strcasestr(uval, "websocket")) {
1318 is_ws_upgrade = true;
1319 }
1320 }
1321 } else if (avx_strcasestr(upgrade_hdr, "websocket")) {
1322 is_ws_upgrade = true;
1323 }
1324 }
1325 const char *key_hdr = avx_strcasestr(c->req_buf, "Sec-WebSocket-Key:");
1326 if (is_ws_upgrade && key_hdr) {
1327 char client_key[64] = {0};
1328 key_hdr += 18; /* Skip "Sec-WebSocket-Key:" */
1329 while (*key_hdr == ' ') key_hdr++;
1330 sscanf(key_hdr, "%63s", client_key);
1331  
1332 char accept_str[64] = {0};
1333 if (avx_websocket_compute_accept(client_key, accept_str, sizeof(accept_str)) > 0) {
1334 char ws_resp[256];
1335 snprintf(ws_resp, sizeof(ws_resp),
1336 "HTTP/1.1 101 Switching Protocols\r\n"
1337 "Upgrade: websocket\r\n"
1338 "Connection: Upgrade\r\n"
1339 "Sec-WebSocket-Accept: %s\r\n\r\n",
1340 accept_str);
1341 send(c->fd, ws_resp, strlen(ws_resp), MSG_NOSIGNAL);
1342 c->is_websocket = true;
1343 c->streaming = false;
1344 c->received_keyframe = false;
1345 c->ws_cap = 256 * 1024;
1346 c->ws_buf = (uint8_t*)malloc(c->ws_cap);
1347 c->ws_len = 0;
1348  
1349 /* Push initial tally status immediately upon upgrade */
1350 bool prog = (srv->current_tally.flags & OAVX_TALLY_PROGRAM) != 0;
1351 bool prev = (srv->current_tally.flags & OAVX_TALLY_PREVIEW) != 0;
1352 bool rec = (srv->current_tally.flags & OAVX_TALLY_RECORDING) != 0;
1353 char tally_json[160];
1354 snprintf(tally_json, sizeof(tally_json),
1355 "{\"type\":\"tally\",\"program\":%s,\"preview\":%s,\"recording\":%s,\"flags\":%u}",
1356 prog ? "true" : "false",
1357 prev ? "true" : "false",
1358 rec ? "true" : "false",
1359 srv->current_tally.flags);
1360 send_ws_text_frame_locked(c->fd, tally_json);
1361 return;
1362 } else {
1363 close_client_locked(c);
1364 return;
1365 }
1366 }
1367  
1368 if (strcmp(path, "/") == 0 || strcmp(path, "/index.html") == 0) {
1369 char hdr[512];
1370 size_t html_len = strlen(k_player_html);
1371 snprintf(hdr, sizeof(hdr),
1372 "HTTP/1.1 200 OK\r\n"
1373 "Content-Type: text/html; charset=utf-8\r\n"
1374 "Content-Length: %zu\r\n"
1375 "Access-Control-Allow-Origin: *\r\n"
1376 "Connection: close\r\n\r\n",
1377 html_len);
1378 #if defined(AVX_OS_POSIX)
1379 struct iovec iov[2];
1380 iov[0].iov_base = hdr;
1381 iov[0].iov_len = strlen(hdr);
1382 iov[1].iov_base = (void*)k_player_html;
1383 iov[1].iov_len = html_len;
1384 struct msghdr msg;
1385 memset(&msg, 0, sizeof(msg));
1386 msg.msg_iov = iov;
1387 msg.msg_iovlen = 2;
1388 (void)sendmsg(c->fd, &msg, MSG_NOSIGNAL);
1389 #else
1390 send(c->fd, hdr, (int)strlen(hdr), MSG_NOSIGNAL);
1391 send(c->fd, k_player_html, (int)html_len, MSG_NOSIGNAL);
1392 #endif
1393 close_client_locked(c);
1394 } else if (strcmp(path, "/camera") == 0 || strcmp(path, "/camera/") == 0 || strcmp(path, "/camera.html") == 0) {
1395 char hdr[512];
1396 size_t html_len = strlen(k_camera_html);
1397 snprintf(hdr, sizeof(hdr),
1398 "HTTP/1.1 200 OK\r\n"
1399 "Content-Type: text/html; charset=utf-8\r\n"
1400 "Content-Length: %zu\r\n"
1401 "Access-Control-Allow-Origin: *\r\n"
1402 "Connection: close\r\n\r\n",
1403 html_len);
1404 #if defined(AVX_OS_POSIX)
1405 struct iovec iov[2];
1406 iov[0].iov_base = hdr;
1407 iov[0].iov_len = strlen(hdr);
1408 iov[1].iov_base = (void*)k_camera_html;
1409 iov[1].iov_len = html_len;
1410 struct msghdr msg;
1411 memset(&msg, 0, sizeof(msg));
1412 msg.msg_iov = iov;
1413 msg.msg_iovlen = 2;
1414 (void)sendmsg(c->fd, &msg, MSG_NOSIGNAL);
1415 #else
1416 send(c->fd, hdr, (int)strlen(hdr), MSG_NOSIGNAL);
1417 send(c->fd, k_camera_html, (int)html_len, MSG_NOSIGNAL);
1418 #endif
1419 close_client_locked(c);
1420 } else if (strcmp(path, "/live.mp4") == 0 || strncmp(path, "/live.mp4?", 10) == 0) {
1421 const char *codec_mime = "video/mp4; codecs=\"avc1.640028\"";
1422 if (srv->codec == AVX_RTSP_CODEC_HEVC) {
1423 codec_mime = "video/mp4; codecs=\"hvc1.1.6.L93.B0\"";
1424 } else if (srv->codec == AVX_RTSP_CODEC_AV1) {
1425 codec_mime = "video/mp4; codecs=\"av01.0.08M.10\"";
1426 }
1427  
1428 char hdr[512];
1429 snprintf(hdr, sizeof(hdr),
1430 "HTTP/1.1 200 OK\r\n"
1431 "Content-Type: %s\r\n"
1432 "Cache-Control: no-cache, no-store, must-revalidate\r\n"
1433 "Pragma: no-cache\r\n"
1434 "Expires: 0\r\n"
1435 "Access-Control-Allow-Origin: *\r\n"
1436 "Connection: close\r\n\r\n",
1437 codec_mime);
1438 send(c->fd, hdr, strlen(hdr), MSG_NOSIGNAL);
1439  
1440 c->streaming = true;
1441 c->received_keyframe = false;
1442  
1443 /* If init segment is available, send it immediately */
1444 if (srv->init_segment_len > 0) {
1445 send(c->fd, (const char*)srv->init_segment, srv->init_segment_len, MSG_NOSIGNAL);
1446 }
1447  
1448 /* Request instant IDR keyframe from upstream encoder */
1449 if (srv->on_keyframe_request) {
1450 srv->on_keyframe_request(srv->user_ctx);
1451 }
1452 } else if (strcmp(path, "/status") == 0 || strcmp(path, "/api/status") == 0) {
1453 int client_count = 0;
1454 for (int i = 0; i < AVX_WEB_MAX_CLIENTS; ++i) {
1455 if (srv->clients[i].active && srv->clients[i].streaming) client_count++;
1456 }
1457 const char *cname = (srv->codec == AVX_RTSP_CODEC_HEVC) ? "HEVC" :
1458 ((srv->codec == AVX_RTSP_CODEC_AV1) ? "AV1" : "H264");
1459 char body[256];
1460 snprintf(body, sizeof(body),
1461 "{\"status\":\"online\",\"name\":\"%s\",\"codec\":\"%s\",\"port\":%u,\"clients\":%d,\"width\":%u,\"height\":%u}\n",
1462 srv->stream_name, cname, srv->port, client_count, srv->width, srv->height);
1463 char resp_full[1024];
1464 snprintf(resp_full, sizeof(resp_full),
1465 "HTTP/1.1 200 OK\r\n"
1466 "Content-Type: application/json\r\n"
1467 "Content-Length: %zu\r\n"
1468 "Access-Control-Allow-Origin: *\r\n"
1469 "Connection: close\r\n\r\n"
1470 "%s",
1471 strlen(body), body);
1472 send(c->fd, resp_full, strlen(resp_full), MSG_NOSIGNAL);
1473 close_client_locked(c);
1474 } else if (strcmp(path, "/tally") == 0 || strcmp(path, "/api/tally") == 0 ||
1475 strncmp(path, "/tally?", 7) == 0 || strncmp(path, "/api/tally?", 11) == 0) {
1476 void (*cb)(void*, const oavx_tally_t*) = NULL;
1477 void *cb_ctx = NULL;
1478 oavx_tally_t cb_tally = {0};
1479  
1480 const char *q = strchr(path, '?');
1481 if (q && strstr(q, "set=")) {
1482 srv->current_tally.flags = parse_tally_flags_from_str(q, srv->current_tally.flags);
1483 broadcast_tally_locked(srv, &srv->current_tally);
1484 cb = srv->on_tally_change;
1485 cb_ctx = srv->user_ctx;
1486 cb_tally = srv->current_tally;
1487 }
1488 bool prog = (srv->current_tally.flags & OAVX_TALLY_PROGRAM) != 0;
1489 bool prev = (srv->current_tally.flags & OAVX_TALLY_PREVIEW) != 0;
1490 bool rec = (srv->current_tally.flags & OAVX_TALLY_RECORDING) != 0;
1491 char body[160];
1492 snprintf(body, sizeof(body),
1493 "{\"program\":%s,\"preview\":%s,\"recording\":%s,\"flags\":%u}\n",
1494 prog ? "true" : "false",
1495 prev ? "true" : "false",
1496 rec ? "true" : "false",
1497 srv->current_tally.flags);
1498 char resp_full[512];
1499 snprintf(resp_full, sizeof(resp_full),
1500 "HTTP/1.1 200 OK\r\n"
1501 "Content-Type: application/json\r\n"
1502 "Content-Length: %zu\r\n"
1503 "Access-Control-Allow-Origin: *\r\n"
1504 "Connection: close\r\n\r\n"
1505 "%s",
1506 strlen(body), body);
1507 send(c->fd, resp_full, strlen(resp_full), MSG_NOSIGNAL);
1508 close_client_locked(c);
1509 if (cb) {
1510 avx_mutex_unlock(&srv->lock);
1511 cb(cb_ctx, &cb_tally);
1512 avx_mutex_lock(&srv->lock);
1513 }
1514 } else if (strcmp(path, "/tally/text") == 0 || strcmp(path, "/api/tally/text") == 0) {
1515 bool prog = (srv->current_tally.flags & OAVX_TALLY_PROGRAM) != 0;
1516 bool prev = (srv->current_tally.flags & OAVX_TALLY_PREVIEW) != 0;
1517 bool rec = (srv->current_tally.flags & OAVX_TALLY_RECORDING) != 0;
1518 const char *status_str = "OFF";
1519 if (prog && rec) status_str = "PROGRAM+RECORDING";
1520 else if (prog) status_str = "PROGRAM";
1521 else if (prev && rec) status_str = "PREVIEW+RECORDING";
1522 else if (prev) status_str = "PREVIEW";
1523 else if (rec) status_str = "RECORDING";
1524  
1525 char resp_full[256];
1526 snprintf(resp_full, sizeof(resp_full),
1527 "HTTP/1.1 200 OK\r\n"
1528 "Content-Type: text/plain\r\n"
1529 "Content-Length: %zu\r\n"
1530 "Access-Control-Allow-Origin: *\r\n"
1531 "Connection: close\r\n\r\n"
1532 "%s\n",
1533 strlen(status_str) + 1, status_str);
1534 send(c->fd, resp_full, strlen(resp_full), MSG_NOSIGNAL);
1535 close_client_locked(c);
1536 } else if (strcmp(path, "/tally/sse") == 0 || strcmp(path, "/api/tally/sse") == 0 || strcmp(path, "/events") == 0) {
1537 const char *sse_hdr =
1538 "HTTP/1.1 200 OK\r\n"
1539 "Content-Type: text/event-stream\r\n"
1540 "Cache-Control: no-cache, no-transform\r\n"
1541 "Connection: keep-alive\r\n"
1542 "Access-Control-Allow-Origin: *\r\n\r\n";
1543 send(c->fd, sse_hdr, strlen(sse_hdr), MSG_NOSIGNAL);
1544 c->is_sse = true;
1545 c->streaming = false;
1546 c->received_keyframe = false;
1547  
1548 bool prog = (srv->current_tally.flags & OAVX_TALLY_PROGRAM) != 0;
1549 bool prev = (srv->current_tally.flags & OAVX_TALLY_PREVIEW) != 0;
1550 bool rec = (srv->current_tally.flags & OAVX_TALLY_RECORDING) != 0;
1551 char initial_event[256];
1552 snprintf(initial_event, sizeof(initial_event),
1553 "data: {\"type\":\"tally\",\"program\":%s,\"preview\":%s,\"recording\":%s,\"flags\":%u}\n\n",
1554 prog ? "true" : "false",
1555 prev ? "true" : "false",
1556 rec ? "true" : "false",
1557 srv->current_tally.flags);
1558 send(c->fd, initial_event, strlen(initial_event), MSG_NOSIGNAL);
1559 return;
1560 } else {
1561 const char *resp =
1562 "HTTP/1.1 404 Not Found\r\n"
1563 "Content-Length: 9\r\n"
1564 "Connection: close\r\n\r\n"
1565 "Not Found";
1566 send(c->fd, resp, strlen(resp), MSG_NOSIGNAL);
1567 close_client_locked(c);
1568 }
1569 } else if (strcmp(method, "POST") == 0) {
1570 if (strcmp(path, "/tally") == 0 || strcmp(path, "/api/tally") == 0 ||
1571 strcmp(path, "/tally/set") == 0 || strcmp(path, "/api/tally/set") == 0) {
1572 const char *body_start = strstr(c->req_buf, "\r\n\r\n");
1573 if (body_start) body_start += 4;
1574 srv->current_tally.flags = parse_tally_flags_from_str(body_start ? body_start : c->req_buf, srv->current_tally.flags);
1575 broadcast_tally_locked(srv, &srv->current_tally);
1576 void (*cb)(void*, const oavx_tally_t*) = srv->on_tally_change;
1577 void *cb_ctx = srv->user_ctx;
1578 oavx_tally_t cb_tally = srv->current_tally;
1579  
1580 bool prog = (srv->current_tally.flags & OAVX_TALLY_PROGRAM) != 0;
1581 bool prev = (srv->current_tally.flags & OAVX_TALLY_PREVIEW) != 0;
1582 bool rec = (srv->current_tally.flags & OAVX_TALLY_RECORDING) != 0;
1583 char body[160];
1584 snprintf(body, sizeof(body),
1585 "{\"ok\":true,\"program\":%s,\"preview\":%s,\"recording\":%s,\"flags\":%u}\n",
1586 prog ? "true" : "false",
1587 prev ? "true" : "false",
1588 rec ? "true" : "false",
1589 srv->current_tally.flags);
1590 char resp_full[512];
1591 snprintf(resp_full, sizeof(resp_full),
1592 "HTTP/1.1 200 OK\r\n"
1593 "Content-Type: application/json\r\n"
1594 "Content-Length: %zu\r\n"
1595 "Access-Control-Allow-Origin: *\r\n"
1596 "Connection: close\r\n\r\n"
1597 "%s",
1598 strlen(body), body);
1599 send(c->fd, resp_full, strlen(resp_full), MSG_NOSIGNAL);
1600 close_client_locked(c);
1601 if (cb) {
1602 avx_mutex_unlock(&srv->lock);
1603 cb(cb_ctx, &cb_tally);
1604 avx_mutex_lock(&srv->lock);
1605 }
1606 } else {
1607 const char *resp =
1608 "HTTP/1.1 404 Not Found\r\n"
1609 "Content-Length: 9\r\n"
1610 "Connection: close\r\n\r\n"
1611 "Not Found";
1612 send(c->fd, resp, strlen(resp), MSG_NOSIGNAL);
1613 close_client_locked(c);
1614 }
1615 } else {
1616 const char *resp =
1617 "HTTP/1.1 405 Method Not Allowed\r\n"
1618 "Content-Length: 0\r\n"
1619 "Connection: close\r\n\r\n";
1620 send(c->fd, resp, strlen(resp), MSG_NOSIGNAL);
1621 close_client_locked(c);
1622 }
1623 }
1624  
1625 static void* avx_web_server_worker(void *arg) {
1626 avx_web_server_t *srv = (avx_web_server_t*)arg;
1627  
1628 while (srv->running) {
1629 avx_pollfd_t pfds[AVX_WEB_MAX_CLIENTS + 1];
1630 int client_indices[AVX_WEB_MAX_CLIENTS + 1];
1631 int nfds = 0;
1632  
1633 avx_mutex_lock(&srv->lock);
1634 if (avx_socket_is_valid(srv->listen_fd)) {
1635 pfds[nfds].fd = srv->listen_fd;
1636 pfds[nfds].events = POLLIN;
1637 pfds[nfds].revents = 0;
1638 client_indices[nfds] = -1;
1639 nfds++;
1640 }
1641  
1642 for (int i = 0; i < AVX_WEB_MAX_CLIENTS; ++i) {
1643 if (srv->clients[i].active && (!srv->clients[i].streaming || srv->clients[i].is_websocket || srv->clients[i].is_sse) && avx_socket_is_valid(srv->clients[i].fd)) {
1644 pfds[nfds].fd = srv->clients[i].fd;
1645 pfds[nfds].events = POLLIN;
1646 pfds[nfds].revents = 0;
1647 client_indices[nfds] = i;
1648 nfds++;
1649 }
1650 }
1651 avx_mutex_unlock(&srv->lock);
1652  
1653 if (nfds == 0) {
1654 avx_sleep_ms(10);
1655 continue;
1656 }
1657  
1658 int pr = avx_poll(pfds, (avx_nfds_t)nfds, 30);
1659 if (pr <= 0) continue;
1660  
1661 for (int j = 0; j < nfds; ++j) {
1662 if (!(pfds[j].revents & (POLLIN | POLLERR | POLLHUP))) continue;
1663  
1664 if (client_indices[j] == -1) {
1665 /* New connection on HTTP listener */
1666 struct sockaddr_in client_addr;
1667 socklen_t addr_len = sizeof(client_addr);
1668 avx_socket_t cfd = accept(srv->listen_fd, (struct sockaddr*)&client_addr, &addr_len);
1669 if (avx_socket_is_valid(cfd)) {
1670 avx_socket_set_tcp_nodelay(cfd, true);
1671 avx_socket_set_nonblocking(cfd, true);
1672  
1673 avx_mutex_lock(&srv->lock);
1674 int slot = -1;
1675 for (int i = 0; i < AVX_WEB_MAX_CLIENTS; ++i) {
1676 if (!srv->clients[i].active) {
1677 slot = i;
1678 break;
1679 }
1680 }
1681 if (slot >= 0) {
1682 srv->clients[slot].fd = cfd;
1683 srv->clients[slot].active = true;
1684 srv->clients[slot].streaming = false;
1685 srv->clients[slot].received_keyframe = false;
1686 srv->clients[slot].is_websocket = false;
1687 srv->clients[slot].is_sse = false;
1688 srv->clients[slot].ws_buf = NULL;
1689 srv->clients[slot].ws_cap = 0;
1690 srv->clients[slot].ws_len = 0;
1691 srv->clients[slot].req_len = 0;
1692 } else {
1693 avx_socket_close(cfd);
1694 }
1695 avx_mutex_unlock(&srv->lock);
1696 }
1697 } else {
1698 int idx = client_indices[j];
1699 avx_mutex_lock(&srv->lock);
1700 if (srv->clients[idx].active) {
1701 avx_web_client_t *c = &srv->clients[idx];
1702 if (c->is_websocket) {
1703 if (!c->ws_buf) {
1704 c->ws_cap = 256 * 1024;
1705 c->ws_buf = (uint8_t*)malloc(c->ws_cap);
1706 c->ws_len = 0;
1707 }
1708 if (c->ws_len + 65536 > c->ws_cap) {
1709 size_t ncap = c->ws_cap * 2;
1710 if (ncap > 16 * 1024 * 1024) ncap = 16 * 1024 * 1024;
1711 uint8_t *nb = (uint8_t*)realloc(c->ws_buf, ncap);
1712 if (nb) {
1713 c->ws_buf = nb;
1714 c->ws_cap = ncap;
1715 }
1716 }
1717  
1718 ssize_t n = recv(c->fd, (char*)(c->ws_buf + c->ws_len), c->ws_cap - c->ws_len, 0);
1719 if (n > 0) {
1720 c->ws_len += (size_t)n;
1721 while (c->ws_len >= 2) {
1722 uint8_t b0 = c->ws_buf[0];
1723 uint8_t b1 = c->ws_buf[1];
1724 uint8_t opcode = b0 & 0x0F;
1725 bool masked = (b1 & 0x80) != 0;
1726 uint64_t payload_len = b1 & 0x7F;
1727 size_t header_len = 2;
1728  
1729 if (payload_len == 126) {
1730 if (c->ws_len < 4) break;
1731 payload_len = ((uint64_t)c->ws_buf[2] << 8) | c->ws_buf[3];
1732 header_len = 4;
1733 } else if (payload_len == 127) {
1734 if (c->ws_len < 10) break;
1735 payload_len = 0;
1736 for (int k = 0; k < 8; ++k) {
1737 payload_len = (payload_len << 8) | c->ws_buf[2 + k];
1738 }
1739 header_len = 10;
1740 }
1741  
1742 uint8_t mask[4] = {0};
1743 if (masked) {
1744 if (c->ws_len < header_len + 4) break;
1745 memcpy(mask, c->ws_buf + header_len, 4);
1746 header_len += 4;
1747 }
1748  
1749 if (c->ws_len < header_len + payload_len) {
1750 /* If complete frame exceeds current buffer capacity, expand buffer */
1751 if (header_len + payload_len > c->ws_cap) {
1752 size_t ncap = (header_len + payload_len + 65535) & ~65535;
1753 if (ncap > 16 * 1024 * 1024) ncap = 16 * 1024 * 1024;
1754 uint8_t *nb = (uint8_t*)realloc(c->ws_buf, ncap);
1755 if (nb) {
1756 c->ws_buf = nb;
1757 c->ws_cap = ncap;
1758 }
1759 }
1760 break; /* Incomplete frame, wait for more data */
1761 }
1762  
1763 uint8_t *payload = c->ws_buf + header_len;
1764 if (masked) {
1765 for (size_t k = 0; k < payload_len; ++k) {
1766 payload[k] ^= mask[k & 3];
1767 }
1768 }
1769  
1770 if (opcode == 0x8) {
1771 /* Connection Close */
1772 uint8_t cr[2] = { 0x88, 0x00 };
1773 send(c->fd, (const char*)cr, 2, MSG_NOSIGNAL);
1774 close_client_locked(c);
1775 break;
1776 } else if (opcode == 0x9) {
1777 /* Ping -> Send Pong */
1778 uint8_t pong[10];
1779 pong[0] = 0x8A;
1780 size_t plen = 2;
1781 if (payload_len < 126) {
1782 pong[1] = (uint8_t)payload_len;
1783 } else {
1784 pong[1] = 126;
1785 pong[2] = (uint8_t)(payload_len >> 8);
1786 pong[3] = (uint8_t)(payload_len & 0xFF);
1787 plen = 4;
1788 }
1789 send(c->fd, (const char*)pong, plen, MSG_NOSIGNAL);
1790 if (payload_len > 0) {
1791 send(c->fd, (const char*)payload, (size_t)payload_len, MSG_NOSIGNAL);
1792 }
1793 } else if (opcode == 0x2) {
1794 /* Binary Video Frame */
1795 if (srv->on_ingress_frame && payload_len > 0) {
1796 uint32_t fourcc = OAVX_FOURCC_VIDEO_TYPE_H264;
1797 uint32_t w = 0, h = 0;
1798 bool is_key = false;
1799 const uint8_t *vbytes = payload;
1800 size_t vsize = payload_len;
1801  
1802 if (payload_len >= sizeof(avx_web_frame_header_t)) {
1803 const avx_web_frame_header_t *whdr = (const avx_web_frame_header_t*)payload;
1804 if (whdr->magic == AVX_WEB_FRAME_MAGIC || whdr->magic == 0x4F415658U) {
1805 if (whdr->magic == 0x4F415658U) {
1806 /* Network / Big Endian fallback */
1807 fourcc = ((whdr->fourcc >> 24) & 0xff) | ((whdr->fourcc >> 8) & 0xff00) |
1808 ((whdr->fourcc << 8) & 0xff0000) | ((whdr->fourcc << 24) & 0xff000000);
1809 w = ((whdr->width >> 8) & 0xff) | ((whdr->width << 8) & 0xff00);
1810 h = ((whdr->height >> 8) & 0xff) | ((whdr->height << 8) & 0xff00);
1811 is_key = (whdr->flags != 0);
1812 } else {
1813 fourcc = whdr->fourcc;
1814 w = whdr->width;
1815 h = whdr->height;
1816 is_key = (whdr->flags & 0x01) != 0;
1817 }
1818 vbytes = payload + sizeof(avx_web_frame_header_t);
1819 vsize = payload_len - sizeof(avx_web_frame_header_t);
1820 }
1821 }
1822  
1823 avx_web_ingress_frame_cb cb = srv->on_ingress_frame;
1824 void *uctx = srv->user_ctx;
1825 avx_mutex_unlock(&srv->lock);
1826 cb(vbytes, vsize, fourcc, w, h, is_key, uctx);
1827 avx_mutex_lock(&srv->lock);
1828 if (!c->active) break;
1829 }
1830 }
1831  
1832 size_t total_consumed = header_len + payload_len;
1833 size_t rem = c->ws_len - total_consumed;
1834 if (rem > 0) {
1835 memmove(c->ws_buf, c->ws_buf + total_consumed, rem);
1836 }
1837 c->ws_len = rem;
1838 }
1839 } else if (n == 0 || (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK)) {
1840 close_client_locked(c);
1841 }
1842 } else if (c->is_sse) {
1843 char dummy[64];
1844 ssize_t n = recv(c->fd, dummy, sizeof(dummy), 0);
1845 if (n == 0 || (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK)) {
1846 close_client_locked(c);
1847 }
1848 } else if (!c->streaming) {
1849 if (c->req_len >= sizeof(c->req_buf) - 1) {
1850 const char *resp = "HTTP/1.1 431 Request Header Fields Too Large\r\nConnection: close\r\n\r\n";
1851 send(c->fd, resp, strlen(resp), MSG_NOSIGNAL);
1852 close_client_locked(c);
1853 continue;
1854 }
1855 ssize_t n = recv(c->fd, c->req_buf + c->req_len, sizeof(c->req_buf) - 1 - c->req_len, 0);
1856 if (n > 0) {
1857 c->req_len += (size_t)n;
1858 c->req_buf[c->req_len] = '\0';
1859 if (strstr(c->req_buf, "\r\n\r\n") || strstr(c->req_buf, "\n\n")) {
1860 handle_client_http_request(srv, c);
1861 }
1862 } else if (n == 0 || (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK)) {
1863 close_client_locked(c);
1864 }
1865 }
1866 }
1867 avx_mutex_unlock(&srv->lock);
1868 }
1869 }
1870 }
1871  
1872 return NULL;
1873 }
1874  
1875 /* ========================================================================= */
1876 /* 4. PUBLIC API IMPLEMENTATION */
1877 /* ========================================================================= */
1878  
1879 OPENAVX_API avx_web_server_t* avx_web_server_create(const avx_web_server_config_t *config) {
1880 if (!config) return NULL;
1881 avx_platform_sockets_init();
1882  
1883 avx_web_server_t *srv = (avx_web_server_t*)calloc(1, sizeof(avx_web_server_t));
1884 if (!srv) return NULL;
1885  
1886 srv->port = config->port;
1887 srv->codec = config->codec;
1888 srv->on_keyframe_request = config->on_keyframe_request;
1889 srv->on_ingress_frame = config->on_ingress_frame;
1890 srv->on_tally_change = config->on_tally_change;
1891 srv->user_ctx = config->user_ctx;
1892 srv->width = 1920;
1893 srv->height = 1080;
1894 srv->seq_num = 1;
1895  
1896 if (config->stream_name && config->stream_name[0]) {
1897 snprintf(srv->stream_name, sizeof(srv->stream_name), "%s", config->stream_name);
1898 } else {
1899 snprintf(srv->stream_name, sizeof(srv->stream_name), "OpenAVX");
1900 }
1901  
1902 avx_mutex_init(&srv->lock);
1903 for (int i = 0; i < AVX_WEB_MAX_CLIENTS; ++i) {
1904 srv->clients[i].fd = AVX_INVALID_SOCKET;
1905 }
1906  
1907 /* Allocate scratch buffers */
1908 srv->avcc_cap = 2 * 1024 * 1024; /* 2MB default */
1909 srv->avcc_buf = (uint8_t*)malloc(srv->avcc_cap);
1910 srv->frag_cap = srv->avcc_cap + 4096;
1911 srv->frag_buf = (uint8_t*)malloc(srv->frag_cap);
1912  
1913 if (!srv->avcc_buf || !srv->frag_buf) {
1914 avx_web_server_destroy(srv);
1915 return NULL;
1916 }
1917  
1918 /* Create TCP socket */
1919 srv->listen_fd = socket(AF_INET, SOCK_STREAM, 0);
1920 if (!avx_socket_is_valid(srv->listen_fd)) {
1921 avx_web_server_destroy(srv);
1922 return NULL;
1923 }
1924  
1925 int opt = 1;
1926 setsockopt(srv->listen_fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
1927 #ifdef SO_REUSEPORT
1928 setsockopt(srv->listen_fd, SOL_SOCKET, SO_REUSEPORT, (const char*)&opt, sizeof(opt));
1929 #endif
1930  
1931 struct sockaddr_in sin;
1932 memset(&sin, 0, sizeof(sin));
1933 sin.sin_family = AF_INET;
1934 sin.sin_addr.s_addr = htonl(INADDR_ANY);
1935 sin.sin_port = htons(srv->port);
1936  
1937 if (bind(srv->listen_fd, (struct sockaddr*)&sin, sizeof(sin)) != 0) {
1938 avx_web_server_destroy(srv);
1939 return NULL;
1940 }
1941  
1942 if (srv->port == 0) {
1943 socklen_t sl = sizeof(sin);
1944 if (getsockname(srv->listen_fd, (struct sockaddr*)&sin, &sl) == 0) {
1945 srv->port = ntohs(sin.sin_port);
1946 }
1947 }
1948  
1949 if (listen(srv->listen_fd, 16) != 0) {
1950 avx_web_server_destroy(srv);
1951 return NULL;
1952 }
1953  
1954 avx_socket_set_nonblocking(srv->listen_fd, true);
1955  
1956 srv->running = true;
1957 if (avx_thread_create(&srv->thread, avx_web_server_worker, srv) != 0) {
1958 srv->running = false;
1959 avx_web_server_destroy(srv);
1960 return NULL;
1961 }
1962  
1963 return srv;
1964 }
1965  
1966 OPENAVX_API void avx_web_server_destroy(avx_web_server_t *server) {
1967 if (!server) return;
1968  
1969 server->running = false;
1970 if (avx_socket_is_valid(server->listen_fd)) {
1971 avx_socket_close(server->listen_fd);
1972 server->listen_fd = AVX_INVALID_SOCKET;
1973 }
1974  
1975 if (server->thread) {
1976 avx_thread_join(server->thread);
1977 server->thread = 0;
1978 }
1979  
1980 avx_mutex_lock(&server->lock);
1981 for (int i = 0; i < AVX_WEB_MAX_CLIENTS; ++i) {
1982 close_client_locked(&server->clients[i]);
1983 }
1984 free(server->sps);
1985 free(server->pps);
1986 free(server->vps);
1987 free(server->avcc_buf);
1988 free(server->frag_buf);
1989 server->sps = NULL;
1990 server->pps = NULL;
1991 server->vps = NULL;
1992 server->avcc_buf = NULL;
1993 server->frag_buf = NULL;
1994 avx_mutex_unlock(&server->lock);
1995  
1996 avx_mutex_destroy(&server->lock);
1997 free(server);
1998 }
1999  
2000 OPENAVX_API uint16_t avx_web_server_get_port(const avx_web_server_t *server) {
2001 return server ? server->port : 0;
2002 }
2003  
2004 OPENAVX_API int avx_web_server_get_client_count(const avx_web_server_t *server) {
2005 if (!server) return 0;
2006 avx_web_server_t *srv = (avx_web_server_t*)server;
2007 avx_mutex_lock(&srv->lock);
2008 int count = 0;
2009 for (int i = 0; i < AVX_WEB_MAX_CLIENTS; ++i) {
2010 if (srv->clients[i].active && srv->clients[i].streaming) count++;
2011 }
2012 avx_mutex_unlock(&srv->lock);
2013 return count;
2014 }
2015  
2016 OPENAVX_API void avx_web_server_set_ingress_callback(
2017 avx_web_server_t *server,
2018 avx_web_ingress_frame_cb cb,
2019 void *user_ctx
2020 ) {
2021 if (!server) return;
2022 avx_mutex_lock(&server->lock);
2023 server->on_ingress_frame = cb;
2024 server->user_ctx = user_ctx;
2025 avx_mutex_unlock(&server->lock);
2026 }
2027  
2028 OPENAVX_API void avx_web_server_broadcast_tally(avx_web_server_t *server, const oavx_tally_t *tally) {
2029 if (!server) return;
2030 avx_mutex_lock(&server->lock);
2031 broadcast_tally_locked(server, tally);
2032 avx_mutex_unlock(&server->lock);
2033 }
2034  
2035 /* Packages incoming video frame into fMP4 fragment and broadcasts to active HTTP/WS clients. */
2036 OPENAVX_API bool avx_web_server_feed_frame(
2037 avx_web_server_t *server,
2038 const uint8_t *frame_data,
2039 size_t frame_size,
2040 uint64_t pts_ns,
2041 bool is_keyframe
2042 ) {
2043 if (!server || !frame_data || frame_size == 0) return false;
2044  
2045 avx_mutex_lock(&server->lock);
2046  
2047 /* 1. Extract NALUs from Annex-B bitstream */
2048 typedef struct {
2049 const uint8_t *ptr;
2050 size_t len;
2051 } nalu_entry_t;
2052 nalu_entry_t nalus[128];
2053 size_t num_nalus = 0;
2054  
2055 size_t pos = 0;
2056 while (pos + 3 <= frame_size && num_nalus < 128) {
2057 size_t sc_len = 0;
2058 if (frame_data[pos] == 0 && frame_data[pos+1] == 0) {
2059 if (frame_data[pos+2] == 1) sc_len = 3;
2060 else if (pos + 4 <= frame_size && frame_data[pos+2] == 0 && frame_data[pos+3] == 1) sc_len = 4;
2061 }
2062  
2063 if (sc_len > 0) {
2064 size_t nalu_start = pos + sc_len;
2065 size_t next_pos = nalu_start;
2066 while (next_pos + 3 <= frame_size) {
2067 if (frame_data[next_pos] == 0 && frame_data[next_pos+1] == 0 &&
2068 (frame_data[next_pos+2] == 1 || (next_pos + 4 <= frame_size && frame_data[next_pos+2] == 0 && frame_data[next_pos+3] == 1))) {
2069 break;
2070 }
2071 next_pos++;
2072 }
2073 if (next_pos + 3 > frame_size) next_pos = frame_size;
2074  
2075 size_t nalu_len = next_pos - nalu_start;
2076 if (nalu_len > 0) {
2077 nalus[num_nalus].ptr = frame_data + nalu_start;
2078 nalus[num_nalus].len = nalu_len;
2079 num_nalus++;
2080 }
2081 pos = next_pos;
2082 } else {
2083 pos++;
2084 }
2085 }
2086  
2087 if (num_nalus == 0) {
2088 nalus[0].ptr = frame_data;
2089 nalus[0].len = frame_size;
2090 num_nalus = 1;
2091 }
2092  
2093 /* 2. Inspect NALUs for Parameter Sets & Keyframe Slices */
2094 bool params_updated = false;
2095  
2096 for (size_t i = 0; i < num_nalus; ++i) {
2097 const uint8_t *np = nalus[i].ptr;
2098 size_t nl = nalus[i].len;
2099 if (nl == 0) continue;
2100  
2101 if (server->codec == AVX_RTSP_CODEC_H264) {
2102 uint8_t type = np[0] & 0x1F;
2103 if (type == 7) { /* SPS */
2104 free(server->sps);
2105 server->sps = (uint8_t*)malloc(nl);
2106 if (server->sps) {
2107 memcpy(server->sps, np, nl);
2108 server->sps_len = nl;
2109 int w = 0, h = 0, prof = 0, lvl = 0;
2110 if (avx_rtsp_parse_sps_h264(server->sps, server->sps_len, &w, &h, &prof, &lvl)) {
2111 server->width = (uint32_t)w;
2112 server->height = (uint32_t)h;
2113 server->profile = (uint8_t)prof;
2114 server->level = (uint8_t)lvl;
2115 }
2116 params_updated = true;
2117 }
2118 } else if (type == 8) { /* PPS */
2119 free(server->pps);
2120 server->pps = (uint8_t*)malloc(nl);
2121 if (server->pps) {
2122 memcpy(server->pps, np, nl);
2123 server->pps_len = nl;
2124 params_updated = true;
2125 }
2126 } else if (avx_rtsp_is_keyframe(AVX_RTSP_CODEC_H264, np, nl)) {
2127 is_keyframe = true;
2128 }
2129 } else if (server->codec == AVX_RTSP_CODEC_HEVC) {
2130 uint8_t type = (np[0] >> 1) & 0x3F;
2131 if (type == 32) { /* VPS */
2132 free(server->vps);
2133 server->vps = (uint8_t*)malloc(nl);
2134 if (server->vps) {
2135 memcpy(server->vps, np, nl);
2136 server->vps_len = nl;
2137 params_updated = true;
2138 }
2139 } else if (type == 33) { /* SPS */
2140 free(server->sps);
2141 server->sps = (uint8_t*)malloc(nl);
2142 if (server->sps) {
2143 memcpy(server->sps, np, nl);
2144 server->sps_len = nl;
2145 int w = 0, h = 0, prof = 0, lvl = 0;
2146 if (avx_rtsp_parse_sps_hevc(server->sps, server->sps_len, &w, &h, &prof, &lvl)) {
2147 server->width = (uint32_t)w;
2148 server->height = (uint32_t)h;
2149 server->profile = (uint8_t)prof;
2150 server->level = (uint8_t)lvl;
2151 }
2152 params_updated = true;
2153 }
2154 } else if (type == 34) { /* PPS */
2155 free(server->pps);
2156 server->pps = (uint8_t*)malloc(nl);
2157 if (server->pps) {
2158 memcpy(server->pps, np, nl);
2159 server->pps_len = nl;
2160 params_updated = true;
2161 }
2162 } else if (avx_rtsp_is_keyframe(AVX_RTSP_CODEC_HEVC, np, nl)) { /* IDR / BLA / CRA */
2163 is_keyframe = true;
2164 }
2165 } else if (server->codec == AVX_RTSP_CODEC_AV1) {
2166 uint8_t type = (np[0] >> 3) & 0x0F;
2167 if (type == 1) { /* Sequence Header */
2168 free(server->sps);
2169 server->sps = (uint8_t*)malloc(nl);
2170 if (server->sps) {
2171 memcpy(server->sps, np, nl);
2172 server->sps_len = nl;
2173 params_updated = true;
2174 }
2175 }
2176 if (!is_keyframe && avx_rtsp_is_keyframe(AVX_RTSP_CODEC_AV1, np, nl)) {
2177 is_keyframe = true;
2178 }
2179 }
2180 }
2181  
2182 /* Update Init Segment if parameter sets changed */
2183 if (params_updated || server->init_segment_len == 0) {
2184 server->init_segment_len = avx_fmp4_generate_init_segment(
2185 server->codec,
2186 server->width,
2187 server->height,
2188 server->sps,
2189 server->sps_len,
2190 server->pps,
2191 server->pps_len,
2192 server->vps,
2193 server->vps_len,
2194 server->init_segment,
2195 sizeof(server->init_segment)
2196 );
2197 }
2198  
2199 /* 3. Check if any streaming clients are active */
2200 bool has_streaming_clients = false;
2201 for (int i = 0; i < AVX_WEB_MAX_CLIENTS; ++i) {
2202 if (server->clients[i].active && server->clients[i].streaming) {
2203 has_streaming_clients = true;
2204 break;
2205 }
2206 }
2207 if (!has_streaming_clients) {
2208 avx_mutex_unlock(&server->lock);
2209 return true;
2210 }
2211  
2212 /* 4. Convert NALUs to AVCC format in scratch buffer */
2213 size_t total_avcc_len = 0;
2214 for (size_t i = 0; i < num_nalus; ++i) {
2215 total_avcc_len += 4 + nalus[i].len;
2216 }
2217  
2218 if (total_avcc_len > server->avcc_cap) {
2219 server->avcc_cap = total_avcc_len + (256 * 1024);
2220 uint8_t *nb = (uint8_t*)realloc(server->avcc_buf, server->avcc_cap);
2221 if (!nb) {
2222 avx_mutex_unlock(&server->lock);
2223 return false;
2224 }
2225 server->avcc_buf = nb;
2226 }
2227  
2228 uint8_t *ap = server->avcc_buf;
2229 for (size_t i = 0; i < num_nalus; ++i) {
2230 avx_put_u32(&ap, (uint32_t)nalus[i].len);
2231 memcpy(ap, nalus[i].ptr, nalus[i].len);
2232 ap += nalus[i].len;
2233 }
2234  
2235 /* 5. Compute Timestamps */
2236 uint64_t pts_90k;
2237 if (pts_ns > 0) {
2238 pts_90k = (pts_ns * 9) / 100000ULL;
2239 } else {
2240 pts_90k = server->last_pts_90k + 1500;
2241 }
2242 server->last_pts_90k = pts_90k;
2243  
2244 /* 6. Generate fMP4 Media Fragment (moof + mdat) */
2245 size_t needed_frag_cap = total_avcc_len + 256;
2246 if (needed_frag_cap > server->frag_cap) {
2247 server->frag_cap = needed_frag_cap + (256 * 1024);
2248 uint8_t *fb = (uint8_t*)realloc(server->frag_buf, server->frag_cap);
2249 if (!fb) {
2250 avx_mutex_unlock(&server->lock);
2251 return false;
2252 }
2253 server->frag_buf = fb;
2254 }
2255  
2256 size_t frag_len = avx_fmp4_generate_media_fragment(
2257 server->seq_num++,
2258 pts_90k,
2259 1500, /* 60fps duration @ 90kHz */
2260 is_keyframe,
2261 server->avcc_buf,
2262 total_avcc_len,
2263 server->frag_buf,
2264 server->frag_cap
2265 );
2266  
2267 if (frag_len == 0) {
2268 avx_mutex_unlock(&server->lock);
2269 return false;
2270 }
2271  
2272 /* 7. Fan-out Fragment to all Streaming Clients */
2273 for (int i = 0; i < AVX_WEB_MAX_CLIENTS; ++i) {
2274 avx_web_client_t *c = &server->clients[i];
2275 if (!c->active || !c->streaming) continue;
2276  
2277 if (!c->received_keyframe) {
2278 if (is_keyframe) {
2279 /* Client's first keyframe: send init segment first, then fragment */
2280 if (server->init_segment_len > 0) {
2281 send(c->fd, (const char*)server->init_segment, server->init_segment_len, MSG_NOSIGNAL);
2282 }
2283 c->received_keyframe = true;
2284 } else {
2285 /* Skip non-keyframe while waiting for initial IDR */
2286 continue;
2287 }
2288 }
2289  
2290 /* Non-blocking push */
2291 #ifdef MSG_DONTWAIT
2292 const int send_flags = MSG_NOSIGNAL | MSG_DONTWAIT;
2293 #else
2294 const int send_flags = MSG_NOSIGNAL;
2295 #endif
2296 ssize_t sent = send(c->fd, (const char*)server->frag_buf, frag_len, send_flags);
2297 if (sent < 0) {
2298 int err = avx_socket_errno();
2299 #if defined(AVX_OS_WINDOWS) || defined(_WIN32)
2300 if (err == WSAEWOULDBLOCK) {
2301 continue;
2302 } else if (err == WSAECONNRESET || err == WSAESHUTDOWN || err == WSAECONNABORTED || err == WSAENOTCONN || err == WSAEINTR) {
2303 close_client_locked(c);
2304 }
2305 #else
2306 if (err == EAGAIN || err == EWOULDBLOCK) {
2307 continue;
2308 } else if (err == EPIPE || err == ECONNRESET) {
2309 close_client_locked(c);
2310 }
2311 #endif
2312 }
2313 }
2314  
2315 avx_mutex_unlock(&server->lock);
2316 return true;
2317 }