@tradalab/mediakit 1.1.0 → 1.3.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/worker.js CHANGED
@@ -3993,12 +3993,15 @@
3993
3993
 
3994
3994
  // src/segmenter.ts
3995
3995
  var WASM_DIR = "/mediakit/mp";
3996
- var MODEL_URL = "/mediakit/selfie_segmenter.tflite";
3997
- async function createSegmenter(canvas) {
3996
+ var MODEL_URL = {
3997
+ person: "/mediakit/selfie_segmenter.tflite",
3998
+ classes: "/mediakit/selfie_multiclass_256x256.tflite"
3999
+ };
4000
+ async function createSegmenter(canvas, model = "person") {
3998
4001
  const fileset = await Xo.forVisionTasks(WASM_DIR);
3999
4002
  const segmenter = await Uh.createFromOptions(fileset, {
4000
4003
  baseOptions: {
4001
- modelAssetPath: MODEL_URL,
4004
+ modelAssetPath: MODEL_URL[model],
4002
4005
  // MediaPipe's GPU delegate runs on WebGL2, which Chrome, Safari and Firefox all
4003
4006
  // have. That is why mediakit picked MediaPipe over ONNX Runtime Web at P1: ORT's
4004
4007
  // fast path is WebGPU, which Firefox only has on Windows.
@@ -4165,32 +4168,73 @@
4165
4168
  blushColor: [0.9, 0.5, 0.42],
4166
4169
  iris: 0,
4167
4170
  irisColor: [0.3, 0.5, 0.75],
4171
+ eyeShadow: 0,
4172
+ eyeShadowColor: [0.55, 0.42, 0.37],
4173
+ lipGloss: 0,
4174
+ rosy: 0,
4175
+ rosyColor: [0.9, 0.42, 0.49],
4176
+ whiten: 0,
4177
+ skinLight: 0,
4178
+ clarity: 0,
4179
+ skinScope: "person",
4168
4180
  lut: "",
4169
4181
  grade: 0,
4182
+ gradeScope: "frame",
4183
+ chromaKey: false,
4184
+ keyColor: [0, 0, 0],
4185
+ keyTolerance: 0,
4170
4186
  autoLight: false,
4187
+ mirror: false,
4171
4188
  slimFace: 0,
4172
4189
  enlargeEyes: 0,
4173
4190
  noseSlim: 0,
4174
- chin: 0
4191
+ chin: 0,
4192
+ jaw: 0,
4193
+ cheekbone: 0,
4194
+ forehead: 0,
4195
+ brow: 0,
4196
+ browColor: [0.36, 0.27, 0.22],
4197
+ contour: 0,
4198
+ highlight: 0,
4199
+ makeupTexture: "",
4200
+ makeup: 0,
4201
+ makeupBlend: "softLight",
4202
+ whitenStyle: "natural"
4175
4203
  };
4176
4204
  var MODE_NONE = 0;
4177
4205
  var MODE_BLUR = 1;
4178
4206
  var MODE_IMAGE = 2;
4207
+ var MODE_CUTOUT = 3;
4208
+ var SKIN_SCOPE = { person: 0, face: 1 };
4209
+ var MAKEUP_BLEND = { softLight: 0, multiply: 1, overlay: 2, hardLight: 3, normal: 4 };
4210
+ var GRADE_SCOPE = { frame: 0, person: 1, skin: 2 };
4179
4211
  function backgroundMode(f2) {
4180
4212
  switch (f2.kind) {
4181
4213
  case "blur":
4182
4214
  return MODE_BLUR;
4183
4215
  case "image":
4184
4216
  return MODE_IMAGE;
4217
+ case "cutout":
4218
+ return MODE_CUTOUT;
4185
4219
  default:
4186
4220
  return MODE_NONE;
4187
4221
  }
4188
4222
  }
4189
4223
  function needsMask(f2, e2) {
4190
- return f2.kind !== "none" || e2.beautify > 0 || e2.autoframe;
4224
+ return f2.kind !== "none" || e2.beautify > 0 || e2.autoframe || hasSkin(e2) || e2.grade > 0 && (e2.gradeScope ?? "frame") !== "frame";
4225
+ }
4226
+ function hasSkin(e2) {
4227
+ return (e2.whiten ?? 0) > 0 || (e2.skinLight ?? 0) > 0 || (e2.clarity ?? 0) > 0;
4228
+ }
4229
+ function needsSegmentation(f2, e2) {
4230
+ return needsMask(f2, e2) && !e2.chromaKey;
4231
+ }
4232
+ function needsSkinClasses(_f, e2) {
4233
+ return (e2.whiten ?? 0) > 0 || (e2.skinLight ?? 0) > 0 || e2.grade > 0 && (e2.gradeScope ?? "frame") !== "frame";
4191
4234
  }
4192
4235
  function needsFace(e2) {
4193
- return e2.teeth > 0 || e2.eyeBright > 0 || e2.underEye > 0 || e2.smileLines > 0 || e2.lips > 0 || e2.blush > 0 || e2.iris > 0 || e2.slimFace > 0 || e2.enlargeEyes > 0 || e2.noseSlim > 0 || e2.chin !== 0;
4236
+ return e2.teeth > 0 || e2.eyeBright > 0 || e2.underEye > 0 || e2.smileLines > 0 || e2.lips > 0 || e2.blush > 0 || e2.iris > 0 || (e2.eyeShadow ?? 0) > 0 || (e2.lipGloss ?? 0) > 0 || (e2.rosy ?? 0) > 0 || e2.skinScope === "face" && (e2.beautify > 0 || hasSkin(e2)) || // Whitening and skin light measure skin on the face; clarity is held to it.
4237
+ hasSkin(e2) || e2.grade > 0 && e2.gradeScope === "skin" || e2.slimFace > 0 || e2.enlargeEyes > 0 || e2.noseSlim > 0 || e2.chin !== 0 || (e2.jaw ?? 0) > 0 || (e2.cheekbone ?? 0) > 0 || (e2.forehead ?? 0) !== 0 || (e2.brow ?? 0) > 0 || (e2.contour ?? 0) > 0 || (e2.highlight ?? 0) > 0 || (e2.makeup ?? 0) > 0 && !!e2.makeupTexture;
4194
4238
  }
4195
4239
  function coreRecipe(f2, e2) {
4196
4240
  return {
@@ -4212,12 +4256,36 @@
4212
4256
  blushColor: e2.blushColor,
4213
4257
  iris: e2.iris,
4214
4258
  irisColor: e2.irisColor,
4259
+ eyeShadow: e2.eyeShadow ?? 0,
4260
+ eyeShadowColor: e2.eyeShadowColor ?? NO_EFFECTS.eyeShadowColor,
4261
+ lipGloss: e2.lipGloss ?? 0,
4262
+ rosy: e2.rosy ?? 0,
4263
+ rosyColor: e2.rosyColor ?? NO_EFFECTS.rosyColor,
4264
+ whiten: e2.whiten ?? 0,
4265
+ skinLight: e2.skinLight ?? 0,
4266
+ clarity: e2.clarity ?? 0,
4267
+ skinScope: SKIN_SCOPE[e2.skinScope] ?? 0,
4215
4268
  grade: e2.grade,
4269
+ gradeScope: GRADE_SCOPE[e2.gradeScope] ?? 0,
4270
+ chromaKey: e2.chromaKey,
4271
+ keyColor: e2.keyColor,
4272
+ keyTolerance: e2.keyTolerance,
4216
4273
  autoLight: e2.autoLight,
4274
+ mirror: e2.mirror,
4217
4275
  slimFace: e2.slimFace,
4218
4276
  enlargeEyes: e2.enlargeEyes,
4219
4277
  noseSlim: e2.noseSlim,
4220
- chin: e2.chin
4278
+ chin: e2.chin,
4279
+ jaw: e2.jaw ?? 0,
4280
+ cheekbone: e2.cheekbone ?? 0,
4281
+ forehead: e2.forehead ?? 0,
4282
+ brow: e2.brow ?? 0,
4283
+ browColor: e2.browColor ?? NO_EFFECTS.browColor,
4284
+ contour: e2.contour ?? 0,
4285
+ highlight: e2.highlight ?? 0,
4286
+ makeup: e2.makeupTexture ? e2.makeup ?? 0 : 0,
4287
+ makeupBlend: MAKEUP_BLEND[e2.makeupBlend] ?? 0,
4288
+ whitenStyle: e2.whitenStyle === "pink" ? 1 : 0
4221
4289
  };
4222
4290
  }
4223
4291
 
@@ -4251,6 +4319,10 @@
4251
4319
  backgroundPath = null;
4252
4320
  /** The LUT the core holds, by path, so a slider drag does not decode it again. */
4253
4321
  lutPath = "";
4322
+ /** The makeup texture the core holds, by path - see setRecipe. */
4323
+ makeupPath = "";
4324
+ /** Whether the core holds the pink whitening table. */
4325
+ skinLutState = "none";
4254
4326
  closed = false;
4255
4327
  /**
4256
4328
  * The segmenter loads LAZILY - only once a recipe actually needs a person mask.
@@ -4260,6 +4332,11 @@
4260
4332
  */
4261
4333
  segmenter = null;
4262
4334
  segmenterLoading = null;
4335
+ /** The multiclass segmenter, for recipes that tell skin from clothes (`needsSkinClasses`). */
4336
+ classSegmenter = null;
4337
+ classLoading = null;
4338
+ /** The segmenter whose result this frame borrowed, to give it back after process(). */
4339
+ used = null;
4263
4340
  /**
4264
4341
  * The landmark detector, also lazy and independent of the segmenter.
4265
4342
  *
@@ -4282,18 +4359,22 @@
4282
4359
  this.core = core;
4283
4360
  }
4284
4361
  /** Main thread: makes its own canvas. A worker calls `on` with an OffscreenCanvas. */
4285
- static async create(width, height, filter, effects = NO_EFFECTS) {
4362
+ static async create(width, height, filter, effects = NO_EFFECTS, alpha = false) {
4286
4363
  const canvas = document.createElement("canvas");
4287
4364
  canvas.width = width;
4288
4365
  canvas.height = height;
4289
- return _Engine.on(canvas, filter, effects);
4366
+ return _Engine.on(canvas, filter, effects, void 0, alpha);
4290
4367
  }
4291
- /** `background`: see {@link Engine.setRecipe}. */
4292
- static async on(canvas, filter, effects = NO_EFFECTS, background) {
4368
+ /**
4369
+ * `background`: see {@link Engine.setRecipe}. `alpha` keeps the output's alpha channel, which
4370
+ * only a `cutout` background writes; it is fixed for the life of the context, so a host that
4371
+ * may switch to `cutout` later has to ask for it here.
4372
+ */
4373
+ static async on(canvas, filter, effects = NO_EFFECTS, background, alpha = false) {
4293
4374
  const width = canvas.width;
4294
4375
  const height = canvas.height;
4295
4376
  const gl = canvas.getContext("webgl2", {
4296
- alpha: false,
4377
+ alpha,
4297
4378
  premultipliedAlpha: false,
4298
4379
  antialias: false,
4299
4380
  depth: false,
@@ -4321,6 +4402,9 @@
4321
4402
  throw err;
4322
4403
  }
4323
4404
  }
4405
+ get loading() {
4406
+ return this.segmenterLoading !== null || this.classLoading !== null || this.faceLoading !== null;
4407
+ }
4324
4408
  get outputCanvas() {
4325
4409
  return this.canvas;
4326
4410
  }
@@ -4366,8 +4450,44 @@
4366
4450
  }
4367
4451
  this.lutPath = effects.lut;
4368
4452
  }
4453
+ if (effects.whitenStyle === "pink" && this.skinLutState === "none") {
4454
+ this.skinLutState = "loading";
4455
+ decodeImage("/mediakit/whiten_pink.png", { colorSpaceConversion: "none", premultiplyAlpha: "none" }).then((bmp) => {
4456
+ if (this.closed) {
4457
+ bmp.close();
4458
+ return;
4459
+ }
4460
+ this.core.setSkinLut(bmp);
4461
+ bmp.close();
4462
+ this.skinLutState = "ready";
4463
+ }).catch((err) => {
4464
+ console.error("mediakit: pink whitening table failed to load", err);
4465
+ this.skinLutState = "failed";
4466
+ });
4467
+ }
4468
+ const makeupTexture = effects.makeupTexture ?? "";
4469
+ if (makeupTexture !== this.makeupPath) {
4470
+ if (makeupTexture) {
4471
+ let bmp = null;
4472
+ try {
4473
+ bmp = await decodeImage(makeupTexture, { premultiplyAlpha: "none" });
4474
+ } catch (e2) {
4475
+ console.error("mediakit: makeup texture failed to load", e2);
4476
+ }
4477
+ if (this.closed || this.filter !== filter || this.effects !== effects) {
4478
+ bmp?.close();
4479
+ return;
4480
+ }
4481
+ this.core.setMakeup(bmp);
4482
+ bmp?.close();
4483
+ } else {
4484
+ this.core.setMakeup(null);
4485
+ }
4486
+ this.makeupPath = makeupTexture;
4487
+ }
4369
4488
  this.core.setRecipe(coreRecipe(filter, effects));
4370
- if (needsMask(filter, effects)) void this.ensureSegmenter();
4489
+ if (needsSegmentation(filter, effects)) void this.ensureSegmenter();
4490
+ if (needsSkinClasses(filter, effects)) void this.ensureClassSegmenter();
4371
4491
  if (needsFace(effects)) void this.ensureFace();
4372
4492
  }
4373
4493
  ensureFace() {
@@ -4389,6 +4509,22 @@
4389
4509
  });
4390
4510
  return this.faceLoading;
4391
4511
  }
4512
+ ensureClassSegmenter() {
4513
+ if (this.classSegmenter || this.closed) return Promise.resolve();
4514
+ if (this.classLoading) return this.classLoading;
4515
+ this.classLoading = createSegmenter(this.canvas, "classes").then((s2) => {
4516
+ if (this.closed) {
4517
+ s2.close();
4518
+ return;
4519
+ }
4520
+ this.classSegmenter = s2;
4521
+ }).catch((e2) => {
4522
+ console.error("mediakit: multiclass segmenter failed to load", e2);
4523
+ }).finally(() => {
4524
+ this.classLoading = null;
4525
+ });
4526
+ return this.classLoading;
4527
+ }
4392
4528
  ensureSegmenter() {
4393
4529
  if (this.segmenter || this.closed) return Promise.resolve();
4394
4530
  if (this.segmenterLoading) return this.segmenterLoading;
@@ -4424,14 +4560,20 @@
4424
4560
  const [lo2, hi2] = splitMicros(timestampUs);
4425
4561
  const needSeg = this.core.decide(lo2, hi2, this.prevTotalMs, this.prevSegMs) === 1;
4426
4562
  let mask = null;
4563
+ let maskKind = 0;
4427
4564
  let segMs = 0;
4565
+ this.used = null;
4428
4566
  if (needSeg) {
4429
- if (!this.segmenter) {
4567
+ const classes = this.classSegmenter !== null && needsSkinClasses(this.filter, this.effects);
4568
+ const seg = classes ? this.classSegmenter : this.segmenter;
4569
+ if (!seg) {
4430
4570
  void this.ensureSegmenter();
4431
4571
  } else {
4432
4572
  const s0 = performance.now();
4433
- mask = this.segmenter.segment(source, timestampUs / 1e3);
4573
+ mask = seg.segment(source, timestampUs / 1e3);
4434
4574
  segMs = performance.now() - s0;
4575
+ this.used = seg;
4576
+ maskKind = classes ? 1 : 0;
4435
4577
  }
4436
4578
  }
4437
4579
  if (this.core.decideFace() === 1) {
@@ -4442,8 +4584,9 @@
4442
4584
  this.core.setFace(lo2, hi2, n2);
4443
4585
  }
4444
4586
  }
4445
- const glCalls = this.core.process(source, mask, this.background);
4446
- if (mask) this.segmenter?.release();
4587
+ const glCalls = this.core.process(source, mask, this.background, maskKind);
4588
+ if (mask) this.used?.release();
4589
+ this.used = null;
4447
4590
  this.prevSegMs = segMs;
4448
4591
  this.prevTotalMs = performance.now() - t0;
4449
4592
  const s2 = this.core.stats();
@@ -4475,14 +4618,16 @@
4475
4618
  * for the governor and the graph to decide with. See the ToMicros comment in
4476
4619
  * `core/clock.go`.
4477
4620
  */
4478
- capture(timestampUs) {
4479
- return new VideoFrame(this.canvas, { timestamp: timestampUs, alpha: "discard" });
4621
+ capture(timestampUs, keepAlpha = false) {
4622
+ return new VideoFrame(this.canvas, { timestamp: timestampUs, alpha: keepAlpha ? "keep" : "discard" });
4480
4623
  }
4481
4624
  close() {
4482
4625
  if (this.closed) return;
4483
4626
  this.closed = true;
4484
4627
  this.segmenter?.close();
4485
4628
  this.segmenter = null;
4629
+ this.classSegmenter?.close();
4630
+ this.classSegmenter = null;
4486
4631
  this.face?.close();
4487
4632
  this.face = null;
4488
4633
  this.lmBuf = null;
@@ -4491,6 +4636,7 @@
4491
4636
  this.background = null;
4492
4637
  this.backgroundPath = null;
4493
4638
  this.lutPath = "";
4639
+ this.makeupPath = "";
4494
4640
  this.gl.getExtension("WEBGL_lose_context")?.loseContext();
4495
4641
  }
4496
4642
  };
@@ -4548,14 +4694,38 @@
4548
4694
  var post = (m2) => self.postMessage(m2);
4549
4695
  var engine = null;
4550
4696
  var abort = null;
4697
+ var framesOn = false;
4551
4698
  async function start(m2) {
4699
+ await run(m2, m2.readable, m2.writable);
4700
+ }
4701
+ async function startTrack(m2) {
4702
+ const g2 = globalThis;
4703
+ if (!g2.MediaStreamTrackProcessor || !g2.VideoTrackGenerator) {
4704
+ m2.track.stop();
4705
+ throw new Error("mediakit: this worker has no MediaStreamTrackProcessor / VideoTrackGenerator");
4706
+ }
4707
+ const processor = new g2.MediaStreamTrackProcessor({ track: m2.track });
4708
+ const generator = new g2.VideoTrackGenerator();
4709
+ await run(m2, processor.readable, generator.writable, generator.track);
4710
+ }
4711
+ async function run(m2, readable, writable, outTrack) {
4552
4712
  const canvas = new OffscreenCanvas(m2.width, m2.height);
4553
- engine = await Engine.on(canvas, m2.filter, m2.effects, m2.background);
4713
+ engine = await Engine.on(canvas, m2.filter, m2.effects, m2.background, m2.alpha ?? false);
4554
4714
  abort = new AbortController();
4555
4715
  let n2 = 0;
4716
+ let lastPost = performance.now();
4717
+ let lastLoading = engine.loading;
4556
4718
  const transform = new TransformStream({
4557
4719
  transform: (frame, controller) => {
4558
4720
  const ts2 = frame.timestamp ?? 0;
4721
+ n2++;
4722
+ const now = performance.now();
4723
+ const loading = engine?.loading ?? false;
4724
+ if (engine && (now - lastPost >= 500 || loading !== lastLoading)) {
4725
+ lastPost = now;
4726
+ lastLoading = loading;
4727
+ post({ t: "stats", stats: engine.last, frames: n2, loading });
4728
+ }
4559
4729
  let drew = false;
4560
4730
  try {
4561
4731
  drew = engine?.render(frame, ts2) ?? false;
@@ -4563,16 +4733,28 @@
4563
4733
  post({ t: "error", message: e2 instanceof Error ? e2.message : String(e2) });
4564
4734
  }
4565
4735
  if (!drew || !engine) {
4736
+ if (framesOn) {
4737
+ const copy = frame.clone();
4738
+ self.postMessage({ t: "frame", frame: copy }, [copy]);
4739
+ }
4566
4740
  controller.enqueue(frame);
4567
4741
  return;
4568
4742
  }
4569
4743
  controller.enqueue(engine.capture(ts2));
4744
+ if (framesOn) {
4745
+ const copy = engine.capture(ts2, true);
4746
+ self.postMessage({ t: "frame", frame: copy }, [copy]);
4747
+ }
4570
4748
  frame.close();
4571
- if (++n2 % 15 === 0) post({ t: "stats", stats: engine.last });
4572
4749
  }
4573
4750
  });
4574
- post({ t: "ready" });
4575
- void m2.readable.pipeThrough(transform, { signal: abort.signal }).pipeTo(m2.writable, { signal: abort.signal }).catch((e2) => {
4751
+ if (outTrack) {
4752
+ ;
4753
+ self.postMessage({ t: "ready", track: outTrack, loading: engine.loading }, [outTrack]);
4754
+ } else {
4755
+ post({ t: "ready", loading: engine.loading });
4756
+ }
4757
+ void readable.pipeThrough(transform, { signal: abort.signal }).pipeTo(writable, { signal: abort.signal }).catch((e2) => {
4576
4758
  if (abort?.signal.aborted) return;
4577
4759
  post({ t: "error", message: e2 instanceof Error ? e2.message : String(e2) });
4578
4760
  });
@@ -4586,12 +4768,16 @@
4586
4768
  self.onmessage = (e2) => {
4587
4769
  const m2 = e2.data;
4588
4770
  try {
4589
- if (m2.t === "start") {
4590
- void start(m2).catch((err) => {
4771
+ if (m2.t === "start" || m2.t === "startTrack") {
4772
+ void (m2.t === "start" ? start(m2) : startTrack(m2)).catch((err) => {
4591
4773
  post({ t: "error", message: err instanceof Error ? err.message : String(err) });
4592
4774
  });
4775
+ } else if (m2.t === "frames") {
4776
+ framesOn = m2.on;
4593
4777
  } else if (m2.t === "recipe") {
4594
- engine?.setRecipe(m2.filter, m2.effects ?? NO_EFFECTS, m2.background).catch((err) => {
4778
+ engine?.setRecipe(m2.filter, m2.effects ?? NO_EFFECTS, m2.background).then(() => {
4779
+ if (engine?.loading) post({ t: "stats", stats: engine.last, frames: -1, loading: true });
4780
+ }).catch((err) => {
4595
4781
  post({ t: "error", message: err instanceof Error ? err.message : String(err) });
4596
4782
  });
4597
4783
  } else {