UNPKG

libpag

Version:
1,522 lines (1,496 loc) 314 kB
///////////////////////////////////////////////////////////////////////////////////////////////// // // Tencent is pleased to support the open source community by making libpag available. // // Copyright (C) 2025 Tencent. All rights reserved. // // 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. // ///////////////////////////////////////////////////////////////////////////////////////////////// (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.libpag = {})); })(this, (function (exports) { 'use strict'; const getGlobalObject = () => { if (typeof globalThis !== "undefined") { return globalThis; } if (typeof window !== "undefined") { return window; } if (typeof global !== "undefined") { return global; } if (typeof self !== "undefined") { return self; } throw new Error("unable to locate global object"); }; const globalObject = getGlobalObject(); if (typeof globalObject.globalThis === "undefined") { Object.defineProperty(globalObject, "globalThis", { get() { return globalObject; } }); } let PAGModule; const setPAGModule = (module) => { PAGModule = module; }; function destroyVerify$1(constructor) { let functions = Object.getOwnPropertyNames(constructor.prototype).filter( (name) => name !== "constructor" && typeof constructor.prototype[name] === "function" ); const proxyFn = (target, methodName) => { const fn = target[methodName]; target[methodName] = function(...args) { if (this["isDestroyed"]) { console.error(`Don't call ${methodName} of the ${constructor.name} that is destroyed.`); return; } return fn.call(this, ...args); }; }; functions.forEach((name) => proxyFn(constructor.prototype, name)); } var PAGScaleMode = /* @__PURE__ */ ((PAGScaleMode2) => { PAGScaleMode2[PAGScaleMode2["None"] = 0] = "None"; PAGScaleMode2[PAGScaleMode2["Stretch"] = 1] = "Stretch"; PAGScaleMode2[PAGScaleMode2["LetterBox"] = 2] = "LetterBox"; PAGScaleMode2[PAGScaleMode2["Zoom"] = 3] = "Zoom"; return PAGScaleMode2; })(PAGScaleMode || {}); var PAGViewListenerEvent = /* @__PURE__ */ ((PAGViewListenerEvent2) => { PAGViewListenerEvent2["onAnimationStart"] = "onAnimationStart"; PAGViewListenerEvent2["onAnimationEnd"] = "onAnimationEnd"; PAGViewListenerEvent2["onAnimationCancel"] = "onAnimationCancel"; PAGViewListenerEvent2["onAnimationRepeat"] = "onAnimationRepeat"; PAGViewListenerEvent2["onAnimationUpdate"] = "onAnimationUpdate"; PAGViewListenerEvent2["onAnimationPlay"] = "onAnimationPlay"; PAGViewListenerEvent2["onAnimationPause"] = "onAnimationPause"; PAGViewListenerEvent2["onAnimationFlushed"] = "onAnimationFlushed"; return PAGViewListenerEvent2; })(PAGViewListenerEvent || {}); var ParagraphJustification = /* @__PURE__ */ ((ParagraphJustification2) => { ParagraphJustification2[ParagraphJustification2["LeftJustify"] = 0] = "LeftJustify"; ParagraphJustification2[ParagraphJustification2["CenterJustify"] = 1] = "CenterJustify"; ParagraphJustification2[ParagraphJustification2["RightJustify"] = 2] = "RightJustify"; ParagraphJustification2[ParagraphJustification2["FullJustifyLastLineLeft"] = 3] = "FullJustifyLastLineLeft"; ParagraphJustification2[ParagraphJustification2["FullJustifyLastLineRight"] = 4] = "FullJustifyLastLineRight"; ParagraphJustification2[ParagraphJustification2["FullJustifyLastLineCenter"] = 5] = "FullJustifyLastLineCenter"; ParagraphJustification2[ParagraphJustification2["FullJustifyLastLineFull"] = 6] = "FullJustifyLastLineFull"; return ParagraphJustification2; })(ParagraphJustification || {}); var TextDirection = /* @__PURE__ */ ((TextDirection2) => { TextDirection2[TextDirection2["Default"] = 0] = "Default"; TextDirection2[TextDirection2["Horizontal"] = 1] = "Horizontal"; TextDirection2[TextDirection2["Vertical"] = 2] = "Vertical"; return TextDirection2; })(TextDirection || {}); var LayerType = /* @__PURE__ */ ((LayerType2) => { LayerType2[LayerType2["Unknown"] = 0] = "Unknown"; LayerType2[LayerType2["Null"] = 1] = "Null"; LayerType2[LayerType2["Solid"] = 2] = "Solid"; LayerType2[LayerType2["Text"] = 3] = "Text"; LayerType2[LayerType2["Shape"] = 4] = "Shape"; LayerType2[LayerType2["Image"] = 5] = "Image"; LayerType2[LayerType2["PreCompose"] = 6] = "PreCompose"; return LayerType2; })(LayerType || {}); var PAGTimeStretchMode = /* @__PURE__ */ ((PAGTimeStretchMode2) => { PAGTimeStretchMode2[PAGTimeStretchMode2["None"] = 0] = "None"; PAGTimeStretchMode2[PAGTimeStretchMode2["Scale"] = 1] = "Scale"; PAGTimeStretchMode2[PAGTimeStretchMode2["Repeat"] = 2] = "Repeat"; PAGTimeStretchMode2[PAGTimeStretchMode2["RepeatInverted"] = 3] = "RepeatInverted"; return PAGTimeStretchMode2; })(PAGTimeStretchMode || {}); var MatrixIndex$1 = /* @__PURE__ */ ((MatrixIndex2) => { MatrixIndex2[MatrixIndex2["a"] = 0] = "a"; MatrixIndex2[MatrixIndex2["c"] = 1] = "c"; MatrixIndex2[MatrixIndex2["tx"] = 2] = "tx"; MatrixIndex2[MatrixIndex2["b"] = 3] = "b"; MatrixIndex2[MatrixIndex2["d"] = 4] = "d"; MatrixIndex2[MatrixIndex2["ty"] = 5] = "ty"; return MatrixIndex2; })(MatrixIndex$1 || {}); var DecoderResult = /* @__PURE__ */ ((DecoderResult2) => { DecoderResult2[DecoderResult2["Success"] = 0] = "Success"; DecoderResult2[DecoderResult2["TryAgainLater"] = -1] = "TryAgainLater"; DecoderResult2[DecoderResult2["Error"] = -2] = "Error"; return DecoderResult2; })(DecoderResult || {}); var ColorType = /* @__PURE__ */ ((ColorType2) => { ColorType2[ColorType2["Unknown"] = 0] = "Unknown"; ColorType2[ColorType2["ALPHA_8"] = 1] = "ALPHA_8"; ColorType2[ColorType2["RGBA_8888"] = 2] = "RGBA_8888"; ColorType2[ColorType2["BGRA_8888"] = 3] = "BGRA_8888"; return ColorType2; })(ColorType || {}); var AlphaType = /* @__PURE__ */ ((AlphaType2) => { AlphaType2[AlphaType2["Unknown"] = 0] = "Unknown"; AlphaType2[AlphaType2["Opaque"] = 1] = "Opaque"; AlphaType2[AlphaType2["Premultiplied"] = 2] = "Premultiplied"; AlphaType2[AlphaType2["Unpremultiplied"] = 3] = "Unpremultiplied"; return AlphaType2; })(AlphaType || {}); class VecArray extends Array { constructor(...items) { super(...items); this.isDeleted = false; Object.setPrototypeOf(this, VecArray.prototype); } static create() { return new VecArray(); } get(index) { this.ensureNotDeleted(); if (index < 0 || index >= this.length) { throw new RangeError("Index out of bounds"); } return this[index]; } push_back(value) { this.ensureNotDeleted(); this.push(value); } size() { this.ensureNotDeleted(); return this.length; } delete() { this.ensureNotDeleted(); this.length = 0; this.isDeleted = true; } ensureNotDeleted() { if (this.isDeleted) { throw new Error("This VecArray instance has been deleted."); } } } var types = /*#__PURE__*/Object.freeze({ __proto__: null, PAGScaleMode: PAGScaleMode, PAGViewListenerEvent: PAGViewListenerEvent, ParagraphJustification: ParagraphJustification, TextDirection: TextDirection, LayerType: LayerType, PAGTimeStretchMode: PAGTimeStretchMode, MatrixIndex: MatrixIndex$1, DecoderResult: DecoderResult, ColorType: ColorType, AlphaType: AlphaType, VecArray: VecArray }); var __defProp$f = Object.defineProperty; var __getOwnPropDesc$e = Object.getOwnPropertyDescriptor; var __decorateClass$e = (decorators, target, key, kind) => { var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$e(target, key) : target; for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result; if (kind && result) __defProp$f(target, key, result); return result; }; let Matrix$1 = class { constructor(wasmIns) { this.isDestroyed = false; this.wasmIns = wasmIns; } static makeAll(scaleX, skewX, transX, skewY, scaleY, transY, pers0 = 0, pers1 = 0, pers2 = 1) { const wasmIns = PAGModule._Matrix._MakeAll(scaleX, skewX, transX, skewY, scaleY, transY, pers0, pers1, pers2); if (!wasmIns) throw new Error("Matrix.makeAll fail, please check parameters valid!"); return new Matrix$1(wasmIns); } static makeScale(scaleX, scaleY) { let wasmIns; if (scaleY !== void 0) { wasmIns = PAGModule._Matrix._MakeScale(scaleX, scaleY); } else { wasmIns = PAGModule._Matrix._MakeScale(scaleX); } if (!wasmIns) throw new Error("Matrix.makeScale fail, please check parameters valid!"); return new Matrix$1(wasmIns); } static makeTrans(dx, dy) { const wasmIns = PAGModule._Matrix._MakeTrans(dx, dy); if (!wasmIns) throw new Error("Matrix.makeTrans fail, please check parameters valid!"); return new Matrix$1(wasmIns); } get a() { return this.wasmIns ? this.wasmIns._get(MatrixIndex$1.a) : 0; } set a(value) { this.wasmIns?._set(MatrixIndex$1.a, value); } get b() { return this.wasmIns ? this.wasmIns._get(MatrixIndex$1.b) : 0; } set b(value) { this.wasmIns?._set(MatrixIndex$1.b, value); } get c() { return this.wasmIns ? this.wasmIns._get(MatrixIndex$1.c) : 0; } set c(value) { this.wasmIns?._set(MatrixIndex$1.c, value); } get d() { return this.wasmIns ? this.wasmIns._get(MatrixIndex$1.d) : 0; } set d(value) { this.wasmIns?._set(MatrixIndex$1.d, value); } get tx() { return this.wasmIns ? this.wasmIns._get(MatrixIndex$1.tx) : 0; } set tx(value) { this.wasmIns?._set(MatrixIndex$1.tx, value); } get ty() { return this.wasmIns ? this.wasmIns._get(MatrixIndex$1.ty) : 0; } set ty(value) { this.wasmIns?._set(MatrixIndex$1.ty, value); } get(index) { return this.wasmIns ? this.wasmIns._get(index) : 0; } set(index, value) { this.wasmIns?._set(index, value); } setAll(scaleX, skewX, transX, skewY, scaleY, transY) { this.wasmIns?._setAll(scaleX, skewX, transX, skewY, scaleY, transY, 0, 0, 1); } setAffine(a, b, c, d, tx, ty) { this.wasmIns?._setAffine(a, b, c, d, tx, ty); } reset() { this.wasmIns?._reset(); } setTranslate(dx, dy) { this.wasmIns?._setTranslate(dx, dy); } setScale(sx, sy, px = 0, py = 0) { this.wasmIns?._setScale(sx, sy, px, py); } setRotate(degrees, px = 0, py = 0) { this.wasmIns?._setRotate(degrees, px, py); } setSinCos(sinV, cosV, px = 0, py = 0) { this.wasmIns?._setSinCos(sinV, cosV, px, py); } setSkew(kx, ky, px = 0, py = 0) { this.wasmIns?._setSkew(kx, ky, px, py); } setConcat(a, b) { this.wasmIns?._setConcat(a.wasmIns, b.wasmIns); } preTranslate(dx, dy) { this.wasmIns?._preTranslate(dx, dy); } preScale(sx, sy, px = 0, py = 0) { this.wasmIns?._preScale(sx, sy, px, py); } preRotate(degrees, px = 0, py = 0) { this.wasmIns?._preRotate(degrees, px, py); } preSkew(kx, ky, px = 0, py = 0) { this.wasmIns?._preSkew(kx, ky, px, py); } preConcat(other) { this.wasmIns?._preConcat(other.wasmIns); } postTranslate(dx, dy) { this.wasmIns?._postTranslate(dx, dy); } postScale(sx, sy, px = 0, py = 0) { this.wasmIns?._postScale(sx, sy, px, py); } postRotate(degrees, px = 0, py = 0) { this.wasmIns?._postRotate(degrees, px, py); } postSkew(kx, ky, px = 0, py = 0) { this.wasmIns?._postSkew(kx, ky, px, py); } postConcat(other) { this.wasmIns?._postConcat(other.wasmIns); } destroy() { this.wasmIns.delete(); } }; Matrix$1 = __decorateClass$e([ destroyVerify$1 ], Matrix$1); const rewindData = (fn, scope, ...args) => { return fn.call(scope, ...args); }; const proxyVector = (vector, process) => { const proxy = new Proxy(vector, { get(target, property, receiver) { switch (property) { case "get": return (index) => { const wasmIns = rewindData(target.get, target, index); return !wasmIns ? wasmIns : process(wasmIns); }; case "push_back": return (value) => { rewindData(target.push_back, target, value.wasmIns || value); return void 0; }; case "size": return () => { return rewindData(target.size, target); }; default: return Reflect.get(target, property, receiver); } } }); return proxy; }; const layer2typeLayer = (wasmIns) => { switch (rewindData(wasmIns._layerType, wasmIns)) { case LayerType.Solid: return new PAGModule.PAGSolidLayer(wasmIns); case LayerType.Text: return new PAGModule.PAGTextLayer(wasmIns); case LayerType.Image: return new PAGModule.PAGImageLayer(wasmIns); default: return new PAGModule.PAGLayer(wasmIns); } }; const getLayerTypeName = (layerType) => { switch (layerType) { case LayerType.Solid: return "Solid"; case LayerType.Text: return "Text"; case LayerType.Shape: return "Shape"; case LayerType.Image: return "Image"; case LayerType.PreCompose: return "PreCompose"; default: return "Unknown"; } }; const getWasmIns = (value) => { if (value?.wasmIns) { return value.wasmIns; } return value; }; const isInstanceOf$1 = (value, type) => typeof type !== "undefined" && value instanceof type; var __defProp$e = Object.defineProperty; var __getOwnPropDesc$d = Object.getOwnPropertyDescriptor; var __decorateClass$d = (decorators, target, key, kind) => { var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$d(target, key) : target; for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result; if (kind && result) __defProp$e(target, key, result); return result; }; let PAGLayer = class { constructor(wasmIns) { this.isDestroyed = false; this.wasmIns = wasmIns; } uniqueID() { return this.wasmIns._uniqueID(); } layerType() { return this.wasmIns._layerType(); } layerName() { return this.wasmIns._layerName(); } matrix() { const wasmIns = this.wasmIns._matrix(); if (!wasmIns) throw new Error("Get matrix fail!"); return new Matrix$1(wasmIns); } setMatrix(matrix) { this.wasmIns._setMatrix(matrix.wasmIns); } resetMatrix() { this.wasmIns._resetMatrix(); } getTotalMatrix() { const wasmIns = this.wasmIns._getTotalMatrix(); if (!wasmIns) throw new Error("Get total matrix fail!"); return new Matrix$1(this.wasmIns._getTotalMatrix()); } alpha() { return this.wasmIns._alpha(); } setAlpha(opacity) { this.wasmIns._setAlpha(opacity); } visible() { return this.wasmIns._visible(); } setVisible(visible) { this.wasmIns._setVisible(visible); } editableIndex() { return this.wasmIns._editableIndex(); } parent() { const wasmIns = this.wasmIns._parent(); if (!wasmIns) throw new Error("Get total matrix fail!"); return new PAGComposition(wasmIns); } markers() { const wasmIns = this.wasmIns._markers(); if (!wasmIns) throw new Error("Get markers fail!"); return proxyVector(wasmIns, (wasmIns2) => wasmIns2); } localTimeToGlobal(localTime) { return this.wasmIns._localTimeToGlobal(localTime); } globalToLocalTime(globalTime) { return this.wasmIns._globalToLocalTime(globalTime); } duration() { return this.wasmIns._duration(); } frameRate() { return this.wasmIns._frameRate(); } startTime() { return this.wasmIns._startTime(); } setStartTime(time) { this.wasmIns._setStartTime(time); } currentTime() { return this.wasmIns._currentTime(); } setCurrentTime(time) { this.wasmIns._setCurrentTime(time); } getProgress() { return this.wasmIns._getProgress(); } setProgress(percent) { this.wasmIns._setProgress(percent); } preFrame() { this.wasmIns._preFrame(); } nextFrame() { this.wasmIns._nextFrame(); } getBounds() { return this.wasmIns._getBounds(); } trackMatteLayer() { const wasmIns = this.wasmIns._trackMatteLayer(); if (!wasmIns) throw new Error("Get track matte layer fail!"); return layer2typeLayer(wasmIns); } excludedFromTimeline() { return this.wasmIns._excludedFromTimeline(); } setExcludedFromTimeline(value) { this.wasmIns._setExcludedFromTimeline(value); } isPAGFile() { return this.wasmIns._isPAGFile(); } asTypeLayer() { return layer2typeLayer(this.wasmIns); } isDelete() { return this.wasmIns.isDelete(); } destroy() { this.wasmIns.delete(); this.isDestroyed = true; } }; PAGLayer = __decorateClass$d([ destroyVerify$1 ], PAGLayer); var __defProp$d = Object.defineProperty; var __getOwnPropDesc$c = Object.getOwnPropertyDescriptor; var __decorateClass$c = (decorators, target, key, kind) => { var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$c(target, key) : target; for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result; if (kind && result) __defProp$d(target, key, result); return result; }; let PAGComposition = class extends PAGLayer { static make(width, height) { const wasmIns = PAGModule._PAGComposition._Make(width, height); if (!wasmIns) throw new Error("Make PAGComposition fail!"); return new PAGComposition(wasmIns); } width() { return this.wasmIns._width(); } height() { return this.wasmIns._height(); } setContentSize(width, height) { this.wasmIns._setContentSize(width, height); } numChildren() { return this.wasmIns._numChildren(); } getLayerAt(index) { const wasmIns = this.wasmIns._getLayerAt(index); if (!wasmIns) throw new Error(`Get layer at ${index} fail!`); return layer2typeLayer(wasmIns); } getLayerIndex(pagLayer) { return this.wasmIns._getLayerIndex(pagLayer.wasmIns); } setLayerIndex(pagLayer, index) { return this.wasmIns._setLayerIndex(pagLayer.wasmIns, index); } addLayer(pagLayer) { return this.wasmIns._addLayer(pagLayer.wasmIns); } addLayerAt(pagLayer, index) { return this.wasmIns._addLayerAt(pagLayer.wasmIns, index); } contains(pagLayer) { return this.wasmIns._contains(pagLayer.wasmIns); } removeLayer(pagLayer) { const wasmIns = this.wasmIns._removeLayer(pagLayer.wasmIns); if (!wasmIns) throw new Error("Remove layer fail!"); return layer2typeLayer(wasmIns); } removeLayerAt(index) { const wasmIns = this.wasmIns._removeLayerAt(index); if (!wasmIns) throw new Error(`Remove layer at ${index} fail!`); return layer2typeLayer(wasmIns); } removeAllLayers() { this.wasmIns._removeAllLayers(); } swapLayer(pagLayer1, pagLayer2) { this.wasmIns._swapLayer(pagLayer1.wasmIns, pagLayer2.wasmIns); } swapLayerAt(index1, index2) { this.wasmIns._swapLayerAt(index1, index2); } audioBytes() { return this.wasmIns._audioBytes(); } audioMarkers() { const wasmIns = this.wasmIns._audioMarkers(); if (!wasmIns) throw new Error(`Get audioMarkers fail!`); return proxyVector(wasmIns, (wasmIns2) => wasmIns2); } audioStartTime() { return this.wasmIns._audioStartTime(); } getLayersByName(layerName) { const wasmIns = this.wasmIns._getLayersByName(layerName); if (!wasmIns) throw new Error(`Get layers by ${layerName} fail!`); const layerArray = VecArray.create(); for (const wasmIn of wasmIns) { layerArray.push(layer2typeLayer(wasmIn)); } return layerArray; } getLayersUnderPoint(localX, localY) { const wasmIns = this.wasmIns._getLayersUnderPoint(localX, localY); if (!wasmIns) throw new Error(`Get layers under point ${localX},${localY} fail!`); const layerArray = VecArray.create(); for (const wasmIn of wasmIns) { layerArray.push(layer2typeLayer(wasmIn)); } return layerArray; } }; PAGComposition = __decorateClass$c([ destroyVerify$1 ], PAGComposition); const readFile = (file) => new Promise((resolve) => { const reader = new FileReader(); reader.onload = () => { resolve(reader.result); }; reader.onerror = () => { console.error(reader.error.message); }; reader.readAsArrayBuffer(file); }); const transferToArrayBuffer = (data) => { if (isInstanceOf$1(data, globalThis.File)) { return readFile(data); } else if (isInstanceOf$1(data, globalThis.Blob)) { return readFile(new File([data], "")); } else if (isInstanceOf$1(data, globalThis.ArrayBuffer)) { return Promise.resolve(data); } return Promise.resolve(null); }; var __defProp$c = Object.defineProperty; var __getOwnPropDesc$b = Object.getOwnPropertyDescriptor; var __decorateClass$b = (decorators, target, key, kind) => { var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$b(target, key) : target; for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result; if (kind && result) __defProp$c(target, key, result); return result; }; let PAGFile = class extends PAGComposition { static async load(data) { const buffer = await transferToArrayBuffer(data); if (!buffer) throw new Error( "Initialize PAGFile data type error, please put check data type must to be File \uFF5C Blob | ArrayBuffer!" ); return PAGFile.loadFromBuffer(buffer); } static loadFromBuffer(buffer) { if (!buffer || !(buffer.byteLength > 0)) throw new Error("Initialize PAGFile data not be empty!"); const uint8Buffer = new Uint8Array(buffer); const wasmIns = PAGModule._PAGFile._Load(uint8Buffer); if (!wasmIns) throw new Error("Load PAGFile fail!"); const pagFile = new PAGFile(wasmIns); return pagFile; } static maxSupportedTagLevel() { return PAGModule._PAGFile._MaxSupportedTagLevel(); } tagLevel() { return this.wasmIns._tagLevel(); } numTexts() { return this.wasmIns._numTexts(); } numImages() { return this.wasmIns._numImages(); } numVideos() { return this.wasmIns._numVideos(); } getTextData(editableTextIndex) { return this.wasmIns._getTextData(editableTextIndex); } replaceText(editableTextIndex, textData) { this.wasmIns._replaceText(editableTextIndex, textData); } replaceImage(editableImageIndex, pagImage) { this.wasmIns._replaceImage(editableImageIndex, pagImage.wasmIns); } getLayersByEditableIndex(editableIndex, layerType) { const wasmIns = this.wasmIns._getLayersByEditableIndex(editableIndex, layerType); if (!wasmIns) throw new Error(`Get ${getLayerTypeName(layerType)} layers by ${editableIndex} fail!`); const layerArray = VecArray.create(); for (const wasmIn of wasmIns) { layerArray.push(layer2typeLayer(wasmIn)); } return layerArray; } getEditableIndices(layerType) { return this.wasmIns._getEditableIndices(layerType); } timeStretchMode() { return this.wasmIns._timeStretchMode(); } setTimeStretchMode(value) { this.wasmIns._setTimeStretchMode(value); } setDuration(duration) { this.wasmIns._setDuration(duration); } copyOriginal() { const wasmIns = this.wasmIns._copyOriginal(); if (!wasmIns) throw new Error(`Copy original fail!`); return new PAGFile(wasmIns); } }; PAGFile = __decorateClass$b([ destroyVerify$1 ], PAGFile); var __defProp$b = Object.defineProperty; var __getOwnPropDesc$a = Object.getOwnPropertyDescriptor; var __decorateClass$a = (decorators, target, key, kind) => { var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$a(target, key) : target; for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result; if (kind && result) __defProp$b(target, key, result); return result; }; let PAGSurface = class { constructor(wasmIns) { this.isDestroyed = false; this.wasmIns = wasmIns; } static fromCanvas(canvasID) { const wasmIns = PAGModule._PAGSurface._FromCanvas(canvasID); if (!wasmIns) throw new Error(`Make PAGSurface from canvas ${canvasID} fail!`); return new PAGSurface(wasmIns); } static fromTexture(textureID, width, height, flipY) { const wasmIns = PAGModule._PAGSurface._FromTexture(textureID, width, height, flipY); if (!wasmIns) throw new Error(`Make PAGSurface from texture ${textureID} fail!`); return new PAGSurface(wasmIns); } static fromRenderTarget(frameBufferID, width, height, flipY) { const wasmIns = PAGModule._PAGSurface._FromRenderTarget(frameBufferID, width, height, flipY); if (!wasmIns) throw new Error(`Make PAGSurface from frameBuffer ${frameBufferID} fail!`); return new PAGSurface(wasmIns); } width() { return this.wasmIns._width(); } height() { return this.wasmIns._height(); } updateSize() { this.wasmIns._updateSize(); } clearAll() { return this.wasmIns._clearAll(); } freeCache() { this.wasmIns._freeCache(); } readPixels(colorType, alphaType) { if (colorType === ColorType.Unknown) return null; const rowBytes = this.wasmIns._width() * (colorType === ColorType.ALPHA_8 ? 1 : 4); return this.wasmIns._readPixels(colorType, alphaType, rowBytes); } destroy() { this.wasmIns.delete(); this.isDestroyed = true; } }; PAGSurface = __decorateClass$a([ destroyVerify$1 ], PAGSurface); var __defProp$a = Object.defineProperty; var __getOwnPropDesc$9 = Object.getOwnPropertyDescriptor; var __decorateClass$9 = (decorators, target, key, kind) => { var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$9(target, key) : target; for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result; if (kind && result) __defProp$a(target, key, result); return result; }; let VideoReaderManager = class { constructor(wasmIns) { this.videoIDs = []; this.isDestroyed = false; this.videoReaderMap = /* @__PURE__ */ new Map(); this.wasmIns = PAGModule._videoInfoManager._Make(wasmIns); if (!this.wasmIns) { throw new Error("create VideoReaderManager fail!"); } this.videoIDs = this.wasmIns._getVideoIDs(); if (this.wasmIns._hasTimeRangeOverlap()) { console.error("The current file contains multiple layers referencing the same video with overlapping timelines. This scenario is not supported, and the rendered result may not match expectations. It is recommended to offset the timelines of these layers."); } } static HasVideo(wasmIns) { return PAGModule._videoInfoManager._HasVideo(wasmIns); } static async make(wasmIns) { const videoManage = new VideoReaderManager(wasmIns); await videoManage.createVideoReader(); return videoManage; } async createVideoReader() { for (const id of this.videoIDs) { const mp4Data = this.wasmIns._getMp4DataByID(id); if (mp4Data !== null) { this.videoReaderMap.set(id, await PAGModule.VideoReader.create( mp4Data, this.wasmIns._getWidthByID(id), this.wasmIns._getHeightByID(id), this.wasmIns._getFrameRateByID(id), this.wasmIns._getStaticTimeRangesByID(id) )); await this.videoReaderMap.get(id)?.prepare(0, this.wasmIns._getPlaybackRateByID(id)); } } } getVideoReaderByID(id) { if (this.videoReaderMap.get(id) === void 0) { console.error(`get VideoReader fail!,id:${id}`); return void 0; } return this.videoReaderMap.get(id); } async prepareTargetFrame() { for (const id of this.videoIDs) { if (this.isDestroyed) return; const targetFrame = this.wasmIns._getTargetFrameByID(id); if (targetFrame < 0) { continue; } if (this.videoReaderMap.get(id) !== void 0) { await this.videoReaderMap.get(id)?.prepare(targetFrame, this.wasmIns._getPlaybackRateByID(id)); } else { console.error("videoReader is undefined,id:", id); } } } destroy() { this.wasmIns.delete(); for (const key of this.videoReaderMap.keys()) { this.videoReaderMap.get(key)?.onDestroy(); } this.videoReaderMap.clear(); this.isDestroyed = true; } }; VideoReaderManager = __decorateClass$9([ destroyVerify$1 ], VideoReaderManager); var __defProp$9 = Object.defineProperty; var __getOwnPropDesc$8 = Object.getOwnPropertyDescriptor; var __decorateClass$8 = (decorators, target, key, kind) => { var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$8(target, key) : target; for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result; if (kind && result) __defProp$9(target, key, result); return result; }; let PAGPlayer = class { constructor(wasmIns) { this.isDestroyed = false; this.videoReaders = []; this.pagComposition = null; this.videoReaderManager = null; this.wasmIns = wasmIns; } static create() { const wasmIns = new PAGModule._PAGPlayer(); if (!wasmIns) throw new Error("Create PAGPlayer fail!"); return new PAGPlayer(wasmIns); } setProgress(progress) { this.wasmIns._setProgress(progress); } async flush() { PAGModule.currentPlayer = this; await this.prepareVideoFrame(); return PAGModule.webAssemblyQueue.exec(async () => { const res = await this.wasmIns._flush(); PAGModule.currentPlayer = null; return res; }, this.wasmIns); } async flushInternal(callback) { PAGModule.currentPlayer = this; await this.prepareVideoFrame(); const res = await PAGModule.webAssemblyQueue.exec(async () => { const res2 = await this.wasmIns._flush(); PAGModule.currentPlayer = null; callback(res2); return res2; }, this.wasmIns); for (const videoReader of this.videoReaders) { const error = await videoReader.getError(); if (error !== null) { console.warn("[PAGPlayer] VideoReader error:", error); } } return res; } duration() { return this.wasmIns._duration(); } getProgress() { return this.wasmIns._getProgress(); } currentFrame() { return this.wasmIns._currentFrame(); } videoEnabled() { return this.wasmIns._videoEnabled(); } setVideoEnabled(enabled) { this.wasmIns._setVideoEnabled(enabled); } cacheEnabled() { return this.wasmIns._cacheEnabled(); } setCacheEnabled(enabled) { this.wasmIns._setCacheEnabled(enabled); } cacheScale() { return this.wasmIns._cacheScale(); } setCacheScale(value) { this.wasmIns._setCacheScale(value); } maxFrameRate() { return this.wasmIns._maxFrameRate(); } setMaxFrameRate(value) { this.wasmIns._setMaxFrameRate(value); } scaleMode() { return this.wasmIns._scaleMode(); } setScaleMode(value) { this.wasmIns._setScaleMode(value); } setSurface(pagSurface) { this.wasmIns._setSurface(getWasmIns(pagSurface)); } getComposition() { const wasmIns = this.wasmIns._getComposition(); if (!wasmIns) throw new Error("Get composition fail!"); if (wasmIns._isPAGFile()) { return new PAGFile(wasmIns); } return new PAGComposition(wasmIns); } setComposition(pagComposition) { this.destroyVideoReaderManager(); this.pagComposition = pagComposition; this.wasmIns._setComposition(getWasmIns(pagComposition)); } getSurface() { const wasmIns = this.wasmIns._getSurface(); if (!wasmIns) throw new Error("Get surface fail!"); return new PAGSurface(wasmIns); } matrix() { const wasmIns = this.wasmIns._matrix(); if (!wasmIns) throw new Error("Get matrix fail!"); return new Matrix$1(wasmIns); } setMatrix(matrix) { this.wasmIns._setMatrix(matrix.wasmIns); } nextFrame() { this.wasmIns._nextFrame(); } preFrame() { this.wasmIns._preFrame(); } autoClear() { return this.wasmIns._autoClear(); } setAutoClear(value) { this.wasmIns._setAutoClear(value); } getBounds(pagLayer) { return this.wasmIns._getBounds(pagLayer.wasmIns); } getLayersUnderPoint(localX, localY) { const wasmIns = this.wasmIns._getLayersUnderPoint(localX, localY); if (!wasmIns) throw new Error(`Get layers under point, x: ${localX} y:${localY} fail!`); const layerArray = VecArray.create(); for (const wasmIn of wasmIns) { layerArray.push(layer2typeLayer(wasmIn)); } return layerArray; } hitTestPoint(pagLayer, surfaceX, surfaceY, pixelHitTest = false) { return this.wasmIns._hitTestPoint(pagLayer.wasmIns, surfaceX, surfaceY, pixelHitTest); } renderingTime() { return this.wasmIns._renderingTime(); } imageDecodingTime() { return this.wasmIns._imageDecodingTime(); } presentingTime() { return this.wasmIns._presentingTime(); } graphicsMemory() { return this.wasmIns._graphicsMemory(); } prepare() { return PAGModule.webAssemblyQueue.exec(async () => { PAGModule.currentPlayer = this; await this.wasmIns._prepare(); PAGModule.currentPlayer = null; }, this.wasmIns); } destroy() { this.destroyVideoReaderManager(); this.wasmIns.delete(); this.isDestroyed = true; } linkVideoReader(videoReader) { this.videoReaders.push(videoReader); } unlinkVideoReader(videoReader) { const index = this.videoReaders.indexOf(videoReader); if (index !== -1) { this.videoReaders.splice(index, 1); } } async prepareVideoFrame() { if (PAGModule._useSoftwareDecoder !== void 0 && !PAGModule._useSoftwareDecoder) { if (this.pagComposition !== null) { if (this.videoReaderManager === null && VideoReaderManager.HasVideo(this.pagComposition?.wasmIns)) { this.videoReaderManager = await VideoReaderManager.make(this.pagComposition?.wasmIns); PAGModule.videoReaderManager = this.videoReaderManager; } if (this.videoReaderManager !== null) { await this.videoReaderManager.prepareTargetFrame(); } } else { console.error("PAGComposition is null. A valid PAG file is missing."); } } } destroyVideoReaderManager() { if (this.videoReaderManager !== null) { this.videoReaderManager.destroy(); this.videoReaderManager = null; PAGModule.videoReaderManage = null; } } }; PAGPlayer = __decorateClass$8([ destroyVerify$1 ], PAGPlayer); var __defProp$8 = Object.defineProperty; var __getOwnPropDesc$7 = Object.getOwnPropertyDescriptor; var __decorateClass$7 = (decorators, target, key, kind) => { var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$7(target, key) : target; for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result; if (kind && result) __defProp$8(target, key, result); return result; }; let PAGImage = class { constructor(wasmIns) { this.isDestroyed = false; this.wasmIns = wasmIns; } static async fromFile(data) { return new Promise((resolve, reject) => { const image = new Image(); image.onload = async () => { resolve(PAGImage.fromSource(image)); }; image.onerror = (error) => { reject(error); }; image.src = URL.createObjectURL(data); }); } static fromSource(source) { const wasmIns = PAGModule._PAGImage._FromNativeImage(source); if (!wasmIns) throw new Error("Make PAGImage from source fail!"); return new PAGImage(wasmIns); } static fromPixels(pixels, width, height, colorType, alphaType) { const rowBytes = width * (colorType === ColorType.ALPHA_8 ? 1 : 4); const wasmIns = PAGModule._PAGImage._FromPixels(pixels, width, height, rowBytes, colorType, alphaType); if (!wasmIns) throw new Error("Make PAGImage from pixels fail!"); return new PAGImage(wasmIns); } static fromTexture(textureID, width, height, flipY) { const wasmIns = PAGModule._PAGImage._FromTexture(textureID, width, height, flipY); if (!wasmIns) throw new Error("Make PAGImage from texture fail!"); return new PAGImage(wasmIns); } width() { return this.wasmIns._width(); } height() { return this.wasmIns._height(); } scaleMode() { return this.wasmIns._scaleMode(); } setScaleMode(scaleMode) { this.wasmIns._setScaleMode(scaleMode); } matrix() { const wasmIns = this.wasmIns._matrix(); if (!wasmIns) throw new Error("Get matrix fail!"); return new Matrix$1(wasmIns); } setMatrix(matrix) { this.wasmIns._setMatrix(matrix.wasmIns); } destroy() { this.wasmIns.delete(); this.isDestroyed = true; } }; PAGImage = __decorateClass$7([ destroyVerify$1 ], PAGImage); class EventManager { constructor() { this.listenerMap = /* @__PURE__ */ new Map(); } on(eventName, listener) { let listenerList = []; if (this.listenerMap.has(eventName)) { listenerList = this.listenerMap.get(eventName); } listenerList.push(listener); this.listenerMap.set(eventName, listenerList); } off(eventName, listener) { if (!this.listenerMap.has(eventName)) return false; const listenerList = this.listenerMap.get(eventName); if (listenerList.length === 0) return false; if (!listener) { this.listenerMap.delete(eventName); return true; } const index = listenerList.indexOf(listener); if (index === -1) return false; listenerList.splice(index, 1); return true; } emit(eventName, event) { if (!this.listenerMap.has(eventName)) return false; const listenerList = this.listenerMap.get(eventName); if (listenerList.length === 0) return false; listenerList.forEach((listener) => listener(event)); return true; } } const VIDEO_DECODE_WAIT_FRAME = 1; const VIDEO_DECODE_SEEK_TIMEOUT_FRAME = 12; const DEFAULT_CANVAS_SIZE = 2560; const WEBGL_CONTEXT_ATTRIBUTES = { depth: false, stencil: false, antialias: false }; const VIDEO_PLAYBACK_RATE_MIN = 0.125; const VIDEO_PLAYBACK_RATE_MAX = 4; class BackendContext { constructor(handle, externallyOwned = false) { this.isDestroyed = false; this.oldHandle = 0; this.handle = handle; this.externallyOwned = externallyOwned; } static from(gl) { if (gl instanceof BackendContext) { return new BackendContext(gl.handle, true); } else { const majorVersion = isInstanceOf$1(gl, globalThis.WebGL2RenderingContext) ? 2 : 1; const { GL } = PAGModule; let id = 0; if (GL.contexts.length > 0) { id = GL.contexts.findIndex((context) => context?.GLctx === gl); } if (id < 1) { id = GL.registerContext(gl, { majorVersion, minorVersion: 0, ...WEBGL_CONTEXT_ATTRIBUTES }); return new BackendContext(id); } return new BackendContext(id, true); } } getContext() { return PAGModule.GL.getContext(this.handle).GLctx; } makeCurrent() { if (this.isDestroyed) return false; this.oldHandle = PAGModule.GL.currentContext?.handle || 0; if (this.oldHandle === this.handle) return true; return PAGModule.GL.makeContextCurrent(this.handle); } clearCurrent() { if (this.isDestroyed) return; if (this.oldHandle === this.handle) return; PAGModule.GL.makeContextCurrent(0); if (this.oldHandle) { PAGModule.GL.makeContextCurrent(this.oldHandle); } } registerTexture(texture) { return this.register(PAGModule.GL.textures, texture); } getTexture(handled) { return PAGModule.GL.textures[handled]; } unregisterTexture(handle) { PAGModule.GL.textures[handle] = null; } registerRenderTarget(framebuffer) { return this.register(PAGModule.GL.framebuffers, framebuffer); } getRenderTarget(handle) { return PAGModule.GL.framebuffers[handle]; } unregisterRenderTarget(handle) { PAGModule.GL.framebuffers[handle] = null; } destroy() { if (this.externallyOwned) { return; } PAGModule.GL.deleteContext(this.handle); } register(table, item) { const handle = PAGModule.GL.getNewId(table); table[handle] = item; return handle; } } const renderCanvasList = []; class RenderCanvas { constructor(canvas, contextAttributes) { this._canvas = null; this._glContext = null; this.retainCount = 0; this._canvas = canvas; const gl = canvas.getContext("webgl", { ...WEBGL_CONTEXT_ATTRIBUTES, ...contextAttributes }); if (!gl) throw new Error("Canvas context is not WebGL!"); this._glContext = BackendContext.from(gl); } static from(canvas, contextAttributes) { let renderCanvas = renderCanvasList.find((targetCanvas) => targetCanvas.canvas === canvas); if (renderCanvas) return renderCanvas; renderCanvas = new RenderCanvas(canvas, contextAttributes); renderCanvasList.push(renderCanvas); return renderCanvas; } retain() { this.retainCount += 1; } release() { this.retainCount -= 1; if (this.retainCount === 0) { if (!this._glContext) return; this._glContext.destroy(); this._glContext = null; this._canvas = null; } } get canvas() { return this._canvas; } get glContext() { return this._glContext; } } let getTime; try { getTime = performance.now.bind(performance); } catch (e) { getTime = Date.now.bind(Date); } class Clock { constructor() { this.startTime = getTime(); this.markers = {}; } reset() { this.startTime = getTime(); this.markers = {}; } mark(key) { if (!key) { console.log("Clock.mark(): An empty marker name was specified!"); return; } if (Object.keys(this.markers).find((markerKey) => markerKey === key)) { console.log(`Clock.mark(): The specified marker name '${key}' already exists!`); return; } this.markers[key] = getTime(); } measure(makerFrom, makerTo) { let start; let end; if (!makerFrom) { start = this.startTime; } else { if (!Object.keys(this.markers).find((markerKey) => markerKey === makerFrom)) { console.log(`Clock.measure(): The specified makerFrom '${makerFrom}' does not exist!`); return 0; } start = this.markers[makerFrom]; } if (!makerTo) { end = getTime(); } else { if (!Object.keys(this.markers).find((markerKey) => markerKey === makerTo)) { console.log(`Clock.measure(): The specified makerTo '${makerTo}' does not exist!`); return 0; } end = this.markers[makerTo]; } return end - start; } } const CANVAS_POOL_MAX_SIZE = 10; const isInstanceOf = (value, type) => typeof type !== "undefined" && value instanceof type; const nav$1 = navigator?.userAgent || ""; const ANDROID$1 = /android|adr/i.test(nav$1); const MOBILE$1 = /(mobile)/i.test(nav$1) && ANDROID$1; !(/(mobile)/i.test(nav$1) || MOBILE$1) && /Mac OS X/i.test(nav$1); const IPHONE$1 = /(iphone|ipad|ipod)/i.test(nav$1); /MicroMessenger/i.test(nav$1); const SAFARI_OR_IOS_WEBVIEW$1 = /^((?!chrome|android).)*safari/i.test(nav$1) || IPHONE$1; const WORKER = typeof globalThis.importScripts === "function"; const canvasPool = new Array(); const isOffscreenCanvas = (element) => isInstanceOf(element, globalThis.OffscreenCanvas); const isCanvas = (element) => isOffscreenCanvas(element) || isInstanceOf(element, globalThis.HTMLCanvasElement); const getCanvas2D = (width, height) => { let canvas = canvasPool.pop() || createCanvas2D(); if (canvas !== null) { canvas.width = width; canvas.height = height; } return canvas; }; const releaseCanvas2D = (canvas) => { if (canvasPool.length < CANVAS_POOL_MAX_SIZE) { canvasPool.push(canvas); } }; const createCanvas2D = () => { if (SAFARI_OR_IOS_WEBVIEW$1 && !WORKER) { return document.createElement("canvas"); } try { const offscreenCanvas = new OffscreenCanvas(0, 0); const context = offscreenCanvas.getContext("2d"); if (typeof context.measureText === "function") return offscreenCanvas; return document.createElement("canvas"); } catch (err) { return document.createElement("canvas"); } }; const calculateDisplaySize = (canvas) => { const styleDeclaration = globalThis.getComputedStyle(canvas, null); const computedSize = { width: Number(styleDeclaration.width.replace("px", "")), height: Number(styleDeclaration.height.replace("px", "")) }; if (computedSize.width > 0 && computedSize.height > 0) { return computedSize; } else { const styleSize = { width: Number(canvas.style.width.replace("px", "")), height: Number(canvas.style.height.replace("px", "")) }; if (styleSize.width > 0 && styleSize.height > 0) { return styleSize; } else { return { width: canvas.width, height: canvas.height }; } } }; var __defProp$7 = Object.defineProperty; var __getOwnPropDesc$6 = Object.getOwnPropertyDescriptor; var __decorateClass$6 = (decorators, target, key, kind) => { var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$6(target, key) : target; for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result; if (kind && result) __defProp$7(target, key, result); return result; }; let PAGView = class { constructor(pagPlayer, canvasElement) { this.repeatCount = 0; this.isPlaying = false; this.isDestroyed = false; this.pagViewOptions = { useScale: true, useCanvas2D: false, firstFrame: true }; this.renderCanvas = null; this.pagGlContext = null; this.frameRate = 0; this.pagSurface = null; this.p