@tradalab/mediakit 1.0.0 → 1.2.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.js CHANGED
@@ -1,9 +1,21 @@
1
1
  import {
2
2
  NO_EFFECTS,
3
+ TOUCH_UP,
3
4
  coreRecipe,
4
5
  needsFace,
5
- needsMask
6
- } from "./chunk-5KXLFDFV.js";
6
+ needsMask,
7
+ needsSegmentation,
8
+ touchUp,
9
+ touchUpAmount
10
+ } from "./chunk-V47SDU4L.js";
11
+ import {
12
+ BLEND_MODES,
13
+ TRANSITIONS,
14
+ coreLayer,
15
+ hitTest,
16
+ layouts,
17
+ parseColor
18
+ } from "./chunk-BMIOUOT3.js";
7
19
 
8
20
  // src/segmenter.ts
9
21
  import { FilesetResolver, ImageSegmenter } from "@mediapipe/tasks-vision";
@@ -55,15 +67,16 @@ async function createSegmenter(canvas) {
55
67
  import { FaceLandmarker, FilesetResolver as FilesetResolver2 } from "@mediapipe/tasks-vision";
56
68
  var WASM_DIR2 = "/mediakit/mp";
57
69
  var MODEL_URL2 = "/mediakit/face_landmarker.task";
58
- async function createFaceDetector(canvas) {
70
+ var FACE_FLOATS = 478 * 3;
71
+ async function createFaceDetector(canvas, maxFaces) {
59
72
  const fileset = await FilesetResolver2.forVisionTasks(WASM_DIR2);
60
73
  const landmarker = await FaceLandmarker.createFromOptions(fileset, {
61
74
  baseOptions: { modelAssetPath: MODEL_URL2, delegate: "GPU" },
62
75
  canvas,
63
76
  runningMode: "VIDEO",
64
- // One face: this is the user's own camera. More faces is more inference for a result
65
- // the layer above can only use one of.
66
- numFaces: 1,
77
+ // As many as the core tracks: one landmark pass returns them all, so the cost of a second
78
+ // face is the copy below and its own shader passes, not a second inference.
79
+ numFaces: maxFaces,
67
80
  // No blendshapes and no transformation matrix - extra work for data nobody reads.
68
81
  outputFaceBlendshapes: false,
69
82
  outputFacialTransformationMatrixes: false
@@ -71,14 +84,16 @@ async function createFaceDetector(canvas) {
71
84
  return {
72
85
  detect(frame, timestampMs, out) {
73
86
  const res = landmarker.detectForVideo(frame, timestampMs);
74
- const lm = res.faceLandmarks?.[0];
75
- if (!lm || lm.length === 0) return 0;
76
- const n = Math.min(lm.length * 3, out.length);
77
- for (let i = 0; i * 3 < n; i++) {
78
- const p = lm[i];
79
- out[i * 3] = p.x;
80
- out[i * 3 + 1] = p.y;
81
- out[i * 3 + 2] = p.z;
87
+ let n = 0;
88
+ for (const lm of res.faceLandmarks ?? []) {
89
+ if (lm.length * 3 !== FACE_FLOATS || n + FACE_FLOATS > out.length) break;
90
+ for (let i = 0; i < lm.length; i++) {
91
+ const p = lm[i];
92
+ out[n + i * 3] = p.x;
93
+ out[n + i * 3 + 1] = p.y;
94
+ out[n + i * 3 + 2] = p.z;
95
+ }
96
+ n += FACE_FLOATS;
82
97
  }
83
98
  return n;
84
99
  },
@@ -174,7 +189,9 @@ var ZERO_STATS = {
174
189
  needsMask: false,
175
190
  faceFound: false,
176
191
  faceSize: 0,
177
- needsFace: false
192
+ needsFace: false,
193
+ autoExposure: 0,
194
+ faces: 0
178
195
  };
179
196
  var Engine = class _Engine {
180
197
  canvas;
@@ -186,6 +203,8 @@ var Engine = class _Engine {
186
203
  // image background is on costs a fetch plus two createImageBitmap calls, which is a
187
204
  // visible stutter under a dragged finger and the exact case setRecipe exists to make cheap.
188
205
  backgroundPath = null;
206
+ /** The LUT the core holds, by path, so a slider drag does not decode it again. */
207
+ lutPath = "";
189
208
  closed = false;
190
209
  /**
191
210
  * The segmenter loads LAZILY - only once a recipe actually needs a person mask.
@@ -223,11 +242,16 @@ var Engine = class _Engine {
223
242
  canvas.height = height;
224
243
  return _Engine.on(canvas, filter, effects);
225
244
  }
226
- static async on(canvas, filter, effects = NO_EFFECTS) {
245
+ /**
246
+ * `background`: see {@link Engine.setRecipe}. `alpha` keeps the output's alpha channel, which
247
+ * only a `cutout` background writes; it is fixed for the life of the context, so a host that
248
+ * may switch to `cutout` later has to ask for it here.
249
+ */
250
+ static async on(canvas, filter, effects = NO_EFFECTS, background, alpha = false) {
227
251
  const width = canvas.width;
228
252
  const height = canvas.height;
229
253
  const gl = canvas.getContext("webgl2", {
230
- alpha: false,
254
+ alpha,
231
255
  premultipliedAlpha: false,
232
256
  antialias: false,
233
257
  depth: false,
@@ -241,7 +265,7 @@ var Engine = class _Engine {
241
265
  const err = core.init(gl, width, height);
242
266
  if (err) throw new Error(`mediakit: ${err}`);
243
267
  engine = new _Engine(canvas, gl, core);
244
- await engine.setRecipe(filter, effects);
268
+ await engine.setRecipe(filter, effects, background);
245
269
  return engine;
246
270
  } catch (err) {
247
271
  try {
@@ -258,13 +282,21 @@ var Engine = class _Engine {
258
282
  get outputCanvas() {
259
283
  return this.canvas;
260
284
  }
261
- /** Change the recipe without rebuilding the pipeline, so dragging a slider does not flash. */
262
- async setRecipe(filter, effects = this.effects) {
285
+ /**
286
+ * Change the recipe without rebuilding the pipeline, so dragging a slider does not flash.
287
+ *
288
+ * `background` is `filter.imagePath` already decoded, and the Engine takes ownership of it.
289
+ * A worker needs it: there is no `Image` there, so an SVG - every background meet bundles -
290
+ * cannot be decoded at all, and the main thread has to do it and transfer the bitmap.
291
+ */
292
+ async setRecipe(filter, effects = this.effects, background) {
263
293
  if (this.closed) return;
264
294
  this.filter = filter;
265
295
  this.effects = effects;
266
- if (filter.kind === "image" && filter.imagePath !== this.backgroundPath) {
267
- const bmp = await loadBitmap(filter.imagePath, this.canvas.width, this.canvas.height);
296
+ if (filter.kind === "image" && (background || filter.imagePath !== this.backgroundPath)) {
297
+ const w = this.canvas.width;
298
+ const h = this.canvas.height;
299
+ const bmp = background ? await coverCrop(background, w, h) : await loadBitmap(filter.imagePath, w, h);
268
300
  if (this.closed) {
269
301
  bmp.close();
270
302
  return;
@@ -273,20 +305,41 @@ var Engine = class _Engine {
273
305
  this.background = bmp;
274
306
  this.backgroundPath = filter.imagePath;
275
307
  }
308
+ if (effects.lut !== this.lutPath) {
309
+ if (effects.lut) {
310
+ let bmp = null;
311
+ try {
312
+ bmp = await decodeImage(effects.lut, { colorSpaceConversion: "none", premultiplyAlpha: "none" });
313
+ } catch (e) {
314
+ console.error("mediakit: LUT failed to load", e);
315
+ }
316
+ if (this.closed || this.filter !== filter || this.effects !== effects) {
317
+ bmp?.close();
318
+ return;
319
+ }
320
+ this.core.setLut(bmp);
321
+ bmp?.close();
322
+ } else {
323
+ this.core.setLut(null);
324
+ }
325
+ this.lutPath = effects.lut;
326
+ }
276
327
  this.core.setRecipe(coreRecipe(filter, effects));
277
- if (needsMask(filter, effects)) void this.ensureSegmenter();
328
+ if (needsSegmentation(filter, effects)) void this.ensureSegmenter();
278
329
  if (needsFace(effects)) void this.ensureFace();
279
330
  }
280
331
  ensureFace() {
281
332
  if (this.face || this.closed) return Promise.resolve();
282
333
  if (this.faceLoading) return this.faceLoading;
283
- this.faceLoading = createFaceDetector(this.canvas).then((f) => {
334
+ const buf = this.core.faceBuffer();
335
+ if (!buf) return Promise.resolve();
336
+ this.faceLoading = createFaceDetector(this.canvas, Math.max(1, Math.floor(buf.length / FACE_FLOATS))).then((f) => {
284
337
  if (this.closed) {
285
338
  f.close();
286
339
  return;
287
340
  }
288
341
  this.face = f;
289
- this.lmBuf = this.core.faceBuffer();
342
+ this.lmBuf = buf;
290
343
  }).catch((e) => {
291
344
  console.error("mediakit: face detector failed to load", e);
292
345
  }).finally(() => {
@@ -365,7 +418,9 @@ var Engine = class _Engine {
365
418
  needsMask: s ? s[7] > 0.5 : false,
366
419
  faceFound: s ? s[8] > 0.5 : false,
367
420
  faceSize: s ? s[9] : 0,
368
- needsFace: s ? s[10] > 0.5 : false
421
+ needsFace: s ? s[10] > 0.5 : false,
422
+ autoExposure: s ? s[11] : 0,
423
+ faces: s ? s[12] : 0
369
424
  };
370
425
  return glCalls > 0;
371
426
  }
@@ -393,16 +448,17 @@ var Engine = class _Engine {
393
448
  this.background?.close();
394
449
  this.background = null;
395
450
  this.backgroundPath = null;
451
+ this.lutPath = "";
396
452
  this.gl.getExtension("WEBGL_lose_context")?.loseContext();
397
453
  }
398
454
  };
399
- async function decodeImage(path) {
455
+ async function decodeImage(path, opts) {
400
456
  if (typeof Image === "undefined") {
401
457
  const res = await fetch(path);
402
- if (!res.ok) throw new Error(`mediakit: cannot load background image ${path} (HTTP ${res.status})`);
458
+ if (!res.ok) throw new Error(`mediakit: cannot load image ${path} (HTTP ${res.status})`);
403
459
  const blob = await res.blob();
404
460
  try {
405
- return await createImageBitmap(blob);
461
+ return await createImageBitmap(blob, opts);
406
462
  } catch (err) {
407
463
  if (blob.type.includes("svg")) {
408
464
  throw new Error(
@@ -424,10 +480,12 @@ async function decodeImage(path) {
424
480
  `mediakit: background image ${path} has no intrinsic size - an SVG needs width and height, a viewBox alone is not enough`
425
481
  );
426
482
  }
427
- return createImageBitmap(img);
483
+ return createImageBitmap(img, opts);
428
484
  }
429
485
  async function loadBitmap(path, w, h) {
430
- const src = await decodeImage(path);
486
+ return coverCrop(await decodeImage(path), w, h);
487
+ }
488
+ async function coverCrop(src, w, h) {
431
489
  if (src.width * h === src.height * w) return src;
432
490
  const scale = Math.max(w / src.width, h / src.height);
433
491
  const cw = Math.min(src.width, Math.round(w / scale));
@@ -467,6 +525,8 @@ var VideoPipeline = class {
467
525
  // worker path
468
526
  worker = null;
469
527
  workerStats = null;
528
+ /** The background path the worker already holds; see backgroundForWorker. */
529
+ workerBackgroundPath = null;
470
530
  // canvas path
471
531
  video = null;
472
532
  rvfcHandle = 0;
@@ -489,7 +549,7 @@ var VideoPipeline = class {
489
549
  this.stopped = false;
490
550
  if (hasInsertableStreams() && typeof Worker !== "undefined" && typeof OffscreenCanvas !== "undefined") {
491
551
  try {
492
- await this.startWorker(source, width, height);
552
+ await this.startWorker(source, width, height, await this.backgroundForWorker(this.filter));
493
553
  this.transport = "worker";
494
554
  return;
495
555
  } catch (e) {
@@ -517,7 +577,9 @@ var VideoPipeline = class {
517
577
  }
518
578
  async pushRecipe() {
519
579
  if (this.worker) {
520
- this.send({ t: "recipe", filter: this.filter, effects: this.effects });
580
+ const filter = this.filter;
581
+ const background = await this.backgroundForWorker(filter);
582
+ this.send({ t: "recipe", filter, effects: this.effects, background }, background ? [background] : []);
521
583
  return;
522
584
  }
523
585
  await this.engine?.setRecipe(this.filter, this.effects);
@@ -543,6 +605,17 @@ var VideoPipeline = class {
543
605
  this.engine = null;
544
606
  }
545
607
  // ── worker ───────────────────────────────────────────────────────────────────────
608
+ /**
609
+ * The image background decoded HERE, for the worker: it has no `Image`, so it cannot decode
610
+ * an SVG, which is every background meet bundles. Only when the path changed - the worker
611
+ * Engine keeps the last one by path, and a slider drag must not decode it again.
612
+ */
613
+ async backgroundForWorker(filter) {
614
+ if (filter.kind !== "image" || filter.imagePath === this.workerBackgroundPath) return void 0;
615
+ const bmp = await decodeImage(filter.imagePath);
616
+ this.workerBackgroundPath = filter.imagePath;
617
+ return bmp;
618
+ }
546
619
  send(m, transfer = []) {
547
620
  this.worker?.postMessage(m, transfer);
548
621
  }
@@ -552,6 +625,7 @@ var VideoPipeline = class {
552
625
  this.worker.terminate();
553
626
  this.worker = null;
554
627
  this.workerStats = null;
628
+ this.workerBackgroundPath = null;
555
629
  }
556
630
  /**
557
631
  * Give the worker the frame STREAMS, and keep the track on this thread.
@@ -580,7 +654,7 @@ var VideoPipeline = class {
580
654
  * so it is the Chrome dialect. A browser that only has them inside a worker (Safari) does
581
655
  * not get this path and stays on the canvas transport until someone can test that.
582
656
  */
583
- startWorker(source, width, height) {
657
+ startWorker(source, width, height, background) {
584
658
  const processor = new MediaStreamTrackProcessor({ track: source });
585
659
  const generator = new MediaStreamTrackGenerator({
586
660
  kind: "video",
@@ -630,9 +704,10 @@ var VideoPipeline = class {
630
704
  width,
631
705
  height,
632
706
  filter: this.filter,
633
- effects: this.effects
707
+ effects: this.effects,
708
+ background
634
709
  },
635
- [processor.readable, generator.writable]
710
+ background ? [processor.readable, generator.writable, background] : [processor.readable, generator.writable]
636
711
  );
637
712
  } catch (err) {
638
713
  fail(err instanceof Error ? err : new Error(String(err)));
@@ -711,12 +786,426 @@ var VideoPipeline = class {
711
786
  this.rvfcHandle = video.requestVideoFrameCallback(pump);
712
787
  }
713
788
  };
789
+
790
+ // src/scene.ts
791
+ var MAX_SOURCES = 8;
792
+ var Scene = class _Scene {
793
+ canvas;
794
+ core;
795
+ gl;
796
+ sources = /* @__PURE__ */ new Map();
797
+ current = [];
798
+ fps;
799
+ timer = null;
800
+ closed = false;
801
+ recorder = null;
802
+ recorded = [];
803
+ last = { glCalls: 0, frameMs: 0, sources: 0, layers: 0 };
804
+ constructor(canvas, gl, core, fps) {
805
+ this.canvas = canvas;
806
+ this.gl = gl;
807
+ this.core = core;
808
+ this.fps = fps;
809
+ }
810
+ static async create(opts) {
811
+ const canvas = document.createElement("canvas");
812
+ canvas.width = opts.width;
813
+ canvas.height = opts.height;
814
+ const gl = canvas.getContext("webgl2", {
815
+ alpha: false,
816
+ premultipliedAlpha: false,
817
+ antialias: false,
818
+ depth: false,
819
+ stencil: false,
820
+ preserveDrawingBuffer: true
821
+ });
822
+ if (!gl) throw new Error("mediakit: no WebGL2 in this browser");
823
+ let core;
824
+ try {
825
+ core = await loadCore();
826
+ const err = core.sceneInit(gl, opts.width, opts.height);
827
+ if (err) throw new Error(`mediakit: ${err}`);
828
+ } catch (err) {
829
+ core?.sceneClose();
830
+ gl.getExtension("WEBGL_lose_context")?.loseContext();
831
+ throw err;
832
+ }
833
+ const scene = new _Scene(canvas, gl, core, opts.fps ?? 30);
834
+ scene.setBackground(opts.background ?? "#000");
835
+ return scene;
836
+ }
837
+ setBackground(c) {
838
+ const [r, g, b] = parseColor(c);
839
+ this.core.sceneBackground(r, g, b);
840
+ }
841
+ /** Add a source, or replace the one with this id; it keeps its slot, so layers stay put. */
842
+ async addSource(id, spec) {
843
+ if (this.closed) return;
844
+ const old = this.sources.get(id);
845
+ const slot = old ? old.slot : this.freeSlot();
846
+ if (slot < 0) throw new Error(`mediakit: a scene holds at most ${MAX_SOURCES} sources`);
847
+ if (old) this.dispose(old);
848
+ const live = { slot, spec, dirty: false, fresh: false };
849
+ this.sources.set(id, live);
850
+ try {
851
+ await this.open(live);
852
+ } catch (err) {
853
+ this.dispose(live);
854
+ if (this.sources.get(id) === live) {
855
+ this.sources.delete(id);
856
+ this.core.sceneUpload(slot, null, 0, 0);
857
+ }
858
+ throw err;
859
+ }
860
+ if (this.closed || this.sources.get(id) !== live) {
861
+ this.dispose(live);
862
+ return;
863
+ }
864
+ this.push(0);
865
+ }
866
+ /**
867
+ * Change a source without replacing it: new text or style for text, a new recipe for a
868
+ * camera. Anything else is the same as {@link addSource}.
869
+ */
870
+ async updateSource(id, spec) {
871
+ const live = this.sources.get(id);
872
+ if (!live || this.closed) return;
873
+ if (spec.kind === "text" && live.spec.kind === "text") {
874
+ live.spec = spec;
875
+ live.picture = renderText(spec.text, spec.style);
876
+ live.dirty = true;
877
+ return;
878
+ }
879
+ if (spec.kind === "camera" && live.spec.kind === "camera" && spec.track === live.spec.track) {
880
+ live.spec = spec;
881
+ await this.ensureEngine(live);
882
+ return;
883
+ }
884
+ return this.addSource(id, spec);
885
+ }
886
+ removeSource(id) {
887
+ const live = this.sources.get(id);
888
+ if (!live) return;
889
+ this.dispose(live);
890
+ this.sources.delete(id);
891
+ this.core.sceneUpload(live.slot, null, 0, 0);
892
+ this.push(0);
893
+ }
894
+ get layers() {
895
+ return this.current;
896
+ }
897
+ /** Change the layout in place. With `animate` (ms) layers glide to their new state. */
898
+ setLayers(layers, opts = {}) {
899
+ this.current = layers.slice();
900
+ this.push(opts.animate ?? 0);
901
+ }
902
+ /** Move to another layout through a transition. */
903
+ switchTo(layers, transition = { kind: "cut" }) {
904
+ if (this.closed) return;
905
+ this.current = layers.slice();
906
+ const [lo, hi] = splitMicros(now());
907
+ this.core.sceneSwitch(this.coreLayers(), lo, hi, Math.max(0, TRANSITIONS.indexOf(transition.kind)), transition.duration ?? 500);
908
+ }
909
+ /** The topmost layer under a point of the output, in fractions, for picking and dragging. */
910
+ layerAt(x, y) {
911
+ return hitTest(this.current, x, y, this.canvas.width / this.canvas.height);
912
+ }
913
+ start() {
914
+ if (this.timer || this.closed) return;
915
+ const period = 1e3 / this.fps;
916
+ let next = performance.now();
917
+ let failed = false;
918
+ const tick = () => {
919
+ try {
920
+ this.render();
921
+ } catch (err) {
922
+ if (!failed) console.error("mediakit: scene frame failed", err);
923
+ failed = true;
924
+ }
925
+ next += period;
926
+ const t = performance.now();
927
+ if (next < t) next = t;
928
+ this.timer = setTimeout(tick, next - t);
929
+ };
930
+ tick();
931
+ }
932
+ stop() {
933
+ if (this.timer) clearTimeout(this.timer);
934
+ this.timer = null;
935
+ }
936
+ /** Draw one frame now. The loop calls this; a host with its own loop can instead. */
937
+ render() {
938
+ if (this.closed) return 0;
939
+ const t0 = performance.now();
940
+ const us = now();
941
+ for (const live of this.sources.values()) this.feed(live, us);
942
+ const [lo, hi] = splitMicros(us);
943
+ const calls = this.core.sceneRender(lo, hi);
944
+ this.last = { glCalls: calls, frameMs: performance.now() - t0, sources: this.sources.size, layers: this.current.length };
945
+ return calls;
946
+ }
947
+ /** The output as a live stream, for a call, a recorder or a `<video>`. */
948
+ captureStream(fps = this.fps) {
949
+ return this.canvas.captureStream(fps);
950
+ }
951
+ /** The current frame as an image file. */
952
+ snapshot(type = "image/png") {
953
+ return new Promise(
954
+ (resolve, reject) => this.canvas.toBlob((b) => b ? resolve(b) : reject(new Error("mediakit: snapshot failed")), type)
955
+ );
956
+ }
957
+ /** Record the output, optionally with an audio track, until {@link stopRecording}. */
958
+ startRecording(opts = {}) {
959
+ if (this.recorder) return;
960
+ const stream = this.captureStream();
961
+ if (opts.audio) stream.addTrack(opts.audio);
962
+ const rec = new MediaRecorder(stream, { mimeType: opts.mimeType, videoBitsPerSecond: opts.videoBitsPerSecond });
963
+ const chunks = [];
964
+ rec.ondataavailable = (e) => chunks.push(e.data);
965
+ this.recorder = rec;
966
+ this.recorded = chunks;
967
+ rec.start(1e3);
968
+ }
969
+ stopRecording() {
970
+ const rec = this.recorder;
971
+ if (!rec) return Promise.reject(new Error("mediakit: not recording"));
972
+ const chunks = this.recorded;
973
+ this.recorder = null;
974
+ this.recorded = [];
975
+ return new Promise((resolve) => {
976
+ rec.onstop = () => {
977
+ for (const t of rec.stream.getVideoTracks()) t.stop();
978
+ resolve(new Blob(chunks, { type: rec.mimeType }));
979
+ };
980
+ rec.stop();
981
+ });
982
+ }
983
+ close() {
984
+ if (this.closed) return;
985
+ this.stop();
986
+ if (this.recorder && this.recorder.state !== "inactive") this.recorder.stop();
987
+ for (const t of this.recorder?.stream.getVideoTracks() ?? []) t.stop();
988
+ this.recorder = null;
989
+ this.recorded = [];
990
+ for (const live of this.sources.values()) this.dispose(live);
991
+ this.sources.clear();
992
+ this.closed = true;
993
+ this.core.sceneClose();
994
+ this.gl.getExtension("WEBGL_lose_context")?.loseContext();
995
+ }
996
+ freeSlot() {
997
+ const used = new Set([...this.sources.values()].map((s) => s.slot));
998
+ for (let i = 0; i < MAX_SOURCES; i++) if (!used.has(i)) return i;
999
+ return -1;
1000
+ }
1001
+ coreLayers() {
1002
+ return this.current.map((l) => coreLayer(l, (id) => this.sources.get(id)?.slot ?? -1));
1003
+ }
1004
+ push(animateMs) {
1005
+ if (this.closed) return;
1006
+ const [lo, hi] = splitMicros(now());
1007
+ this.core.sceneSet(this.coreLayers(), lo, hi, animateMs);
1008
+ }
1009
+ async open(live) {
1010
+ const s = live.spec;
1011
+ switch (s.kind) {
1012
+ case "camera":
1013
+ case "track":
1014
+ live.video = await playVideo((v) => v.srcObject = new MediaStream([s.track]));
1015
+ watchFrames(live);
1016
+ if (s.kind === "camera") await this.ensureEngine(live);
1017
+ return;
1018
+ case "video":
1019
+ live.video = await playVideo((v) => {
1020
+ v.src = s.url;
1021
+ v.loop = s.loop ?? true;
1022
+ v.crossOrigin = "anonymous";
1023
+ });
1024
+ watchFrames(live);
1025
+ return;
1026
+ case "image":
1027
+ live.picture = "bitmap" in s ? s.bitmap : await decodeImage(s.url);
1028
+ live.dirty = true;
1029
+ return;
1030
+ case "text":
1031
+ live.picture = renderText(s.text, s.style);
1032
+ live.dirty = true;
1033
+ return;
1034
+ case "canvas":
1035
+ live.picture = s.canvas;
1036
+ return;
1037
+ }
1038
+ }
1039
+ /**
1040
+ * Build, update or drop a camera's Engine to match its recipe and its current size. An
1041
+ * Engine is sized at creation, so a camera that changes resolution needs a new one.
1042
+ */
1043
+ async ensureEngine(live) {
1044
+ const s = live.spec;
1045
+ const v = live.video;
1046
+ if (s.kind !== "camera" || !v || live.engineBusy) return;
1047
+ const filter = s.filter ?? { kind: "none" };
1048
+ const effects = s.effects ?? NO_EFFECTS;
1049
+ const wanted = filter.kind !== "none" || active(effects);
1050
+ const w = v.videoWidth;
1051
+ const h = v.videoHeight;
1052
+ const e = live.engine;
1053
+ if (e && wanted && e.outputCanvas.width === w && e.outputCanvas.height === h) {
1054
+ await e.setRecipe(filter, effects);
1055
+ return;
1056
+ }
1057
+ e?.close();
1058
+ live.engine = void 0;
1059
+ if (!wanted || !w || !h) return;
1060
+ live.engineBusy = true;
1061
+ try {
1062
+ const canvas = document.createElement("canvas");
1063
+ canvas.width = w;
1064
+ canvas.height = h;
1065
+ const engine = await Engine.on(canvas, filter, effects, void 0, true);
1066
+ if (this.closed || ![...this.sources.values()].includes(live)) engine.close();
1067
+ else live.engine = engine;
1068
+ } finally {
1069
+ live.engineBusy = false;
1070
+ }
1071
+ if (live.engine && live.spec !== s) await this.ensureEngine(live);
1072
+ }
1073
+ feed(live, us) {
1074
+ const v = live.video;
1075
+ if (v) {
1076
+ if (live.rvfc && !live.fresh || v.readyState < 2 || !v.videoWidth) return;
1077
+ live.fresh = false;
1078
+ const e = live.engine;
1079
+ if (e && (e.outputCanvas.width !== v.videoWidth || e.outputCanvas.height !== v.videoHeight)) {
1080
+ void this.ensureEngine(live);
1081
+ } else if (e && e.render(v, us)) {
1082
+ this.core.sceneUpload(live.slot, e.outputCanvas, e.outputCanvas.width, e.outputCanvas.height);
1083
+ return;
1084
+ }
1085
+ this.core.sceneUpload(live.slot, v, v.videoWidth, v.videoHeight);
1086
+ return;
1087
+ }
1088
+ const p = live.picture;
1089
+ if (!p) return;
1090
+ if (live.spec.kind === "canvas" || live.dirty) {
1091
+ live.dirty = false;
1092
+ this.core.sceneUpload(live.slot, p, p.width, p.height);
1093
+ }
1094
+ }
1095
+ dispose(live) {
1096
+ live.engine?.close();
1097
+ live.engine = void 0;
1098
+ if (live.video) {
1099
+ live.video.pause();
1100
+ live.video.srcObject = null;
1101
+ live.video.removeAttribute("src");
1102
+ live.video.load();
1103
+ live.video = void 0;
1104
+ }
1105
+ const s = live.spec;
1106
+ if (live.picture instanceof ImageBitmap && !(s.kind === "image" && "bitmap" in s)) live.picture.close();
1107
+ live.picture = void 0;
1108
+ }
1109
+ };
1110
+ function now() {
1111
+ return Math.round(performance.now() * 1e3);
1112
+ }
1113
+ function active(e) {
1114
+ const r = coreRecipe({ kind: "none" }, e);
1115
+ return Object.entries(r).some(([k, v]) => k !== "background" && (typeof v === "number" ? v !== 0 : v === true));
1116
+ }
1117
+ async function playVideo(setup) {
1118
+ const v = document.createElement("video");
1119
+ v.muted = true;
1120
+ v.playsInline = true;
1121
+ setup(v);
1122
+ await v.play();
1123
+ return v;
1124
+ }
1125
+ function watchFrames(live) {
1126
+ const v = live.video;
1127
+ if (!v || !("requestVideoFrameCallback" in v)) return;
1128
+ live.rvfc = true;
1129
+ const on = () => {
1130
+ if (live.video !== v) return;
1131
+ live.fresh = true;
1132
+ v.requestVideoFrameCallback(on);
1133
+ };
1134
+ v.requestVideoFrameCallback(on);
1135
+ }
1136
+ function renderText(text, style = {}) {
1137
+ const font = style.font ?? "600 48px sans-serif";
1138
+ const pad = style.padding ?? 16;
1139
+ const c = document.createElement("canvas");
1140
+ const ctx = c.getContext("2d");
1141
+ ctx.font = font;
1142
+ const size = ctx.measureText("M").width * 1.2;
1143
+ const lineH = size * (style.lineHeight ?? 1.25);
1144
+ const lines = [];
1145
+ for (const para of text.split("\n")) {
1146
+ if (!style.maxWidth) {
1147
+ lines.push(para);
1148
+ continue;
1149
+ }
1150
+ let line = "";
1151
+ for (const word of para.split(/\s+/)) {
1152
+ const next = line ? `${line} ${word}` : word;
1153
+ if (line && ctx.measureText(next).width > style.maxWidth) {
1154
+ lines.push(line);
1155
+ line = word;
1156
+ } else line = next;
1157
+ }
1158
+ lines.push(line);
1159
+ }
1160
+ const outline = style.outline?.width ?? 0;
1161
+ const textW = Math.max(1, ...lines.map((l) => ctx.measureText(l).width));
1162
+ c.width = Math.ceil(textW + 2 * pad + 2 * outline);
1163
+ c.height = Math.ceil(lines.length * lineH + 2 * pad + 2 * outline);
1164
+ ctx.font = font;
1165
+ if (style.background !== void 0) {
1166
+ ctx.fillStyle = css(style.background);
1167
+ ctx.beginPath();
1168
+ ctx.roundRect(0, 0, c.width, c.height, style.radius ?? 0);
1169
+ ctx.fill();
1170
+ }
1171
+ const align = style.align ?? "left";
1172
+ ctx.textAlign = align;
1173
+ ctx.textBaseline = "middle";
1174
+ const x = align === "left" ? pad + outline : align === "right" ? c.width - pad - outline : c.width / 2;
1175
+ lines.forEach((line, i) => {
1176
+ const y = pad + outline + lineH * (i + 0.5);
1177
+ if (outline > 0) {
1178
+ ctx.lineWidth = outline * 2;
1179
+ ctx.lineJoin = "round";
1180
+ ctx.strokeStyle = css(style.outline.color);
1181
+ ctx.strokeText(line, x, y);
1182
+ }
1183
+ ctx.fillStyle = css(style.color ?? "#fff");
1184
+ ctx.fillText(line, x, y);
1185
+ });
1186
+ return c;
1187
+ }
1188
+ function css(c) {
1189
+ const [r, g, b, a] = parseColor(c);
1190
+ return `rgba(${Math.round(r * 255)},${Math.round(g * 255)},${Math.round(b * 255)},${a})`;
1191
+ }
714
1192
  export {
1193
+ BLEND_MODES,
715
1194
  Engine,
716
1195
  NO_EFFECTS,
1196
+ Scene,
1197
+ TOUCH_UP,
1198
+ TRANSITIONS,
717
1199
  VideoPipeline,
1200
+ hitTest,
1201
+ layouts,
718
1202
  mediakitSupported,
719
1203
  needsFace,
720
- needsMask
1204
+ needsMask,
1205
+ needsSegmentation,
1206
+ parseColor,
1207
+ renderText,
1208
+ touchUp,
1209
+ touchUpAmount
721
1210
  };
722
1211
  //# sourceMappingURL=index.js.map