@camstack/lib-pipeline-analysis 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,1279 @@
1
+ // src/zones/geometry.ts
2
+ function pointInPolygon(point, polygon) {
3
+ if (polygon.length < 3) return false;
4
+ let inside = false;
5
+ const { x, y } = point;
6
+ const n = polygon.length;
7
+ for (let i = 0, j = n - 1; i < n; j = i++) {
8
+ const xi = polygon[i].x;
9
+ const yi = polygon[i].y;
10
+ const xj = polygon[j].x;
11
+ const yj = polygon[j].y;
12
+ const intersect = yi > y !== yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi;
13
+ if (intersect) inside = !inside;
14
+ }
15
+ return inside;
16
+ }
17
+ function lineIntersection(a, b) {
18
+ const dx1 = a.p2.x - a.p1.x;
19
+ const dy1 = a.p2.y - a.p1.y;
20
+ const dx2 = b.p2.x - b.p1.x;
21
+ const dy2 = b.p2.y - b.p1.y;
22
+ const denom = dx1 * dy2 - dy1 * dx2;
23
+ if (Math.abs(denom) < 1e-10) return null;
24
+ const dx3 = b.p1.x - a.p1.x;
25
+ const dy3 = b.p1.y - a.p1.y;
26
+ const t = (dx3 * dy2 - dy3 * dx2) / denom;
27
+ const u = (dx3 * dy1 - dy3 * dx1) / denom;
28
+ if (t < 0 || t > 1 || u < 0 || u > 1) return null;
29
+ return {
30
+ x: a.p1.x + t * dx1,
31
+ y: a.p1.y + t * dy1
32
+ };
33
+ }
34
+ function tripwireCrossing(prev, curr, tripwire) {
35
+ const movement = { p1: prev, p2: curr };
36
+ const intersection = lineIntersection(movement, tripwire);
37
+ if (intersection === null) return null;
38
+ const twDx = tripwire.p2.x - tripwire.p1.x;
39
+ const twDy = tripwire.p2.y - tripwire.p1.y;
40
+ const movDx = curr.x - prev.x;
41
+ const movDy = curr.y - prev.y;
42
+ const cross = twDx * movDy - twDy * movDx;
43
+ const direction = cross > 0 ? "left" : "right";
44
+ return { crossed: true, direction };
45
+ }
46
+ function bboxCentroid(bbox) {
47
+ return {
48
+ x: bbox.x + bbox.w / 2,
49
+ y: bbox.y + bbox.h / 2
50
+ };
51
+ }
52
+ function normalizeToPixel(point, imageWidth, imageHeight) {
53
+ return {
54
+ x: point.x * imageWidth,
55
+ y: point.y * imageHeight
56
+ };
57
+ }
58
+
59
+ // src/tracker/hungarian.ts
60
+ function greedyAssignment(costMatrix, threshold) {
61
+ const numTracks = costMatrix.length;
62
+ const numDetections = numTracks > 0 ? costMatrix[0]?.length ?? 0 : 0;
63
+ const candidates = [];
64
+ for (let t = 0; t < numTracks; t++) {
65
+ for (let d = 0; d < numDetections; d++) {
66
+ const iou2 = costMatrix[t][d] ?? 0;
67
+ if (iou2 >= threshold) {
68
+ candidates.push({ iou: iou2, trackIdx: t, detIdx: d });
69
+ }
70
+ }
71
+ }
72
+ candidates.sort((a, b) => b.iou - a.iou);
73
+ const assignedTracks = /* @__PURE__ */ new Set();
74
+ const assignedDets = /* @__PURE__ */ new Set();
75
+ const matches = [];
76
+ for (const { trackIdx, detIdx } of candidates) {
77
+ if (assignedTracks.has(trackIdx) || assignedDets.has(detIdx)) continue;
78
+ matches.push([trackIdx, detIdx]);
79
+ assignedTracks.add(trackIdx);
80
+ assignedDets.add(detIdx);
81
+ }
82
+ const unmatchedTracks = [];
83
+ for (let t = 0; t < numTracks; t++) {
84
+ if (!assignedTracks.has(t)) unmatchedTracks.push(t);
85
+ }
86
+ const unmatchedDetections = [];
87
+ for (let d = 0; d < numDetections; d++) {
88
+ if (!assignedDets.has(d)) unmatchedDetections.push(d);
89
+ }
90
+ return { matches, unmatchedTracks, unmatchedDetections };
91
+ }
92
+
93
+ // src/tracker/sort-tracker.ts
94
+ var MAX_PATH_LENGTH = 300;
95
+ function iou(a, b) {
96
+ const ax1 = a.x;
97
+ const ay1 = a.y;
98
+ const ax2 = a.x + a.w;
99
+ const ay2 = a.y + a.h;
100
+ const bx1 = b.x;
101
+ const by1 = b.y;
102
+ const bx2 = b.x + b.w;
103
+ const by2 = b.y + b.h;
104
+ const interX1 = Math.max(ax1, bx1);
105
+ const interY1 = Math.max(ay1, by1);
106
+ const interX2 = Math.min(ax2, bx2);
107
+ const interY2 = Math.min(ay2, by2);
108
+ const interW = Math.max(0, interX2 - interX1);
109
+ const interH = Math.max(0, interY2 - interY1);
110
+ const interArea = interW * interH;
111
+ if (interArea === 0) return 0;
112
+ const aArea = a.w * a.h;
113
+ const bArea = b.w * b.h;
114
+ const unionArea = aArea + bArea - interArea;
115
+ return unionArea <= 0 ? 0 : interArea / unionArea;
116
+ }
117
+ function trackToTrackedDetection(track) {
118
+ return {
119
+ class: track.class,
120
+ originalClass: track.originalClass,
121
+ score: track.score,
122
+ bbox: track.bbox,
123
+ landmarks: track.landmarks,
124
+ trackId: track.id,
125
+ trackAge: track.hits,
126
+ velocity: track.velocity,
127
+ path: track.path.slice()
128
+ };
129
+ }
130
+ function pushToRingBuffer(buffer, item, maxLength) {
131
+ if (buffer.length >= maxLength) {
132
+ buffer.shift();
133
+ }
134
+ buffer.push(item);
135
+ }
136
+ var DEFAULT_TRACKER_CONFIG = {
137
+ maxAge: 30,
138
+ minHits: 3,
139
+ iouThreshold: 0.3
140
+ };
141
+ var SortTracker = class {
142
+ tracks = [];
143
+ lostTracks = [];
144
+ nextTrackId = 1;
145
+ config;
146
+ constructor(config = {}) {
147
+ this.config = { ...DEFAULT_TRACKER_CONFIG, ...config };
148
+ }
149
+ update(detections, frameTimestamp) {
150
+ this.lostTracks = [];
151
+ if (this.tracks.length === 0) {
152
+ for (const det of detections) {
153
+ this.createTrack(det, frameTimestamp);
154
+ }
155
+ return this.getConfirmedTracks();
156
+ }
157
+ if (detections.length === 0) {
158
+ this.ageTracksAndPruneLost(frameTimestamp);
159
+ return this.getConfirmedTracks();
160
+ }
161
+ const costMatrix = this.tracks.map(
162
+ (track) => detections.map((det) => iou(track.bbox, det.bbox))
163
+ );
164
+ const { matches, unmatchedTracks, unmatchedDetections } = greedyAssignment(
165
+ costMatrix,
166
+ this.config.iouThreshold
167
+ );
168
+ for (const [trackIdx, detIdx] of matches) {
169
+ const track = this.tracks[trackIdx];
170
+ const det = detections[detIdx];
171
+ const prevCx = track.bbox.x + track.bbox.w / 2;
172
+ const prevCy = track.bbox.y + track.bbox.h / 2;
173
+ const newCx = det.bbox.x + det.bbox.w / 2;
174
+ const newCy = det.bbox.y + det.bbox.h / 2;
175
+ pushToRingBuffer(track.path, track.bbox, MAX_PATH_LENGTH);
176
+ track.bbox = det.bbox;
177
+ track.class = det.class;
178
+ track.originalClass = det.originalClass;
179
+ track.score = det.score;
180
+ track.landmarks = det.landmarks;
181
+ track.age = 0;
182
+ track.hits++;
183
+ track.lastSeen = frameTimestamp;
184
+ track.velocity = { dx: newCx - prevCx, dy: newCy - prevCy };
185
+ }
186
+ for (const trackIdx of unmatchedTracks) {
187
+ const track = this.tracks[trackIdx];
188
+ track.age++;
189
+ }
190
+ const survived = [];
191
+ for (const track of this.tracks) {
192
+ if (track.age > this.config.maxAge) {
193
+ track.lost = true;
194
+ this.lostTracks.push(track);
195
+ } else {
196
+ survived.push(track);
197
+ }
198
+ }
199
+ this.tracks = survived;
200
+ for (const detIdx of unmatchedDetections) {
201
+ const det = detections[detIdx];
202
+ this.createTrack(det, frameTimestamp);
203
+ }
204
+ return this.getConfirmedTracks();
205
+ }
206
+ getActiveTracks() {
207
+ return this.tracks.map(trackToTrackedDetection);
208
+ }
209
+ getLostTracks() {
210
+ return this.lostTracks.map(trackToTrackedDetection);
211
+ }
212
+ reset() {
213
+ this.tracks = [];
214
+ this.lostTracks = [];
215
+ this.nextTrackId = 1;
216
+ }
217
+ createTrack(det, timestamp) {
218
+ const track = {
219
+ id: String(this.nextTrackId++),
220
+ bbox: det.bbox,
221
+ class: det.class,
222
+ originalClass: det.originalClass,
223
+ score: det.score,
224
+ landmarks: det.landmarks,
225
+ age: 0,
226
+ hits: 1,
227
+ path: [],
228
+ firstSeen: timestamp,
229
+ lastSeen: timestamp,
230
+ velocity: { dx: 0, dy: 0 },
231
+ lost: false
232
+ };
233
+ this.tracks.push(track);
234
+ return track;
235
+ }
236
+ getConfirmedTracks() {
237
+ return this.tracks.filter((t) => t.hits >= this.config.minHits).map(trackToTrackedDetection);
238
+ }
239
+ ageTracksAndPruneLost(frameTimestamp) {
240
+ const survived = [];
241
+ for (const track of this.tracks) {
242
+ track.age++;
243
+ if (track.age > this.config.maxAge) {
244
+ track.lost = true;
245
+ this.lostTracks.push(track);
246
+ } else {
247
+ survived.push(track);
248
+ }
249
+ }
250
+ this.tracks = survived;
251
+ void frameTimestamp;
252
+ }
253
+ };
254
+
255
+ // src/state/state-analyzer.ts
256
+ var DEFAULT_STATE_ANALYZER_CONFIG = {
257
+ stationaryThresholdSec: 10,
258
+ loiteringThresholdSec: 60,
259
+ velocityThreshold: 2,
260
+ enteringFrames: 5
261
+ };
262
+ function magnitude(v) {
263
+ return Math.sqrt(v.dx * v.dx + v.dy * v.dy);
264
+ }
265
+ var StateAnalyzer = class {
266
+ states = /* @__PURE__ */ new Map();
267
+ config;
268
+ constructor(config = {}) {
269
+ this.config = { ...DEFAULT_STATE_ANALYZER_CONFIG, ...config };
270
+ }
271
+ analyze(tracks, timestamp) {
272
+ const results = [];
273
+ const activeIds = /* @__PURE__ */ new Set();
274
+ for (const track of tracks) {
275
+ activeIds.add(track.trackId);
276
+ const prev = this.states.get(track.trackId);
277
+ const centroid = {
278
+ x: track.bbox.x + track.bbox.w / 2,
279
+ y: track.bbox.y + track.bbox.h / 2
280
+ };
281
+ const speed = track.velocity ? magnitude(track.velocity) : 0;
282
+ let enteredAt;
283
+ let stationarySince;
284
+ let totalDistancePx;
285
+ if (!prev) {
286
+ enteredAt = timestamp;
287
+ stationarySince = speed <= this.config.velocityThreshold ? timestamp : void 0;
288
+ totalDistancePx = 0;
289
+ } else {
290
+ enteredAt = prev.enteredAt;
291
+ const dx = centroid.x - prev.lastPosition.x;
292
+ const dy = centroid.y - prev.lastPosition.y;
293
+ const dist = Math.sqrt(dx * dx + dy * dy);
294
+ totalDistancePx = prev.totalDistancePx + dist;
295
+ if (speed > this.config.velocityThreshold) {
296
+ stationarySince = void 0;
297
+ } else {
298
+ stationarySince = prev.stationarySince ?? timestamp;
299
+ }
300
+ }
301
+ const newInternal = {
302
+ enteredAt,
303
+ stationarySince,
304
+ totalDistancePx,
305
+ lastPosition: centroid
306
+ };
307
+ this.states.set(track.trackId, newInternal);
308
+ const dwellTimeMs = timestamp - enteredAt;
309
+ const state = this.computeObjectState(track.trackAge, speed, stationarySince, timestamp);
310
+ results.push({
311
+ trackId: track.trackId,
312
+ state,
313
+ stationarySince,
314
+ enteredAt,
315
+ totalDistancePx,
316
+ dwellTimeMs
317
+ });
318
+ }
319
+ for (const [id, internalState] of this.states) {
320
+ if (!activeIds.has(id)) {
321
+ results.push({
322
+ trackId: id,
323
+ state: "leaving",
324
+ stationarySince: internalState.stationarySince,
325
+ enteredAt: internalState.enteredAt,
326
+ totalDistancePx: internalState.totalDistancePx,
327
+ dwellTimeMs: timestamp - internalState.enteredAt
328
+ });
329
+ this.states.delete(id);
330
+ }
331
+ }
332
+ return results;
333
+ }
334
+ computeObjectState(trackAge, speed, stationarySince, timestamp) {
335
+ if (trackAge <= this.config.enteringFrames) {
336
+ return "entering";
337
+ }
338
+ if (stationarySince !== void 0) {
339
+ const stationaryDurationSec = (timestamp - stationarySince) / 1e3;
340
+ if (stationaryDurationSec >= this.config.loiteringThresholdSec) {
341
+ return "loitering";
342
+ }
343
+ if (stationaryDurationSec >= this.config.stationaryThresholdSec) {
344
+ return "stationary";
345
+ }
346
+ }
347
+ if (speed > this.config.velocityThreshold) {
348
+ return "moving";
349
+ }
350
+ return "moving";
351
+ }
352
+ };
353
+
354
+ // src/zones/zone-evaluator.ts
355
+ var ZoneEvaluator = class {
356
+ /** Track which zones each track was in last frame */
357
+ trackZoneState = /* @__PURE__ */ new Map();
358
+ evaluate(tracks, zones, imageWidth, imageHeight, timestamp) {
359
+ const events = [];
360
+ const activeTrackIds = /* @__PURE__ */ new Set();
361
+ for (const track of tracks) {
362
+ activeTrackIds.add(track.trackId);
363
+ const centroid = bboxCentroid(track.bbox);
364
+ const prevZones = this.trackZoneState.get(track.trackId) ?? /* @__PURE__ */ new Set();
365
+ const currZones = /* @__PURE__ */ new Set();
366
+ for (const zone of zones) {
367
+ if (zone.alertOnClasses && zone.alertOnClasses.length > 0) {
368
+ if (!zone.alertOnClasses.includes(track.class)) continue;
369
+ }
370
+ if (zone.type === "polygon") {
371
+ const pixelPoints = zone.points.map((p) => normalizeToPixel(p, imageWidth, imageHeight));
372
+ const inside = pointInPolygon(centroid, pixelPoints);
373
+ if (inside) {
374
+ currZones.add(zone.id);
375
+ }
376
+ if (inside && !prevZones.has(zone.id)) {
377
+ events.push({
378
+ type: "zone-enter",
379
+ zoneId: zone.id,
380
+ zoneName: zone.name,
381
+ trackId: track.trackId,
382
+ detection: track,
383
+ timestamp
384
+ });
385
+ }
386
+ if (!inside && prevZones.has(zone.id)) {
387
+ events.push({
388
+ type: "zone-exit",
389
+ zoneId: zone.id,
390
+ zoneName: zone.name,
391
+ trackId: track.trackId,
392
+ detection: track,
393
+ timestamp
394
+ });
395
+ }
396
+ } else if (zone.type === "tripwire" && track.path.length >= 1) {
397
+ const prevBbox = track.path[track.path.length - 1];
398
+ if (!prevBbox) continue;
399
+ const prevCentroid = bboxCentroid(prevBbox);
400
+ const p0 = zone.points[0];
401
+ const p1 = zone.points[1];
402
+ if (!p0 || !p1) continue;
403
+ const tripwireLine = {
404
+ p1: normalizeToPixel(p0, imageWidth, imageHeight),
405
+ p2: normalizeToPixel(p1, imageWidth, imageHeight)
406
+ };
407
+ const cross = tripwireCrossing(prevCentroid, centroid, tripwireLine);
408
+ if (cross?.crossed) {
409
+ events.push({
410
+ type: "tripwire-cross",
411
+ zoneId: zone.id,
412
+ zoneName: zone.name,
413
+ trackId: track.trackId,
414
+ detection: track,
415
+ direction: cross.direction,
416
+ timestamp
417
+ });
418
+ }
419
+ }
420
+ }
421
+ this.trackZoneState.set(track.trackId, currZones);
422
+ }
423
+ for (const trackId of this.trackZoneState.keys()) {
424
+ if (!activeTrackIds.has(trackId)) {
425
+ this.trackZoneState.delete(trackId);
426
+ }
427
+ }
428
+ return events;
429
+ }
430
+ /** Returns a snapshot of the current track → zones mapping */
431
+ getTrackZones() {
432
+ return new Map(this.trackZoneState);
433
+ }
434
+ };
435
+
436
+ // src/events/event-filters.ts
437
+ var DEFAULT_EVENT_FILTER_CONFIG = {
438
+ minTrackAge: 3,
439
+ cooldownSec: 5,
440
+ enabledTypes: [
441
+ "object.entering",
442
+ "object.leaving",
443
+ "object.stationary",
444
+ "object.loitering",
445
+ "zone.enter",
446
+ "zone.exit",
447
+ "tripwire.cross"
448
+ ]
449
+ };
450
+ var EventFilter = class {
451
+ constructor(config) {
452
+ this.config = config;
453
+ }
454
+ /** key: `${trackId}:${eventType}` → last emitted timestamp */
455
+ lastEmitted = /* @__PURE__ */ new Map();
456
+ shouldEmit(trackId, eventType, trackAge, timestamp) {
457
+ if (!this.config.enabledTypes.includes(eventType)) return false;
458
+ if (trackAge < this.config.minTrackAge) return false;
459
+ const key = `${trackId}:${eventType}`;
460
+ const last = this.lastEmitted.get(key);
461
+ if (last !== void 0 && timestamp - last < this.config.cooldownSec * 1e3) return false;
462
+ this.lastEmitted.set(key, timestamp);
463
+ return true;
464
+ }
465
+ /** Record an emission without a gate check — for events that bypass normal cooldown logic */
466
+ recordEmission(trackId, eventType, timestamp) {
467
+ const key = `${trackId}:${eventType}`;
468
+ this.lastEmitted.set(key, timestamp);
469
+ }
470
+ /** Remove cooldown entries for tracks that are no longer active */
471
+ cleanup(activeTrackIds) {
472
+ for (const key of this.lastEmitted.keys()) {
473
+ const colonIdx = key.indexOf(":");
474
+ if (colonIdx === -1) continue;
475
+ const trackId = key.slice(0, colonIdx);
476
+ if (!activeTrackIds.has(trackId)) {
477
+ this.lastEmitted.delete(key);
478
+ }
479
+ }
480
+ }
481
+ /** Reset all cooldown state */
482
+ reset() {
483
+ this.lastEmitted.clear();
484
+ }
485
+ };
486
+
487
+ // src/events/event-emitter.ts
488
+ import { randomUUID } from "crypto";
489
+ var DetectionEventEmitter = class {
490
+ filter;
491
+ /** trackId → last known ObjectState */
492
+ previousStates = /* @__PURE__ */ new Map();
493
+ constructor(filterConfig = {}) {
494
+ this.filter = new EventFilter({ ...DEFAULT_EVENT_FILTER_CONFIG, ...filterConfig });
495
+ }
496
+ emit(tracks, states, zoneEvents, classifications, deviceId) {
497
+ const events = [];
498
+ const timestamp = Date.now();
499
+ const trackMap = /* @__PURE__ */ new Map();
500
+ for (const t of tracks) trackMap.set(t.trackId, t);
501
+ const stateMap = /* @__PURE__ */ new Map();
502
+ for (const s of states) stateMap.set(s.trackId, s);
503
+ const classifMap = /* @__PURE__ */ new Map();
504
+ for (const c of classifications) classifMap.set(c.trackId, c.classifications);
505
+ for (const state of states) {
506
+ const track = trackMap.get(state.trackId);
507
+ if (!track) continue;
508
+ const prevState = this.previousStates.get(state.trackId);
509
+ const classifs = classifMap.get(state.trackId) ?? [];
510
+ if (state.state === "entering" && prevState === void 0) {
511
+ this.tryEmit(events, "object.entering", track, state, classifs, [], deviceId, timestamp);
512
+ }
513
+ if (state.state === "leaving") {
514
+ this.tryEmit(events, "object.leaving", track, state, classifs, [], deviceId, timestamp);
515
+ }
516
+ if (state.state === "stationary" && prevState !== void 0 && prevState !== "stationary" && prevState !== "loitering") {
517
+ this.tryEmit(events, "object.stationary", track, state, classifs, [], deviceId, timestamp);
518
+ }
519
+ if (state.state === "loitering" && prevState === "stationary") {
520
+ this.tryEmit(events, "object.loitering", track, state, classifs, [], deviceId, timestamp);
521
+ }
522
+ if (state.state !== "leaving") {
523
+ this.previousStates.set(state.trackId, state.state);
524
+ } else {
525
+ this.previousStates.delete(state.trackId);
526
+ }
527
+ }
528
+ for (const ze of zoneEvents) {
529
+ const track = trackMap.get(ze.trackId);
530
+ if (!track) continue;
531
+ const state = stateMap.get(ze.trackId);
532
+ if (!state) continue;
533
+ let eventType;
534
+ if (ze.type === "tripwire-cross") {
535
+ eventType = "tripwire.cross";
536
+ } else if (ze.type === "zone-enter") {
537
+ eventType = "zone.enter";
538
+ } else {
539
+ eventType = "zone.exit";
540
+ }
541
+ const classifs = classifMap.get(ze.trackId) ?? [];
542
+ this.tryEmit(events, eventType, track, state, classifs, [ze], deviceId, timestamp);
543
+ }
544
+ const activeIds = new Set(tracks.map((t) => t.trackId));
545
+ this.filter.cleanup(activeIds);
546
+ return events;
547
+ }
548
+ tryEmit(events, eventType, track, state, classifications, zoneEvents, deviceId, timestamp) {
549
+ if (!this.filter.shouldEmit(track.trackId, eventType, track.trackAge, timestamp)) return;
550
+ events.push({
551
+ id: randomUUID(),
552
+ type: eventType,
553
+ timestamp,
554
+ deviceId,
555
+ detection: track,
556
+ classifications,
557
+ objectState: state,
558
+ zoneEvents,
559
+ trackPath: track.path
560
+ });
561
+ }
562
+ reset() {
563
+ this.previousStates.clear();
564
+ this.filter.reset();
565
+ }
566
+ };
567
+
568
+ // src/analytics/track-store.ts
569
+ var MAX_PATH_LENGTH2 = 300;
570
+ var TrackStore = class {
571
+ activeTracks = /* @__PURE__ */ new Map();
572
+ update(tracks, states, zoneEvents, classifications) {
573
+ const stateMap = /* @__PURE__ */ new Map();
574
+ for (const s of states) stateMap.set(s.trackId, s);
575
+ const classifMap = /* @__PURE__ */ new Map();
576
+ for (const c of classifications) classifMap.set(c.trackId, c.classifications);
577
+ const now = Date.now();
578
+ for (const track of tracks) {
579
+ let acc = this.activeTracks.get(track.trackId);
580
+ if (!acc) {
581
+ acc = {
582
+ trackId: track.trackId,
583
+ class: track.class,
584
+ originalClass: track.originalClass,
585
+ state: "entering",
586
+ firstSeen: track.path.length === 0 ? now : now,
587
+ lastSeen: now,
588
+ path: [],
589
+ zoneTransitions: [],
590
+ events: []
591
+ };
592
+ this.activeTracks.set(track.trackId, acc);
593
+ }
594
+ acc.class = track.class;
595
+ acc.originalClass = track.originalClass;
596
+ acc.lastSeen = now;
597
+ const state = stateMap.get(track.trackId);
598
+ if (state) acc.state = state.state;
599
+ const pathPoint = {
600
+ timestamp: now,
601
+ bbox: track.bbox,
602
+ velocity: track.velocity ?? { dx: 0, dy: 0 }
603
+ };
604
+ if (acc.path.length >= MAX_PATH_LENGTH2) {
605
+ acc.path.shift();
606
+ }
607
+ acc.path.push(pathPoint);
608
+ const classifs = classifMap.get(track.trackId) ?? [];
609
+ for (const c of classifs) {
610
+ if (c.metadata?.type === "face-recognition" && typeof c.text === "string") {
611
+ acc.identity = { name: c.text, confidence: c.score, matchedAt: now };
612
+ } else if (c.metadata?.type === "plate-recognition" && typeof c.text === "string") {
613
+ acc.plateText = { text: c.text, confidence: c.score, readAt: now };
614
+ } else if (c.metadata?.type === "sub-class") {
615
+ acc.subClass = { class: c.class, confidence: c.score };
616
+ }
617
+ }
618
+ }
619
+ for (const ze of zoneEvents) {
620
+ const acc = this.activeTracks.get(ze.trackId);
621
+ if (!acc) continue;
622
+ if (ze.type === "zone-enter") {
623
+ acc.zoneTransitions.push({
624
+ zoneId: ze.zoneId,
625
+ zoneName: ze.zoneName,
626
+ entered: ze.timestamp,
627
+ dwellMs: 0
628
+ });
629
+ } else if (ze.type === "zone-exit") {
630
+ let openIdx = -1;
631
+ for (let i = acc.zoneTransitions.length - 1; i >= 0; i--) {
632
+ const t = acc.zoneTransitions[i];
633
+ if (t.zoneId === ze.zoneId && t.exited === void 0) {
634
+ openIdx = i;
635
+ break;
636
+ }
637
+ }
638
+ if (openIdx >= 0) {
639
+ const open = acc.zoneTransitions[openIdx];
640
+ acc.zoneTransitions[openIdx] = {
641
+ ...open,
642
+ exited: ze.timestamp,
643
+ dwellMs: ze.timestamp - open.entered
644
+ };
645
+ }
646
+ }
647
+ }
648
+ }
649
+ /** Attach a DetectionEvent to its associated track accumulator */
650
+ addEvent(trackId, event) {
651
+ const acc = this.activeTracks.get(trackId);
652
+ if (!acc) return;
653
+ acc.events.push(event);
654
+ if (event.snapshot && !acc.bestSnapshot) {
655
+ acc.bestSnapshot = event.snapshot;
656
+ }
657
+ }
658
+ /** Get accumulated detail for an active track */
659
+ getTrackDetail(trackId) {
660
+ const acc = this.activeTracks.get(trackId);
661
+ if (!acc) return null;
662
+ return this.buildTrackDetail(acc);
663
+ }
664
+ /** Called when a track ends — returns complete TrackDetail and removes from active set */
665
+ finishTrack(trackId) {
666
+ const acc = this.activeTracks.get(trackId);
667
+ if (!acc) return null;
668
+ const detail = this.buildTrackDetail(acc);
669
+ this.activeTracks.delete(trackId);
670
+ return detail;
671
+ }
672
+ /** Get all active track IDs */
673
+ getActiveTrackIds() {
674
+ return Array.from(this.activeTracks.keys());
675
+ }
676
+ /** Clear all accumulated state */
677
+ reset() {
678
+ this.activeTracks.clear();
679
+ }
680
+ buildTrackDetail(acc) {
681
+ return {
682
+ trackId: acc.trackId,
683
+ class: acc.class,
684
+ originalClass: acc.originalClass,
685
+ state: acc.state,
686
+ firstSeen: acc.firstSeen,
687
+ lastSeen: acc.lastSeen,
688
+ totalDwellMs: acc.lastSeen - acc.firstSeen,
689
+ path: acc.path,
690
+ identity: acc.identity,
691
+ plateText: acc.plateText,
692
+ subClass: acc.subClass,
693
+ zoneTransitions: acc.zoneTransitions,
694
+ bestSnapshot: acc.bestSnapshot,
695
+ events: acc.events
696
+ };
697
+ }
698
+ };
699
+
700
+ // src/analytics/live-state-manager.ts
701
+ var FpsCounter = class {
702
+ frameTimes = [];
703
+ windowMs = 5e3;
704
+ tick(timestamp) {
705
+ this.frameTimes.push(timestamp);
706
+ const cutoff = timestamp - this.windowMs;
707
+ while (this.frameTimes.length > 0 && this.frameTimes[0] < cutoff) {
708
+ this.frameTimes.shift();
709
+ }
710
+ }
711
+ getFps() {
712
+ if (this.frameTimes.length < 2) return 0;
713
+ const oldest = this.frameTimes[0];
714
+ const newest = this.frameTimes[this.frameTimes.length - 1];
715
+ const durationSec = (newest - oldest) / 1e3;
716
+ if (durationSec <= 0) return 0;
717
+ return (this.frameTimes.length - 1) / durationSec;
718
+ }
719
+ };
720
+ var LiveStateManager = class {
721
+ zones = [];
722
+ fpsCounter = new FpsCounter();
723
+ pipelineMsHistory = [];
724
+ maxPipelineHistory = 30;
725
+ setZones(zones) {
726
+ this.zones = [...zones];
727
+ }
728
+ buildState(deviceId, tracks, states, trackZones, pipelineStatus, pipelineMs, lastEvent, timestamp) {
729
+ this.fpsCounter.tick(timestamp);
730
+ if (this.pipelineMsHistory.length >= this.maxPipelineHistory) {
731
+ this.pipelineMsHistory.shift();
732
+ }
733
+ this.pipelineMsHistory.push(pipelineMs);
734
+ const avgPipelineMs = this.pipelineMsHistory.length === 0 ? 0 : this.pipelineMsHistory.reduce((sum, v) => sum + v, 0) / this.pipelineMsHistory.length;
735
+ const stateMap = /* @__PURE__ */ new Map();
736
+ for (const s of states) stateMap.set(s.trackId, s);
737
+ const trackSummaries = tracks.map((track) => {
738
+ const state = stateMap.get(track.trackId);
739
+ const inZones = Array.from(trackZones.get(track.trackId) ?? []);
740
+ return {
741
+ trackId: track.trackId,
742
+ class: track.class,
743
+ originalClass: track.originalClass,
744
+ state: state?.state ?? "moving",
745
+ bbox: track.bbox,
746
+ velocity: track.velocity ?? { dx: 0, dy: 0 },
747
+ dwellTimeMs: state?.dwellTimeMs ?? 0,
748
+ inZones
749
+ };
750
+ });
751
+ let movingObjects = 0;
752
+ let stationaryObjects = 0;
753
+ for (const summary of trackSummaries) {
754
+ if (summary.state === "moving" || summary.state === "entering") movingObjects++;
755
+ else if (summary.state === "stationary" || summary.state === "loitering") stationaryObjects++;
756
+ }
757
+ const objectCounts = {};
758
+ for (const summary of trackSummaries) {
759
+ objectCounts[summary.class] = (objectCounts[summary.class] ?? 0) + 1;
760
+ }
761
+ const zoneLiveStates = this.zones.map((zone) => {
762
+ const tracksInZone = trackSummaries.filter((t) => t.inZones.includes(zone.id));
763
+ const objectsByClass = {};
764
+ const loiteringTracks = [];
765
+ for (const t of tracksInZone) {
766
+ objectsByClass[t.class] = (objectsByClass[t.class] ?? 0) + 1;
767
+ if (t.state === "loitering") loiteringTracks.push(t.trackId);
768
+ }
769
+ const avgDwellTimeMs = tracksInZone.length === 0 ? 0 : tracksInZone.reduce((sum, t) => sum + t.dwellTimeMs, 0) / tracksInZone.length;
770
+ return {
771
+ zoneId: zone.id,
772
+ zoneName: zone.name,
773
+ occupied: tracksInZone.length > 0,
774
+ objectCount: tracksInZone.length,
775
+ objectsByClass,
776
+ trackIds: tracksInZone.map((t) => t.trackId),
777
+ avgDwellTimeMs,
778
+ totalEntrancesToday: 0,
779
+ // requires DB — left for server orchestrator
780
+ totalExitsToday: 0,
781
+ loiteringTracks
782
+ };
783
+ });
784
+ return {
785
+ deviceId,
786
+ lastFrameTimestamp: timestamp,
787
+ activeObjects: trackSummaries.length,
788
+ movingObjects,
789
+ stationaryObjects,
790
+ objectCounts,
791
+ tracks: trackSummaries,
792
+ zones: zoneLiveStates,
793
+ lastEvent,
794
+ pipelineStatus,
795
+ avgPipelineMs,
796
+ currentFps: this.fpsCounter.getFps()
797
+ };
798
+ }
799
+ reset() {
800
+ this.pipelineMsHistory.length = 0;
801
+ }
802
+ };
803
+
804
+ // src/analytics/heatmap-aggregator.ts
805
+ var HeatmapAggregator = class {
806
+ constructor(width, height, gridSize) {
807
+ this.width = width;
808
+ this.height = height;
809
+ this.gridSize = gridSize;
810
+ if (gridSize <= 0) throw new Error("gridSize must be > 0");
811
+ this.grid = new Float32Array(gridSize * gridSize);
812
+ }
813
+ grid;
814
+ maxCount = 0;
815
+ /**
816
+ * Add a normalized point (0–1 range) to the heatmap.
817
+ * Points outside [0, 1] are clamped to the grid boundary.
818
+ */
819
+ addPoint(x, y) {
820
+ const col = Math.min(Math.floor(x * this.gridSize), this.gridSize - 1);
821
+ const row = Math.min(Math.floor(y * this.gridSize), this.gridSize - 1);
822
+ const idx = row * this.gridSize + col;
823
+ this.grid[idx] += 1;
824
+ if (this.grid[idx] > this.maxCount) {
825
+ this.maxCount = this.grid[idx];
826
+ }
827
+ }
828
+ /** Add a pixel-coordinate point. Normalizes against the configured width/height. */
829
+ addPixelPoint(px, py) {
830
+ this.addPoint(px / this.width, py / this.height);
831
+ }
832
+ getHeatmap() {
833
+ return {
834
+ width: this.width,
835
+ height: this.height,
836
+ gridSize: this.gridSize,
837
+ cells: new Float32Array(this.grid),
838
+ maxCount: this.maxCount
839
+ };
840
+ }
841
+ reset() {
842
+ this.grid.fill(0);
843
+ this.maxCount = 0;
844
+ }
845
+ /** Total number of points accumulated */
846
+ get totalPoints() {
847
+ let total = 0;
848
+ for (let i = 0; i < this.grid.length; i++) {
849
+ total += this.grid[i];
850
+ }
851
+ return total;
852
+ }
853
+ };
854
+
855
+ // src/analytics/analytics-provider.ts
856
+ var AnalyticsProvider = class {
857
+ constructor(liveStateManager, trackStore, getZoneHistoryCb, getHeatmapCb, lastLiveState = null) {
858
+ this.liveStateManager = liveStateManager;
859
+ this.trackStore = trackStore;
860
+ this.getZoneHistoryCb = getZoneHistoryCb;
861
+ this.getHeatmapCb = getHeatmapCb;
862
+ this.lastLiveState = lastLiveState;
863
+ }
864
+ /** Called by the orchestrator each frame to update the cached live state */
865
+ updateLiveState(state) {
866
+ this.lastLiveState = state;
867
+ }
868
+ getLiveState(_deviceId) {
869
+ return this.lastLiveState;
870
+ }
871
+ getTracks(_deviceId, filter) {
872
+ const tracks = this.lastLiveState?.tracks ?? [];
873
+ if (!filter) return [...tracks];
874
+ return tracks.filter((t) => {
875
+ if (filter.class && !filter.class.includes(t.class)) return false;
876
+ if (filter.state && !filter.state.includes(t.state)) return false;
877
+ if (filter.inZone && !t.inZones.includes(filter.inZone)) return false;
878
+ if (filter.minDwellMs !== void 0 && t.dwellTimeMs < filter.minDwellMs) return false;
879
+ return true;
880
+ });
881
+ }
882
+ getZoneState(_deviceId, zoneId) {
883
+ return this.lastLiveState?.zones.find((z) => z.zoneId === zoneId) ?? null;
884
+ }
885
+ async getZoneHistory(deviceId, zoneId, options) {
886
+ if (this.getZoneHistoryCb) {
887
+ return this.getZoneHistoryCb(deviceId, zoneId, options);
888
+ }
889
+ return [];
890
+ }
891
+ async getHeatmap(deviceId, options) {
892
+ if (this.getHeatmapCb) {
893
+ return this.getHeatmapCb(deviceId, options);
894
+ }
895
+ const gridSize = options.resolution;
896
+ return {
897
+ width: 1920,
898
+ height: 1080,
899
+ gridSize,
900
+ cells: new Float32Array(gridSize * gridSize),
901
+ maxCount: 0
902
+ };
903
+ }
904
+ getTrackDetail(_deviceId, trackId) {
905
+ return this.trackStore.getTrackDetail(trackId);
906
+ }
907
+ getCameraStatus(_deviceId) {
908
+ return this.lastLiveState ? [...this.lastLiveState.pipelineStatus] : [];
909
+ }
910
+ };
911
+
912
+ // src/snapshots/snapshot-manager.ts
913
+ var DEFAULT_SNAPSHOT_CONFIG = {
914
+ enabled: false,
915
+ saveThumbnail: true,
916
+ saveAnnotatedFrame: false,
917
+ saveDebugThumbnails: false
918
+ };
919
+ var SnapshotManager = class {
920
+ constructor(config) {
921
+ this.config = config;
922
+ }
923
+ async capture(frame, detection, allDetections, eventId) {
924
+ if (!this.config.enabled) return void 0;
925
+ await this.ensureOutputDir();
926
+ let thumbnailPath;
927
+ let annotatedFramePath;
928
+ if (this.config.saveThumbnail) {
929
+ thumbnailPath = await this.saveThumbnail(frame, detection.bbox, eventId);
930
+ }
931
+ if (this.config.saveAnnotatedFrame) {
932
+ annotatedFramePath = await this.saveAnnotatedFrame(frame, allDetections, eventId);
933
+ }
934
+ if (!thumbnailPath && !annotatedFramePath) return void 0;
935
+ return {
936
+ thumbnailPath: thumbnailPath ?? "",
937
+ annotatedFramePath: annotatedFramePath ?? ""
938
+ };
939
+ }
940
+ async saveThumbnail(frame, bbox, eventId) {
941
+ const sharp = await import("sharp");
942
+ const { frameWidth, frameHeight } = await this.resolveFrameDimensions(frame);
943
+ const left = Math.max(0, Math.round(bbox.x));
944
+ const top = Math.max(0, Math.round(bbox.y));
945
+ const width = Math.min(Math.round(bbox.w), frameWidth - left);
946
+ const height = Math.min(Math.round(bbox.h), frameHeight - top);
947
+ if (width <= 0 || height <= 0) {
948
+ throw new Error(`Invalid crop dimensions for event ${eventId}: ${JSON.stringify({ left, top, width, height, frameWidth, frameHeight })}`);
949
+ }
950
+ const relativePath = `${eventId}_thumb.jpg`;
951
+ const inputOptions = this.sharpInputOptions(frame);
952
+ const buffer = await sharp.default(frame.data, inputOptions).extract({ left, top, width, height }).jpeg({ quality: 85 }).toBuffer();
953
+ await this.writeOutput(relativePath, buffer);
954
+ return relativePath;
955
+ }
956
+ async saveAnnotatedFrame(frame, detections, eventId) {
957
+ const sharp = await import("sharp");
958
+ const { frameWidth, frameHeight } = await this.resolveFrameDimensions(frame);
959
+ const relativePath = `${eventId}_annotated.jpg`;
960
+ const svgBoxes = detections.map((det) => {
961
+ const x = Math.max(0, Math.round(det.bbox.x));
962
+ const y = Math.max(0, Math.round(det.bbox.y));
963
+ const w = Math.min(Math.round(det.bbox.w), frameWidth - x);
964
+ const h = Math.min(Math.round(det.bbox.h), frameHeight - y);
965
+ const label = `${det.class} ${(det.score * 100).toFixed(0)}%`;
966
+ return `<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="none" stroke="lime" stroke-width="2"/>
967
+ <text x="${x + 2}" y="${Math.max(y - 2, 10)}" font-size="12" fill="lime" font-family="sans-serif">${label}</text>`;
968
+ }).join("\n");
969
+ const svgOverlay = Buffer.from(
970
+ `<svg width="${frameWidth}" height="${frameHeight}" xmlns="http://www.w3.org/2000/svg">${svgBoxes}</svg>`
971
+ );
972
+ const inputOptions = this.sharpInputOptions(frame);
973
+ const buffer = await sharp.default(frame.data, inputOptions).composite([{ input: svgOverlay, top: 0, left: 0 }]).jpeg({ quality: 85 }).toBuffer();
974
+ await this.writeOutput(relativePath, buffer);
975
+ return relativePath;
976
+ }
977
+ /**
978
+ * Write output using mediaStorage if available, otherwise fall back to fs.writeFile.
979
+ */
980
+ async writeOutput(relativePath, data) {
981
+ if (this.config.mediaStorage) {
982
+ await this.config.mediaStorage.writeFile(relativePath, data);
983
+ } else if (this.config.outputDir) {
984
+ const { writeFile } = await import("fs/promises");
985
+ const { join } = await import("path");
986
+ await writeFile(join(this.config.outputDir, relativePath), data);
987
+ }
988
+ }
989
+ /**
990
+ * Resolve actual frame dimensions. JPEG frames from decoders may report
991
+ * width=0, height=0 — in that case read the real size from sharp metadata.
992
+ */
993
+ async resolveFrameDimensions(frame) {
994
+ if (frame.width > 0 && frame.height > 0) {
995
+ return { frameWidth: frame.width, frameHeight: frame.height };
996
+ }
997
+ if (frame.format === "jpeg") {
998
+ const sharp = await import("sharp");
999
+ const meta = await sharp.default(frame.data).metadata();
1000
+ return {
1001
+ frameWidth: meta.width ?? 0,
1002
+ frameHeight: meta.height ?? 0
1003
+ };
1004
+ }
1005
+ return { frameWidth: frame.width, frameHeight: frame.height };
1006
+ }
1007
+ sharpInputOptions(frame) {
1008
+ if (frame.format === "jpeg") {
1009
+ return {};
1010
+ }
1011
+ const channels = frame.format === "rgb" ? 3 : 3;
1012
+ return {
1013
+ raw: {
1014
+ width: frame.width,
1015
+ height: frame.height,
1016
+ channels
1017
+ }
1018
+ };
1019
+ }
1020
+ async ensureOutputDir() {
1021
+ if (this.config.outputDir) {
1022
+ const { mkdir } = await import("fs/promises");
1023
+ await mkdir(this.config.outputDir, { recursive: true });
1024
+ }
1025
+ }
1026
+ };
1027
+
1028
+ // src/pipeline/analysis-pipeline.ts
1029
+ var AnalysisPipeline = class {
1030
+ id = "pipeline-analysis";
1031
+ manifest = {
1032
+ id: "pipeline-analysis",
1033
+ name: "Pipeline Analysis",
1034
+ version: "0.1.0",
1035
+ description: "Object tracking, state analysis, zone evaluation, and event emission",
1036
+ packageName: "@camstack/lib-pipeline-analysis"
1037
+ };
1038
+ config;
1039
+ cameras = /* @__PURE__ */ new Map();
1040
+ knownFaces = [];
1041
+ knownPlates = [];
1042
+ listeners = /* @__PURE__ */ new Map();
1043
+ /** Optional callback: server orchestrator can hook in to persist finished tracks */
1044
+ onTrackFinished;
1045
+ constructor(config = {}) {
1046
+ this.config = {
1047
+ tracker: config.tracker ?? {},
1048
+ stateAnalyzer: config.stateAnalyzer ?? {},
1049
+ eventFilter: config.eventFilter ?? {},
1050
+ snapshot: config.snapshot ?? {},
1051
+ heatmapGridSize: config.heatmapGridSize ?? 32,
1052
+ defaultFrameWidth: config.defaultFrameWidth ?? 1920,
1053
+ defaultFrameHeight: config.defaultFrameHeight ?? 1080
1054
+ };
1055
+ }
1056
+ async initialize(_ctx) {
1057
+ }
1058
+ async shutdown() {
1059
+ this.cameras.clear();
1060
+ this.listeners.clear();
1061
+ }
1062
+ async processFrame(deviceId, frame, pipelineResult) {
1063
+ const camera = this.getOrCreateCamera(deviceId);
1064
+ const frameWidth = frame.width > 0 ? frame.width : this.config.defaultFrameWidth;
1065
+ const frameHeight = frame.height > 0 ? frame.height : this.config.defaultFrameHeight;
1066
+ const timestamp = frame.timestamp;
1067
+ const detections = pipelineResult ? this.extractDetections(pipelineResult) : [];
1068
+ const tracked = camera.tracker.update(detections, timestamp);
1069
+ const states = camera.stateAnalyzer.analyze(tracked, timestamp);
1070
+ const zoneEvents = camera.zoneEvaluator.evaluate(
1071
+ tracked,
1072
+ camera.zones,
1073
+ frameWidth,
1074
+ frameHeight,
1075
+ timestamp
1076
+ );
1077
+ const classificationsByTrack = pipelineResult ? this.matchClassifications(pipelineResult, tracked.map((t) => t.trackId)) : [];
1078
+ camera.trackStore.update(tracked, states, zoneEvents, classificationsByTrack);
1079
+ const events = camera.eventEmitter.emit(
1080
+ tracked,
1081
+ states,
1082
+ zoneEvents,
1083
+ classificationsByTrack,
1084
+ deviceId
1085
+ );
1086
+ for (const event of events) {
1087
+ const snapshot = await camera.snapshotManager.capture(frame, event.detection, tracked, event.id);
1088
+ if (snapshot) {
1089
+ ;
1090
+ event.snapshot = snapshot;
1091
+ }
1092
+ camera.trackStore.addEvent(event.detection.trackId, event);
1093
+ }
1094
+ for (const track of tracked) {
1095
+ const cx = (track.bbox.x + track.bbox.w / 2) / frameWidth;
1096
+ const cy = (track.bbox.y + track.bbox.h / 2) / frameHeight;
1097
+ camera.heatmapAggregator.addPoint(cx, cy);
1098
+ }
1099
+ for (const lostTrack of camera.tracker.getLostTracks()) {
1100
+ const detail = camera.trackStore.finishTrack(lostTrack.trackId);
1101
+ if (detail && this.onTrackFinished) {
1102
+ this.onTrackFinished(deviceId, detail);
1103
+ }
1104
+ }
1105
+ const pipelineMs = pipelineResult?.totalMs ?? 0;
1106
+ const pipelineStatus = [];
1107
+ const liveState = camera.liveStateManager.buildState(
1108
+ deviceId,
1109
+ tracked,
1110
+ states,
1111
+ camera.zoneEvaluator.getTrackZones(),
1112
+ pipelineStatus,
1113
+ pipelineMs,
1114
+ events[events.length - 1],
1115
+ timestamp
1116
+ );
1117
+ camera.lastLiveState = liveState;
1118
+ camera.analyticsProvider.updateLiveState(liveState);
1119
+ const cameraListeners = this.listeners.get(deviceId);
1120
+ if (cameraListeners) {
1121
+ for (const cb of cameraListeners) {
1122
+ cb(liveState);
1123
+ }
1124
+ }
1125
+ return events;
1126
+ }
1127
+ setCameraPipeline(deviceId, _config) {
1128
+ this.getOrCreateCamera(deviceId);
1129
+ }
1130
+ setCameraZones(deviceId, zones) {
1131
+ const camera = this.getOrCreateCamera(deviceId);
1132
+ camera.zones = [...zones];
1133
+ camera.liveStateManager.setZones(zones);
1134
+ }
1135
+ setKnownFaces(faces) {
1136
+ this.knownFaces = [...faces];
1137
+ }
1138
+ setKnownPlates(plates) {
1139
+ this.knownPlates = [...plates];
1140
+ }
1141
+ onLiveStateChange(deviceId, callback) {
1142
+ if (!this.listeners.has(deviceId)) {
1143
+ this.listeners.set(deviceId, /* @__PURE__ */ new Set());
1144
+ }
1145
+ this.listeners.get(deviceId).add(callback);
1146
+ return () => {
1147
+ this.listeners.get(deviceId)?.delete(callback);
1148
+ };
1149
+ }
1150
+ // ICameraAnalyticsProvider delegates to per-camera AnalyticsProvider
1151
+ getLiveState(deviceId) {
1152
+ return this.cameras.get(deviceId)?.lastLiveState ?? null;
1153
+ }
1154
+ getTracks(deviceId, filter) {
1155
+ const camera = this.cameras.get(deviceId);
1156
+ if (!camera) return [];
1157
+ return camera.analyticsProvider.getTracks(deviceId, filter);
1158
+ }
1159
+ getZoneState(deviceId, zoneId) {
1160
+ const camera = this.cameras.get(deviceId);
1161
+ if (!camera) return null;
1162
+ return camera.analyticsProvider.getZoneState(deviceId, zoneId);
1163
+ }
1164
+ async getZoneHistory(deviceId, zoneId, options) {
1165
+ const camera = this.cameras.get(deviceId);
1166
+ if (!camera) return [];
1167
+ return camera.analyticsProvider.getZoneHistory(deviceId, zoneId, options);
1168
+ }
1169
+ async getHeatmap(deviceId, options) {
1170
+ const camera = this.cameras.get(deviceId);
1171
+ if (!camera) {
1172
+ const gridSize = options.resolution;
1173
+ return {
1174
+ width: this.config.defaultFrameWidth,
1175
+ height: this.config.defaultFrameHeight,
1176
+ gridSize,
1177
+ cells: new Float32Array(gridSize * gridSize),
1178
+ maxCount: 0
1179
+ };
1180
+ }
1181
+ return camera.heatmapAggregator.getHeatmap();
1182
+ }
1183
+ getTrackDetail(deviceId, trackId) {
1184
+ const camera = this.cameras.get(deviceId);
1185
+ if (!camera) return null;
1186
+ return camera.trackStore.getTrackDetail(trackId);
1187
+ }
1188
+ getCameraStatus(deviceId) {
1189
+ const camera = this.cameras.get(deviceId);
1190
+ if (!camera) return [];
1191
+ return camera.analyticsProvider.getCameraStatus(deviceId);
1192
+ }
1193
+ getOrCreateCamera(deviceId) {
1194
+ const existing = this.cameras.get(deviceId);
1195
+ if (existing) return existing;
1196
+ const tracker = new SortTracker(this.config.tracker);
1197
+ const stateAnalyzer = new StateAnalyzer(this.config.stateAnalyzer);
1198
+ const zoneEvaluator = new ZoneEvaluator();
1199
+ const eventEmitter = new DetectionEventEmitter(this.config.eventFilter);
1200
+ const trackStore = new TrackStore();
1201
+ const liveStateManager = new LiveStateManager();
1202
+ const heatmapAggregator = new HeatmapAggregator(
1203
+ this.config.defaultFrameWidth,
1204
+ this.config.defaultFrameHeight,
1205
+ this.config.heatmapGridSize
1206
+ );
1207
+ const analyticsProvider = new AnalyticsProvider(liveStateManager, trackStore);
1208
+ const snapshotManager = new SnapshotManager({
1209
+ ...DEFAULT_SNAPSHOT_CONFIG,
1210
+ ...this.config.snapshot
1211
+ });
1212
+ const cameraState = {
1213
+ tracker,
1214
+ stateAnalyzer,
1215
+ zoneEvaluator,
1216
+ eventEmitter,
1217
+ trackStore,
1218
+ liveStateManager,
1219
+ heatmapAggregator,
1220
+ analyticsProvider,
1221
+ snapshotManager,
1222
+ zones: [],
1223
+ lastLiveState: null
1224
+ };
1225
+ this.cameras.set(deviceId, cameraState);
1226
+ return cameraState;
1227
+ }
1228
+ extractDetections(pipelineResult) {
1229
+ const detections = [];
1230
+ for (const stepResult of pipelineResult.results) {
1231
+ if (stepResult.slot === "detector") {
1232
+ const output = stepResult.output;
1233
+ if (output.detections) {
1234
+ detections.push(...output.detections);
1235
+ }
1236
+ }
1237
+ }
1238
+ return detections;
1239
+ }
1240
+ matchClassifications(pipelineResult, trackIds) {
1241
+ const classifierResults = [];
1242
+ for (const stepResult of pipelineResult.results) {
1243
+ if (stepResult.slot === "classifier") {
1244
+ const output = stepResult.output;
1245
+ if (output.classifications) {
1246
+ classifierResults.push([...output.classifications]);
1247
+ }
1248
+ }
1249
+ }
1250
+ return trackIds.slice(0, classifierResults.length).map((trackId, i) => ({
1251
+ trackId,
1252
+ classifications: classifierResults[i] ?? []
1253
+ }));
1254
+ }
1255
+ };
1256
+ export {
1257
+ AnalysisPipeline,
1258
+ AnalyticsProvider,
1259
+ DEFAULT_EVENT_FILTER_CONFIG,
1260
+ DEFAULT_SNAPSHOT_CONFIG,
1261
+ DEFAULT_STATE_ANALYZER_CONFIG,
1262
+ DEFAULT_TRACKER_CONFIG,
1263
+ DetectionEventEmitter,
1264
+ EventFilter,
1265
+ HeatmapAggregator,
1266
+ LiveStateManager,
1267
+ SnapshotManager,
1268
+ SortTracker,
1269
+ StateAnalyzer,
1270
+ TrackStore,
1271
+ ZoneEvaluator,
1272
+ bboxCentroid,
1273
+ greedyAssignment,
1274
+ lineIntersection,
1275
+ normalizeToPixel,
1276
+ pointInPolygon,
1277
+ tripwireCrossing
1278
+ };
1279
+ //# sourceMappingURL=index.mjs.map