@joplo-app/plugin-av 0.7.1 → 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.
- package/dist/guide.d.ts +1 -1
- package/dist/guide.js +9 -3
- package/dist/plugin.js +5 -1
- package/dist/runtime.js +32 -13
- package/dist/sfx.d.ts +2 -0
- package/dist/version.json +1 -1
- package/dist/video-frame.d.ts +4 -0
- package/dist/video-frame.js +69 -0
- package/package.json +2 -2
package/dist/guide.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const skill = "# Joplo media: media\n\nFor moments a product UI cannot show by itself: a short screen recording, a product shot in motion, a polished success animation. Clips play on the engine clock (pause, speed, jumps, screenshots and video export stay consistent).\nInstall at the same version as Joplo. Example: examples/media-upload.\n\nThe npm package is @joplo-app/plugin-av; its plugin namespace and skill topic remain media. For projects using the earlier source-checkout package @joplo-app/plugin-media, replace the dependency and imports with the matching plugin-av version. Keep media:Video/media:Lottie and existing playback data unchanged; never enable both manifests with the same media id.\n\n## Enable\nimport media, { Video, Lottie, playClip } from '@joplo-app/plugin-av'; config({ plugins: [ui, media, \u2026] }).\n\n## Independent local one-shot sounds\nUse withSoundEffects instead of the default media manifest (never enable both):\n```tsx\nimport { asset } from '@joplo-app/kit';\nimport { withSoundEffects, sfx } from '@joplo-app/plugin-av';\nconfig({ plugins: [ui, withSoundEffects({ send: asset('./assets/send.wav') })] });\n// In a scripted system step (not a free-reaction handler):\nsfx.play('send', { volume: .5, offsetMs: 0 });\n```\
|
|
1
|
+
export declare const skill = "# Joplo media: media\n\nFor moments a product UI cannot show by itself: a short screen recording, a product shot in motion, a polished success animation. Clips play on the engine clock (pause, speed, jumps, screenshots and video export stay consistent).\nInstall at the same version as Joplo. Example: examples/media-upload.\n\nThe npm package is @joplo-app/plugin-av; its plugin namespace and skill topic remain media. For projects using the earlier source-checkout package @joplo-app/plugin-media, replace the dependency and imports with the matching plugin-av version. Keep media:Video/media:Lottie and existing playback data unchanged; never enable both manifests with the same media id.\n\n## Enable\nimport media, { Video, Lottie, playClip } from '@joplo-app/plugin-av'; config({ plugins: [ui, media, \u2026] }).\n\n## Independent local one-shot sounds\nUse withSoundEffects instead of the default media manifest (never enable both):\n```tsx\nimport { asset } from '@joplo-app/kit';\nimport { withSoundEffects, sfx } from '@joplo-app/plugin-av';\nconfig({ plugins: [ui, withSoundEffects({ send: asset('./assets/send.wav') })] });\n// In a scripted system step (not a free-reaction handler):\nsfx.play('send', { volume: .5, offsetMs: 0, startDelayMs: 300, duck: false });\n```\nThe host has independent 4 MiB encoded and 32 MiB decoded Float32 caches shared by overlapping tracks; the 50 MiB local artifact ceiling is not playback admission. Prepared local resources report MEDIA_ENCODE_BUDGET separately, and runtime failures identify encoded/decoded bytes. This plugin currently accepts PCM WAV, so very large cues must be shortened; use another compatible local compiler for compressed FLAC rather than feeding FLAC into this WAV-only parser. First release supports local PCM WAV only (8/16/24/32-bit, 1\u20138 channels). Convert other formats offline; unknown/truncated duration is an error, never guessed. offsetMs is a source trim, not an event delay, and must be shorter than the asset. volume is 0\u20131. Optional startDelayMs (0\u201360000 engine ms) waits after the step commits without advancing the source offset or consuming the sound\u2019s natural length. Pause freezes that wait; speed changes its wall-clock duration. Omit it for the existing immediate behavior. duck defaults true (narration multiplies gain by .25); duck:false exempts this cue only, so keep its authored volume restrained. No streaming or nested audio timeline is created. Each call creates a deterministic independent one-shot event; repeated calls and Alda BGM overlap. Effects use the host clock, pause/speed/seek/chapter continuation and narration ducking, and are included in offline build/share and video audio capture. No Alda compiler, network or paid generation is needed.\n\nInspect scenario step media snapshots: track keys include stable step/event identity, resource is the generated asset ID, offsetMs is source position, endAfterMs is sounding time remaining to natural end, excluding waiting. startDelayMs preserves the original plan, delayRemainingMs is the snapshot\u2019s remaining wait, and startEventId distinguishes explicit delayed events; inherited chapter snapshots retain that identity. A static seek restores remaining wait and source position, not the original full wait. For a timeline observation at engineMs, nominal eligibility time for this observation is engineMs + delayRemainingMs, using startDelayMs only if remaining is absent. An inherited cue first seen by a chapter/deep-link export may appear as play; retain startEventId to distinguish continued observations from new explicit plays. Do not add the original delay again. If remaining is zero on a continued identity, it is already eligible: do not emit another start or infer its original onset from that snapshot. Without the earlier play observation, the original start is unknown. This predicts scheduling, not the first audible sample: a source trim, fade-in or silence inside the WAV changes audible onset, and metadata cannot establish it. The natural end removes the event without fading its volume; pause does not consume time. The same source shares the host resource cache; ending one event releases only its lease. For reproducible offline mixes retain the selected scenario timeline and packaged media assets. Resource inputs stay on the author machine; only used audio bytes ship. Use joplo check first; SFX_INVALID means fix name, PCM file or numeric options. Listen to overlapping cues with Voice enabled and record a local clip to verify the final mix.\n\n## Write\n- <Video id=\"rec\" src={asset('./upload.mp4')} w={640} h={360} fit=\"cover\" /> \u2014 MP4 or WebM in the project. Video is always muted in this version (narration and music stay the soundtrack).\n- <Lottie id=\"ok\" src={asset('./success.json')} w={160} h={160} /> \u2014 a Lottie (Bodymovin) JSON export.\n- playClip('rec') plays from where the clip last stopped to its end; playClip('rec', { from: 2, to: 5 }) plays seconds 2\u20135. The step stays until the clip ends (holdMs), so autoplay never cuts it off. Before the first play, a clip shows its start frame (start={seconds} to choose another).\n- MP4 and Lottie lengths are read at compile time. WebM length is unknown: always write { to }.\n\nStatic screenshots and paused frames copy decoded video pixels into a canvas after the requested seek, before releasing the hold. Film strips and --frames-out additionally use explicit host sampling mode: every engine sample seeks each Video to its engine-clock target, waits for decoding and commits canvas pixels before capture. Multiple videos all have to finish; pause/resume, jumps and continuing chapters keep using that same engine clock. No browser automation detection is involved.\n\nVerify moving footage with render --frames-out output/frames --fps 30, then inspect consecutive JPEGs at the expected source positions (currentTime alone is not evidence of decoded pixels). Use --film for motion diagnostics. Frame extraction retains the host's existing 50 ms observation tolerance; it does not promise sub-frame source interpolation or byte-identical encodes. A source video presents the decoded source frame containing the target time. A failed decoder or a frameReady task still pending after 10 wall-clock seconds fails the export with sample time/component context; fix the resource/codec or task cleanup and retry. Waiting never advances the engine to manufacture readiness. Real-time --video recording and normal browser playback retain native video playback and may show compositor/scheduling differences; they do not use this per-sample handshake.\n\nresetKey is scene ID plus player epoch: pause/resume does not change it; jump/reset/replay mode changes can. Continuing chapters can retain the epoch, but a changed scene still changes the key. It is not a per-step timestamp or a guarantee that the current video frame has been composited.\n\n## Assets\n- Keep clips short (\u2264 15 s) and small: 720p H.264 MP4, no audio track needed. Published sites keep every asset as its own file (assets/<hash>.<ext>), uploaded once per content.\n- Prefer licensed libraries (LottieFiles free animations under their license, your own recordings). Record the source and license in assets/SOURCES.md.\n- GIFs play on the browser's own clock and cannot be paused or seeked: show them with the ui Image, or convert them to MP4 and use Video when timing matters.\n\n## Pitfalls\n- MEDIA_SRC_INVALID: src must be asset() of an MP4/WebM (Video) or a Lottie JSON (Lottie), not a URL.\n- MEDIA_DURATION_UNKNOWN: WebM without { to }.\n- Static frames (screenshots, jumps) show the frame where the clip ends in that step; only playback moves.\n- A clip has no sound and does not duck narration; put spoken words in narrate().\n";
|
package/dist/guide.js
CHANGED
|
@@ -15,11 +15,11 @@ import { asset } from '@joplo-app/kit';
|
|
|
15
15
|
import { withSoundEffects, sfx } from '@joplo-app/plugin-av';
|
|
16
16
|
config({ plugins: [ui, withSoundEffects({ send: asset('./assets/send.wav') })] });
|
|
17
17
|
// In a scripted system step (not a free-reaction handler):
|
|
18
|
-
sfx.play('send', { volume: .5, offsetMs: 0 });
|
|
18
|
+
sfx.play('send', { volume: .5, offsetMs: 0, startDelayMs: 300, duck: false });
|
|
19
19
|
\`\`\`
|
|
20
|
-
First release supports local PCM WAV only (8/16/24/32-bit, 1–8 channels). Convert other formats offline; unknown/truncated duration is an error, never guessed. offsetMs is a source trim, not an event delay, and must be shorter than the asset. volume is 0–1. Each call creates a deterministic independent one-shot event; repeated calls and Alda BGM overlap. Effects use the host clock, pause/speed/seek/chapter continuation and narration ducking, and are included in offline build/share and video audio capture. No Alda compiler, network or paid generation is needed.
|
|
20
|
+
The host has independent 4 MiB encoded and 32 MiB decoded Float32 caches shared by overlapping tracks; the 50 MiB local artifact ceiling is not playback admission. Prepared local resources report MEDIA_ENCODE_BUDGET separately, and runtime failures identify encoded/decoded bytes. This plugin currently accepts PCM WAV, so very large cues must be shortened; use another compatible local compiler for compressed FLAC rather than feeding FLAC into this WAV-only parser. First release supports local PCM WAV only (8/16/24/32-bit, 1–8 channels). Convert other formats offline; unknown/truncated duration is an error, never guessed. offsetMs is a source trim, not an event delay, and must be shorter than the asset. volume is 0–1. Optional startDelayMs (0–60000 engine ms) waits after the step commits without advancing the source offset or consuming the sound’s natural length. Pause freezes that wait; speed changes its wall-clock duration. Omit it for the existing immediate behavior. duck defaults true (narration multiplies gain by .25); duck:false exempts this cue only, so keep its authored volume restrained. No streaming or nested audio timeline is created. Each call creates a deterministic independent one-shot event; repeated calls and Alda BGM overlap. Effects use the host clock, pause/speed/seek/chapter continuation and narration ducking, and are included in offline build/share and video audio capture. No Alda compiler, network or paid generation is needed.
|
|
21
21
|
|
|
22
|
-
Inspect scenario step media snapshots: track keys include stable step/event identity, resource is the generated asset ID, offsetMs is source position, endAfterMs is time remaining to natural end. The natural end removes the event without fading its volume; pause does not consume time. The same source shares the host resource cache; ending one event releases only its lease. For reproducible offline mixes retain the selected scenario timeline and packaged media assets. Resource inputs stay on the author machine; only used audio bytes ship. Use joplo check first; SFX_INVALID means fix name, PCM file or numeric options. Listen to overlapping cues with Voice enabled and record a local clip to verify the final mix.
|
|
22
|
+
Inspect scenario step media snapshots: track keys include stable step/event identity, resource is the generated asset ID, offsetMs is source position, endAfterMs is sounding time remaining to natural end, excluding waiting. startDelayMs preserves the original plan, delayRemainingMs is the snapshot’s remaining wait, and startEventId distinguishes explicit delayed events; inherited chapter snapshots retain that identity. A static seek restores remaining wait and source position, not the original full wait. For a timeline observation at engineMs, nominal eligibility time for this observation is engineMs + delayRemainingMs, using startDelayMs only if remaining is absent. An inherited cue first seen by a chapter/deep-link export may appear as play; retain startEventId to distinguish continued observations from new explicit plays. Do not add the original delay again. If remaining is zero on a continued identity, it is already eligible: do not emit another start or infer its original onset from that snapshot. Without the earlier play observation, the original start is unknown. This predicts scheduling, not the first audible sample: a source trim, fade-in or silence inside the WAV changes audible onset, and metadata cannot establish it. The natural end removes the event without fading its volume; pause does not consume time. The same source shares the host resource cache; ending one event releases only its lease. For reproducible offline mixes retain the selected scenario timeline and packaged media assets. Resource inputs stay on the author machine; only used audio bytes ship. Use joplo check first; SFX_INVALID means fix name, PCM file or numeric options. Listen to overlapping cues with Voice enabled and record a local clip to verify the final mix.
|
|
23
23
|
|
|
24
24
|
## Write
|
|
25
25
|
- <Video id="rec" src={asset('./upload.mp4')} w={640} h={360} fit="cover" /> — MP4 or WebM in the project. Video is always muted in this version (narration and music stay the soundtrack).
|
|
@@ -27,6 +27,12 @@ Inspect scenario step media snapshots: track keys include stable step/event iden
|
|
|
27
27
|
- playClip('rec') plays from where the clip last stopped to its end; playClip('rec', { from: 2, to: 5 }) plays seconds 2–5. The step stays until the clip ends (holdMs), so autoplay never cuts it off. Before the first play, a clip shows its start frame (start={seconds} to choose another).
|
|
28
28
|
- MP4 and Lottie lengths are read at compile time. WebM length is unknown: always write { to }.
|
|
29
29
|
|
|
30
|
+
Static screenshots and paused frames copy decoded video pixels into a canvas after the requested seek, before releasing the hold. Film strips and --frames-out additionally use explicit host sampling mode: every engine sample seeks each Video to its engine-clock target, waits for decoding and commits canvas pixels before capture. Multiple videos all have to finish; pause/resume, jumps and continuing chapters keep using that same engine clock. No browser automation detection is involved.
|
|
31
|
+
|
|
32
|
+
Verify moving footage with render --frames-out output/frames --fps 30, then inspect consecutive JPEGs at the expected source positions (currentTime alone is not evidence of decoded pixels). Use --film for motion diagnostics. Frame extraction retains the host's existing 50 ms observation tolerance; it does not promise sub-frame source interpolation or byte-identical encodes. A source video presents the decoded source frame containing the target time. A failed decoder or a frameReady task still pending after 10 wall-clock seconds fails the export with sample time/component context; fix the resource/codec or task cleanup and retry. Waiting never advances the engine to manufacture readiness. Real-time --video recording and normal browser playback retain native video playback and may show compositor/scheduling differences; they do not use this per-sample handshake.
|
|
33
|
+
|
|
34
|
+
resetKey is scene ID plus player epoch: pause/resume does not change it; jump/reset/replay mode changes can. Continuing chapters can retain the epoch, but a changed scene still changes the key. It is not a per-step timestamp or a guarantee that the current video frame has been composited.
|
|
35
|
+
|
|
30
36
|
## Assets
|
|
31
37
|
- Keep clips short (≤ 15 s) and small: 720p H.264 MP4, no audio track needed. Published sites keep every asset as its own file (assets/<hash>.<ext>), uploaded once per content.
|
|
32
38
|
- Prefer licensed libraries (LottieFiles free animations under their license, your own recordings). Record the source and license in assets/SOURCES.md.
|
package/dist/plugin.js
CHANGED
|
@@ -121,8 +121,12 @@ export function withSoundEffects(assets) {
|
|
|
121
121
|
throw new Error('volume must be 0–1');
|
|
122
122
|
if (typeof offsetMs !== 'number' || !Number.isFinite(offsetMs) || offsetMs < 0 || offsetMs >= durationMs)
|
|
123
123
|
throw new Error('offsetMs must be inside the sound duration');
|
|
124
|
+
if (p.startDelayMs !== undefined && (typeof p.startDelayMs !== 'number' || !Number.isFinite(p.startDelayMs) || p.startDelayMs < 0 || p.startDelayMs > 60000))
|
|
125
|
+
throw new Error('startDelayMs must be 0–60000 engine milliseconds');
|
|
126
|
+
if (p.duck !== undefined && typeof p.duck !== 'boolean')
|
|
127
|
+
throw new Error('duck must be boolean');
|
|
124
128
|
const resource = ctx.resource({ compiler: 'sfx', input: assets[p.name] });
|
|
125
|
-
return { media: [{ track: 'sfx', action: 'play', resource, oneShot: true, durationMs, volume, offsetMs }] };
|
|
129
|
+
return { media: [{ track: 'sfx', action: 'play', resource, oneShot: true, durationMs, volume, offsetMs, ...(p.startDelayMs !== undefined ? { startDelayMs: p.startDelayMs } : {}), ...(p.duck !== undefined ? { duck: p.duck } : {}) }] };
|
|
126
130
|
}
|
|
127
131
|
catch (error) {
|
|
128
132
|
ctx.report('SFX_INVALID', error instanceof Error ? error.message : 'Invalid sound effect', ctx.source);
|
package/dist/runtime.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
import { jsx as _jsx } from "react/jsx-runtime";
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
2
|
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
|
|
3
3
|
import lottie from 'lottie-web/build/player/lottie_light.js';
|
|
4
4
|
import { defineRuntime, embeddedAsset } from '@joplo-app/kit/plugin';
|
|
5
5
|
import { useEngineFrame, useRoot } from '@joplo-app/kit/renderer';
|
|
6
|
+
import { presentDecodedFrame, seekVideoFrame } from "./video-frame.js";
|
|
6
7
|
const num = (v, d) => (typeof v === 'number' && Number.isFinite(v) ? v : d);
|
|
7
8
|
/** 片段这一步要逐帧定位:只在它在播时订阅每一帧(D99)。 */
|
|
8
9
|
function useClipTime(ctx, clip) {
|
|
9
10
|
const clock = ctx.frame.clock;
|
|
10
|
-
useEngineFrame(!!clip?.live && ctx.frame.animate && !!clock);
|
|
11
|
+
useEngineFrame((!!clip?.live || !!ctx.frame.sampling) && ctx.frame.animate && !!clock);
|
|
11
12
|
return timeOf(ctx, clip);
|
|
12
13
|
}
|
|
13
14
|
function timeOf(ctx, clip) {
|
|
@@ -27,15 +28,25 @@ function Video({ ctx }) {
|
|
|
27
28
|
const { t, playing } = useClipTime(ctx, clip);
|
|
28
29
|
const src = embeddedAsset(p.src, 'video');
|
|
29
30
|
const ref = useRef(null);
|
|
31
|
+
const canvas = useRef(null);
|
|
32
|
+
const [frozen, setFrozen] = useState(false);
|
|
30
33
|
const { src: _s, w, h, fit, start: _st, ...rest } = p;
|
|
31
34
|
const root = useRoot(node, rest, { style: { width: num(w) ?? '100%', height: num(h) ?? 'auto', position: 'relative', overflow: 'hidden', borderRadius: 10, background: '#000' } });
|
|
32
35
|
const speed = ctx.frame.clock?.speed ?? 1;
|
|
36
|
+
const sampleTime = ctx.frame.sampling ? (ctx.frame.clock?.timeMs ?? 0) : 0;
|
|
33
37
|
useLayoutEffect(() => {
|
|
34
38
|
const v = ref.current;
|
|
35
39
|
if (!v)
|
|
36
40
|
return;
|
|
37
41
|
v.playbackRate = speed;
|
|
42
|
+
if (ctx.frame.sampling) {
|
|
43
|
+
if (!canvas.current)
|
|
44
|
+
return;
|
|
45
|
+
const image = canvas.current;
|
|
46
|
+
return ctx.frameReady(signal => seekVideoFrame(v, image, t, signal, () => setFrozen(true)));
|
|
47
|
+
}
|
|
38
48
|
if (playing) {
|
|
49
|
+
setFrozen(false);
|
|
39
50
|
if (Math.abs(v.currentTime - t) > 0.25)
|
|
40
51
|
v.currentTime = t;
|
|
41
52
|
if (v.paused)
|
|
@@ -44,7 +55,9 @@ function Video({ ctx }) {
|
|
|
44
55
|
}
|
|
45
56
|
if (!v.paused)
|
|
46
57
|
v.pause();
|
|
47
|
-
|
|
58
|
+
const present = () => { if (!canvas.current || !presentDecodedFrame(v, canvas.current, t))
|
|
59
|
+
return false; setFrozen(true); return true; };
|
|
60
|
+
if (present())
|
|
48
61
|
return;
|
|
49
62
|
// 静止画面:定位到这一帧,截图等它解码好
|
|
50
63
|
const done = ctx.hold();
|
|
@@ -53,21 +66,27 @@ function Video({ ctx }) {
|
|
|
53
66
|
released = true;
|
|
54
67
|
done();
|
|
55
68
|
} };
|
|
56
|
-
const ready = () => {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
try {
|
|
60
|
-
v.currentTime = t;
|
|
61
|
-
}
|
|
62
|
-
catch {
|
|
69
|
+
const ready = () => { if (present()) {
|
|
70
|
+
v.removeEventListener('seeked', ready);
|
|
71
|
+
v.removeEventListener('loadeddata', loaded);
|
|
63
72
|
release();
|
|
73
|
+
} };
|
|
74
|
+
const loaded = () => { if (t === 0)
|
|
75
|
+
ready(); };
|
|
76
|
+
const seek = () => { try {
|
|
77
|
+
v.currentTime = t;
|
|
64
78
|
}
|
|
79
|
+
catch { /* Metadata will retry. */ } };
|
|
80
|
+
v.addEventListener('loadedmetadata', seek);
|
|
81
|
+
v.addEventListener('seeked', ready);
|
|
82
|
+
v.addEventListener('loadeddata', loaded);
|
|
83
|
+
seek();
|
|
65
84
|
const timer = setTimeout(release, 5000);
|
|
66
|
-
return () => { clearTimeout(timer); v.removeEventListener('seeked', ready); v.removeEventListener('loadeddata',
|
|
67
|
-
}, [t, playing, speed, src]);
|
|
85
|
+
return () => { clearTimeout(timer); v.removeEventListener('loadedmetadata', seek); v.removeEventListener('seeked', ready); v.removeEventListener('loadeddata', loaded); release(); };
|
|
86
|
+
}, [t, playing, speed, src, sampleTime, ctx.frame.sampling, ctx.frame.resetKey, ctx.frame.scenarioId]);
|
|
68
87
|
if (!src)
|
|
69
88
|
return _jsx("div", { ...root });
|
|
70
|
-
return (
|
|
89
|
+
return (_jsxs("div", { ...root, children: [_jsx("video", { ref: ref, src: src, muted: true, playsInline: true, preload: "auto", style: { width: '100%', height: '100%', objectFit: fit === 'contain' ? 'contain' : 'cover', display: 'block', visibility: frozen ? 'hidden' : 'visible' } }), _jsx("canvas", { ref: canvas, "data-jvideo-presented": frozen ? '1' : '0', style: { position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: fit === 'contain' ? 'contain' : 'cover', visibility: frozen ? 'visible' : 'hidden' } })] }));
|
|
71
90
|
}
|
|
72
91
|
function Lottie({ ctx }) {
|
|
73
92
|
const node = ctx.model;
|
package/dist/sfx.d.ts
CHANGED
package/dist/version.json
CHANGED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** Copy the decoder image synchronously; native <video> compositor presentation may lag seeked. */
|
|
2
|
+
export declare function presentDecodedFrame(video: HTMLVideoElement, canvas: HTMLCanvasElement, target: number): boolean;
|
|
3
|
+
/** A cancellable decoder transaction. Its Promise settles only after the canvas owns target pixels. */
|
|
4
|
+
export declare function seekVideoFrame(video: HTMLVideoElement, canvas: HTMLCanvasElement, target: number, signal: AbortSignal, committed: () => void): Promise<void>;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/** Copy the decoder image synchronously; native <video> compositor presentation may lag seeked. */
|
|
2
|
+
export function presentDecodedFrame(video, canvas, target) {
|
|
3
|
+
if (video.seeking || video.readyState < 2 || !video.videoWidth || !video.videoHeight || Math.abs(video.currentTime - target) > .001)
|
|
4
|
+
return false;
|
|
5
|
+
const context = canvas.getContext('2d');
|
|
6
|
+
if (!context)
|
|
7
|
+
return false;
|
|
8
|
+
canvas.width = video.videoWidth;
|
|
9
|
+
canvas.height = video.videoHeight;
|
|
10
|
+
context.drawImage(video, 0, 0, canvas.width, canvas.height);
|
|
11
|
+
return true;
|
|
12
|
+
}
|
|
13
|
+
/** A cancellable decoder transaction. Its Promise settles only after the canvas owns target pixels. */
|
|
14
|
+
export function seekVideoFrame(video, canvas, target, signal, committed) {
|
|
15
|
+
return new Promise((resolve, reject) => {
|
|
16
|
+
let settled = false;
|
|
17
|
+
const cleanup = () => { video.removeEventListener('loadedmetadata', seek); video.removeEventListener('loadeddata', loaded); video.removeEventListener('seeked', ready); video.removeEventListener('error', failed); signal.removeEventListener('abort', aborted); };
|
|
18
|
+
const fail = (error) => { if (settled)
|
|
19
|
+
return; settled = true; cleanup(); reject(error); };
|
|
20
|
+
const ready = () => {
|
|
21
|
+
if (settled || signal.aborted)
|
|
22
|
+
return;
|
|
23
|
+
try {
|
|
24
|
+
if (!presentDecodedFrame(video, canvas, target))
|
|
25
|
+
return;
|
|
26
|
+
committed();
|
|
27
|
+
settled = true;
|
|
28
|
+
cleanup();
|
|
29
|
+
resolve();
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
fail(error);
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
const seek = () => { if (signal.aborted)
|
|
36
|
+
return; try {
|
|
37
|
+
if (video.readyState >= 1)
|
|
38
|
+
video.currentTime = target;
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
fail(error);
|
|
42
|
+
} };
|
|
43
|
+
const loaded = () => { if (target === 0)
|
|
44
|
+
ready(); };
|
|
45
|
+
const failed = () => fail(new Error(`Video decode failed${video.error ? ` (code ${video.error.code}): ${video.error.message}` : ''}`));
|
|
46
|
+
const aborted = () => fail(new DOMException('Frame presentation cancelled', 'AbortError'));
|
|
47
|
+
if (signal.aborted) {
|
|
48
|
+
aborted();
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
video.pause();
|
|
52
|
+
// A changed src must not reuse pixels left over from the previous resource.
|
|
53
|
+
if (video.currentSrc === video.src && !video.seeking && Math.abs(video.currentTime - target) <= .001) {
|
|
54
|
+
ready();
|
|
55
|
+
if (settled)
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
video.addEventListener('loadedmetadata', seek);
|
|
59
|
+
video.addEventListener('loadeddata', loaded);
|
|
60
|
+
video.addEventListener('seeked', ready);
|
|
61
|
+
video.addEventListener('error', failed);
|
|
62
|
+
signal.addEventListener('abort', aborted, { once: true });
|
|
63
|
+
if (video.error) {
|
|
64
|
+
failed();
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
seek();
|
|
68
|
+
});
|
|
69
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@joplo-app/plugin-av",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"joplo": {
|
|
6
6
|
"api": 2
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
}
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@joplo-app/kit": "0.7.
|
|
28
|
+
"@joplo-app/kit": "0.7.2",
|
|
29
29
|
"lottie-web": "5.13.0",
|
|
30
30
|
"react": "19.3.1",
|
|
31
31
|
"zod": "4.6.7"
|