@meframe/core 0.6.13 → 0.7.2

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.
Files changed (209) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/README.md +17 -5
  3. package/dist/Meframe.d.ts +14 -3
  4. package/dist/Meframe.d.ts.map +1 -1
  5. package/dist/Meframe.js +22 -12
  6. package/dist/Meframe.js.map +1 -1
  7. package/dist/cache/CacheManager.d.ts +2 -0
  8. package/dist/cache/CacheManager.d.ts.map +1 -1
  9. package/dist/cache/CacheManager.js +5 -0
  10. package/dist/cache/CacheManager.js.map +1 -1
  11. package/dist/cache/l1/VideoL1Cache.d.ts +2 -0
  12. package/dist/cache/l1/VideoL1Cache.d.ts.map +1 -1
  13. package/dist/cache/l1/VideoL1Cache.js +13 -7
  14. package/dist/cache/l1/VideoL1Cache.js.map +1 -1
  15. package/dist/cache/l2/IndexedDBStore.d.ts +1 -2
  16. package/dist/cache/l2/IndexedDBStore.d.ts.map +1 -1
  17. package/dist/cache/l2/L2Cache.d.ts +3 -2
  18. package/dist/cache/l2/L2Cache.d.ts.map +1 -1
  19. package/dist/cache/l2/L2OPFSStore.d.ts +3 -3
  20. package/dist/cache/l2/L2OPFSStore.d.ts.map +1 -1
  21. package/dist/cache/l2/OPFSStore.d.ts +1 -2
  22. package/dist/cache/l2/OPFSStore.d.ts.map +1 -1
  23. package/dist/cache/resource/AudioSampleCache.d.ts +12 -0
  24. package/dist/cache/resource/AudioSampleCache.d.ts.map +1 -1
  25. package/dist/cache/resource/AudioSampleCache.js +39 -5
  26. package/dist/cache/resource/AudioSampleCache.js.map +1 -1
  27. package/dist/cache/resource/ResourceCache.d.ts +4 -12
  28. package/dist/cache/resource/ResourceCache.d.ts.map +1 -1
  29. package/dist/cache/resource/ResourceCache.js +7 -24
  30. package/dist/cache/resource/ResourceCache.js.map +1 -1
  31. package/dist/config/defaults.d.ts.map +1 -1
  32. package/dist/config/defaults.js +4 -1
  33. package/dist/config/defaults.js.map +1 -1
  34. package/dist/config/index.d.ts +1 -1
  35. package/dist/config/index.d.ts.map +1 -1
  36. package/dist/config/types.d.ts +29 -0
  37. package/dist/config/types.d.ts.map +1 -1
  38. package/dist/config/validation.d.ts.map +1 -1
  39. package/dist/config/validation.js +3 -0
  40. package/dist/config/validation.js.map +1 -1
  41. package/dist/controllers/PlaybackController.d.ts +38 -9
  42. package/dist/controllers/PlaybackController.d.ts.map +1 -1
  43. package/dist/controllers/PlaybackController.js +269 -154
  44. package/dist/controllers/PlaybackController.js.map +1 -1
  45. package/dist/controllers/PlaybackStateMachine.d.ts.map +1 -1
  46. package/dist/controllers/PlaybackStateMachine.js +2 -1
  47. package/dist/controllers/PlaybackStateMachine.js.map +1 -1
  48. package/dist/controllers/types.d.ts +10 -2
  49. package/dist/controllers/types.d.ts.map +1 -1
  50. package/dist/controllers/types.js.map +1 -1
  51. package/dist/event/events.d.ts +2 -0
  52. package/dist/event/events.d.ts.map +1 -1
  53. package/dist/event/events.js.map +1 -1
  54. package/dist/index.d.ts +2 -2
  55. package/dist/index.d.ts.map +1 -1
  56. package/dist/index.js +1 -1
  57. package/dist/index.js.map +1 -1
  58. package/dist/model/CompositionModel.d.ts +0 -1
  59. package/dist/model/CompositionModel.d.ts.map +1 -1
  60. package/dist/model/CompositionModel.js +0 -6
  61. package/dist/model/CompositionModel.js.map +1 -1
  62. package/dist/model/patch.js +12 -12
  63. package/dist/model/patch.js.map +1 -1
  64. package/dist/node_modules/.pnpm/{mp4-muxer@5.2.2 → mp4-muxer@5.2.2_patch_hash_452653ac44da4ef32d244694e500e34d084eaa3c4232515ddec962eacc5f30ea}/node_modules/mp4-muxer/build/mp4-muxer.js +17 -3
  65. package/dist/node_modules/.pnpm/mp4-muxer@5.2.2_patch_hash_452653ac44da4ef32d244694e500e34d084eaa3c4232515ddec962eacc5f30ea/node_modules/mp4-muxer/build/mp4-muxer.js.map +1 -0
  66. package/dist/orchestrator/AudioExportSession.d.ts +28 -3
  67. package/dist/orchestrator/AudioExportSession.d.ts.map +1 -1
  68. package/dist/orchestrator/AudioExportSession.js +131 -15
  69. package/dist/orchestrator/AudioExportSession.js.map +1 -1
  70. package/dist/orchestrator/AudioPreviewSession.d.ts +6 -1
  71. package/dist/orchestrator/AudioPreviewSession.d.ts.map +1 -1
  72. package/dist/orchestrator/AudioPreviewSession.js +57 -18
  73. package/dist/orchestrator/AudioPreviewSession.js.map +1 -1
  74. package/dist/orchestrator/AudioWindowPreparer.d.ts +6 -4
  75. package/dist/orchestrator/AudioWindowPreparer.d.ts.map +1 -1
  76. package/dist/orchestrator/AudioWindowPreparer.js +247 -54
  77. package/dist/orchestrator/AudioWindowPreparer.js.map +1 -1
  78. package/dist/orchestrator/CompositionPlanner.d.ts +5 -2
  79. package/dist/orchestrator/CompositionPlanner.d.ts.map +1 -1
  80. package/dist/orchestrator/CompositionPlanner.js +8 -3
  81. package/dist/orchestrator/CompositionPlanner.js.map +1 -1
  82. package/dist/orchestrator/ExportScheduler.d.ts +1 -0
  83. package/dist/orchestrator/ExportScheduler.d.ts.map +1 -1
  84. package/dist/orchestrator/ExportScheduler.js +177 -106
  85. package/dist/orchestrator/ExportScheduler.js.map +1 -1
  86. package/dist/orchestrator/Orchestrator.d.ts +30 -4
  87. package/dist/orchestrator/Orchestrator.d.ts.map +1 -1
  88. package/dist/orchestrator/Orchestrator.js +264 -111
  89. package/dist/orchestrator/Orchestrator.js.map +1 -1
  90. package/dist/orchestrator/PreviewFrameScheduler.d.ts +21 -1
  91. package/dist/orchestrator/PreviewFrameScheduler.d.ts.map +1 -1
  92. package/dist/orchestrator/PreviewFrameScheduler.js +129 -30
  93. package/dist/orchestrator/PreviewFrameScheduler.js.map +1 -1
  94. package/dist/orchestrator/VideoWindowDecodeSession.d.ts +22 -1
  95. package/dist/orchestrator/VideoWindowDecodeSession.d.ts.map +1 -1
  96. package/dist/orchestrator/VideoWindowDecodeSession.js +426 -198
  97. package/dist/orchestrator/VideoWindowDecodeSession.js.map +1 -1
  98. package/dist/orchestrator/aac-window-timeline.d.ts +6 -2
  99. package/dist/orchestrator/aac-window-timeline.d.ts.map +1 -1
  100. package/dist/orchestrator/aac-window-timeline.js +156 -19
  101. package/dist/orchestrator/aac-window-timeline.js.map +1 -1
  102. package/dist/orchestrator/types.d.ts +5 -1
  103. package/dist/orchestrator/types.d.ts.map +1 -1
  104. package/dist/stages/compose/FrameRateConverter.d.ts +2 -1
  105. package/dist/stages/compose/FrameRateConverter.d.ts.map +1 -1
  106. package/dist/stages/compose/LayerRenderPolicy.d.ts +14 -0
  107. package/dist/stages/compose/LayerRenderPolicy.d.ts.map +1 -0
  108. package/dist/stages/compose/LayerRenderPolicy.js +18 -0
  109. package/dist/stages/compose/LayerRenderPolicy.js.map +1 -0
  110. package/dist/stages/compose/OfflineAudioMixer.d.ts +2 -0
  111. package/dist/stages/compose/OfflineAudioMixer.d.ts.map +1 -1
  112. package/dist/stages/compose/OfflineAudioMixer.js +14 -2
  113. package/dist/stages/compose/OfflineAudioMixer.js.map +1 -1
  114. package/dist/stages/compose/OwnedFrameTransform.d.ts +52 -0
  115. package/dist/stages/compose/OwnedFrameTransform.d.ts.map +1 -0
  116. package/dist/stages/compose/OwnedFrameTransform.js +154 -0
  117. package/dist/stages/compose/OwnedFrameTransform.js.map +1 -0
  118. package/dist/stages/compose/TransitionProcessor.js +0 -1
  119. package/dist/stages/compose/TransitionProcessor.js.map +1 -1
  120. package/dist/stages/compose/VideoComposer.d.ts +12 -2
  121. package/dist/stages/compose/VideoComposer.d.ts.map +1 -1
  122. package/dist/stages/compose/VideoComposer.js +100 -92
  123. package/dist/stages/compose/VideoComposer.js.map +1 -1
  124. package/dist/stages/compose/text-renderers/basic-text-renderer.d.ts.map +1 -1
  125. package/dist/stages/compose/text-renderers/basic-text-renderer.js +24 -21
  126. package/dist/stages/compose/text-renderers/basic-text-renderer.js.map +1 -1
  127. package/dist/stages/compose/text-renderers/caption-stagger-entrance-renderer.d.ts.map +1 -1
  128. package/dist/stages/compose/text-renderers/caption-stagger-entrance-renderer.js +110 -99
  129. package/dist/stages/compose/text-renderers/caption-stagger-entrance-renderer.js.map +1 -1
  130. package/dist/stages/compose/text-renderers/character-ktv-renderer.d.ts.map +1 -1
  131. package/dist/stages/compose/text-renderers/character-ktv-renderer.js +41 -38
  132. package/dist/stages/compose/text-renderers/character-ktv-renderer.js.map +1 -1
  133. package/dist/stages/compose/text-renderers/word-by-word-renderer.d.ts.map +1 -1
  134. package/dist/stages/compose/text-renderers/word-by-word-renderer.js +47 -39
  135. package/dist/stages/compose/text-renderers/word-by-word-renderer.js.map +1 -1
  136. package/dist/stages/compose/text-renderers/word-fancy-renderer.d.ts.map +1 -1
  137. package/dist/stages/compose/text-renderers/word-fancy-renderer.js +54 -48
  138. package/dist/stages/compose/text-renderers/word-fancy-renderer.js.map +1 -1
  139. package/dist/stages/compose/text-utils/text-metrics.d.ts.map +1 -1
  140. package/dist/stages/compose/text-utils/text-metrics.js +6 -4
  141. package/dist/stages/compose/text-utils/text-metrics.js.map +1 -1
  142. package/dist/stages/compose/types.d.ts +12 -0
  143. package/dist/stages/compose/types.d.ts.map +1 -1
  144. package/dist/stages/decode/BaseDecoder.d.ts +5 -0
  145. package/dist/stages/decode/BaseDecoder.d.ts.map +1 -1
  146. package/dist/stages/decode/BaseDecoder.js +52 -10
  147. package/dist/stages/decode/BaseDecoder.js.map +1 -1
  148. package/dist/stages/decode/preview-video-decoder.d.ts +48 -2
  149. package/dist/stages/decode/preview-video-decoder.d.ts.map +1 -1
  150. package/dist/stages/decode/preview-video-decoder.js +241 -71
  151. package/dist/stages/decode/preview-video-decoder.js.map +1 -1
  152. package/dist/stages/decode/video-decoder.d.ts +2 -11
  153. package/dist/stages/decode/video-decoder.d.ts.map +1 -1
  154. package/dist/stages/decode/video-decoder.js +60 -61
  155. package/dist/stages/decode/video-decoder.js.map +1 -1
  156. package/dist/stages/demux/MP3FrameParser.d.ts +18 -0
  157. package/dist/stages/demux/MP3FrameParser.d.ts.map +1 -1
  158. package/dist/stages/demux/MP3FrameParser.js +143 -11
  159. package/dist/stages/demux/MP3FrameParser.js.map +1 -1
  160. package/dist/stages/demux/MP4IndexParser.d.ts +32 -21
  161. package/dist/stages/demux/MP4IndexParser.d.ts.map +1 -1
  162. package/dist/stages/demux/MP4IndexParser.js +202 -309
  163. package/dist/stages/demux/MP4IndexParser.js.map +1 -1
  164. package/dist/stages/demux/sample-collector.d.ts +35 -0
  165. package/dist/stages/demux/sample-collector.d.ts.map +1 -0
  166. package/dist/stages/demux/sample-collector.js +105 -0
  167. package/dist/stages/demux/sample-collector.js.map +1 -0
  168. package/dist/stages/encode/BaseEncoder.d.ts +9 -2
  169. package/dist/stages/encode/BaseEncoder.d.ts.map +1 -1
  170. package/dist/stages/encode/BaseEncoder.js +90 -59
  171. package/dist/stages/encode/BaseEncoder.js.map +1 -1
  172. package/dist/stages/load/ResourceLoader.d.ts +71 -18
  173. package/dist/stages/load/ResourceLoader.d.ts.map +1 -1
  174. package/dist/stages/load/ResourceLoader.js +369 -143
  175. package/dist/stages/load/ResourceLoader.js.map +1 -1
  176. package/dist/stages/load/TaskManager.d.ts.map +1 -1
  177. package/dist/stages/load/TaskManager.js +9 -3
  178. package/dist/stages/load/TaskManager.js.map +1 -1
  179. package/dist/stages/load/types.d.ts +2 -2
  180. package/dist/stages/load/types.d.ts.map +1 -1
  181. package/dist/stages/mux/MP4Muxer.d.ts +7 -1
  182. package/dist/stages/mux/MP4Muxer.d.ts.map +1 -1
  183. package/dist/stages/mux/MP4Muxer.js +8 -10
  184. package/dist/stages/mux/MP4Muxer.js.map +1 -1
  185. package/dist/stages/mux/MuxManager.d.ts +7 -0
  186. package/dist/stages/mux/MuxManager.d.ts.map +1 -1
  187. package/dist/stages/mux/MuxManager.js +9 -0
  188. package/dist/stages/mux/MuxManager.js.map +1 -1
  189. package/dist/types.d.ts +1 -1
  190. package/dist/types.d.ts.map +1 -1
  191. package/dist/utils/errors.d.ts +2 -0
  192. package/dist/utils/errors.d.ts.map +1 -1
  193. package/dist/utils/errors.js +10 -1
  194. package/dist/utils/errors.js.map +1 -1
  195. package/dist/utils/until-aborted.d.ts +8 -0
  196. package/dist/utils/until-aborted.d.ts.map +1 -0
  197. package/dist/utils/until-aborted.js +33 -0
  198. package/dist/utils/until-aborted.js.map +1 -0
  199. package/dist/worker/WorkerChannel.d.ts.map +1 -1
  200. package/dist/worker/WorkerChannel.js +45 -10
  201. package/dist/worker/WorkerChannel.js.map +1 -1
  202. package/dist/worker/worker-manifest.js +1 -1
  203. package/dist/worker/worker-manifest.js.map +1 -1
  204. package/dist/workers/stages/export/{export.worker.C8jKSbVj.js → export.worker.BG8HA7dY.js} +745 -450
  205. package/dist/workers/stages/export/export.worker.BG8HA7dY.js.map +1 -0
  206. package/dist/workers/worker-manifest.json +1 -1
  207. package/package.json +23 -22
  208. package/dist/node_modules/.pnpm/mp4-muxer@5.2.2/node_modules/mp4-muxer/build/mp4-muxer.js.map +0 -1
  209. package/dist/workers/stages/export/export.worker.C8jKSbVj.js.map +0 -1
@@ -463,6 +463,10 @@ class WorkerChannel {
463
463
  */
464
464
  async receiveStream(onStream) {
465
465
  const chunkedStreams = /* @__PURE__ */ new Map();
466
+ const release = (chunk) => {
467
+ chunk?.close?.();
468
+ chunk?.frame?.close?.();
469
+ };
466
470
  const prev = this.port.onmessage;
467
471
  const handler = (event) => {
468
472
  const raw = event.data;
@@ -474,32 +478,63 @@ class WorkerChannel {
474
478
  return;
475
479
  }
476
480
  if (envelopeType === "stream_start" && payload?.streamId) {
477
- const stream = new ReadableStream({
478
- start(controller) {
479
- chunkedStreams.set(payload.streamId, { controller, metadata: payload });
480
- }
481
- });
481
+ const entry = {
482
+ metadata: payload,
483
+ held: [],
484
+ wanted: false,
485
+ ended: false,
486
+ cancelled: false
487
+ };
488
+ const stream = new ReadableStream(
489
+ {
490
+ start(controller) {
491
+ entry.controller = controller;
492
+ chunkedStreams.set(payload.streamId, entry);
493
+ },
494
+ pull(controller) {
495
+ if (!entry.held.length) {
496
+ entry.wanted = true;
497
+ return;
498
+ }
499
+ controller.enqueue(entry.held.shift());
500
+ if (entry.ended && !entry.held.length) controller.close();
501
+ },
502
+ cancel() {
503
+ entry.cancelled = true;
504
+ for (const chunk of entry.held.splice(0)) release(chunk);
505
+ }
506
+ },
507
+ { highWaterMark: 0 }
508
+ );
482
509
  onStream(stream, payload);
483
510
  return;
484
511
  }
485
512
  if (envelopeType === "stream_chunk" && payload?.streamId && chunkedStreams.has(payload.streamId)) {
486
513
  const s = chunkedStreams.get(payload.streamId);
487
- if (s) s.controller.enqueue(payload.chunk);
514
+ if (!s) return;
515
+ const chunk = payload.chunk;
516
+ if (s.cancelled) release(chunk);
517
+ else if (s.wanted) {
518
+ s.wanted = false;
519
+ s.controller.enqueue(chunk);
520
+ } else s.held.push(chunk);
488
521
  return;
489
522
  }
490
523
  if (envelopeType === "stream_end" && payload?.streamId && chunkedStreams.has(payload.streamId)) {
491
524
  const s = chunkedStreams.get(payload.streamId);
492
- if (s) {
493
- s.controller.close();
494
- chunkedStreams.delete(payload.streamId);
525
+ chunkedStreams.delete(payload.streamId);
526
+ if (s && !s.cancelled) {
527
+ s.ended = true;
528
+ if (!s.held.length) s.controller.close();
495
529
  }
496
530
  return;
497
531
  }
498
532
  if (envelopeType === "stream_error" && payload?.streamId && chunkedStreams.has(payload.streamId)) {
499
533
  const s = chunkedStreams.get(payload.streamId);
534
+ chunkedStreams.delete(payload.streamId);
500
535
  if (s) {
536
+ for (const chunk of s.held.splice(0)) release(chunk);
501
537
  s.controller.error(new Error(String(payload.error || "stream error")));
502
- chunkedStreams.delete(payload.streamId);
503
538
  }
504
539
  return;
505
540
  }
@@ -553,10 +588,12 @@ function calculateCaptionStartY(canvasHeight, totalHeight, globalPosition) {
553
588
  }
554
589
  function measureTextWidth(ctx, text, fontSize, fontFamily, fontWeight = 400) {
555
590
  ctx.save();
556
- ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;
557
- const metrics = ctx.measureText(text);
558
- ctx.restore();
559
- return metrics.width;
591
+ try {
592
+ ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;
593
+ return ctx.measureText(text).width;
594
+ } finally {
595
+ ctx.restore();
596
+ }
560
597
  }
561
598
  function getLetterCaseText(text, letterCase) {
562
599
  if (letterCase === "upper") {
@@ -884,29 +921,32 @@ function drawBasicTextLines(ctx, layer, canvasWidth, canvasHeight, lines) {
884
921
  const strokeWidth = fontConfig.strokeWidth || 0;
885
922
  const lineHeight = fontConfig.lineHeight || 1.2;
886
923
  ctx.save();
887
- ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;
888
- ctx.textAlign = "center";
889
- ctx.textBaseline = "middle";
890
- ctx.lineJoin = "round";
891
- ctx.lineCap = "round";
892
- const totalHeight = lines.length * fontSize * lineHeight;
893
- const startY = calculateCaptionStartY(
894
- canvasHeight,
895
- totalHeight,
896
- layer.fontConfig?.globalPosition
897
- );
898
- for (let i = 0; i < lines.length; i++) {
899
- const line = lines[i];
900
- const y = startY + i * fontSize * lineHeight + fontSize / 2;
901
- if (strokeColor && strokeWidth > 0) {
902
- ctx.strokeStyle = strokeColor;
903
- ctx.lineWidth = strokeWidth;
904
- ctx.strokeText(line, canvasWidth / 2, y);
905
- }
906
- ctx.fillStyle = fill;
907
- ctx.fillText(line, canvasWidth / 2, y);
924
+ try {
925
+ ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;
926
+ ctx.textAlign = "center";
927
+ ctx.textBaseline = "middle";
928
+ ctx.lineJoin = "round";
929
+ ctx.lineCap = "round";
930
+ const totalHeight = lines.length * fontSize * lineHeight;
931
+ const startY = calculateCaptionStartY(
932
+ canvasHeight,
933
+ totalHeight,
934
+ layer.fontConfig?.globalPosition
935
+ );
936
+ for (let i = 0; i < lines.length; i++) {
937
+ const line = lines[i];
938
+ const y = startY + i * fontSize * lineHeight + fontSize / 2;
939
+ if (strokeColor && strokeWidth > 0) {
940
+ ctx.strokeStyle = strokeColor;
941
+ ctx.lineWidth = strokeWidth;
942
+ ctx.strokeText(line, canvasWidth / 2, y);
943
+ }
944
+ ctx.fillStyle = fill;
945
+ ctx.fillText(line, canvasWidth / 2, y);
946
+ }
947
+ } finally {
948
+ ctx.restore();
908
949
  }
909
- ctx.restore();
910
950
  }
911
951
  function resolveBasicTextLines(ctx, layer, canvasWidth) {
912
952
  const fontConfig = layer.fontConfig?.textStyle;
@@ -1040,28 +1080,31 @@ function buildCharSlots(ctx, layer, canvasWidth, canvasHeight) {
1040
1080
  layer.fontConfig?.globalPosition
1041
1081
  );
1042
1082
  ctx.save();
1043
- ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;
1044
- const slots = [];
1045
- let globalIndex = 0;
1046
- for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
1047
- const line = lines[lineIndex];
1048
- const y = startY + lineIndex * fontSize * lineHeight + fontSize / 2;
1049
- const lineWidth = measureTextWidth(ctx, line, fontSize, fontFamily, fontWeight);
1050
- let cx = canvasWidth / 2 - lineWidth / 2;
1051
- for (const ch of Array.from(line)) {
1052
- const cw = measureTextWidth(ctx, ch, fontSize, fontFamily, fontWeight);
1053
- slots.push({
1054
- ch,
1055
- x: cx + cw / 2,
1056
- y,
1057
- globalIndex
1058
- });
1059
- globalIndex++;
1060
- cx += cw;
1083
+ try {
1084
+ ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;
1085
+ const slots = [];
1086
+ let globalIndex = 0;
1087
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
1088
+ const line = lines[lineIndex];
1089
+ const y = startY + lineIndex * fontSize * lineHeight + fontSize / 2;
1090
+ const lineWidth = measureTextWidth(ctx, line, fontSize, fontFamily, fontWeight);
1091
+ let cx = canvasWidth / 2 - lineWidth / 2;
1092
+ for (const ch of Array.from(line)) {
1093
+ const cw = measureTextWidth(ctx, ch, fontSize, fontFamily, fontWeight);
1094
+ slots.push({
1095
+ ch,
1096
+ x: cx + cw / 2,
1097
+ y,
1098
+ globalIndex
1099
+ });
1100
+ globalIndex++;
1101
+ cx += cw;
1102
+ }
1061
1103
  }
1104
+ return { slots, fontSize, lineHeight };
1105
+ } finally {
1106
+ ctx.restore();
1062
1107
  }
1063
- ctx.restore();
1064
- return { slots, fontSize, lineHeight };
1065
1108
  }
1066
1109
  function getCachedCharSlots(ctx, layer, canvasWidth, canvasHeight) {
1067
1110
  const key = layoutCacheKey(layer, canvasWidth, canvasHeight);
@@ -1087,88 +1130,96 @@ function drawStaggerEntranceFrame(ctx, layer, built, relativeFrame, fps, preset,
1087
1130
  const staggerMs = DEFAULT_STAGGER_MS * scale;
1088
1131
  const charDurationMs = DEFAULT_DURATION_MS * scale;
1089
1132
  ctx.save();
1090
- ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;
1091
- ctx.textAlign = "center";
1092
- ctx.textBaseline = "middle";
1093
- ctx.lineJoin = "round";
1094
- ctx.lineCap = "round";
1095
- const tMsGlobal = relativeFrame / fps * 1e3;
1096
- for (const slot of slots) {
1097
- let p;
1098
- if (forceComplete) {
1099
- p = 1;
1100
- } else if (preset === "typewriter") {
1101
- const startMs = slot.globalIndex * staggerMs;
1102
- p = tMsGlobal >= startMs ? 1 : 0;
1103
- } else {
1104
- p = charProgress(relativeFrame, fps, slot.globalIndex, staggerMs, charDurationMs);
1105
- }
1106
- if (p <= 0 && preset !== "blur") continue;
1107
- const slidePx = SLIDE_BASE_PX * scalePx;
1108
- const spreadPx = LETTER_SPREAD_BASE_PX * scalePx;
1109
- ctx.save();
1110
- let opacity = p;
1111
- let tx = 0;
1112
- let ty = 0;
1113
- let rot = 0;
1114
- let sc = 1;
1115
- let sy = 1;
1116
- let blurPx = 0;
1117
- switch (preset) {
1118
- case "fade":
1119
- opacity = p;
1120
- break;
1121
- case "slideUp":
1122
- opacity = p;
1123
- ty = (1 - p) * slidePx;
1124
- break;
1125
- case "scale":
1126
- opacity = p;
1127
- sc = Math.max(0.04, p);
1128
- break;
1129
- case "rotateScale":
1130
- opacity = p;
1131
- rot = (1 - p) * 45 * Math.PI / 180;
1132
- sc = 0.5 + p * 0.5;
1133
- break;
1134
- case "blur":
1135
- opacity = p;
1136
- blurPx = (1 - p) * BLUR_START_PX;
1137
- break;
1138
- case "flip3d":
1139
- opacity = p;
1140
- sy = Math.max(0.04, p);
1141
- sc = 1;
1142
- break;
1143
- case "typewriter":
1144
- opacity = p >= 1 ? 1 : p;
1145
- break;
1146
- case "letterSpread":
1147
- opacity = p;
1148
- tx = (1 - p) * spreadPx * slot.globalIndex;
1149
- break;
1150
- }
1151
- ctx.globalAlpha = opacity;
1152
- if (blurPx > 0.01) {
1153
- ctx.filter = `blur(${blurPx}px)`;
1154
- }
1155
- ctx.translate(slot.x + tx, slot.y + ty);
1156
- ctx.rotate(rot);
1157
- if (preset === "flip3d") {
1158
- ctx.scale(1, sy);
1159
- } else {
1160
- ctx.scale(sc, sc);
1161
- }
1162
- if (strokeColor && strokeWidth > 0) {
1163
- ctx.strokeStyle = strokeColor;
1164
- ctx.lineWidth = strokeWidth;
1165
- ctx.strokeText(slot.ch, 0, 0);
1133
+ try {
1134
+ ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;
1135
+ ctx.textAlign = "center";
1136
+ ctx.textBaseline = "middle";
1137
+ ctx.lineJoin = "round";
1138
+ ctx.lineCap = "round";
1139
+ const tMsGlobal = relativeFrame / fps * 1e3;
1140
+ for (const slot of slots) {
1141
+ let p;
1142
+ if (forceComplete) {
1143
+ p = 1;
1144
+ } else if (preset === "typewriter") {
1145
+ const startMs = slot.globalIndex * staggerMs;
1146
+ p = tMsGlobal >= startMs ? 1 : 0;
1147
+ } else {
1148
+ p = charProgress(relativeFrame, fps, slot.globalIndex, staggerMs, charDurationMs);
1149
+ }
1150
+ if (p <= 0 && preset !== "blur") continue;
1151
+ const slidePx = SLIDE_BASE_PX * scalePx;
1152
+ const spreadPx = LETTER_SPREAD_BASE_PX * scalePx;
1153
+ ctx.save();
1154
+ try {
1155
+ let opacity = p;
1156
+ let tx = 0;
1157
+ let ty = 0;
1158
+ let rot = 0;
1159
+ let sc = 1;
1160
+ let sy = 1;
1161
+ let blurPx = 0;
1162
+ switch (preset) {
1163
+ case "fade":
1164
+ opacity = p;
1165
+ break;
1166
+ case "slideUp":
1167
+ opacity = p;
1168
+ ty = (1 - p) * slidePx;
1169
+ break;
1170
+ case "scale":
1171
+ opacity = p;
1172
+ sc = Math.max(0.04, p);
1173
+ break;
1174
+ case "rotateScale":
1175
+ opacity = p;
1176
+ rot = (1 - p) * 45 * Math.PI / 180;
1177
+ sc = 0.5 + p * 0.5;
1178
+ break;
1179
+ case "blur":
1180
+ opacity = p;
1181
+ blurPx = (1 - p) * BLUR_START_PX;
1182
+ break;
1183
+ case "flip3d":
1184
+ opacity = p;
1185
+ sy = Math.max(0.04, p);
1186
+ sc = 1;
1187
+ break;
1188
+ case "typewriter":
1189
+ opacity = p >= 1 ? 1 : p;
1190
+ break;
1191
+ case "letterSpread":
1192
+ opacity = p;
1193
+ tx = (1 - p) * spreadPx * slot.globalIndex;
1194
+ break;
1195
+ default:
1196
+ break;
1197
+ }
1198
+ ctx.globalAlpha = opacity;
1199
+ if (blurPx > 0.01) {
1200
+ ctx.filter = `blur(${blurPx}px)`;
1201
+ }
1202
+ ctx.translate(slot.x + tx, slot.y + ty);
1203
+ ctx.rotate(rot);
1204
+ if (preset === "flip3d") {
1205
+ ctx.scale(1, sy);
1206
+ } else {
1207
+ ctx.scale(sc, sc);
1208
+ }
1209
+ if (strokeColor && strokeWidth > 0) {
1210
+ ctx.strokeStyle = strokeColor;
1211
+ ctx.lineWidth = strokeWidth;
1212
+ ctx.strokeText(slot.ch, 0, 0);
1213
+ }
1214
+ ctx.fillStyle = fill;
1215
+ ctx.fillText(slot.ch, 0, 0);
1216
+ } finally {
1217
+ ctx.restore();
1218
+ }
1166
1219
  }
1167
- ctx.fillStyle = fill;
1168
- ctx.fillText(slot.ch, 0, 0);
1220
+ } finally {
1169
1221
  ctx.restore();
1170
1222
  }
1171
- ctx.restore();
1172
1223
  }
1173
1224
  function clearCaptionStaggerCache() {
1174
1225
  charSlotsCache.clear();
@@ -1266,50 +1317,58 @@ function renderWordByWord(ctx, layer, canvasWidth, canvasHeight, relativeFrame,
1266
1317
  }
1267
1318
  }
1268
1319
  ctx.save();
1269
- ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;
1270
- ctx.textAlign = "center";
1271
- ctx.textBaseline = "middle";
1272
- ctx.lineJoin = "round";
1273
- ctx.lineCap = "round";
1274
- for (const wordPos of wordPositions) {
1275
- let currentFill = fill;
1276
- let currentStroke = strokeColor;
1277
- if (wordPos.timing) {
1278
- const { startFrame, endFrame } = wordPos.timing;
1279
- if (relativeFrame >= startFrame && relativeFrame <= endFrame) {
1280
- const transitionProgressIn = interpolate(
1281
- relativeFrame,
1282
- [startFrame, startFrame + 3],
1283
- [0, 1],
1284
- {
1285
- extrapolateLeft: "clamp",
1286
- extrapolateRight: "clamp"
1320
+ try {
1321
+ ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;
1322
+ ctx.textAlign = "center";
1323
+ ctx.textBaseline = "middle";
1324
+ ctx.lineJoin = "round";
1325
+ ctx.lineCap = "round";
1326
+ for (const wordPos of wordPositions) {
1327
+ let currentFill = fill;
1328
+ let currentStroke = strokeColor;
1329
+ if (wordPos.timing) {
1330
+ const { startFrame, endFrame } = wordPos.timing;
1331
+ if (relativeFrame >= startFrame && relativeFrame <= endFrame) {
1332
+ const transitionProgressIn = interpolate(
1333
+ relativeFrame,
1334
+ [startFrame, startFrame + 3],
1335
+ [0, 1],
1336
+ {
1337
+ extrapolateLeft: "clamp",
1338
+ extrapolateRight: "clamp"
1339
+ }
1340
+ );
1341
+ currentFill = interpolateColor(fill, highlightFill, transitionProgressIn);
1342
+ if (strokeColor && highlightStroke) {
1343
+ currentStroke = interpolateColor(strokeColor, highlightStroke, transitionProgressIn);
1344
+ }
1345
+ } else if (relativeFrame > endFrame) {
1346
+ const transitionProgressOut = interpolate(
1347
+ relativeFrame,
1348
+ [endFrame, endFrame + 3],
1349
+ [1, 0],
1350
+ {
1351
+ extrapolateLeft: "clamp",
1352
+ extrapolateRight: "clamp"
1353
+ }
1354
+ );
1355
+ currentFill = interpolateColor(fill, highlightFill, transitionProgressOut);
1356
+ if (strokeColor && highlightStroke) {
1357
+ currentStroke = interpolateColor(strokeColor, highlightStroke, transitionProgressOut);
1287
1358
  }
1288
- );
1289
- currentFill = interpolateColor(fill, highlightFill, transitionProgressIn);
1290
- if (strokeColor && highlightStroke) {
1291
- currentStroke = interpolateColor(strokeColor, highlightStroke, transitionProgressIn);
1292
- }
1293
- } else if (relativeFrame > endFrame) {
1294
- const transitionProgressOut = interpolate(relativeFrame, [endFrame, endFrame + 3], [1, 0], {
1295
- extrapolateLeft: "clamp",
1296
- extrapolateRight: "clamp"
1297
- });
1298
- currentFill = interpolateColor(fill, highlightFill, transitionProgressOut);
1299
- if (strokeColor && highlightStroke) {
1300
- currentStroke = interpolateColor(strokeColor, highlightStroke, transitionProgressOut);
1301
1359
  }
1302
1360
  }
1361
+ if (currentStroke && strokeWidth > 0) {
1362
+ ctx.strokeStyle = currentStroke;
1363
+ ctx.lineWidth = strokeWidth;
1364
+ ctx.strokeText(wordPos.text, wordPos.x, wordPos.y);
1365
+ }
1366
+ ctx.fillStyle = currentFill;
1367
+ ctx.fillText(wordPos.text, wordPos.x, wordPos.y);
1303
1368
  }
1304
- if (currentStroke && strokeWidth > 0) {
1305
- ctx.strokeStyle = currentStroke;
1306
- ctx.lineWidth = strokeWidth;
1307
- ctx.strokeText(wordPos.text, wordPos.x, wordPos.y);
1308
- }
1309
- ctx.fillStyle = currentFill;
1310
- ctx.fillText(wordPos.text, wordPos.x, wordPos.y);
1369
+ } finally {
1370
+ ctx.restore();
1311
1371
  }
1312
- ctx.restore();
1313
1372
  }
1314
1373
  function usToFrame$1(us, fps) {
1315
1374
  return Math.floor(us / (1e6 / fps));
@@ -1379,49 +1438,52 @@ function renderCharacterKTV(ctx, layer, canvasWidth, canvasHeight, relativeFrame
1379
1438
  const fullText = characterTimings.map((ct) => ct.char).join("");
1380
1439
  const fullTextLines = wrapText(ctx, fullText, maxWidth, fontSize, fontFamily, fontWeight);
1381
1440
  ctx.save();
1382
- ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;
1383
- ctx.textAlign = "left";
1384
- ctx.textBaseline = "middle";
1385
- ctx.lineJoin = "round";
1386
- ctx.lineCap = "round";
1387
- const totalHeight = fullTextLines.length * fontSize * lineHeight;
1388
- const startY = calculateCaptionStartY(
1389
- canvasHeight,
1390
- totalHeight,
1391
- layer.fontConfig?.globalPosition
1392
- );
1393
- let charIndexInText = 0;
1394
- for (let lineIndex = 0; lineIndex < fullTextLines.length; lineIndex++) {
1395
- const line = fullTextLines[lineIndex];
1396
- const y = startY + lineIndex * fontSize * lineHeight + fontSize / 2;
1397
- const lineWidth = measureTextWidth(ctx, line, fontSize, fontFamily, fontWeight);
1398
- let currentX = canvasWidth / 2 - lineWidth / 2;
1399
- for (let i = 0; i < line.length; i++) {
1400
- const char = line[i];
1401
- const timing = characterTimings[charIndexInText];
1402
- if (timing) {
1403
- const hasScanned = relativeFrame >= timing.startFrame;
1404
- const isCurrentlySinging = hasScanned && relativeFrame < timing.startFrame + transitionFrames;
1405
- ctx.fillStyle = hasScanned ? highlightFill : baseFill;
1406
- if (isCurrentlySinging) {
1407
- ctx.shadowColor = glowColor;
1408
- ctx.shadowBlur = glowIntensity * 10;
1409
- } else {
1441
+ try {
1442
+ ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;
1443
+ ctx.textAlign = "left";
1444
+ ctx.textBaseline = "middle";
1445
+ ctx.lineJoin = "round";
1446
+ ctx.lineCap = "round";
1447
+ const totalHeight = fullTextLines.length * fontSize * lineHeight;
1448
+ const startY = calculateCaptionStartY(
1449
+ canvasHeight,
1450
+ totalHeight,
1451
+ layer.fontConfig?.globalPosition
1452
+ );
1453
+ let charIndexInText = 0;
1454
+ for (let lineIndex = 0; lineIndex < fullTextLines.length; lineIndex++) {
1455
+ const line = fullTextLines[lineIndex];
1456
+ const y = startY + lineIndex * fontSize * lineHeight + fontSize / 2;
1457
+ const lineWidth = measureTextWidth(ctx, line, fontSize, fontFamily, fontWeight);
1458
+ let currentX = canvasWidth / 2 - lineWidth / 2;
1459
+ for (let i = 0; i < line.length; i++) {
1460
+ const char = line[i];
1461
+ const timing = characterTimings[charIndexInText];
1462
+ if (timing) {
1463
+ const hasScanned = relativeFrame >= timing.startFrame;
1464
+ const isCurrentlySinging = hasScanned && relativeFrame < timing.startFrame + transitionFrames;
1465
+ ctx.fillStyle = hasScanned ? highlightFill : baseFill;
1466
+ if (isCurrentlySinging) {
1467
+ ctx.shadowColor = glowColor;
1468
+ ctx.shadowBlur = glowIntensity * 10;
1469
+ } else {
1470
+ ctx.shadowBlur = 0;
1471
+ }
1472
+ if (strokeColor && strokeWidth > 0) {
1473
+ ctx.strokeStyle = strokeColor;
1474
+ ctx.lineWidth = strokeWidth;
1475
+ ctx.strokeText(char, currentX, y);
1476
+ }
1477
+ ctx.fillText(char, currentX, y);
1410
1478
  ctx.shadowBlur = 0;
1411
1479
  }
1412
- if (strokeColor && strokeWidth > 0) {
1413
- ctx.strokeStyle = strokeColor;
1414
- ctx.lineWidth = strokeWidth;
1415
- ctx.strokeText(char, currentX, y);
1416
- }
1417
- ctx.fillText(char, currentX, y);
1418
- ctx.shadowBlur = 0;
1480
+ currentX += measureTextWidth(ctx, char, fontSize, fontFamily, fontWeight);
1481
+ charIndexInText++;
1419
1482
  }
1420
- currentX += measureTextWidth(ctx, char, fontSize, fontFamily, fontWeight);
1421
- charIndexInText++;
1422
1483
  }
1484
+ } finally {
1485
+ ctx.restore();
1423
1486
  }
1424
- ctx.restore();
1425
1487
  }
1426
1488
  function usToFrame(us, fps) {
1427
1489
  return Math.floor(us / (1e6 / fps));
@@ -1485,57 +1547,63 @@ function renderWordByWordFancy(ctx, layer, canvasWidth, canvasHeight, relativeFr
1485
1547
  }
1486
1548
  }
1487
1549
  ctx.save();
1488
- ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;
1489
- ctx.textAlign = "center";
1490
- ctx.textBaseline = "middle";
1491
- ctx.lineJoin = "round";
1492
- ctx.lineCap = "round";
1493
- for (const wordPos of wordPositions) {
1494
- let backgroundOpacity = 0;
1495
- let backgroundScale = 0.8;
1496
- if (wordPos.timing) {
1497
- const { startFrame, endFrame } = wordPos.timing;
1498
- const preStartFrames = 3;
1499
- const isActive = relativeFrame >= startFrame && relativeFrame <= endFrame;
1500
- if (isActive) {
1501
- const scaleSpringIn = springEasing(relativeFrame - (startFrame - preStartFrames), {
1502
- damping: 6,
1503
- mass: 0.35,
1504
- stiffness: 200,
1505
- overshootClamping: false
1506
- });
1507
- const inProgress = interpolate(relativeFrame, [startFrame, startFrame + 1], [0, 1], {
1508
- extrapolateLeft: "clamp",
1509
- extrapolateRight: "clamp"
1510
- });
1511
- backgroundOpacity = 0.9 * inProgress;
1512
- backgroundScale = 0.8 + scaleSpringIn * 0.45;
1513
- } else if (relativeFrame > endFrame) {
1514
- backgroundOpacity = 0;
1515
- backgroundScale = 0.8;
1516
- }
1517
- if (backgroundOpacity > 0) {
1518
- const padding = 8;
1519
- const bgWidth = (wordPos.width + padding * 2) * backgroundScale;
1520
- const bgHeight = (fontSize + padding) * backgroundScale;
1521
- ctx.save();
1522
- ctx.globalAlpha = backgroundOpacity;
1523
- ctx.fillStyle = highlightBackgroundColor;
1524
- ctx.beginPath();
1525
- ctx.roundRect(wordPos.x - bgWidth / 2, wordPos.y - bgHeight / 2, bgWidth, bgHeight, 8);
1526
- ctx.fill();
1527
- ctx.restore();
1550
+ try {
1551
+ ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;
1552
+ ctx.textAlign = "center";
1553
+ ctx.textBaseline = "middle";
1554
+ ctx.lineJoin = "round";
1555
+ ctx.lineCap = "round";
1556
+ for (const wordPos of wordPositions) {
1557
+ let backgroundOpacity = 0;
1558
+ let backgroundScale = 0.8;
1559
+ if (wordPos.timing) {
1560
+ const { startFrame, endFrame } = wordPos.timing;
1561
+ const preStartFrames = 3;
1562
+ const isActive = relativeFrame >= startFrame && relativeFrame <= endFrame;
1563
+ if (isActive) {
1564
+ const scaleSpringIn = springEasing(relativeFrame - (startFrame - preStartFrames), {
1565
+ damping: 6,
1566
+ mass: 0.35,
1567
+ stiffness: 200,
1568
+ overshootClamping: false
1569
+ });
1570
+ const inProgress = interpolate(relativeFrame, [startFrame, startFrame + 1], [0, 1], {
1571
+ extrapolateLeft: "clamp",
1572
+ extrapolateRight: "clamp"
1573
+ });
1574
+ backgroundOpacity = 0.9 * inProgress;
1575
+ backgroundScale = 0.8 + scaleSpringIn * 0.45;
1576
+ } else if (relativeFrame > endFrame) {
1577
+ backgroundOpacity = 0;
1578
+ backgroundScale = 0.8;
1579
+ }
1580
+ if (backgroundOpacity > 0) {
1581
+ const padding = 8;
1582
+ const bgWidth = (wordPos.width + padding * 2) * backgroundScale;
1583
+ const bgHeight = (fontSize + padding) * backgroundScale;
1584
+ ctx.save();
1585
+ try {
1586
+ ctx.globalAlpha = backgroundOpacity;
1587
+ ctx.fillStyle = highlightBackgroundColor;
1588
+ ctx.beginPath();
1589
+ ctx.roundRect(wordPos.x - bgWidth / 2, wordPos.y - bgHeight / 2, bgWidth, bgHeight, 8);
1590
+ ctx.fill();
1591
+ } finally {
1592
+ ctx.restore();
1593
+ }
1594
+ }
1528
1595
  }
1596
+ if (strokeColor && strokeWidth > 0) {
1597
+ ctx.strokeStyle = strokeColor;
1598
+ ctx.lineWidth = strokeWidth;
1599
+ ctx.strokeText(wordPos.text, wordPos.x, wordPos.y);
1600
+ }
1601
+ ctx.fillStyle = fill;
1602
+ ctx.fillText(wordPos.text, wordPos.x, wordPos.y);
1529
1603
  }
1530
- if (strokeColor && strokeWidth > 0) {
1531
- ctx.strokeStyle = strokeColor;
1532
- ctx.lineWidth = strokeWidth;
1533
- ctx.strokeText(wordPos.text, wordPos.x, wordPos.y);
1534
- }
1535
- ctx.fillStyle = fill;
1536
- ctx.fillText(wordPos.text, wordPos.x, wordPos.y);
1604
+ } finally {
1605
+ ctx.restore();
1537
1606
  }
1538
- ctx.restore();
1539
1607
  }
1540
1608
  class LayerRenderer {
1541
1609
  ctx;
@@ -1929,7 +1997,6 @@ class TransitionProcessor {
1929
1997
  return true;
1930
1998
  }
1931
1999
  applyWipe(ctx, progress, direction) {
1932
- ctx.save();
1933
2000
  ctx.beginPath();
1934
2001
  switch (direction) {
1935
2002
  case "left":
@@ -2268,13 +2335,185 @@ class FilterProcessor {
2268
2335
  return this.filterCache.size;
2269
2336
  }
2270
2337
  }
2338
+ class OwnedFrameTransform {
2339
+ readable;
2340
+ writable;
2341
+ transform;
2342
+ flush;
2343
+ disposeInput;
2344
+ disposeOutput;
2345
+ onRelease;
2346
+ inputLimit;
2347
+ outputLimit;
2348
+ queued = [];
2349
+ inFlight = null;
2350
+ owned = [];
2351
+ waiters = [];
2352
+ inputOpen = true;
2353
+ closing = false;
2354
+ finished = false;
2355
+ failure = null;
2356
+ writableController;
2357
+ constructor({
2358
+ transform,
2359
+ flush,
2360
+ // Inputs are native frames unless the caller says how to dispose them.
2361
+ disposeInput = (input) => input.close(),
2362
+ disposeOutput = (item) => item.close(),
2363
+ onRelease = () => {
2364
+ },
2365
+ inputHighWaterMark = 1,
2366
+ outputHighWaterMark = 1
2367
+ }) {
2368
+ this.transform = transform;
2369
+ this.flush = flush;
2370
+ this.disposeInput = disposeInput;
2371
+ this.disposeOutput = disposeOutput;
2372
+ this.onRelease = onRelease;
2373
+ this.inputLimit = inputHighWaterMark;
2374
+ this.outputLimit = outputHighWaterMark;
2375
+ this.readable = new ReadableStream(
2376
+ {
2377
+ pull: (controller) => this.pullOutput(controller),
2378
+ cancel: (reason) => {
2379
+ this.stop(null);
2380
+ this.writableController?.error(reason);
2381
+ }
2382
+ },
2383
+ { highWaterMark: 0 }
2384
+ );
2385
+ this.writable = new WritableStream(
2386
+ {
2387
+ start: (controller) => {
2388
+ this.writableController = controller;
2389
+ },
2390
+ write: (input) => this.writeInput(input),
2391
+ close: () => this.closeInput(),
2392
+ abort: (reason) => this.stop(reason ?? new Error("OwnedFrameTransform aborted"))
2393
+ },
2394
+ { highWaterMark: 1 }
2395
+ );
2396
+ void this.run();
2397
+ }
2398
+ error(reason) {
2399
+ this.stop(reason);
2400
+ this.writableController?.error(reason);
2401
+ }
2402
+ async writeInput(input) {
2403
+ if (this.finished) {
2404
+ this.disposeInput(input);
2405
+ throw this.failure ?? new Error("OwnedFrameTransform cancelled");
2406
+ }
2407
+ this.queued.push(input);
2408
+ this.wake();
2409
+ while (this.queued.length > this.inputLimit && !this.finished) await this.wait();
2410
+ if (this.finished) throw this.failure ?? new Error("OwnedFrameTransform cancelled");
2411
+ }
2412
+ async closeInput() {
2413
+ this.inputOpen = false;
2414
+ this.wake();
2415
+ while (!this.closing && !this.finished) await this.wait();
2416
+ if (this.finished) throw this.failure ?? new Error("OwnedFrameTransform cancelled");
2417
+ }
2418
+ async run() {
2419
+ try {
2420
+ for (; ; ) {
2421
+ while (!this.finished && this.owned.length >= this.outputLimit) await this.wait();
2422
+ while (!this.finished && this.queued.length === 0 && this.inputOpen) await this.wait();
2423
+ if (this.finished) return;
2424
+ if (this.queued.length === 0) {
2425
+ if (this.flush) await this.flush((item) => this.admit(item));
2426
+ if (this.finished) return;
2427
+ this.closing = true;
2428
+ this.wake();
2429
+ return;
2430
+ }
2431
+ const input = this.queued.shift();
2432
+ this.wake();
2433
+ this.inFlight = input;
2434
+ await this.transform(
2435
+ input,
2436
+ (item) => this.admit(item),
2437
+ () => {
2438
+ if (this.inFlight === input) this.inFlight = null;
2439
+ }
2440
+ );
2441
+ if (this.inFlight === input) this.inFlight = null;
2442
+ }
2443
+ } catch (error) {
2444
+ this.stop(error);
2445
+ }
2446
+ }
2447
+ /** Hands an output item to the stream. The stream owns it until a reader takes it. */
2448
+ admit(item) {
2449
+ if (this.finished) {
2450
+ this.disposeOutput(item);
2451
+ return;
2452
+ }
2453
+ this.owned.push(item);
2454
+ this.wake();
2455
+ }
2456
+ async pullOutput(controller) {
2457
+ while (this.owned.length === 0 && !this.finished && !this.closing) await this.wait();
2458
+ if (this.finished) {
2459
+ if (this.failure) controller.error(this.failure);
2460
+ return;
2461
+ }
2462
+ if (this.owned.length > 0) {
2463
+ controller.enqueue(this.owned.shift());
2464
+ this.wake();
2465
+ return;
2466
+ }
2467
+ controller.close();
2468
+ }
2469
+ stop(error) {
2470
+ if (this.finished) return;
2471
+ this.finished = true;
2472
+ this.failure = error ?? null;
2473
+ const inFlight = this.inFlight;
2474
+ this.inFlight = null;
2475
+ if (inFlight) this.disposeInput(inFlight);
2476
+ for (const input of this.queued.splice(0)) this.disposeInput(input);
2477
+ for (const item of this.owned.splice(0)) this.disposeOutput(item);
2478
+ this.onRelease();
2479
+ this.wake();
2480
+ }
2481
+ wait() {
2482
+ return new Promise((resolve) => this.waiters.push(resolve));
2483
+ }
2484
+ wake() {
2485
+ for (const resume of this.waiters.splice(0)) resume();
2486
+ }
2487
+ }
2488
+ function renderLayers(layers, renderLayer, onLayerError) {
2489
+ for (const layer of layers) {
2490
+ if (!layer.visible || layer.opacity <= 0) continue;
2491
+ if (!onLayerError) {
2492
+ renderLayer(layer);
2493
+ continue;
2494
+ }
2495
+ try {
2496
+ renderLayer(layer);
2497
+ } catch (error) {
2498
+ onLayerError(layer, error);
2499
+ }
2500
+ }
2501
+ }
2271
2502
  const closeLayerFrame = (layer) => {
2503
+ if (layer.type === "image") {
2504
+ const imageLayer = layer;
2505
+ if (imageLayer.ownedSource && imageLayer.source) {
2506
+ imageLayer.source.close();
2507
+ imageLayer.source = null;
2508
+ }
2509
+ }
2272
2510
  if (layer.type === "video") {
2273
2511
  const videoLayer = layer;
2274
2512
  if (!videoLayer.rcFrame) {
2275
2513
  const vf = videoLayer.videoFrame;
2276
2514
  if (vf?.close) {
2277
2515
  vf.close();
2516
+ videoLayer.videoFrame = void 0;
2278
2517
  }
2279
2518
  }
2280
2519
  }
@@ -2282,6 +2521,7 @@ const closeLayerFrame = (layer) => {
2282
2521
  class VideoComposer {
2283
2522
  config;
2284
2523
  canvas;
2524
+ fontAbort = new AbortController();
2285
2525
  ctx;
2286
2526
  layerRenderer;
2287
2527
  transitionProcessor;
@@ -2358,31 +2598,28 @@ class VideoComposer {
2358
2598
  };
2359
2599
  }
2360
2600
  createStreams(_instruction) {
2361
- const stream = new TransformStream(
2362
- {
2363
- transform: async (request, controller) => {
2364
- const t0 = performance.now();
2365
- const result = await this.composeFrame(request);
2366
- this.traceComposeMs += performance.now() - t0;
2367
- this.traceComposeFrames++;
2368
- if (result.frame) {
2369
- controller.enqueue(result.frame);
2370
- }
2371
- },
2372
- flush: async () => {
2373
- this.filterProcessor.clearCache();
2374
- clearTextLayoutCache();
2375
- clearCaptionStaggerCache();
2601
+ return new OwnedFrameTransform({
2602
+ transform: async (request, admit) => {
2603
+ const t0 = performance.now();
2604
+ const result = await this.composeFrame(request);
2605
+ this.traceComposeMs += performance.now() - t0;
2606
+ this.traceComposeFrames++;
2607
+ if (result.frame) {
2608
+ admit(result.frame);
2376
2609
  }
2377
2610
  },
2378
- {
2379
- highWaterMark: this.config.inputHighWaterMark
2611
+ flush: async () => {
2612
+ this.filterProcessor.clearCache();
2613
+ clearTextLayoutCache();
2614
+ clearCaptionStaggerCache();
2380
2615
  },
2381
- {
2382
- highWaterMark: this.config.outputHighWaterMark
2383
- }
2384
- );
2385
- return stream;
2616
+ // The request's layers hold native frames; a stream that ends early closes them.
2617
+ disposeInput: (request) => {
2618
+ for (const layer of request.layers) closeLayerFrame(layer);
2619
+ },
2620
+ inputHighWaterMark: this.config.inputHighWaterMark,
2621
+ outputHighWaterMark: this.config.outputHighWaterMark
2622
+ });
2386
2623
  }
2387
2624
  /** 重置合成耗时埋点(每次导出开始时由 export.worker 调用)。 */
2388
2625
  resetTraceStats() {
@@ -2394,13 +2631,28 @@ class VideoComposer {
2394
2631
  return { composeMs: this.traceComposeMs, composeFrames: this.traceComposeFrames };
2395
2632
  }
2396
2633
  async composeFrame(request) {
2634
+ const signal = request.signal;
2635
+ try {
2636
+ signal?.throwIfAborted();
2637
+ return await this.composeLayers(request, signal);
2638
+ } finally {
2639
+ for (const layer of request.layers) closeLayerFrame(layer);
2640
+ }
2641
+ }
2642
+ async composeLayers(request, signal) {
2397
2643
  if (this.fontsLoadingPromise) {
2398
2644
  try {
2399
- await this.withTimeout(this.fontsLoadingPromise, VideoComposer.FONT_LOAD_TIMEOUT_MS);
2400
- } catch {
2645
+ await this.withTimeout(
2646
+ this.fontsLoadingPromise,
2647
+ VideoComposer.FONT_LOAD_TIMEOUT_MS,
2648
+ signal
2649
+ );
2650
+ } catch (error) {
2651
+ if (signal?.aborted) throw error;
2401
2652
  }
2402
2653
  this.fontsLoadingPromise = null;
2403
2654
  }
2655
+ signal?.throwIfAborted();
2404
2656
  if (request.layers.length > this.config.maxLayers) {
2405
2657
  throw new Error(`Too many layers: ${request.layers.length} > ${this.config.maxLayers}`);
2406
2658
  }
@@ -2408,47 +2660,28 @@ class VideoComposer {
2408
2660
  const frameDurationUs = 1e6 / this.config.fps;
2409
2661
  const relativeFrame = Math.floor(request.timeUs / frameDurationUs);
2410
2662
  this.layerRenderer.setCurrentFrame(relativeFrame);
2411
- if (request.transition) {
2412
- this.ctx.save();
2413
- this.transitionProcessor.applyTransition(this.ctx, request.transition);
2414
- }
2415
- for (const layer of request.layers) {
2416
- if (!layer.visible || layer.opacity <= 0) {
2417
- closeLayerFrame(layer);
2418
- continue;
2419
- }
2420
- try {
2421
- const videoLayer = layer;
2422
- if (videoLayer.rcFrame) {
2423
- videoLayer.rcFrame.use((frame2) => {
2424
- videoLayer.videoFrame = frame2;
2425
- if (layer.filters && layer.filters.length > 0) {
2426
- this.ctx.save();
2427
- this.filterProcessor.applyFilters(this.ctx, layer.filters);
2428
- }
2429
- this.layerRenderer.renderLayer(layer);
2430
- if (layer.filters && layer.filters.length > 0) {
2431
- this.ctx.restore();
2432
- }
2433
- });
2434
- } else {
2435
- if (layer.filters && layer.filters.length > 0) {
2436
- this.ctx.save();
2437
- this.filterProcessor.applyFilters(this.ctx, layer.filters);
2438
- }
2439
- this.layerRenderer.renderLayer(layer);
2440
- if (layer.filters && layer.filters.length > 0) {
2441
- this.ctx.restore();
2663
+ if (request.transition) this.ctx.save();
2664
+ try {
2665
+ if (request.transition) {
2666
+ this.transitionProcessor.applyTransition(this.ctx, request.transition);
2667
+ }
2668
+ renderLayers(
2669
+ request.layers,
2670
+ (layer) => {
2671
+ const videoLayer = layer;
2672
+ if (videoLayer.rcFrame) {
2673
+ videoLayer.rcFrame.use((frame2) => {
2674
+ videoLayer.videoFrame = frame2;
2675
+ this.renderIsolatedLayer(layer);
2676
+ });
2677
+ } else {
2678
+ this.renderIsolatedLayer(layer);
2442
2679
  }
2443
- }
2444
- } catch (error) {
2445
- console.error("[VideoComposer] composeFrame error: ", error);
2446
- } finally {
2447
- closeLayerFrame(layer);
2448
- }
2449
- }
2450
- if (request.transition) {
2451
- this.ctx.restore();
2680
+ },
2681
+ request.onLayerError
2682
+ );
2683
+ } finally {
2684
+ if (request.transition) this.ctx.restore();
2452
2685
  }
2453
2686
  let frame = null;
2454
2687
  if (!this.config.externalCanvas) {
@@ -2459,6 +2692,22 @@ class VideoComposer {
2459
2692
  timeUs: request.timeUs
2460
2693
  };
2461
2694
  }
2695
+ /**
2696
+ * Draws one layer inside its own save()/restore(), so whatever state it sets (alpha, composite operation, filter,
2697
+ * transform, font, clip) is undone when it finishes or throws. This relies on every renderer below pairing its own
2698
+ * save() with a restore() in a finally; then a throw unwinds the stack to exactly where this layer started.
2699
+ */
2700
+ renderIsolatedLayer(layer) {
2701
+ this.ctx.save();
2702
+ try {
2703
+ if (layer.filters && layer.filters.length > 0) {
2704
+ this.filterProcessor.applyFilters(this.ctx, layer.filters);
2705
+ }
2706
+ this.layerRenderer.renderLayer(layer);
2707
+ } finally {
2708
+ this.ctx.restore();
2709
+ }
2710
+ }
2462
2711
  async composeTransition(fromRequest, toRequest, transition) {
2463
2712
  await this.composeFrame(fromRequest);
2464
2713
  const toFrameRequest = {
@@ -2502,44 +2751,30 @@ class VideoComposer {
2502
2751
  fontFace.load(),
2503
2752
  VideoComposer.FONT_LOAD_TIMEOUT_MS
2504
2753
  );
2505
- if ("fonts" in self) {
2506
- self.fonts.add(loadedFont);
2507
- }
2754
+ const fontSet = typeof document !== "undefined" ? document.fonts : self.fonts;
2755
+ fontSet.add(loadedFont);
2508
2756
  this.loadedFonts.add(font.family);
2509
2757
  } catch {
2510
2758
  }
2511
2759
  }
2512
2760
  }
2513
- async withTimeout(promise, timeoutMs) {
2514
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
2515
- return promise;
2516
- }
2517
- let timeoutId = null;
2761
+ async withTimeout(promise, timeoutMs, signal = this.fontAbort.signal) {
2762
+ signal?.throwIfAborted();
2763
+ let timer;
2764
+ let abort;
2518
2765
  try {
2519
- const safe = promise.then(
2520
- (value) => ({ ok: true, value }),
2521
- (error) => ({ ok: false, error })
2522
- );
2523
- const result = await Promise.race([
2524
- safe,
2766
+ return await Promise.race([
2767
+ promise,
2525
2768
  new Promise((_, reject) => {
2526
- timeoutId = setTimeout(
2527
- () => reject(new Error(`Timeout after ${timeoutMs}ms`)),
2528
- timeoutMs
2529
- );
2769
+ abort = () => reject(signal?.reason);
2770
+ signal?.addEventListener("abort", abort, { once: true });
2771
+ if (timeoutMs > 0)
2772
+ timer = setTimeout(() => reject(new Error("Font load timeout")), timeoutMs);
2530
2773
  })
2531
2774
  ]);
2532
- if (result?.ok === true) {
2533
- return result.value;
2534
- }
2535
- if (result?.ok === false) {
2536
- throw result.error;
2537
- }
2538
- return result;
2539
2775
  } finally {
2540
- if (timeoutId !== null) {
2541
- clearTimeout(timeoutId);
2542
- }
2776
+ clearTimeout(timer);
2777
+ if (abort) signal?.removeEventListener("abort", abort);
2543
2778
  }
2544
2779
  }
2545
2780
  updateConfig(config) {
@@ -2561,13 +2796,16 @@ class VideoComposer {
2561
2796
  }
2562
2797
  }
2563
2798
  dispose() {
2799
+ this.fontAbort.abort(new DOMException("Composer disposed", "AbortError"));
2564
2800
  this.filterProcessor.clearCache();
2565
2801
  }
2566
2802
  }
2567
2803
  class BaseEncoder {
2568
2804
  encoder;
2569
2805
  config;
2570
- controller = null;
2806
+ output = null;
2807
+ cancelError = null;
2808
+ queueWaiters = /* @__PURE__ */ new Set();
2571
2809
  // 导出耗时埋点:WebCodecs encode() 异步非阻塞,编码真实开销体现在「背压等待」与「flush 排空」。
2572
2810
  traceBackpressureMs = 0;
2573
2811
  traceFlushMs = 0;
@@ -2614,7 +2852,9 @@ class BaseEncoder {
2614
2852
  console.warn("Encoder is already initialized, skipping initialization");
2615
2853
  return;
2616
2854
  }
2855
+ if (this.cancelError) throw this.cancelError;
2617
2856
  const isSupported = await this.isConfigSupported(this.config);
2857
+ if (this.cancelError) throw this.cancelError;
2618
2858
  if (!isSupported.supported) {
2619
2859
  console.warn("Codec not supported:", JSON.stringify(this.config));
2620
2860
  throw new Error(`Codec not supported: ${JSON.stringify(this.config)}`);
@@ -2672,6 +2912,51 @@ class BaseEncoder {
2672
2912
  this.onReset();
2673
2913
  console.info("Encoder is resetted");
2674
2914
  }
2915
+ waitForQueueDrain(codec) {
2916
+ return new Promise((resolve, reject) => {
2917
+ let timer;
2918
+ let settled = false;
2919
+ const finish = (error) => {
2920
+ if (settled) return;
2921
+ settled = true;
2922
+ clearTimeout(timer);
2923
+ this.queueWaiters.delete(finish);
2924
+ if (error) reject(error);
2925
+ else resolve();
2926
+ };
2927
+ this.queueWaiters.add(finish);
2928
+ const check = () => {
2929
+ if (this.cancelError) {
2930
+ finish(this.cancelError);
2931
+ } else if (this.encoder !== codec || codec.state !== "configured") {
2932
+ finish();
2933
+ } else if (codec.encodeQueueSize < this.encodeQueueThreshold - 1) {
2934
+ finish();
2935
+ } else {
2936
+ timer = setTimeout(check, 10);
2937
+ }
2938
+ };
2939
+ check();
2940
+ });
2941
+ }
2942
+ /** Aborts the owner's work: rejects pending waits, closes the native encoder and errors the stream. */
2943
+ cancel(reason) {
2944
+ if (this.cancelError) return;
2945
+ const message = reason instanceof Error ? reason.message : reason == null ? "Codec owner cancelled" : String(reason);
2946
+ const error = reason instanceof DOMException && reason.name === "AbortError" ? reason : new DOMException(message, "AbortError");
2947
+ this.cancelError = error;
2948
+ const codec = this.encoder;
2949
+ this.encoder = void 0;
2950
+ for (const reject of Array.from(this.queueWaiters)) reject(error);
2951
+ try {
2952
+ if (codec && codec.state !== "closed") codec.close();
2953
+ } catch {
2954
+ }
2955
+ try {
2956
+ this.output?.error(error);
2957
+ } catch {
2958
+ }
2959
+ }
2675
2960
  async close() {
2676
2961
  console.info("Encoder is closing...");
2677
2962
  if (!this.encoder) {
@@ -2691,16 +2976,7 @@ class BaseEncoder {
2691
2976
  return this.encoder?.encodeQueueSize ?? 0;
2692
2977
  }
2693
2978
  handleOutput(chunk, metadata) {
2694
- if (this.controller) {
2695
- try {
2696
- this.controller.enqueue({ chunk, metadata });
2697
- } catch (error) {
2698
- console.error("Encoder output error:", error);
2699
- if (!(error instanceof TypeError && error.message.includes("closed"))) {
2700
- throw error;
2701
- }
2702
- }
2703
- }
2979
+ this.output?.admit({ chunk, metadata });
2704
2980
  }
2705
2981
  handleError(error) {
2706
2982
  if (error.message.includes("reclaimed")) {
@@ -2714,7 +2990,7 @@ class BaseEncoder {
2714
2990
  queueSize: this.queueSize,
2715
2991
  platform: typeof navigator !== "undefined" ? navigator.platform : "unknown"
2716
2992
  });
2717
- this.controller?.error(error);
2993
+ this.output?.error(error);
2718
2994
  }
2719
2995
  // Hook for subclasses to handle reset
2720
2996
  onReset() {
@@ -2724,55 +3000,45 @@ class BaseEncoder {
2724
3000
  * Implements common stream logic with backpressure handling
2725
3001
  */
2726
3002
  createStream() {
2727
- return new TransformStream(
2728
- {
2729
- start: async (controller) => {
2730
- this.controller = controller;
2731
- },
2732
- transform: async (input) => {
2733
- if (!this.isReady) {
2734
- console.warn("Encoder is not ready, initializing 1...");
2735
- await this.initialize();
2736
- }
2737
- if (this.encoder && this.encoder.encodeQueueSize >= this.encodeQueueThreshold) {
2738
- const bp0 = performance.now();
2739
- await new Promise((resolve) => {
2740
- const check = () => {
2741
- if (!this.encoder || this.encoder.encodeQueueSize < this.encodeQueueThreshold - 1) {
2742
- resolve();
2743
- } else {
2744
- setTimeout(check, 10);
2745
- }
2746
- };
2747
- check();
2748
- });
2749
- this.traceBackpressureMs += performance.now() - bp0;
2750
- }
2751
- if (!this.isReady) {
2752
- console.warn("Encoder is not ready, initializing 2...");
2753
- await this.initialize();
2754
- }
2755
- if (!this.encoder || this.encoder.state !== "configured") {
2756
- console.error("Encoder not configured, throwing error");
2757
- throw new Error("Encoder not configured");
2758
- }
2759
- const frame = input.frame || input;
2760
- this.encode(frame);
2761
- this.traceFrames++;
2762
- },
2763
- flush: async () => {
2764
- const flush0 = performance.now();
2765
- await this.flush();
2766
- this.traceFlushMs += performance.now() - flush0;
3003
+ this.output = new OwnedFrameTransform({
3004
+ transform: async (input, _admit, releaseInput) => {
3005
+ if (this.cancelError) throw this.cancelError;
3006
+ if (!this.isReady) {
3007
+ console.warn("Encoder is not ready, initializing 1...");
3008
+ await this.initialize();
3009
+ }
3010
+ if (this.encoder && this.encoder.encodeQueueSize >= this.encodeQueueThreshold) {
3011
+ const bp0 = performance.now();
3012
+ await this.waitForQueueDrain(this.encoder);
3013
+ this.traceBackpressureMs += performance.now() - bp0;
3014
+ }
3015
+ if (!this.isReady) {
3016
+ console.warn("Encoder is not ready, initializing 2...");
3017
+ await this.initialize();
2767
3018
  }
3019
+ if (!this.encoder || this.encoder.state !== "configured") {
3020
+ console.error("Encoder not configured, throwing error");
3021
+ throw new Error("Encoder not configured");
3022
+ }
3023
+ const frame = input.frame || input;
3024
+ this.encode(frame);
3025
+ releaseInput();
3026
+ this.traceFrames++;
2768
3027
  },
2769
- // Queuing strategy with backpressure configuration
2770
- {
2771
- highWaterMark: this.highWaterMark,
2772
- size: () => 1
2773
- // Count-based
2774
- }
2775
- );
3028
+ flush: async () => {
3029
+ if (this.cancelError) throw this.cancelError;
3030
+ const flush0 = performance.now();
3031
+ await this.flush();
3032
+ this.traceFlushMs += performance.now() - flush0;
3033
+ },
3034
+ disposeInput: (input) => (input.frame || input).close(),
3035
+ // Encoded chunks hold no native resource.
3036
+ disposeOutput: () => {
3037
+ },
3038
+ // The writable side's bound, as the TransformStream's queuing strategy set it.
3039
+ inputHighWaterMark: this.highWaterMark
3040
+ });
3041
+ return this.output;
2776
3042
  }
2777
3043
  /** 重置编码耗时埋点(每次导出开始时由 export.worker 调用)。 */
2778
3044
  resetTraceStats() {
@@ -2971,21 +3237,20 @@ class FrameRateConverter {
2971
3237
  * Create a TransformStream that converts VFR frames to CFR frames
2972
3238
  */
2973
3239
  createStream() {
2974
- return new TransformStream({
2975
- start: () => {
2976
- this.targetFrameIndex = 0;
2977
- this.targetFrameTimeUs = 0;
2978
- this.sourceFrameBuffer = [];
2979
- this.sourceFrameCount = 0;
2980
- this.outputFrameCount = 0;
2981
- this.maxSourceTimestampUs = null;
3240
+ this.targetFrameIndex = 0;
3241
+ this.targetFrameTimeUs = 0;
3242
+ this.sourceFrameBuffer = [];
3243
+ this.sourceFrameCount = 0;
3244
+ this.outputFrameCount = 0;
3245
+ this.maxSourceTimestampUs = null;
3246
+ return new OwnedFrameTransform({
3247
+ transform: async (sourceFrame, admit, releaseInput) => {
3248
+ this.processSourceFrame(sourceFrame, { enqueue: admit }, releaseInput);
2982
3249
  },
2983
- transform: (sourceFrame, controller) => {
2984
- this.processSourceFrame(sourceFrame, controller);
3250
+ flush: async (admit) => {
3251
+ this.flushRemainingFrames({ enqueue: admit });
2985
3252
  },
2986
- flush: (controller) => {
2987
- this.flushRemainingFrames(controller);
2988
- }
3253
+ onRelease: () => this.cleanupAllFrames(null)
2989
3254
  });
2990
3255
  }
2991
3256
  sourceFrameCount = 0;
@@ -2993,10 +3258,11 @@ class FrameRateConverter {
2993
3258
  /**
2994
3259
  * Process incoming source frame and output target frames
2995
3260
  */
2996
- processSourceFrame(sourceFrame, controller) {
3261
+ processSourceFrame(sourceFrame, controller, releaseInput) {
2997
3262
  const sourceTimestamp = sourceFrame.timestamp ?? 0;
2998
3263
  if (sourceTimestamp < this.trimStartUs) {
2999
3264
  sourceFrame.close();
3265
+ releaseInput();
3000
3266
  return;
3001
3267
  }
3002
3268
  let frameToBuffer;
@@ -3011,6 +3277,7 @@ class FrameRateConverter {
3011
3277
  frameToBuffer = sourceFrame;
3012
3278
  }
3013
3279
  this.sourceFrameBuffer.push(frameToBuffer);
3280
+ releaseInput();
3014
3281
  this.sourceFrameCount++;
3015
3282
  const bufferedTs = frameToBuffer.timestamp ?? 0;
3016
3283
  this.maxSourceTimestampUs = this.maxSourceTimestampUs === null ? bufferedTs : Math.max(this.maxSourceTimestampUs, bufferedTs);
@@ -3401,21 +3668,33 @@ class ExportWorker {
3401
3668
  const fpsConverter = new FrameRateConverter(fps, timelineWindowUs, windowStartUs, playbackRate);
3402
3669
  const cfrStream = stream.pipeThrough(fpsConverter.createStream());
3403
3670
  const composeRequestStream = cfrStream.pipeThrough(
3404
- new TransformStream({
3405
- transform: (frame, controller) => {
3671
+ new OwnedFrameTransform({
3672
+ transform: (frame, admit, releaseInput) => {
3406
3673
  let composeFrame = frame;
3407
3674
  if (windowToClipOffsetUs !== 0) {
3408
3675
  composeFrame = new VideoFrame(frame, {
3409
3676
  timestamp: (frame.timestamp ?? 0) + windowToClipOffsetUs
3410
3677
  });
3411
3678
  frame.close();
3679
+ releaseInput();
3680
+ }
3681
+ let request;
3682
+ try {
3683
+ request = this.buildComposeRequest(this.instructions, composeFrame);
3684
+ } catch (error) {
3685
+ composeFrame.close();
3686
+ if (composeFrame === frame) releaseInput();
3687
+ throw error;
3412
3688
  }
3413
- const request = this.buildComposeRequest(this.instructions, composeFrame);
3414
3689
  if (!request) {
3415
3690
  composeFrame.close();
3691
+ if (composeFrame === frame) releaseInput();
3416
3692
  return;
3417
3693
  }
3418
- controller.enqueue(request);
3694
+ admit(request);
3695
+ },
3696
+ disposeOutput: (request) => {
3697
+ for (const layer of request.layers) closeLayerFrame(layer);
3419
3698
  }
3420
3699
  })
3421
3700
  );
@@ -3471,25 +3750,41 @@ class ExportWorker {
3471
3750
  const encodingTransform = this.encoder.createStream();
3472
3751
  const { clipDurationUs, compositionFps } = timeline;
3473
3752
  let currentTimeUs = 0;
3474
- const readableStream = new ReadableStream({
3475
- pull: (controller) => {
3476
- if (currentTimeUs >= clipDurationUs) {
3477
- controller.close();
3478
- return;
3479
- }
3480
- const videoFrame = new VideoFrame(imageBitmap, {
3481
- timestamp: currentTimeUs,
3482
- duration: frameDurationFromFps(compositionFps)
3483
- });
3484
- const request = this.buildComposeRequest(this.instructions, videoFrame);
3485
- if (request) {
3486
- controller.enqueue(request);
3487
- } else {
3488
- videoFrame.close();
3753
+ const readableStream = new ReadableStream(
3754
+ {
3755
+ pull: (controller) => {
3756
+ if (currentTimeUs >= clipDurationUs) {
3757
+ controller.close();
3758
+ return;
3759
+ }
3760
+ const videoFrame = new VideoFrame(imageBitmap, {
3761
+ timestamp: currentTimeUs,
3762
+ duration: frameDurationFromFps(compositionFps)
3763
+ });
3764
+ let request = null;
3765
+ try {
3766
+ request = this.buildComposeRequest(this.instructions, videoFrame);
3767
+ } finally {
3768
+ if (!request) videoFrame.close();
3769
+ }
3770
+ if (request) {
3771
+ if (!request.layers.some(
3772
+ (l) => l.type === "video" && l.videoFrame === videoFrame
3773
+ )) {
3774
+ videoFrame.close();
3775
+ }
3776
+ try {
3777
+ controller.enqueue(request);
3778
+ } catch (error) {
3779
+ for (const layer of request.layers) closeLayerFrame(layer);
3780
+ throw error;
3781
+ }
3782
+ }
3783
+ currentTimeUs += frameDurationFromFps(compositionFps);
3489
3784
  }
3490
- currentTimeUs += frameDurationFromFps(compositionFps);
3491
- }
3492
- });
3785
+ },
3786
+ { highWaterMark: 0 }
3787
+ );
3493
3788
  readableStream.pipeTo(composeStream.writable).catch((error) => {
3494
3789
  console.error("[ExportWorker] image frame stream error:", error);
3495
3790
  });
@@ -3524,7 +3819,7 @@ class ExportWorker {
3524
3819
  this.composer = null;
3525
3820
  }
3526
3821
  if (this.encoder) {
3527
- await this.encoder.close();
3822
+ this.encoder.cancel(new DOMException("Export worker disposed", "AbortError"));
3528
3823
  this.encoder = null;
3529
3824
  }
3530
3825
  this.imageMap.forEach((bitmap) => bitmap.close());
@@ -3581,4 +3876,4 @@ const export_worker = null;
3581
3876
  export {
3582
3877
  export_worker as default
3583
3878
  };
3584
- //# sourceMappingURL=export.worker.C8jKSbVj.js.map
3879
+ //# sourceMappingURL=export.worker.BG8HA7dY.js.map