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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Cakra CCTV — viewer</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
      integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY="
      crossorigin=""/>
<style>
  :root { color-scheme: dark; }
  body { margin: 0; background:#0a0a0a; color:#e5e5e5;
         font: 13px/1.4 ui-monospace, Menlo, Consolas, monospace; }
  header { padding: 10px 14px; border-bottom: 1px solid #222;
           display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
  header input, header select { background:#111; color:#eee; border:1px solid #333;
                                padding: 6px 10px; border-radius: 4px; }
  header input { width: 320px; }
  header button { background:#1a1a1a; color:#eee; border:1px solid #333;
                  padding: 6px 12px; border-radius: 4px; cursor: pointer; }
  header button:hover { border-color:#555; }
  main { display: grid; grid-template-columns: 1fr 340px; gap: 14px;
         padding: 14px; height: calc(100vh - 60px); box-sizing: border-box; }
  .stage { position: relative; background:#000; border-radius: 6px;
           overflow: hidden; min-height: 0; display:flex;
           align-items:center; justify-content:center; }
  .stage video { width:100%; height:100%; object-fit:contain; display:block; }
  .panel { background:#111; border:1px solid #1f1f1f; border-radius:6px;
           padding: 12px; overflow:auto; }
  .row { display:flex; justify-content: space-between; padding: 3px 0; }
  .row span:first-child { color:#888; }
  .badge { display:inline-block; padding:1px 8px; border-radius:3px;
           font-weight:600; color:#000; font-size:11px; }
  .b-SMOOTH, .b-NORMAL { background:#34c759; }
  .b-MODERATE, .b-BUSY { background:#ffcc00; }
  .b-HEAVY, .b-OVERCROWDED { background:#ff3b30; color:#fff; }
  h3 { margin: 14px 0 6px; font-size: 12px; color:#8a8a8a;
       letter-spacing: .05em; text-transform: uppercase; }
  table { width:100%; border-collapse: collapse; }
  td { padding: 3px 6px; border-bottom: 1px solid #1d1d1d; }
  td:first-child { color:#888; }
  .pill { background:#222; padding: 1px 6px; border-radius:3px; }
  .status-on { color:#34c759; } .status-off { color:#ff3b30; }
  #map { height: 260px; border-radius: 4px; background: #0a0a0a;
         border: 1px solid #1d1d1d; }
  .leaflet-container { background: #0a0a0a; }
  .leaflet-tooltip { background:#111; color:#eee; border:1px solid #333;
                     font: 11px ui-monospace, monospace; }
</style>
</head>
<body>
<header>
  <strong>Cakra CCTV viewer</strong>
  <input id="base" placeholder="http://localhost:8000" value="http://localhost:8000" />
  <input id="camid" placeholder="camera_id" />
  <select id="prebuffer" title="Pre-load this many seconds before video starts playing (YouTube-style). Higher = smoother but more delay.">
    <option value="0">no pre-buffer (live edge)</option>
    <option value="3">pre-buffer: 3s</option>
    <option value="5" selected>pre-buffer: 5s</option>
    <option value="8">pre-buffer: 8s</option>
  </select>
  <button id="go">Connect &amp; play</button>
  <span id="connstate" class="status-off">disconnected</span>
</header>

<main>
  <div class="stage">
    <video id="v" autoplay muted playsinline></video>
  </div>
  <aside class="panel">
    <div class="row"><span>camera_id</span><span id="cid">—</span></div>
    <div class="row"><span>name</span><span id="name">—</span></div>
    <div class="row"><span>connected</span><span id="rconn">—</span></div>
    <div class="row"><span>cap fps</span><span id="capfps">—</span></div>
    <div class="row"><span>proc fps</span><span id="procfps">—</span></div>
    <div class="row"><span>enc fps</span><span id="encfps">—</span></div>

    <h3>now</h3>
    <div class="row"><span>vehicles</span><span id="veh">0</span></div>
    <div class="row"><span>people</span><span id="ppl">0</span></div>
    <div class="row"><span>traffic</span><span><em class="badge" id="ts">—</em></span></div>
    <div class="row"><span>crowd</span><span><em class="badge" id="cs">—</em></span></div>

    <h3>session (since first connect)</h3>
    <div class="row"><span>started at</span><span id="sStart">—</span></div>
    <div class="row"><span>duration</span><span id="sDur">—</span></div>
    <div class="row"><span>samples</span><span id="sCount">0</span></div>
    <div class="row"><span>avg vehicles</span><span id="sAvgV">0</span></div>
    <div class="row"><span>avg people</span><span id="sAvgP">0</span></div>
    <div class="row"><span>max vehicles</span><span id="sMaxV">0</span></div>
    <div class="row"><span>max people</span><span id="sMaxP">0</span></div>

    <h3>geo</h3>
    <div class="row"><span>cam lat/lng</span><span id="camLL">—</span></div>
    <div class="row"><span>coverage</span><span id="camCov">—</span></div>
    <div id="map"></div>

    <h3>detections (with geo)</h3>
    <table><tbody id="dets"><tr><td colspan="5" style="color:#666;">waiting…</td></tr></tbody></table>

    <h3>raw ws</h3>
    <div id="raw" style="white-space:pre-wrap; color:#666; max-height:180px; overflow:auto; background:#0a0a0a; padding:6px; border:1px solid #1d1d1d; border-radius:4px;">—</div>
  </aside>
</main>

<script src="https://cdn.jsdelivr.net/npm/hls.js@1.5.13/dist/hls.min.js"></script>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
        integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo="
        crossorigin=""></script>
<script>
const $ = (id) => document.getElementById(id);
const v = $("v");

let hls = null, ws = null;

// Leaflet state — initialised lazily on the first WS message that
// carries camera lat/lng. Detections redraw on every tick.
let leafletMap = null, camMarker = null, polyLayer = null, detLayer = null;
const COLORS = {
  car: "#34c759", motorcycle: "#5ac8fa", bus: "#ff9500",
  truck: "#ffcc00", person: "#ff3b30", van: "#af52de",
  scooter: "#5ac8fa", bicycle: "#5ac8fa",
};

function setBadge(el, status){
  el.textContent = status || "—";
  el.className = "badge b-" + (status||"").replace(/[^A-Z]/g,"");
}

function awaitPrebuffer(videoEl, minSec) {
  // YouTube-style preload: keep the video paused until we have at least
  // `minSec` of content buffered ahead of the current play head. While
  // we wait, surface a countdown in the status pill so the user knows
  // why nothing is moving yet.
  videoEl.pause();
  if (minSec <= 0) {
    videoEl.play().catch(() => {});
    return;
  }
  $("connstate").textContent = `buffering 0.0 / ${minSec.toFixed(1)}s…`;
  $("connstate").className = "status-off";
  let attempts = 0;
  const check = () => {
    attempts++;
    if (!videoEl.buffered.length) {
      if (attempts > 100) {  // ~20s with no buffer = give up, just play
        videoEl.play().catch(() => {});
        return;
      }
      return setTimeout(check, 200);
    }
    const ahead = videoEl.buffered.end(videoEl.buffered.length - 1) - videoEl.currentTime;
    $("connstate").textContent = `buffering ${ahead.toFixed(1)} / ${minSec.toFixed(1)}s…`;
    if (ahead >= minSec) {
      videoEl.play().catch(() => {});
      $("connstate").textContent = "playing";
      $("connstate").className = "status-on";
    } else {
      setTimeout(check, 200);
    }
  };
  setTimeout(check, 300);  // let hls.js attach + start fetching first
}

function ensureMap(lat, lng) {
  if (leafletMap) return;
  leafletMap = L.map("map", {
    zoomControl: true,
    attributionControl: false,
  }).setView([lat, lng], 18);
  // CartoCDN dark tiles to match the viewer theme. Falls back to OSM
  // light tiles if the CDN is reachable but the layer fails.
  L.tileLayer("https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png", {
    maxZoom: 19,
    subdomains: "abcd",
  }).addTo(leafletMap);
  detLayer = L.layerGroup().addTo(leafletMap);
}

function updateMap(camera, dets) {
  if (!camera || camera.lat == null || camera.lng == null) return;
  ensureMap(camera.lat, camera.lng);

  if (!camMarker) {
    camMarker = L.circleMarker([camera.lat, camera.lng], {
      radius: 6, color: "#ff3b30", weight: 2, fillOpacity: 1,
    }).bindTooltip("camera", { permanent: false }).addTo(leafletMap);
  }

  if (polyLayer) leafletMap.removeLayer(polyLayer);
  if (camera.coverage_polygon && camera.coverage_polygon.length) {
    polyLayer = L.polygon(camera.coverage_polygon, {
      color: "#ffcc00", weight: 1, fillOpacity: 0.12,
    }).addTo(leafletMap);
    // Auto-fit to the wedge once we have it.
    if (!leafletMap._fittedCoverage) {
      leafletMap.fitBounds(polyLayer.getBounds(), { padding: [10, 10] });
      leafletMap._fittedCoverage = true;
    }
  }

  detLayer.clearLayers();
  for (const d of dets) {
    if (!d?.geo) continue;
    const color = COLORS[d.class] || "#9af";
    const conf = Math.max(0.15, Math.min(1, d.geo.confidence || 0.3));
    L.circleMarker([d.geo.lat, d.geo.lng], {
      radius: 5,
      color: color,
      fillColor: color,
      fillOpacity: conf,
      weight: 1,
    }).bindTooltip(
      `#${d.id ?? "?"} ${d.class} • ${(d.conf*100|0)}%<br>` +
      `geo conf ${(conf*100|0)}% • ${d.geo.distance_m}m`,
    ).addTo(detLayer);
  }
}

function fmtDuration(sec) {
  if (!sec || sec < 1) return "—";
  const d = Math.floor(sec / 86400);
  const h = Math.floor((sec % 86400) / 3600);
  const m = Math.floor((sec % 3600) / 60);
  const s = Math.floor(sec % 60);
  const parts = [];
  if (d) parts.push(d + "d");
  if (h) parts.push(h + "h");
  if (m) parts.push(m + "m");
  parts.push(s + "s");
  return parts.join(" ");
}

async function connect() {
  const base = $("base").value.trim().replace(/\/$/, "");
  const id = $("camid").value.trim();
  if (!id) { alert("camera_id wajib diisi"); return; }

  if (hls) { try { hls.destroy(); } catch(e){} hls = null; }
  if (ws)  { try { ws.close(); } catch(e){} ws = null; }
  v.srcObject = null; v.src = "";
  // Reset map so a new cam re-centres + re-fits the coverage wedge.
  if (leafletMap) {
    if (camMarker) { leafletMap.removeLayer(camMarker); camMarker = null; }
    if (polyLayer) { leafletMap.removeLayer(polyLayer); polyLayer = null; }
    if (detLayer) detLayer.clearLayers();
    leafletMap._fittedCoverage = false;
  }

  $("connstate").textContent = "activating…";
  $("connstate").className = "status-off";
  try {
    const r = await fetch(`${base}/api/v1/cameras/${id}/connect`, { method: "POST" });
    if (!r.ok) {
      const body = await r.json().catch(() => ({}));
      $("connstate").textContent = `activate failed: ${body?.error?.message || r.status}`;
      return;
    }
  } catch (e) {
    $("connstate").textContent = `network error: ${e.message}`;
    return;
  }

  // Video: HLS with bboxes baked into the encoded stream by the server.
  const m3u8 = `${base}/api/v1/cameras/${id}/hls/playlist.m3u8`;
  const prebufferSec = parseFloat($("prebuffer").value) || 0;

  // hls.js first — it actually works in Chrome/Firefox/Edge/Safari-MSE.
  // Chromium misreports `canPlayType("application/vnd.apple.mpegurl")` as
  // "maybe" but has no native HLS demuxer, so checking that first dumps
  // us into a broken native-play branch with DEMUXER_ERROR_COULD_NOT_PARSE.
  // Native HLS is the iOS-only fallback (no MSE → hls.js can't run).
  if (window.Hls && Hls.isSupported()) {
    hls = new Hls({
      enableWorker: true,
      lowLatencyMode: false,
      // We do our own start positioning via LEVEL_LOADED below, so
      // tell hls.js to start at the very beginning of available content
      // and never auto-sync forward while we're paused.
      liveSyncDurationCount: 999,
      liveMaxLatencyDurationCount: 1000,
      // Allow plenty of forward buffer so the browser keeps fetching
      // segments ahead of currentTime while paused.
      maxBufferLength: 60,
      maxMaxBufferLength: 120,
      backBufferLength: 0,
      liveDurationInfinity: true,
      // ffmpeg needs ~2s warmup before the first segment; retry on 503.
      manifestLoadingMaxRetry: 8,
      manifestLoadingRetryDelay: 500,
      manifestLoadingMaxRetryTimeout: 8000,
      levelLoadingMaxRetry: 8,
      levelLoadingRetryDelay: 500,
      fragLoadingMaxRetry: 4,
      fragLoadingRetryDelay: 500,
    });
    hls.loadSource(m3u8); hls.attachMedia(v);

    // The right way to pre-buffer a live stream: on the first playlist
    // load, anchor currentTime at the OLDEST available fragment, pause,
    // and let the browser fetch segments ahead. As segments append,
    // `buffered.end - currentTime` grows; once it exceeds `prebufferSec`
    // we hit play. Without this, hls.js silently re-syncs currentTime
    // to follow the live edge and the prebuffer never grows.
    let anchored = false;
    hls.on(Hls.Events.LEVEL_LOADED, (_evt, data) => {
      if (anchored) return;
      const frags = data?.details?.fragments;
      if (!frags || !frags.length) return;
      anchored = true;
      const oldest = frags[0];
      try { v.currentTime = oldest.start; } catch (e) {}
      awaitPrebuffer(v, prebufferSec);
    });

    // Safety net: if drift exceeds prebuffer + 30s (browser fell way
    // behind live), snap forward.
    hls.on(Hls.Events.LEVEL_UPDATED, () => {
      if (!v.buffered.length || v.paused) return;
      const end = v.buffered.end(v.buffered.length - 1);
      if (end - v.currentTime > prebufferSec + 30) {
        v.currentTime = end - prebufferSec;
      }
    });
  } else if (v.canPlayType("application/vnd.apple.mpegurl")) {
    // iOS fallback (no MSE → hls.js unsupported). Safari plays HLS
    // natively from the URL; we still gate playback on prebuffer.
    v.preload = "auto";
    v.src = m3u8;
    awaitPrebuffer(v, prebufferSec);
  } else { alert("Browser ga support HLS"); }

  // Mid-play stall → switch state to "buffering"; recover → "playing".
  v.addEventListener("waiting", () => {
    if ($("connstate").textContent !== "buffering") return;  // already shown
    $("connstate").textContent = "re-buffering…";
    $("connstate").className = "status-off";
  });
  v.addEventListener("playing", () => {
    $("connstate").textContent = "playing";
    $("connstate").className = "status-on";
  });

  // Realtime metrics + geo-tagged detections.
  const wsURL = `${base.replace(/^http/,"ws")}/api/v1/cameras/${id}/metrics/ws`;
  ws = new WebSocket(wsURL);
  // Don't touch connstate on ws.open — video buffer/play state owns it.
  ws.onclose = (e) => {
    if (v.paused && !v.ended) {
      $("connstate").textContent = `ws closed (${e.code} ${e.reason||""})`;
      $("connstate").className = "status-off";
    }
  };
  ws.onerror = () => {
    if (v.paused && !v.ended) {
      $("connstate").textContent = "ws error";
      $("connstate").className = "status-off";
    }
  };
  ws.onmessage = (e) => {
    const msg = JSON.parse(e.data);
    if (msg.error) { $("connstate").textContent = `${msg.error.code}: ${msg.error.message}`; return; }
    onMessage(msg);
  };
}

function onMessage(msg) {
  $("raw").textContent = JSON.stringify(msg, null, 2);
  $("cid").textContent = msg.camera_id;
  $("name").textContent = msg.location || "";
  $("rconn").innerHTML = msg.connected
    ? '<span class="status-on">true</span>'
    : '<span class="status-off">false</span>';
  $("capfps").textContent = msg.fps_capture?.toFixed?.(1) ?? msg.fps_capture;
  $("procfps").textContent = msg.fps_process?.toFixed?.(1) ?? msg.fps_process;
  $("encfps").textContent = msg.fps_encoder?.toFixed?.(1) ?? "—";
  $("veh").textContent = msg.vehicle_count;
  $("ppl").textContent = msg.person_count;
  setBadge($("ts"), msg.traffic_status);
  setBadge($("cs"), msg.crowd_status);

  // Session aggregates.
  const s = msg.session || {};
  $("sStart").textContent = s.started_at ? new Date(s.started_at).toLocaleString() : "—";
  $("sDur").textContent = fmtDuration(s.duration_seconds);
  $("sCount").textContent = s.samples_count ?? 0;
  $("sAvgV").textContent = (s.avg_vehicles ?? 0).toFixed(2);
  $("sAvgP").textContent = (s.avg_people ?? 0).toFixed(2);
  $("sMaxV").textContent = s.max_vehicles ?? 0;
  $("sMaxP").textContent = s.max_people ?? 0;

  // Geo.
  const cam = msg.camera || {};
  $("camLL").textContent = (cam.lat != null && cam.lng != null)
    ? `${cam.lat.toFixed(5)}, ${cam.lng.toFixed(5)}` : "—";
  $("camCov").textContent = cam.coverage_polygon
    ? `${cam.coverage_polygon.length} pts (${cam.fov_deg}° @ ${cam.max_distance_m}m)`
    : "—";

  // Map: camera marker + coverage polygon + per-detection dots.
  updateMap(cam, msg.detections || []);

  // Detection table with geo.
  const dets = msg.detections || [];
  const tb = $("dets");
  if (!dets.length) {
    tb.innerHTML = '<tr><td colspan="5" style="color:#666;">none</td></tr>';
  } else {
    tb.innerHTML = dets.map(d => {
      const ll = d.geo
        ? `${d.geo.lat.toFixed(5)}, ${d.geo.lng.toFixed(5)}`
        : "—";
      const dist = d.geo ? `${d.geo.distance_m}m` : "—";
      return `<tr>
        <td>#${d.id ?? "?"}</td>
        <td class="pill">${d.class}</td>
        <td>${(d.conf*100|0)}%</td>
        <td style="color:#888;">${ll}</td>
        <td style="color:#666;">${dist}</td>
      </tr>`;
    }).join("");
  }
}

$("go").addEventListener("click", connect);
$("camid").addEventListener("keydown", e => { if (e.key === "Enter") connect(); });
const qp = new URLSearchParams(location.search);
if (qp.get("base")) $("base").value = qp.get("base");
if (qp.get("camera_id")) { $("camid").value = qp.get("camera_id"); connect(); }
</script>
</body>
</html>