@tradalab/mediakit 1.1.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
@@ -4,9 +4,18 @@ import {
4
4
  coreRecipe,
5
5
  needsFace,
6
6
  needsMask,
7
+ needsSegmentation,
7
8
  touchUp,
8
9
  touchUpAmount
9
- } from "./chunk-XLLQ74JA.js";
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";
10
19
 
11
20
  // src/segmenter.ts
12
21
  import { FilesetResolver, ImageSegmenter } from "@mediapipe/tasks-vision";
@@ -233,12 +242,16 @@ var Engine = class _Engine {
233
242
  canvas.height = height;
234
243
  return _Engine.on(canvas, filter, effects);
235
244
  }
236
- /** `background`: see {@link Engine.setRecipe}. */
237
- static async on(canvas, filter, effects = NO_EFFECTS, background) {
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) {
238
251
  const width = canvas.width;
239
252
  const height = canvas.height;
240
253
  const gl = canvas.getContext("webgl2", {
241
- alpha: false,
254
+ alpha,
242
255
  premultipliedAlpha: false,
243
256
  antialias: false,
244
257
  depth: false,
@@ -312,7 +325,7 @@ var Engine = class _Engine {
312
325
  this.lutPath = effects.lut;
313
326
  }
314
327
  this.core.setRecipe(coreRecipe(filter, effects));
315
- if (needsMask(filter, effects)) void this.ensureSegmenter();
328
+ if (needsSegmentation(filter, effects)) void this.ensureSegmenter();
316
329
  if (needsFace(effects)) void this.ensureFace();
317
330
  }
318
331
  ensureFace() {
@@ -773,14 +786,425 @@ var VideoPipeline = class {
773
786
  this.rvfcHandle = video.requestVideoFrameCallback(pump);
774
787
  }
775
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
+ }
776
1192
  export {
1193
+ BLEND_MODES,
777
1194
  Engine,
778
1195
  NO_EFFECTS,
1196
+ Scene,
779
1197
  TOUCH_UP,
1198
+ TRANSITIONS,
780
1199
  VideoPipeline,
1200
+ hitTest,
1201
+ layouts,
781
1202
  mediakitSupported,
782
1203
  needsFace,
783
1204
  needsMask,
1205
+ needsSegmentation,
1206
+ parseColor,
1207
+ renderText,
784
1208
  touchUp,
785
1209
  touchUpAmount
786
1210
  };