Spaces:
Runtime error
Runtime error
File size: 24,944 Bytes
92189dd |
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 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 |
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
DecodedVideo,
ImageFrame,
decodeStream,
} from '@/common/codecs/VideoDecoder';
import {encode as encodeVideo} from '@/common/codecs/VideoEncoder';
import {
Effect,
EffectActionPoint,
EffectFrameContext,
EffectOptions,
} from '@/common/components/video/effects/Effect';
import AllEffects, {
EffectIndex,
Effects,
} from '@/common/components/video/effects/Effects';
import Logger from '@/common/logger/Logger';
import {Mask, SegmentationPoint, Tracklet} from '@/common/tracker/Tracker';
import {streamFile} from '@/common/utils/FileUtils';
import {Stats} from '@/debug/stats/Stats';
import {VIDEO_WATERMARK_TEXT} from '@/demo/DemoConfig';
import CreateFilmstripError from '@/graphql/errors/CreateFilmstripError';
import DrawFrameError from '@/graphql/errors/DrawFrameError';
import WebGLContextError from '@/graphql/errors/WebGLContextError';
import {RLEObject} from '@/jscocotools/mask';
import invariant from 'invariant';
import {CanvasForm} from 'pts';
import {serializeError} from 'serialize-error';
import {
DecodeResponse,
EffectUpdateResponse,
EncodingCompletedResponse,
EncodingStateUpdateResponse,
FilmstripResponse,
FrameUpdateResponse,
PauseRequest,
PlayRequest,
RenderingErrorResponse,
VideoWorkerResponse,
} from './VideoWorkerTypes';
function getEvenlySpacedItems(decodedVideo: DecodedVideo, x: number) {
const p = Math.floor(decodedVideo.numFrames / Math.max(1, x - 1));
const middleFrames = decodedVideo.frames
.slice(p, p * x)
.filter(function (_, i) {
return 0 == i % p;
});
return [
decodedVideo.frames[0],
...middleFrames,
decodedVideo.frames[decodedVideo.numFrames - 1],
];
}
export type FrameInfo = {
tracklet: Tracklet;
mask: Mask;
};
const WATERMARK_BOX_HORIZONTAL_PADDING = 10;
const WATERMARK_BOX_VERTICAL_PADDING = 10;
export type VideoStats = {
fps?: Stats;
videoFps?: Stats;
total?: Stats;
effect0?: Stats;
effect1?: Stats;
frameBmp?: Stats;
maskBmp?: Stats;
memory?: Stats;
};
export default class VideoWorkerContext {
private _canvas: OffscreenCanvas | null = null;
private _stats: VideoStats = {};
private _ctx: OffscreenCanvasRenderingContext2D | null = null;
private _form: CanvasForm | null = null;
private _decodedVideo: DecodedVideo | null = null;
private _frameIndex: number = 0;
private _isPlaying: boolean = false;
private _playbackRAFHandle: number | null = null;
private _playbackTimeoutHandle: NodeJS.Timeout | null = null;
private _isDrawing: boolean = false;
private _glObjects: WebGL2RenderingContext | null = null;
private _glBackground: WebGL2RenderingContext | null = null;
private _canvasHighlights: OffscreenCanvas | null = null;
private _canvasBackground: OffscreenCanvas | null = null;
private _allowAnimation: boolean = false;
private _currentSegmetationPoint: EffectActionPoint | null = null;
private _effects: Effect[];
private _tracklets: Tracklet[] = [];
public get width(): number {
return this._decodedVideo?.width ?? 0;
}
public get height(): number {
return this._decodedVideo?.height ?? 0;
}
public get frameIndex(): number {
return this._frameIndex;
}
public get currentFrame(): VideoFrame | null {
return this._decodedVideo?.frames[this._frameIndex].bitmap ?? null;
}
constructor() {
this._effects = [
AllEffects.Original, // Image as background
AllEffects.Overlay, // Masks on top
];
// Loading watermark fonts. This is going to be async, but by the time of
// video encoding, the fonts should be available.
this._loadWatermarkFonts();
}
private initializeWebGLContext(width: number, height: number): void {
// Given that we use highlight and background effects as layers,
// we need to create two WebGL contexts, one for each set.
// To avoid memory leaks and too many active contexts,
// these contexts must be re-used over the lifecycle of the session.
if (this._canvasHighlights == null && this._glObjects == null) {
this._canvasHighlights = new OffscreenCanvas(width, height);
this._glObjects = this._canvasHighlights.getContext('webgl2');
this._canvasHighlights.addEventListener(
'webglcontextlost',
event => {
event.preventDefault();
this._sendRenderingError(
new WebGLContextError('WebGL context lost.'),
);
},
false,
);
} else if (
this._canvasHighlights != null &&
(this._canvasHighlights.width !== width ||
this._canvasHighlights.height !== height)
) {
// Resize canvas and webgl viewport
this._canvasHighlights.width = width;
this._canvasHighlights.height = height;
if (this._glObjects != null) {
this._glObjects.viewport(0, 0, width, height);
}
}
if (this._canvasBackground == null && this._glBackground == null) {
this._canvasBackground = new OffscreenCanvas(width, height);
this._glBackground = this._canvasBackground.getContext('webgl2');
this._canvasBackground.addEventListener(
'webglcontextlost',
event => {
event.preventDefault();
this._sendRenderingError(
new WebGLContextError('WebGL context lost.'),
);
},
false,
);
} else if (
this._canvasBackground != null &&
(this._canvasBackground.width != width ||
this._canvasBackground.height != height)
) {
// Resize canvas and webgl viewport
this._canvasBackground.width = width;
this._canvasBackground.height = height;
if (this._glBackground != null) {
this._glBackground.viewport(0, 0, width, height);
}
}
}
public setCanvas(canvas: OffscreenCanvas) {
this._canvas = canvas;
this._ctx = canvas.getContext('2d');
if (this._ctx == null) {
throw new Error('could not initialize drawing context');
}
this._form = new CanvasForm(this._ctx);
}
public setSource(src: string) {
this.close();
// Clear state of previous source.
this.updateFrameIndex(0);
this._tracklets = [];
this._decodeVideo(src);
}
public goToFrame(index: number): void {
// Cancel any ongoing render
this._cancelRender();
this.updateFrameIndex(index);
this._playbackRAFHandle = requestAnimationFrame(this._drawFrame.bind(this));
}
public play(): void {
// Video already playing
if (this._isPlaying) {
return;
}
// Cannot playback without frames
if (this._decodedVideo === null) {
throw new Error('no decoded video');
}
const {numFrames, fps} = this._decodedVideo;
const timePerFrame = 1000 / (fps ?? 30);
let startTime: number | null = null;
// The offset frame index compensate for cases where the video playback
// does not start at frame index 0.
const offsetFrameIndex = this._frameIndex;
const updateFrame = (time: number) => {
if (startTime === null) {
startTime = time;
}
this._stats.fps?.begin();
const diff = time - startTime;
const expectedFrame =
(Math.floor(diff / timePerFrame) + offsetFrameIndex) % numFrames;
if (this._frameIndex !== expectedFrame && !this._isDrawing) {
// Update to the next expected frame
this.updateFrameIndex(expectedFrame);
this._drawFrame();
}
this._playbackRAFHandle = requestAnimationFrame(updateFrame);
this._stats.fps?.end();
};
this.updatePlayback(true);
this._playbackRAFHandle = requestAnimationFrame(updateFrame);
}
public pause(): void {
this.updatePlayback(false);
this._cancelRender();
}
public stop(): void {
this.pause();
this.updateFrameIndex(0);
}
public async createFilmstrip(width: number, height: number): Promise<void> {
if (width < 1 || height < 1) {
Logger.warn(
`Cannot create filmstrip because width ${width} or height ${height} is too small.`,
);
return;
}
try {
const canvas = new OffscreenCanvas(width, height);
const ctx = canvas.getContext('2d');
if (this._decodedVideo !== null) {
const scale = canvas.height / this._decodedVideo.height;
const resizeWidth = this._decodedVideo.width * scale;
const spacedFrames = getEvenlySpacedItems(
this._decodedVideo,
Math.ceil(canvas.width / resizeWidth),
);
spacedFrames.forEach((frame, idx) => {
if (frame != null) {
ctx?.drawImage(
frame.bitmap,
resizeWidth * idx,
0,
resizeWidth,
canvas.height,
);
}
});
}
const filmstrip = await createImageBitmap(canvas);
this.sendResponse<FilmstripResponse>(
'filmstrip',
{
filmstrip,
},
[filmstrip],
);
} catch {
this._sendRenderingError(
new CreateFilmstripError('Failed to create filmstrip'),
);
}
}
public async setEffect(
name: keyof Effects,
index: EffectIndex,
options?: EffectOptions,
): Promise<void> {
const effect: Effect = AllEffects[name];
// The effect has changed.
if (this._effects[index] !== effect) {
// Effect changed. Cleanup old effect first. Effects are responsible for
// cleaning up their memory.
await this._effects[index].cleanup();
const offCanvas =
index === EffectIndex.BACKGROUND
? this._canvasBackground
: this._canvasHighlights;
invariant(offCanvas != null, 'need OffscreenCanvas to render effects');
const webglContext =
index === EffectIndex.BACKGROUND ? this._glBackground : this._glObjects;
invariant(webglContext != null, 'need WebGL context to render effects');
// Initialize the effect. This can be used by effects to prepare
// resources needed for rendering. If the video wasn't decoded yet, the
// effect setup will happen in the _decodeVideo function.
if (this._decodedVideo != null) {
await effect.setup({
width: this._decodedVideo.width,
height: this._decodedVideo.height,
canvas: offCanvas,
gl: webglContext,
});
}
}
// Update effect if already set effect was clicked again. This can happen
// when there is a new variant of the effect.
if (options != null) {
// Update effect if already set effect was clicked again. This can happen
// when there is a new variant of the effect.
await effect.update(options);
}
// Notify the frontend about the effect state including its variant.
this.sendResponse<EffectUpdateResponse>('effectUpdate', {
name,
index,
variant: effect.variant,
numVariants: effect.numVariants,
});
this._effects[index] = effect;
this._playbackRAFHandle = requestAnimationFrame(this._drawFrame.bind(this));
}
async encode() {
const decodedVideo = this._decodedVideo;
invariant(
decodedVideo !== null,
'cannot encode video because there is no decoded video available',
);
const canvas = new OffscreenCanvas(this.width, this.height);
const ctx = canvas.getContext('2d', {willReadFrequently: true});
invariant(
ctx !== null,
'cannot encode video because failed to construct offscreen canvas context',
);
const form = new CanvasForm(ctx);
const file = await encodeVideo(
this.width,
this.height,
decodedVideo.frames.length,
this._framesGenerator(decodedVideo, canvas, form),
progress => {
this.sendResponse<EncodingStateUpdateResponse>('encodingStateUpdate', {
progress,
});
},
);
this.sendResponse<EncodingCompletedResponse>(
'encodingCompleted',
{
file,
},
[file],
);
}
private async *_framesGenerator(
decodedVideo: DecodedVideo,
canvas: OffscreenCanvas,
form: CanvasForm,
): AsyncGenerator<ImageFrame, undefined> {
const frames = decodedVideo.frames;
for (let frameIndex = 0; frameIndex < frames.length; ++frameIndex) {
await this._drawFrameImpl(form, frameIndex, true);
const frame = frames[frameIndex];
const videoFrame = new VideoFrame(canvas, {
timestamp: frame.bitmap.timestamp,
});
yield {
bitmap: videoFrame,
timestamp: frame.timestamp,
duration: frame.duration,
};
videoFrame.close();
}
}
public enableStats() {
this._stats.fps = new Stats('fps');
this._stats.videoFps = new Stats('fps', 'V');
this._stats.total = new Stats('ms', 'T');
this._stats.effect0 = new Stats('ms', 'B');
this._stats.effect1 = new Stats('ms', 'H');
this._stats.frameBmp = new Stats('ms', 'F');
this._stats.maskBmp = new Stats('ms', 'M');
this._stats.memory = new Stats('memory');
}
public allowEffectAnimation(
allow: boolean = true,
objectId?: number,
points?: SegmentationPoint[],
) {
if (objectId != null && points != null && points.length) {
const last_point_position = points[points.length - 1];
this._currentSegmetationPoint = {
objectId,
position: [last_point_position[0], last_point_position[1]],
};
}
if (!allow) {
this._currentSegmetationPoint = null;
}
this._allowAnimation = allow;
}
public close(): void {
// Clear any frame content
this._ctx?.reset();
// Close frames of previously decoded video.
this._decodedVideo?.frames.forEach(f => f.bitmap.close());
this._decodedVideo = null;
}
// TRACKER
public updateTracklets(
frameIndex: number,
tracklets: Tracklet[],
shouldGoToFrame: boolean = true,
): void {
this._tracklets = tracklets;
if (shouldGoToFrame) {
this.goToFrame(frameIndex);
}
}
public clearTrackletMasks(tracklet: Tracklet): void {
this._tracklets = this._tracklets.filter(t => t.id != tracklet.id);
}
public clearMasks(): void {
this._tracklets = [];
}
// PRIVATE FUNCTIONS
private sendResponse<T extends VideoWorkerResponse>(
action: T['action'],
message?: Omit<T, 'action'>,
transfer?: Transferable[],
): void {
self.postMessage(
{
action,
...message,
},
{
transfer,
},
);
}
private async _decodeVideo(src: string): Promise<void> {
const canvas = this._canvas;
invariant(canvas != null, 'need canvas to render decoded video');
this.sendResponse('loadstart');
const fileStream = streamFile(src, {
credentials: 'same-origin',
cache: 'no-store',
});
let renderedFirstFrame = false;
this._decodedVideo = await decodeStream(fileStream, async progress => {
const {fps, height, width, numFrames, frames} = progress;
this._decodedVideo = progress;
if (!renderedFirstFrame) {
renderedFirstFrame = true;
canvas.width = width;
canvas.height = height;
// Set WebGL contexts right after the first frame decoded
this.initializeWebGLContext(width, height);
// Initialize effect once first frame was decoded.
for (const [i, effect] of this._effects.entries()) {
const offCanvas =
i === EffectIndex.BACKGROUND
? this._canvasBackground
: this._canvasHighlights;
invariant(offCanvas != null, 'need canvas to render effects');
const webglContext =
i === EffectIndex.BACKGROUND ? this._glBackground : this._glObjects;
invariant(
webglContext != null,
'need WebGL context to render effects',
);
await effect.setup({
width,
height,
canvas: offCanvas,
gl: webglContext,
});
}
// Need to render frame immediately. Cannot go through
// requestAnimationFrame because then rendering this frame would be
// delayed until the full video has finished decoding.
this._drawFrame();
this._stats.videoFps?.updateMaxValue(fps);
this._stats.total?.updateMaxValue(1000 / fps);
this._stats.effect0?.updateMaxValue(1000 / fps);
this._stats.effect1?.updateMaxValue(1000 / fps);
this._stats.frameBmp?.updateMaxValue(1000 / fps);
this._stats.maskBmp?.updateMaxValue(1000 / fps);
}
this.sendResponse<DecodeResponse>('decode', {
totalFrames: numFrames,
numFrames: frames.length,
fps: fps,
width: width,
height: height,
done: false,
});
});
if (!renderedFirstFrame) {
canvas.width = this._decodedVideo.width;
canvas.height = this._decodedVideo.height;
this._drawFrame();
}
this.sendResponse<DecodeResponse>('decode', {
totalFrames: this._decodedVideo.numFrames,
numFrames: this._decodedVideo.frames.length,
fps: this._decodedVideo.fps,
width: this._decodedVideo.width,
height: this._decodedVideo.height,
done: true,
});
}
private _drawFrame(): void {
if (this._canvas !== null && this._form !== null) {
this._drawFrameImpl(this._form, this._frameIndex);
}
}
private async _drawFrameImpl(
form: CanvasForm,
frameIndex: number,
enableWatermark: boolean = false,
step: number = 0,
maxSteps: number = 40,
): Promise<void> {
if (this._decodedVideo === null) {
return;
}
{
this._stats.videoFps?.begin();
this._stats.total?.begin();
this._stats.memory?.begin();
}
try {
const frame = this._decodedVideo.frames[frameIndex];
const {bitmap} = frame;
this._stats.frameBmp?.begin();
// Need to convert VideoFrame to ImageBitmap because Safari can only apply
// globalCompositeOperation on ImageBitmap and fails on VideoFrame. FWIW,
// Chrome treats VideoFrame similarly to ImageBitmap.
const frameBitmap = await createImageBitmap(bitmap);
this._stats.frameBmp?.end();
const masks: Mask[] = [];
const colors: string[] = [];
const tracklets: Tracklet[] = [];
this._tracklets.forEach(tracklet => {
const mask = tracklet.masks[frameIndex];
if (mask != null) {
masks.push(mask);
tracklets.push(tracklet);
colors.push(tracklet.color);
}
});
const effectActionPoint = this._currentSegmetationPoint;
this._stats.maskBmp?.begin();
const effectMaskPromises = masks.map(async ({data, bounds}) => {
return {
bounds,
bitmap: data as RLEObject,
};
});
const effectMasks = await Promise.all(effectMaskPromises);
this._stats.maskBmp?.end();
form.ctx.fillStyle = 'rgba(0, 0, 0, 0)';
form.ctx.fillRect(0, 0, this.width, this.height);
const effectParams: EffectFrameContext = {
frame: frameBitmap,
masks: effectMasks,
maskColors: colors,
frameIndex: frameIndex,
totalFrames: this._decodedVideo.frames.length,
fps: this._decodedVideo.fps,
width: frameBitmap.width,
height: frameBitmap.height,
actionPoint: null,
};
// Allows animation within a single frame.
if (this._allowAnimation && step < maxSteps) {
const animationDuration = 2; // Total duration of the animation in seconds
const progress = step / maxSteps;
const timeParameter = progress * animationDuration;
// Pass dynamic effect params
effectParams.timeParameter = timeParameter;
effectParams.actionPoint = effectActionPoint;
this._processEffects(form, effectParams, tracklets);
// Use RAF to draw frame, and update the display,
// this avoids to wait until the javascript call stack is cleared.
requestAnimationFrame(() =>
this._drawFrameImpl(form, frameIndex, false, step + 1, maxSteps),
);
} else {
this._processEffects(form, effectParams, tracklets);
}
if (enableWatermark) {
this._drawWatermark(form, frameBitmap);
}
// Do not simply drop the JavaScript reference to the ImageBitmap; doing so
// will keep its graphics resource alive until the next time the garbage
// collector runs.
frameBitmap.close();
{
this._stats.videoFps?.end();
this._stats.total?.end();
this._stats.memory?.end();
}
this._isDrawing = false;
} catch {
this._sendRenderingError(new DrawFrameError('Failed to draw frame'));
}
}
private _drawWatermark(form: CanvasForm, frameBitmap: ImageBitmap): void {
const frameWidth = this._canvas?.width || frameBitmap.width;
const frameHeight = this._canvas?.height || frameBitmap.height;
// Font size is either 12 or smaller based on available width
// since the font is not monospaced, we approximate it'll fit 1.5 more characters than monospaced
const approximateFontSize = Math.min(
Math.floor(frameWidth / (VIDEO_WATERMARK_TEXT.length / 1.5)),
12,
);
form.ctx.font = `${approximateFontSize}px "Inter", sans-serif`;
const measureGeneratedBy = form.ctx.measureText(VIDEO_WATERMARK_TEXT);
const textBoxWidth =
measureGeneratedBy.width + 2 * WATERMARK_BOX_HORIZONTAL_PADDING;
const textBoxHeight =
measureGeneratedBy.actualBoundingBoxAscent +
2 * WATERMARK_BOX_VERTICAL_PADDING;
const textBoxX = frameWidth - textBoxWidth;
const textBoxY = frameHeight - textBoxHeight;
form.ctx.fillStyle = 'rgba(0, 0, 0, 0.4)';
form.ctx.beginPath();
form.ctx.roundRect(
Math.round(textBoxX),
Math.round(textBoxY),
Math.round(textBoxWidth),
Math.round(textBoxHeight),
[WATERMARK_BOX_HORIZONTAL_PADDING, 0, 0, 0],
);
form.ctx.fill();
// Always reset the text style because some effects may change text styling in the same ctx
form.ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
form.ctx.textAlign = 'left';
form.ctx.fillText(
VIDEO_WATERMARK_TEXT,
Math.round(textBoxX + WATERMARK_BOX_HORIZONTAL_PADDING),
Math.round(
textBoxY +
WATERMARK_BOX_VERTICAL_PADDING +
measureGeneratedBy.actualBoundingBoxAscent,
),
);
}
private updateFrameIndex(index: number): void {
this._frameIndex = index;
this.sendResponse<FrameUpdateResponse>('frameUpdate', {
index,
});
}
private _loadWatermarkFonts() {
const requiredFonts = [
{
url: '/fonts/Inter-VariableFont.ttf',
format: 'truetype-variations',
},
];
requiredFonts.forEach(requiredFont => {
const fontFace = new FontFace(
'Inter',
`url(${requiredFont.url}) format('${requiredFont.format}')`,
);
fontFace.load().then(font => {
self.fonts.add(font);
});
});
}
private updatePlayback(playing: boolean): void {
if (playing) {
this.sendResponse<PlayRequest>('play');
} else {
this.sendResponse<PauseRequest>('pause');
}
this._isPlaying = playing;
}
private _cancelRender(): void {
if (this._playbackTimeoutHandle !== null) {
clearTimeout(this._playbackTimeoutHandle);
this._playbackTimeoutHandle = null;
}
if (this._playbackRAFHandle !== null) {
cancelAnimationFrame(this._playbackRAFHandle);
this._playbackRAFHandle = null;
}
}
private _sendRenderingError(error: Error): void {
this.sendResponse<RenderingErrorResponse>('renderingError', {
error: serializeError(error),
});
}
private _processEffects(
form: CanvasForm,
effectParams: EffectFrameContext,
tracklets: Tracklet[],
) {
for (let i = 0; i < this._effects.length; i++) {
const effect = this._effects[i];
if (i === 0) {
this._stats.effect0?.begin();
} else if (i === 1) {
this._stats.effect1?.begin();
}
effect.apply(form, effectParams, tracklets);
if (i === 0) {
this._stats.effect0?.end();
} else if (i === 1) {
this._stats.effect1?.end();
}
}
}
}
|