File size: 3,490 Bytes
4bdf735
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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
/// <reference lib="webworker" />

import {pipeline, type ObjectDetectionOutput} from '@huggingface/transformers';
import type {WorkerRequest, WorkerResponse} from './workerMessages';

const MODEL_ID = 'onnx-community/rfdetr_medium-ONNX';
/** RF-DETR preprocessor input size (see model preprocessor_config.json). */
const MODEL_INPUT_SIZE = 576;

type DetectFn = (
  input: OffscreenCanvas,
  options?: {threshold?: number; percentage?: boolean},
) => Promise<ObjectDetectionOutput>;

let detector: DetectFn | null = null;
let loadPromise: Promise<void> | null = null;
let preprocessCanvas: OffscreenCanvas | null = null;
let preprocessCtx: OffscreenCanvasRenderingContext2D | null = null;

function getPreprocessSurface(): {
  canvas: OffscreenCanvas;
  ctx: OffscreenCanvasRenderingContext2D;
} {
  if (!preprocessCanvas || !preprocessCtx) {
    preprocessCanvas = new OffscreenCanvas(MODEL_INPUT_SIZE, MODEL_INPUT_SIZE);
    const ctx = preprocessCanvas.getContext('2d', {willReadFrequently: true});
    if (!ctx) {
      throw new Error('OffscreenCanvas 2D context not available in worker');
    }
    preprocessCtx = ctx;
  }
  return {canvas: preprocessCanvas, ctx: preprocessCtx};
}

function post(message: WorkerResponse): void {
  self.postMessage(message);
}

async function loadDetector(): Promise<DetectFn> {
  if (detector) {
    return detector;
  }

  if (!loadPromise) {
    loadPromise = (async () => {
      post({type: 'status', message: 'Loading RF-DETR model (WebGPU)…'});
      detector = (await pipeline('object-detection', MODEL_ID, {
        device: 'webgpu',
        dtype: 'fp32',
        progress_callback: (progress) => {
          if (progress.status === 'progress' && progress.file) {
            const percent =
              progress.total && progress.total > 0
                ? Math.round((progress.loaded / progress.total) * 100)
                : null;
            post({
              type: 'status',
              message: percent
                ? `Downloading ${progress.file} (${percent}%)…`
                : `Downloading ${progress.file}…`,
            });
          }
        },
      })) as DetectFn;
      post({type: 'status', message: 'Compiling RF-DETR shaders…'});
    })();
  }

  await loadPromise;
  return detector!;
}

async function runDetection(
  frame: VideoFrame,
  threshold: number,
): Promise<ObjectDetectionOutput> {
  const detect = await loadDetector();
  const {canvas, ctx} = getPreprocessSurface();

  try {
    const bitmap = await createImageBitmap(frame, {
      resizeWidth: MODEL_INPUT_SIZE,
      resizeHeight: MODEL_INPUT_SIZE,
    });
    try {
      ctx.drawImage(bitmap, 0, 0);
    } finally {
      bitmap.close();
    }
  } finally {
    frame.close();
  }

  return detect(canvas, {threshold, percentage: true});
}

self.onmessage = async (event: MessageEvent<WorkerRequest>) => {
  const message = event.data;

  try {
    if (message.type === 'init') {
      await loadDetector();
      post({type: 'ready'});
      return;
    }

    if (message.type === 'detect') {
      const results = await runDetection(message.frame, message.threshold);
      post({type: 'detect-result', id: message.id, results});
      return;
    }
  } catch (error) {
    if (message.type === 'detect') {
      message.frame.close();
    }

    post({
      type: 'error',
      error: error instanceof Error ? error.message : String(error),
      id: message.type === 'detect' ? message.id : undefined,
    });
  }
};