@joplo-app/plugin-av 0.0.0-stage → 0.7.1

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/LICENSE ADDED
@@ -0,0 +1,97 @@
1
+ Required Notice: Copyright 2026 Joplo-app (https://joplo.app, support@joplo.app)
2
+
3
+ Licensor Line of Business: Joplo, a tool for authoring, previewing, reviewing, and publishing interactive product prototypes, demos, and presentations (https://joplo.app)
4
+ Licensor Line of Business: Joplo Cloud, a service for hosting, sharing, commenting on, reviewing, and measuring Joplo prototypes and presentations (https://joplo.app)
5
+
6
+ What counts as competing, and how to ask about other uses: see COMMERCIAL.md
7
+ https://github.com/Joplo-app/Joplo/blob/main/COMMERCIAL.md
8
+
9
+ # PolyForm Shield License 1.0.0
10
+
11
+ <https://polyformproject.org/licenses/shield/1.0.0>
12
+
13
+ ## Acceptance
14
+
15
+ In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
16
+
17
+ ## Copyright License
18
+
19
+ The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license).
20
+
21
+ ## Distribution License
22
+
23
+ The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license).
24
+
25
+ ## Notices
26
+
27
+ You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example:
28
+
29
+ > Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
30
+
31
+ ## Changes and New Works License
32
+
33
+ The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose.
34
+
35
+ ## Patent License
36
+
37
+ The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
38
+
39
+ ## Noncompete
40
+
41
+ Any purpose is a permitted purpose, except for providing any product that competes with the software or any product the licensor or any of its affiliates provides using the software.
42
+
43
+ ## Competition
44
+
45
+ Goods and services compete even when they provide functionality through different kinds of interfaces or for different technical platforms. Applications can compete with services, libraries with plugins, frameworks with development tools, and so on, even if they're written in different programming languages or for different computer architectures. Goods and services compete even when provided free of charge. If you market a product as a practical substitute for the software or another product, it definitely competes.
46
+
47
+ ## New Products
48
+
49
+ If you are using the software to provide a product that does not compete, but the licensor or any of its affiliates brings your product into competition by providing a new version of the software or another product using the software, you may continue using versions of the software available under these terms beforehand to provide your competing product, but not any later versions.
50
+
51
+ ## Discontinued Products
52
+
53
+ You may begin using the software to compete with a product or service that the licensor or any of its affiliates has stopped providing, unless the licensor includes a plain-text line beginning with `Licensor Line of Business:` with the software that mentions that line of business. For example:
54
+
55
+ > Licensor Line of Business: YoyodyneCMS Content Management System (http://example.com/cms)
56
+
57
+ ## Sales of Business
58
+
59
+ If the licensor or any of its affiliates sells a line of business developing the software or using the software to provide a product, the buyer can also enforce [Noncompete](#noncompete) for that product.
60
+
61
+ ## Fair Use
62
+
63
+ You may have "fair use" rights for the software under the law. These terms do not limit them.
64
+
65
+ ## No Other Rights
66
+
67
+ These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.
68
+
69
+ ## Patent Defense
70
+
71
+ If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
72
+
73
+ ## Violations
74
+
75
+ The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.
76
+
77
+ ## No Liability
78
+
79
+ ***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
80
+
81
+ ## Definitions
82
+
83
+ The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
84
+
85
+ A **product** can be a good or service, or a combination of them.
86
+
87
+ **You** refers to the individual or entity agreeing to these terms.
88
+
89
+ **Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all its affiliates.
90
+
91
+ **Affiliates** means the other organizations than an organization has control over, is under the control of, or is under common control with.
92
+
93
+ **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
94
+
95
+ **Your licenses** are all the licenses granted to you for the software under these terms.
96
+
97
+ **Use** means anything you do with the software requiring one of your licenses.
@@ -0,0 +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```\nFirst 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. 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 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.\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\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 ADDED
@@ -0,0 +1,40 @@
1
+ export const skill = `# Joplo media: media
2
+
3
+ For 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).
4
+ Install at the same version as Joplo. Example: examples/media-upload.
5
+
6
+ The 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.
7
+
8
+ ## Enable
9
+ import media, { Video, Lottie, playClip } from '@joplo-app/plugin-av'; config({ plugins: [ui, media, …] }).
10
+
11
+ ## Independent local one-shot sounds
12
+ Use withSoundEffects instead of the default media manifest (never enable both):
13
+ \`\`\`tsx
14
+ import { asset } from '@joplo-app/kit';
15
+ import { withSoundEffects, sfx } from '@joplo-app/plugin-av';
16
+ config({ plugins: [ui, withSoundEffects({ send: asset('./assets/send.wav') })] });
17
+ // In a scripted system step (not a free-reaction handler):
18
+ sfx.play('send', { volume: .5, offsetMs: 0 });
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.
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.
23
+
24
+ ## Write
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).
26
+ - <Lottie id="ok" src={asset('./success.json')} w={160} h={160} /> — a Lottie (Bodymovin) JSON export.
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
+ - MP4 and Lottie lengths are read at compile time. WebM length is unknown: always write { to }.
29
+
30
+ ## Assets
31
+ - 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
+ - Prefer licensed libraries (LottieFiles free animations under their license, your own recordings). Record the source and license in assets/SOURCES.md.
33
+ - 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.
34
+
35
+ ## Pitfalls
36
+ - MEDIA_SRC_INVALID: src must be asset() of an MP4/WebM (Video) or a Lottie JSON (Lottie), not a URL.
37
+ - MEDIA_DURATION_UNKNOWN: WebM without { to }.
38
+ - Static frames (screenshots, jumps) show the frame where the clip ends in that step; only playback moves.
39
+ - A clip has no sound and does not duck narration; put spoken words in narrate().
40
+ `;
@@ -0,0 +1,20 @@
1
+ declare const _default: {
2
+ compilers: {
3
+ sfx: {
4
+ version: string;
5
+ mime: string;
6
+ inspect(input: string): Promise<{
7
+ durationMs: number;
8
+ }>;
9
+ compile(input: string, ctx: {
10
+ directory: string;
11
+ projectDir?: string;
12
+ keys: Readonly<Record<string, string>>;
13
+ cacheDir: string;
14
+ allowSpend?: boolean;
15
+ maxBytes: number;
16
+ }): Uint8Array<ArrayBufferLike>;
17
+ };
18
+ };
19
+ };
20
+ export default _default;
package/dist/local.js ADDED
@@ -0,0 +1,11 @@
1
+ import { wavInfo } from "./sfx.js";
2
+ export default { compilers: { sfx: {
3
+ version: 'pcm-wav-1', mime: 'audio/wav',
4
+ async inspect(input) { return { durationMs: wavInfo(input).durationMs }; },
5
+ compile(input, ctx) {
6
+ const { bytes } = wavInfo(input);
7
+ if (bytes.length > ctx.maxBytes)
8
+ throw new Error('Sound effect exceeds resource size limit');
9
+ return bytes;
10
+ },
11
+ } } };
@@ -0,0 +1,28 @@
1
+ /**
2
+ * 媒体插件的纯函数(Node 编译期):读出片段时长,供 holdMs(D98)与参数校验使用。
3
+ * 素材在编译期是 asset() 的 data URL;只读文件头,不解码画面。
4
+ */
5
+ export type ClipFrame = {
6
+ /** 这一步结束时画面停在的时间(秒)。 */
7
+ to: number;
8
+ /** 这一步从哪里开始播(秒);live = 这一步播放,否则静止在 to。 */
9
+ from: number;
10
+ live: boolean;
11
+ };
12
+ export declare function decodeDataUrl(src: unknown): {
13
+ mime: string;
14
+ bytes: Uint8Array;
15
+ } | null;
16
+ /** MP4 时长(秒):读 moov/mvhd 的 timescale 与 duration;找不到时 null。 */
17
+ export declare function mp4DurationSec(bytes: Uint8Array): number | null;
18
+ /** Lottie 动画信息:帧率、起止帧、尺寸;不是合法的 Lottie JSON 时 null。 */
19
+ export declare function lottieInfo(json: unknown): {
20
+ fr: number;
21
+ ip: number;
22
+ op: number;
23
+ w: number;
24
+ h: number;
25
+ durationSec: number;
26
+ } | null;
27
+ /** 素材的时长(秒):MP4 读文件头;Lottie 读 JSON;WebM 等未知时 null(作者要写 to)。 */
28
+ export declare function durationOf(src: unknown): number | null;
package/dist/model.js ADDED
@@ -0,0 +1,59 @@
1
+ /**
2
+ * 媒体插件的纯函数(Node 编译期):读出片段时长,供 holdMs(D98)与参数校验使用。
3
+ * 素材在编译期是 asset() 的 data URL;只读文件头,不解码画面。
4
+ */
5
+ export function decodeDataUrl(src) {
6
+ if (typeof src !== 'string')
7
+ return null;
8
+ const m = /^data:([a-z0-9.+/-]+)(?:;[^,]*)?;base64,/i.exec(src);
9
+ if (!m)
10
+ return null;
11
+ return { mime: m[1].toLowerCase(), bytes: Uint8Array.from(Buffer.from(src.slice(m[0].length), 'base64')) };
12
+ }
13
+ const u32 = (b, i) => ((b[i] << 24) >>> 0) + (b[i + 1] << 16) + (b[i + 2] << 8) + b[i + 3];
14
+ /** MP4 时长(秒):读 moov/mvhd 的 timescale 与 duration;找不到时 null。 */
15
+ export function mp4DurationSec(bytes) {
16
+ for (let i = 4; i + 32 < bytes.length; i++) {
17
+ if (bytes[i] !== 0x6d || bytes[i + 1] !== 0x76 || bytes[i + 2] !== 0x68 || bytes[i + 3] !== 0x64)
18
+ continue; // 'mvhd'
19
+ const version = bytes[i + 4];
20
+ if (version === 0) {
21
+ const scale = u32(bytes, i + 16), duration = u32(bytes, i + 20);
22
+ return scale ? duration / scale : null;
23
+ }
24
+ if (version === 1) {
25
+ const scale = u32(bytes, i + 24), duration = u32(bytes, i + 28) * 2 ** 32 + u32(bytes, i + 32);
26
+ return scale ? duration / scale : null;
27
+ }
28
+ return null;
29
+ }
30
+ return null;
31
+ }
32
+ /** Lottie 动画信息:帧率、起止帧、尺寸;不是合法的 Lottie JSON 时 null。 */
33
+ export function lottieInfo(json) {
34
+ const j = json;
35
+ if (!j || typeof j !== 'object')
36
+ return null;
37
+ const n = (k) => (typeof j[k] === 'number' && Number.isFinite(j[k]) ? j[k] : null);
38
+ const fr = n('fr'), ip = n('ip'), op = n('op'), w = n('w'), h = n('h');
39
+ if (fr === null || ip === null || op === null || w === null || h === null || fr <= 0 || op <= ip || !Array.isArray(j.layers))
40
+ return null;
41
+ return { fr, ip, op, w, h, durationSec: (op - ip) / fr };
42
+ }
43
+ /** 素材的时长(秒):MP4 读文件头;Lottie 读 JSON;WebM 等未知时 null(作者要写 to)。 */
44
+ export function durationOf(src) {
45
+ const d = decodeDataUrl(src);
46
+ if (!d)
47
+ return null;
48
+ if (d.mime === 'video/mp4')
49
+ return mp4DurationSec(d.bytes);
50
+ if (d.mime === 'application/json') {
51
+ try {
52
+ return lottieInfo(JSON.parse(Buffer.from(d.bytes).toString('utf8')))?.durationSec ?? null;
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ }
58
+ return null;
59
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * 媒体插件(D96 原型):视频片段与 Lottie 动画,跟着引擎时钟播放。
3
+ * 端到端:<Video> / <Lottie> 的 src(asset(),build 后是 assets/ 独立文件,D98)→ playClip 效果校验时段、
4
+ * 按时长给 holdMs → effect 记下这一步的播放 → frame 得到每一步每个片段停在哪里(ext.media.clips)
5
+ * → 运行时按引擎时间定位画面(暂停冻住、倍速跟随、截图定位到终点帧、视频录制一致)。
6
+ * 第一版视频一律静音:通用媒体层只混音频,视频的声音不进旁白压低与视频导出(D98 记录的缺口)。
7
+ */
8
+ type PlayOpts = {
9
+ from?: number;
10
+ to?: number;
11
+ };
12
+ /** 播放 Video / Lottie 的一段(秒):缺省从上次停的地方播到结尾。这一步停留到播完(holdMs)。 */
13
+ export declare const playClip: (id: string, opts?: PlayOpts) => import("@joplo-app/kit/plugin").PluginEffectDef;
14
+ declare const media: import("@joplo-app/kit").PluginDef;
15
+ export declare const Video: (props: import("@joplo-app/kit").JoploProps) => any;
16
+ export declare const Lottie: (props: import("@joplo-app/kit").JoploProps) => any;
17
+ export default media;
18
+ export { sfx, type SfxOptions } from './sfx.js';
19
+ /** Enable this manifest instead of the default media manifest when using local sound effects. */
20
+ export declare function withSoundEffects(assets: Record<string, string>): import("@joplo-app/kit").PluginDef;
package/dist/plugin.js ADDED
@@ -0,0 +1,132 @@
1
+ import { wavInfo } from "./sfx.js";
2
+ import packageInfo from './version.json' with { type: 'json' };
3
+ import { z } from 'zod';
4
+ import { definePlugin, pluginComponent, pluginEffect } from '@joplo-app/kit/plugin';
5
+ import { skill } from "./guide.js";
6
+ import { decodeDataUrl, durationOf, lottieInfo } from "./model.js";
7
+ /** 播放 Video / Lottie 的一段(秒):缺省从上次停的地方播到结尾。这一步停留到播完(holdMs)。 */
8
+ export const playClip = (id, opts = {}) => pluginEffect('media', 'play', { id, ...opts });
9
+ const all = (n) => [n, ...(n.children ?? []).flatMap(all)];
10
+ const clipsIn = (roots) => roots.flatMap(all).filter((n) => n.type === 'media:Video' || n.type === 'media:Lottie');
11
+ const ClipS = z.strictObject({ from: z.number().nonnegative(), to: z.number().nonnegative(), live: z.boolean() });
12
+ const StepS = z.union([
13
+ z.strictObject({ plays: z.array(z.strictObject({ id: z.string(), from: z.number().nullable(), to: z.number().nullable() })) }),
14
+ z.strictObject({ clips: z.record(z.string(), ClipS) }),
15
+ ]);
16
+ const startOf = (node) => (typeof node.props?.start === 'number' && node.props.start >= 0 ? node.props.start : 0);
17
+ const media = definePlugin({
18
+ packageName: '@joplo-app/plugin-av',
19
+ id: 'media', title: 'Media', version: packageInfo.version,
20
+ runtime: new URL(new URL(import.meta.url).pathname.endsWith('.ts') ? './runtime.tsx' : './runtime.js', import.meta.url),
21
+ components: {
22
+ Video: { doc: 'src={asset(\'./clip.mp4\')} (mp4 / webm), w?, h?, fit?=\'cover\'|\'contain\', start? (seconds shown before the first play); a muted video clip played by playClip', needsId: true, selfEvident: true },
23
+ Lottie: { doc: 'src={asset(\'./anim.json\')} (Lottie JSON), w?, h?, start?; a vector animation played by playClip', needsId: true, selfEvident: true },
24
+ },
25
+ skill,
26
+ schemas: { step: StepS },
27
+ data: { step: { scope: [{ path: ['clips'], kind: 'map', domain: 'element' }] } },
28
+ compile: {
29
+ node(n, { report }) {
30
+ if (n.type !== 'media:Video' && n.type !== 'media:Lottie')
31
+ return;
32
+ const { props = {}, source } = n;
33
+ const d = decodeDataUrl(props.src);
34
+ if (n.type === 'media:Video' && !(d && /^video\/(mp4|webm)$/.test(d.mime)))
35
+ report('MEDIA_SRC_INVALID', '<Video src> must be asset(\'./clip.mp4\') or a .webm file in the project', source);
36
+ if (n.type === 'media:Lottie') {
37
+ let ok = false;
38
+ try {
39
+ ok = !!d && d.mime === 'application/json' && !!lottieInfo(JSON.parse(Buffer.from(d.bytes).toString('utf8')));
40
+ }
41
+ catch {
42
+ ok = false;
43
+ }
44
+ if (!ok)
45
+ report('MEDIA_SRC_INVALID', '<Lottie src> must be asset(\'./anim.json\') with a Lottie (Bodymovin) export', source);
46
+ }
47
+ },
48
+ effect(effect, ctx) {
49
+ if (effect.name !== 'play') {
50
+ ctx.report('PLUGIN_EFFECT_UNKNOWN', `Unknown media effect ${effect.name}`, ctx.source);
51
+ return;
52
+ }
53
+ const p = (effect.payload ?? {});
54
+ const id = typeof p.id === 'string' ? p.id : '';
55
+ const node = clipsIn(ctx.roots).find((n) => n.id === id);
56
+ if (!node) {
57
+ ctx.report('MEDIA_UNKNOWN', `playClip("${id}"): no <Video> or <Lottie> with this id on the screens of this step`, ctx.source);
58
+ return;
59
+ }
60
+ const num = (v) => v === undefined ? null : typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : NaN;
61
+ const from = num(p.from), to = num(p.to);
62
+ if (Number.isNaN(from) || Number.isNaN(to)) {
63
+ ctx.report('MEDIA_TIME_INVALID', 'playClip { from, to } are seconds ≥ 0', ctx.source);
64
+ return;
65
+ }
66
+ const duration = durationOf(node.props?.src);
67
+ if (to === null && duration === null) {
68
+ ctx.report('MEDIA_DURATION_UNKNOWN', `playClip("${id}"): this file's length is unknown (WebM); write { to: <seconds> }`, ctx.source);
69
+ return;
70
+ }
71
+ const end = to ?? duration;
72
+ if (duration !== null && end > duration + 0.05) {
73
+ ctx.report('MEDIA_TIME_INVALID', `playClip("${id}") to=${end}s is past the end (${duration.toFixed(2)}s)`, ctx.source);
74
+ return;
75
+ }
76
+ if (from !== null && from >= end) {
77
+ ctx.report('MEDIA_TIME_INVALID', `playClip("${id}") from must be before to`, ctx.source);
78
+ return;
79
+ }
80
+ // 时长按“从哪里播”算:没写 from 时是上一次停的地方,编译期不知道;按最长(从头)估,不会让自动播放提前切走
81
+ const holdMs = Math.min(60_000, Math.ceil((end - (from ?? 0)) * 1000) + 300);
82
+ const plays = [...(ctx.data?.plays ?? []), { id, from, to: end }];
83
+ return { data: { plays }, references: [id], holdMs };
84
+ },
85
+ frame(ctx) {
86
+ const nodes = clipsIn(ctx.roots);
87
+ if (!nodes.length)
88
+ return;
89
+ const previous = ctx.previousData?.clips ?? {};
90
+ const plays = ctx.data?.plays ?? [];
91
+ const clips = {};
92
+ for (const node of nodes) {
93
+ if (clips[node.id])
94
+ continue;
95
+ const base = previous[node.id] ?? { from: startOf(node), to: startOf(node), live: false };
96
+ const play = [...plays].reverse().find((x) => x.id === node.id);
97
+ clips[node.id] = play ? { from: play.from ?? base.to, to: play.to ?? base.to, live: true } : { from: base.to, to: base.to, live: false };
98
+ }
99
+ return { clips };
100
+ },
101
+ },
102
+ });
103
+ export const Video = pluginComponent(media, 'Video');
104
+ export const Lottie = pluginComponent(media, 'Lottie');
105
+ export default media;
106
+ export { sfx } from "./sfx.js";
107
+ /** Enable this manifest instead of the default media manifest when using local sound effects. */
108
+ export function withSoundEffects(assets) {
109
+ return definePlugin({ ...media,
110
+ local: new URL(new URL(import.meta.url).pathname.endsWith('.ts') ? './local.ts' : './local.js', import.meta.url),
111
+ compile: { ...media.compile, effect(effect, ctx) {
112
+ if (effect.name !== 'sfx')
113
+ return media.compile.effect(effect, ctx);
114
+ const p = effect.payload;
115
+ try {
116
+ if (!p || typeof p.name !== 'string' || !Object.hasOwn(assets, p.name))
117
+ throw new Error('Unknown sound name; declare it in withSoundEffects({ name: asset(...) })');
118
+ const { durationMs } = wavInfo(assets[p.name]);
119
+ const volume = p.volume ?? 1, offsetMs = p.offsetMs ?? 0;
120
+ if (typeof volume !== 'number' || !Number.isFinite(volume) || volume < 0 || volume > 1)
121
+ throw new Error('volume must be 0–1');
122
+ if (typeof offsetMs !== 'number' || !Number.isFinite(offsetMs) || offsetMs < 0 || offsetMs >= durationMs)
123
+ throw new Error('offsetMs must be inside the sound duration');
124
+ const resource = ctx.resource({ compiler: 'sfx', input: assets[p.name] });
125
+ return { media: [{ track: 'sfx', action: 'play', resource, oneShot: true, durationMs, volume, offsetMs }] };
126
+ }
127
+ catch (error) {
128
+ ctx.report('SFX_INVALID', error instanceof Error ? error.message : 'Invalid sound effect', ctx.source);
129
+ }
130
+ } },
131
+ });
132
+ }
@@ -0,0 +1,2 @@
1
+ declare const _default: import("@joplo-app/kit/plugin").PluginRuntime;
2
+ export default _default;
@@ -0,0 +1,107 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { useEffect, useLayoutEffect, useRef, useState } from 'react';
3
+ import lottie from 'lottie-web/build/player/lottie_light.js';
4
+ import { defineRuntime, embeddedAsset } from '@joplo-app/kit/plugin';
5
+ import { useEngineFrame, useRoot } from '@joplo-app/kit/renderer';
6
+ const num = (v, d) => (typeof v === 'number' && Number.isFinite(v) ? v : d);
7
+ /** 片段这一步要逐帧定位:只在它在播时订阅每一帧(D99)。 */
8
+ function useClipTime(ctx, clip) {
9
+ const clock = ctx.frame.clock;
10
+ useEngineFrame(!!clip?.live && ctx.frame.animate && !!clock);
11
+ return timeOf(ctx, clip);
12
+ }
13
+ function timeOf(ctx, clip) {
14
+ if (!clip)
15
+ return { t: 0, playing: false };
16
+ const clock = ctx.frame.clock;
17
+ const timed = ctx.frame.animate && !!clock && (clock.running || !!clock.paused);
18
+ if (!clip.live || !timed)
19
+ return { t: clip.to, playing: false };
20
+ const t = Math.min(clip.to, clip.from + clock.elapsedMs / 1000);
21
+ return { t, playing: !!clock.running && t < clip.to };
22
+ }
23
+ function Video({ ctx }) {
24
+ const node = ctx.model;
25
+ const p = ctx.node.props;
26
+ const clip = ctx.ext.media?.clips?.[node.id];
27
+ const { t, playing } = useClipTime(ctx, clip);
28
+ const src = embeddedAsset(p.src, 'video');
29
+ const ref = useRef(null);
30
+ const { src: _s, w, h, fit, start: _st, ...rest } = p;
31
+ const root = useRoot(node, rest, { style: { width: num(w) ?? '100%', height: num(h) ?? 'auto', position: 'relative', overflow: 'hidden', borderRadius: 10, background: '#000' } });
32
+ const speed = ctx.frame.clock?.speed ?? 1;
33
+ useLayoutEffect(() => {
34
+ const v = ref.current;
35
+ if (!v)
36
+ return;
37
+ v.playbackRate = speed;
38
+ if (playing) {
39
+ if (Math.abs(v.currentTime - t) > 0.25)
40
+ v.currentTime = t;
41
+ if (v.paused)
42
+ void v.play().catch(() => { });
43
+ return;
44
+ }
45
+ if (!v.paused)
46
+ v.pause();
47
+ if (Math.abs(v.currentTime - t) <= 0.03 && v.readyState >= 2)
48
+ return;
49
+ // 静止画面:定位到这一帧,截图等它解码好
50
+ const done = ctx.hold();
51
+ let released = false;
52
+ const release = () => { if (!released) {
53
+ released = true;
54
+ done();
55
+ } };
56
+ const ready = () => { v.removeEventListener('seeked', ready); v.removeEventListener('loadeddata', ready); release(); };
57
+ v.addEventListener('seeked', ready);
58
+ v.addEventListener('loadeddata', ready);
59
+ try {
60
+ v.currentTime = t;
61
+ }
62
+ catch {
63
+ release();
64
+ }
65
+ const timer = setTimeout(release, 5000);
66
+ return () => { clearTimeout(timer); v.removeEventListener('seeked', ready); v.removeEventListener('loadeddata', ready); release(); };
67
+ }, [t, playing, speed, src]);
68
+ if (!src)
69
+ return _jsx("div", { ...root });
70
+ return (_jsx("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' } }) }));
71
+ }
72
+ function Lottie({ ctx }) {
73
+ const node = ctx.model;
74
+ const p = ctx.node.props;
75
+ const clip = ctx.ext.media?.clips?.[node.id];
76
+ const { t } = useClipTime(ctx, clip);
77
+ const src = embeddedAsset(p.src, 'json');
78
+ const box = useRef(null);
79
+ const [anim, setAnim] = useState(null);
80
+ const { src: _s, w, h, start: _st, ...rest } = p;
81
+ const root = useRoot(node, rest, { style: { width: num(w) ?? '100%', height: num(h) ?? 'auto', position: 'relative' } });
82
+ // 载入动画(截图等它画出第一帧)
83
+ useEffect(() => {
84
+ const el = box.current;
85
+ if (!el || !src)
86
+ return;
87
+ const done = ctx.hold();
88
+ let alive = true, item = null;
89
+ fetch(src).then((r) => r.json()).then((data) => {
90
+ if (!alive)
91
+ return;
92
+ item = lottie.loadAnimation({ container: el, renderer: 'svg', loop: false, autoplay: false, animationData: data });
93
+ item.addEventListener('DOMLoaded', () => { if (alive)
94
+ setAnim(item); done(); });
95
+ }).catch(() => done());
96
+ return () => { alive = false; item?.destroy(); setAnim(null); done(); };
97
+ }, [src]);
98
+ // 每次渲染按引擎时间定位到对应帧
99
+ useLayoutEffect(() => {
100
+ if (!anim)
101
+ return;
102
+ const frame = Math.max(0, Math.min(anim.totalFrames - 1, t * anim.frameRate));
103
+ anim.goToAndStop(frame, true);
104
+ }, [anim, t]);
105
+ return _jsx("div", { ...root, children: _jsx("div", { ref: box, style: { width: '100%', height: '100%' } }) });
106
+ }
107
+ export default defineRuntime({ id: 'media', components: { Video: { react: Video }, Lottie: { react: Lottie } } });
package/dist/sfx.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ /** Source offset, not a delay; all times use the shared unscaled engine clock. */
2
+ export type SfxOptions = {
3
+ volume?: number;
4
+ offsetMs?: number;
5
+ };
6
+ export declare const sfx: {
7
+ play: (name: string, options?: SfxOptions) => import("@joplo-app/kit/plugin").PluginEffectDef;
8
+ };
9
+ /** PCM WAV only: exact duration without codecs, network access or paid generation. */
10
+ export declare function wavInfo(src: unknown): {
11
+ bytes: Uint8Array;
12
+ durationMs: number;
13
+ };
package/dist/sfx.js ADDED
@@ -0,0 +1,33 @@
1
+ import { pluginEffect } from '@joplo-app/kit/plugin';
2
+ export const sfx = { play: (name, options = {}) => pluginEffect('media', 'sfx', { name, ...options }) };
3
+ /** PCM WAV only: exact duration without codecs, network access or paid generation. */
4
+ export function wavInfo(src) {
5
+ if (typeof src !== 'string' || !/^data:audio\/(?:wav|wave|x-wav);base64,/i.test(src))
6
+ throw new Error('Use asset() with a local PCM WAV file');
7
+ const bytes = Uint8Array.from(Buffer.from(src.slice(src.indexOf(',') + 1), 'base64'));
8
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
9
+ const text = (at) => String.fromCharCode(...bytes.slice(at, at + 4));
10
+ if (bytes.length < 44 || text(0) !== 'RIFF' || text(8) !== 'WAVE')
11
+ throw new Error('Invalid WAV header');
12
+ let rate = 0, block = 0, data = 0;
13
+ for (let at = 12; at + 8 <= bytes.length;) {
14
+ const size = view.getUint32(at + 4, true), start = at + 8;
15
+ if (start + size > bytes.length)
16
+ throw new Error('Truncated WAV chunk');
17
+ if (text(at) === 'fmt ') {
18
+ if (size < 16 || view.getUint16(start, true) !== 1)
19
+ throw new Error('Only PCM WAV is supported');
20
+ rate = view.getUint32(start + 8, true);
21
+ block = view.getUint16(start + 12, true);
22
+ const channels = view.getUint16(start + 2, true), sampleRate = view.getUint32(start + 4, true), bits = view.getUint16(start + 14, true);
23
+ if (![8, 16, 24, 32].includes(bits) || channels < 1 || channels > 8 || block !== channels * bits / 8 || rate !== sampleRate * block)
24
+ throw new Error('Invalid PCM format');
25
+ }
26
+ if (text(at) === 'data')
27
+ data += size;
28
+ at = start + size + size % 2;
29
+ }
30
+ if (!rate || !data || data % block)
31
+ throw new Error('WAV needs complete PCM samples');
32
+ return { bytes, durationMs: data / rate * 1000 };
33
+ }
@@ -0,0 +1,3 @@
1
+ {
2
+ "version": "0.7.1"
3
+ }
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@joplo-app/plugin-av",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.7.1",
4
+ "type": "module",
5
+ "joplo": {
6
+ "api": 2
7
+ },
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/plugin.d.ts",
11
+ "default": "./dist/plugin.js"
12
+ },
13
+ "./runtime": {
14
+ "types": "./dist/runtime.d.ts",
15
+ "default": "./dist/runtime.js"
16
+ },
17
+ "./guide": {
18
+ "types": "./dist/guide.d.ts",
19
+ "default": "./dist/guide.js"
20
+ },
21
+ "./package.json": "./package.json",
22
+ "./local": {
23
+ "types": "./dist/local.d.ts",
24
+ "default": "./dist/local.js"
25
+ }
26
+ },
27
+ "dependencies": {
28
+ "@joplo-app/kit": "0.7.1",
29
+ "lottie-web": "5.13.0",
30
+ "react": "19.3.1",
31
+ "zod": "4.6.7"
32
+ },
33
+ "devDependencies": {
34
+ "@types/react": "^19.3.0"
35
+ },
36
+ "description": "Joplo video, Lottie and local one-shot sound effects on the engine clock",
37
+ "license": "PolyForm-Shield-1.0.0",
38
+ "engines": {
39
+ "node": ">=22"
40
+ },
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "git+https://github.com/Joplo-app/Joplo.git",
44
+ "directory": "plugins/av"
45
+ },
46
+ "files": [
47
+ "dist"
48
+ ],
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "scripts": {
53
+ "build": "node ../../scripts/build-package.mjs"
54
+ }
6
55
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.