@alulore/kumiko 0.19.0 → 0.20.0

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 (138) hide show
  1. package/dist/board/board-api.d.ts +2 -1
  2. package/dist/board/board-api.js +1 -1
  3. package/dist/board/board-motion.js +29 -1
  4. package/dist/board/board-slots.d.ts +14 -7
  5. package/dist/board/board-slots.js +5 -3
  6. package/dist/board/board.d.ts +20 -5
  7. package/dist/board/board.js +28 -5
  8. package/dist/board/keep-capture.d.ts +10 -5
  9. package/dist/board/keep-capture.js +48 -13
  10. package/dist/cooldown/cooldown-button.d.ts +30 -0
  11. package/dist/cooldown/cooldown-button.js +75 -0
  12. package/dist/cooldown/cooldown-labels.d.ts +8 -0
  13. package/dist/cooldown/cooldown-labels.js +4 -0
  14. package/dist/cooldown/cooldown-time.d.ts +8 -0
  15. package/dist/cooldown/cooldown-time.js +20 -0
  16. package/dist/cooldown/cooldown.css +21 -0
  17. package/dist/cooldown/index.d.ts +4 -0
  18. package/dist/cooldown/index.js +4 -0
  19. package/dist/cooldown/use-cooldown.d.ts +30 -0
  20. package/dist/cooldown/use-cooldown.js +63 -0
  21. package/dist/dialog/dialog-content.d.ts +5 -0
  22. package/dist/dialog/dialog-content.js +7 -0
  23. package/dist/dialog/overlay-host.d.ts +1 -1
  24. package/dist/dialog/overlay-host.js +10 -1
  25. package/dist/empty-state/empty-state-labels.d.ts +14 -0
  26. package/dist/empty-state/empty-state-labels.js +10 -0
  27. package/dist/empty-state/empty-state.css +134 -0
  28. package/dist/empty-state/empty-state.d.ts +34 -0
  29. package/dist/empty-state/empty-state.js +61 -0
  30. package/dist/empty-state/index.d.ts +2 -0
  31. package/dist/empty-state/index.js +2 -0
  32. package/dist/form/choice-fields.d.ts +34 -0
  33. package/dist/form/choice-fields.js +41 -0
  34. package/dist/form/error-line.d.ts +8 -0
  35. package/dist/form/error-line.js +47 -0
  36. package/dist/form/field-props.d.ts +12 -0
  37. package/dist/form/field-props.js +8 -0
  38. package/dist/form/field-shell.d.ts +18 -0
  39. package/dist/form/field-shell.js +51 -0
  40. package/dist/form/focus-invalid.d.ts +5 -0
  41. package/dist/form/focus-invalid.js +17 -0
  42. package/dist/form/form-context.d.ts +2 -0
  43. package/dist/form/form-context.js +3 -0
  44. package/dist/form/form-parts.d.ts +20 -0
  45. package/dist/form/form-parts.js +73 -0
  46. package/dist/form/form.css +128 -0
  47. package/dist/form/index.d.ts +10 -0
  48. package/dist/form/index.js +9 -0
  49. package/dist/form/shown-error.d.ts +12 -0
  50. package/dist/form/shown-error.js +27 -0
  51. package/dist/form/submit-errors.d.ts +36 -0
  52. package/dist/form/submit-errors.js +46 -0
  53. package/dist/form/text-fields.d.ts +18 -0
  54. package/dist/form/text-fields.js +21 -0
  55. package/dist/form/use-app-form.d.ts +1655 -0
  56. package/dist/form/use-app-form.js +94 -0
  57. package/dist/form/use-dialog-link.d.ts +5 -0
  58. package/dist/form/use-dialog-link.js +30 -0
  59. package/dist/form/value-fields.d.ts +16 -0
  60. package/dist/form/value-fields.js +15 -0
  61. package/dist/map/geo.d.ts +20 -0
  62. package/dist/map/geo.js +41 -0
  63. package/dist/map/index.d.ts +5 -0
  64. package/dist/map/index.js +4 -0
  65. package/dist/map/label-overlap.d.ts +13 -0
  66. package/dist/map/label-overlap.js +23 -0
  67. package/dist/map/load-map.d.ts +12 -0
  68. package/dist/map/load-map.js +22 -0
  69. package/dist/map/location-map.d.ts +39 -0
  70. package/dist/map/location-map.js +171 -0
  71. package/dist/map/map-frame.d.ts +18 -0
  72. package/dist/map/map-frame.js +6 -0
  73. package/dist/map/map-pin.d.ts +4 -0
  74. package/dist/map/map-pin.js +38 -0
  75. package/dist/map/map-popup.d.ts +17 -0
  76. package/dist/map/map-popup.js +101 -0
  77. package/dist/map/map-source.d.ts +52 -0
  78. package/dist/map/map-source.js +59 -0
  79. package/dist/map/map.css +311 -0
  80. package/dist/map/marker-pins.d.ts +29 -0
  81. package/dist/map/marker-pins.js +144 -0
  82. package/dist/map/markers-map.d.ts +57 -0
  83. package/dist/map/markers-map.js +154 -0
  84. package/dist/map/use-label-overlap.d.ts +9 -0
  85. package/dist/map/use-label-overlap.js +55 -0
  86. package/dist/map/use-map.d.ts +49 -0
  87. package/dist/map/use-map.js +201 -0
  88. package/dist/media/encoding.d.ts +32 -0
  89. package/dist/media/encoding.js +59 -0
  90. package/dist/media/errors.d.ts +33 -0
  91. package/dist/media/errors.js +26 -0
  92. package/dist/media/image.d.ts +9 -0
  93. package/dist/media/image.js +35 -0
  94. package/dist/media/index.d.ts +10 -0
  95. package/dist/media/index.js +10 -0
  96. package/dist/media/load-mediabunny.d.ts +7 -0
  97. package/dist/media/load-mediabunny.js +13 -0
  98. package/dist/media/media-upload.d.ts +40 -0
  99. package/dist/media/media-upload.js +132 -0
  100. package/dist/media/media.css +101 -0
  101. package/dist/media/probe.d.ts +19 -0
  102. package/dist/media/probe.js +49 -0
  103. package/dist/media/sizes.d.ts +28 -0
  104. package/dist/media/sizes.js +51 -0
  105. package/dist/media/slideshow.d.ts +43 -0
  106. package/dist/media/slideshow.js +174 -0
  107. package/dist/media/timeline.d.ts +59 -0
  108. package/dist/media/timeline.js +105 -0
  109. package/dist/media/transcode.d.ts +35 -0
  110. package/dist/media/transcode.js +132 -0
  111. package/dist/media/upload.d.ts +21 -0
  112. package/dist/media/upload.js +54 -0
  113. package/dist/media/use-media-job.d.ts +79 -0
  114. package/dist/media/use-media-job.js +143 -0
  115. package/dist/server-render.test.js +93 -0
  116. package/dist/smooth-caret/caret-controller.js +16 -3
  117. package/dist/table/table-labels.d.ts +2 -0
  118. package/dist/table/table-labels.js +1 -0
  119. package/dist/table/table-sections.js +10 -2
  120. package/dist/table/table.css +1 -0
  121. package/dist/theme/define-theme.d.ts +38 -0
  122. package/dist/theme/define-theme.js +56 -0
  123. package/dist/theme/index.d.ts +3 -0
  124. package/dist/theme/index.js +3 -0
  125. package/dist/theme/theme-style.d.ts +6 -0
  126. package/dist/theme/theme-style.js +11 -0
  127. package/dist/theme/theme-types.d.ts +1 -0
  128. package/dist/theme/theme-types.js +26 -0
  129. package/dist/theme/tokens-1.generated.d.ts +1 -0
  130. package/dist/theme/tokens-1.generated.js +404 -0
  131. package/dist/theme/tokens-2.generated.d.ts +1 -0
  132. package/dist/theme/tokens-2.generated.js +404 -0
  133. package/dist/theme/tokens-3.generated.d.ts +1 -0
  134. package/dist/theme/tokens-3.generated.js +158 -0
  135. package/dist/theme/tokens.generated.d.ts +2 -0
  136. package/dist/theme/tokens.generated.js +6 -0
  137. package/dist/undo/undo-provider.js +24 -9
  138. package/package.json +78 -1
@@ -0,0 +1,51 @@
1
+ /** The orientation of `size`; a square is landscape. */
2
+ export function orientationOf(size) {
3
+ return size.height > size.width ? "portrait" : "landscape";
4
+ }
5
+ /** Rounds to the nearest even number, at least 2: encoders need even sides. */
6
+ export function evenSide(value) {
7
+ return Math.max(2, Math.round(value / 2) * 2);
8
+ }
9
+ /** `evenSide` on both sides of a size. */
10
+ export function evenSize(size) {
11
+ return { width: evenSide(size.width), height: evenSide(size.height) };
12
+ }
13
+ /** Rounding up to even can pass an odd maximum by one pixel. */
14
+ function atMost(side, max) {
15
+ return side > max && side > 2 ? side - 2 : side;
16
+ }
17
+ /**
18
+ * Scales `size` down (never up) to fit `max` turned to the source's orientation, keeping the aspect ratio,
19
+ * with both sides even and at least 2. A size with no area gives `max` in landscape.
20
+ */
21
+ export function fitWithin(size, max) {
22
+ const long = Math.max(max.width, max.height);
23
+ const short = Math.min(max.width, max.height);
24
+ if (!(size.width > 0 && size.height > 0)) {
25
+ return evenSize({ width: long, height: short });
26
+ }
27
+ const turned = orientationOf(size) === "portrait"
28
+ ? { width: short, height: long }
29
+ : { width: long, height: short };
30
+ const scale = Math.min(1, turned.width / size.width, turned.height / size.height);
31
+ const fitted = evenSize({ width: size.width * scale, height: size.height * scale });
32
+ return {
33
+ width: atMost(fitted.width, turned.width),
34
+ height: atMost(fitted.height, turned.height)
35
+ };
36
+ }
37
+ /**
38
+ * Where `source` goes in `target`, centred. `fit` shows all of it, letterboxed (and enlarged when it is
39
+ * smaller, so a small logo doesn't stay tiny); `fill` covers the target, so the frame crops the overflow.
40
+ */
41
+ export function placeImage(source, target, fit) {
42
+ if (!(source.width > 0 && source.height > 0)) {
43
+ return { x: 0, y: 0, width: target.width, height: target.height };
44
+ }
45
+ const scaleX = target.width / source.width;
46
+ const scaleY = target.height / source.height;
47
+ const scale = fit === "fit" ? Math.min(scaleX, scaleY) : Math.max(scaleX, scaleY);
48
+ const width = source.width * scale;
49
+ const height = source.height * scale;
50
+ return { x: (target.width - width) / 2, y: (target.height - height) / 2, width, height };
51
+ }
@@ -0,0 +1,43 @@
1
+ import { type VideoCodec } from "./encoding";
2
+ import { type ImageFit, type Size } from "./sizes";
3
+ import type { TranscodeResult } from "./transcode";
4
+ type Context = OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D;
5
+ /** A CSS colour, a two-stop linear gradient (`angle` in degrees, 180 is top to bottom) or a drawing function. */
6
+ export type SlideBackground = string | {
7
+ readonly from: string;
8
+ readonly to: string;
9
+ readonly angle?: number;
10
+ } | ((context: Context, size: Size) => void);
11
+ export interface Slide {
12
+ readonly image: Blob;
13
+ readonly durationSeconds: number;
14
+ }
15
+ export interface SlideshowOptions {
16
+ /** The video's size, for example 1920 by 1080. Sides are rounded to even. */
17
+ size: Size;
18
+ /** Default `"fit"`. */
19
+ fit?: ImageFit;
20
+ /** Behind a letterboxed picture and under a fade. Default `"#000"`. */
21
+ background?: SlideBackground;
22
+ /** Default `"none"`. */
23
+ transition?: "none" | "fade";
24
+ /** Default 0.6. */
25
+ fadeSeconds?: number;
26
+ /** Tried in order. Default `["av1", "vp9"]`. */
27
+ codecs?: readonly VideoCodec[];
28
+ /** Video bits per second. Default: mediabunny's medium quality. */
29
+ bitrate?: number;
30
+ signal?: AbortSignal;
31
+ /** 0 to 1, from the codec actually in use: it restarts at 0 when the next codec is tried. */
32
+ onProgress?: (fraction: number) => void;
33
+ }
34
+ /**
35
+ * Makes a silent WebM from pictures in the browser, at a variable frame rate: one frame a second while a
36
+ * picture holds and 12 a second in a fade, so the file stays tiny. Pictures are decoded one at a time, down
37
+ * to the video's size. The file is as long as the slides' total.
38
+ *
39
+ * An empty list is a programming error and throws a `RangeError`. Otherwise it rejects with a `MediaError`:
40
+ * `unreadable` (a picture that can't decode), `unsupported`, `encode-failed` or `cancelled`.
41
+ */
42
+ export declare function imagesToVideo(slides: readonly Slide[], options: SlideshowOptions): Promise<TranscodeResult>;
43
+ export {};
@@ -0,0 +1,174 @@
1
+ import { DEFAULT_CODECS, hasVideoEncoder, qualityFor, withFirstCodec } from "./encoding";
2
+ import { MediaError, toMediaError } from "./errors";
3
+ import { decodeImage } from "./image";
4
+ import { loadMediabunny } from "./load-mediabunny";
5
+ import { evenSize, placeImage } from "./sizes";
6
+ import { buildTimeline } from "./timeline";
7
+ function gradientFor(context, size, background) {
8
+ // CSS's gradient line: through the centre, long enough that the corners take the end colours.
9
+ const angle = ((background.angle ?? 180) * Math.PI) / 180;
10
+ const dx = Math.sin(angle);
11
+ const dy = -Math.cos(angle);
12
+ const half = (Math.abs(size.width * dx) + Math.abs(size.height * dy)) / 2;
13
+ const cx = size.width / 2;
14
+ const cy = size.height / 2;
15
+ const gradient = context.createLinearGradient(cx - dx * half, cy - dy * half, cx + dx * half, cy + dy * half);
16
+ gradient.addColorStop(0, background.from);
17
+ gradient.addColorStop(1, background.to);
18
+ return gradient;
19
+ }
20
+ function paintBackground(context, size, background) {
21
+ if (typeof background === "function") {
22
+ background(context, size);
23
+ return;
24
+ }
25
+ context.fillStyle =
26
+ typeof background === "string" ? background : gradientFor(context, size, background);
27
+ context.fillRect(0, 0, size.width, size.height);
28
+ }
29
+ function drawPicture(context, bitmap, size, fit, alpha) {
30
+ const place = placeImage(bitmap, size, fit);
31
+ context.globalAlpha = alpha;
32
+ context.drawImage(bitmap, place.x, place.y, place.width, place.height);
33
+ context.globalAlpha = 1;
34
+ }
35
+ /**
36
+ * Decodes pictures when a frame first needs them and closes each as soon as the timeline has moved past
37
+ * it, so at most the current and the next one are in memory, never the whole list at full size.
38
+ */
39
+ function createBitmapWindow(slides, maxSize, signal) {
40
+ const held = new Map();
41
+ return {
42
+ async get(index, current) {
43
+ for (const [heldIndex, bitmap] of held) {
44
+ if (heldIndex < current) {
45
+ bitmap.close();
46
+ held.delete(heldIndex);
47
+ }
48
+ }
49
+ const have = held.get(index);
50
+ if (have) {
51
+ return have;
52
+ }
53
+ const slide = slides[index];
54
+ if (!slide) {
55
+ throw new RangeError(`There is no slide ${String(index)}`);
56
+ }
57
+ const bitmap = await decodeImage(slide.image, { maxSize, signal });
58
+ held.set(index, bitmap);
59
+ return bitmap;
60
+ },
61
+ closeAll() {
62
+ for (const bitmap of held.values()) {
63
+ bitmap.close();
64
+ }
65
+ held.clear();
66
+ }
67
+ };
68
+ }
69
+ async function drawFrame(drawing, options, frame) {
70
+ const { context, size, bitmaps } = drawing;
71
+ const from = await bitmaps.get(frame.from, frame.from);
72
+ const to = frame.to === null ? null : await bitmaps.get(frame.to, frame.from);
73
+ const fit = options.fit ?? "fit";
74
+ paintBackground(context, size, options.background ?? "#000");
75
+ drawPicture(context, from, size, fit, 1);
76
+ if (to) {
77
+ drawPicture(context, to, size, fit, frame.mix);
78
+ }
79
+ }
80
+ /** Runs `step` on each item one after the other. */
81
+ function inOrder(items, step) {
82
+ return items.reduce((done, item, index) => done.then(() => step(item, index)), Promise.resolve());
83
+ }
84
+ /** Encodes every frame of the timeline with one codec. Throws whatever goes wrong, raw. */
85
+ async function encodeWith(mediabunny, codec, slides, drawing, options) {
86
+ const output = new mediabunny.Output({
87
+ format: new mediabunny.WebMOutputFormat(),
88
+ target: new mediabunny.BufferTarget()
89
+ });
90
+ const source = new mediabunny.CanvasSource(drawing.canvas, {
91
+ codec,
92
+ quality: qualityFor(mediabunny, options.bitrate)
93
+ });
94
+ const fadeSeconds = options.transition === "fade" ? (options.fadeSeconds ?? 0.6) : 0;
95
+ const { frames } = buildTimeline(slides.map((slide) => slide.durationSeconds), { fadeSeconds });
96
+ try {
97
+ output.addVideoTrack(source);
98
+ await output.start();
99
+ await inOrder(frames, async (frame, index) => {
100
+ if (options.signal?.aborted) {
101
+ throw new MediaError("cancelled");
102
+ }
103
+ await drawFrame(drawing, options, frame);
104
+ await source.add(frame.timestamp, frame.duration);
105
+ options.onProgress?.((index + 1) / frames.length);
106
+ });
107
+ source.close();
108
+ await output.finalize();
109
+ if (!output.target.buffer) {
110
+ throw new Error("The slideshow made no file");
111
+ }
112
+ return new Blob([output.target.buffer], { type: "video/webm" });
113
+ }
114
+ catch (error) {
115
+ source.close();
116
+ void output.cancel().catch(() => undefined);
117
+ throw error;
118
+ }
119
+ finally {
120
+ drawing.bitmaps.closeAll();
121
+ }
122
+ }
123
+ function makeDrawing(slides, size, options) {
124
+ const canvas = typeof OffscreenCanvas === "undefined"
125
+ ? Object.assign(document.createElement("canvas"), size)
126
+ : new OffscreenCanvas(size.width, size.height);
127
+ const context = canvas.getContext("2d");
128
+ if (!context) {
129
+ throw new MediaError("unsupported");
130
+ }
131
+ // Cover needs more pixels than fit does on a mismatched shape, so it decodes into a square.
132
+ const longSide = Math.max(size.width, size.height);
133
+ const maxSize = options.fit === "fill" ? { width: longSide, height: longSide } : size;
134
+ return { canvas, context, size, bitmaps: createBitmapWindow(slides, maxSize, options.signal) };
135
+ }
136
+ /**
137
+ * Makes a silent WebM from pictures in the browser, at a variable frame rate: one frame a second while a
138
+ * picture holds and 12 a second in a fade, so the file stays tiny. Pictures are decoded one at a time, down
139
+ * to the video's size. The file is as long as the slides' total.
140
+ *
141
+ * An empty list is a programming error and throws a `RangeError`. Otherwise it rejects with a `MediaError`:
142
+ * `unreadable` (a picture that can't decode), `unsupported`, `encode-failed` or `cancelled`.
143
+ */
144
+ export async function imagesToVideo(slides, options) {
145
+ if (slides.length === 0) {
146
+ throw new RangeError("A slideshow needs at least one slide");
147
+ }
148
+ const { signal } = options;
149
+ if (signal?.aborted) {
150
+ throw new MediaError("cancelled");
151
+ }
152
+ const size = evenSize(options.size);
153
+ try {
154
+ if (!hasVideoEncoder()) {
155
+ throw new MediaError("unsupported");
156
+ }
157
+ const mediabunny = await loadMediabunny();
158
+ return await withFirstCodec({
159
+ mediabunny,
160
+ codecs: options.codecs ?? DEFAULT_CODECS,
161
+ needs: { size, bitrate: options.bitrate },
162
+ signal,
163
+ run: async (codec) => {
164
+ options.onProgress?.(0);
165
+ const drawing = makeDrawing(slides, size, options);
166
+ const blob = await encodeWith(mediabunny, codec, slides, drawing, options);
167
+ return { blob, codec, ...size };
168
+ }
169
+ });
170
+ }
171
+ catch (error) {
172
+ throw toMediaError(error, "encode-failed", signal);
173
+ }
174
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The pure part of a slideshow: the frames the encoder follows, and the rules a list of slide lengths
3
+ * can be checked against. All times inside are whole milliseconds, so frame timestamps never drift.
4
+ */
5
+ export interface TimelineOptions {
6
+ /** The cross-fade at the end of each slide. Default 0: no fade. */
7
+ readonly fadeSeconds?: number;
8
+ /** Frames a second while a slide holds. Default 1. */
9
+ readonly holdFps?: number;
10
+ /** Frames a second during a fade. Default 12. */
11
+ readonly fadeFps?: number;
12
+ }
13
+ export interface TimelineFrame {
14
+ /** Seconds from the start. */
15
+ readonly timestamp: number;
16
+ /** Seconds this frame stays on screen: until the next frame, the last until the end. */
17
+ readonly duration: number;
18
+ /** The slide shown. */
19
+ readonly from: number;
20
+ /** The slide fading in over it, or null when none is. */
21
+ readonly to: number | null;
22
+ /** 0 shows `from` alone; towards 1 `to` shows through. */
23
+ readonly mix: number;
24
+ }
25
+ export interface Timeline {
26
+ readonly frames: readonly TimelineFrame[];
27
+ readonly totalSeconds: number;
28
+ /** The frame on screen at `seconds`, clamped to the video. Throws a `RangeError` with no frames. */
29
+ at: (seconds: number) => TimelineFrame;
30
+ }
31
+ /**
32
+ * The frames of a slideshow: one every `1 / holdFps` seconds while a slide holds and `fadeFps` a second
33
+ * during a fade. The frames add up to exactly the slides' total, so the file is as long as the app said.
34
+ */
35
+ export declare function buildTimeline(durations: readonly number[], options?: TimelineOptions): Timeline;
36
+ /** Limits a slideshow may be held to. Each is optional: one that is not set is not checked. */
37
+ export interface SlideshowLimits {
38
+ readonly minSlideSeconds?: number;
39
+ readonly maxSlideSeconds?: number;
40
+ readonly minTotalSeconds?: number;
41
+ readonly maxTotalSeconds?: number;
42
+ readonly maxSlides?: number;
43
+ }
44
+ /** What stops a list of slide lengths from making a slideshow. */
45
+ export type SlideshowIssue = {
46
+ readonly kind: "no-slides";
47
+ } | {
48
+ readonly kind: "slide-too-short" | "slide-too-long";
49
+ readonly index: number;
50
+ readonly limit: number;
51
+ } | {
52
+ readonly kind: "total-too-short" | "total-too-long";
53
+ readonly limit: number;
54
+ } | {
55
+ readonly kind: "too-many-slides";
56
+ readonly limit: number;
57
+ };
58
+ /** What stops these slide lengths from making a slideshow under `limits`; empty when they are fine. */
59
+ export declare function slideshowIssues(durations: readonly number[], limits: SlideshowLimits): SlideshowIssue[];
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The pure part of a slideshow: the frames the encoder follows, and the rules a list of slide lengths
3
+ * can be checked against. All times inside are whole milliseconds, so frame timestamps never drift.
4
+ */
5
+ function toMs(seconds) {
6
+ return Math.max(0, Math.round(seconds * 1000));
7
+ }
8
+ /** The fade at the end of slide `index`: capped at half of it and half of the next one. */
9
+ function fadeLength(ms, index, wantedMs) {
10
+ const next = ms[index + 1];
11
+ if (next === undefined) {
12
+ return 0;
13
+ }
14
+ return Math.min(wantedMs, Math.floor((ms[index] ?? 0) / 2), Math.floor(next / 2));
15
+ }
16
+ function slideFrames(index, startMs, slideMs, fadeMs, steps) {
17
+ const frames = [];
18
+ const holdEnd = startMs + slideMs - fadeMs;
19
+ const fadeFrames = fadeMs > 0 ? Math.max(1, Math.round((fadeMs / 1000) * steps.fadeFps)) : 0;
20
+ for (let at = startMs; at < holdEnd; at += steps.holdMs) {
21
+ frames.push({ atMs: at, from: index, to: null, mix: 0 });
22
+ }
23
+ for (let step = 0; step < fadeFrames; step += 1) {
24
+ frames.push({
25
+ atMs: holdEnd + Math.round((step * fadeMs) / fadeFrames),
26
+ from: index,
27
+ to: index + 1,
28
+ mix: (step + 1) / (fadeFrames + 1)
29
+ });
30
+ }
31
+ return frames;
32
+ }
33
+ /**
34
+ * The frames of a slideshow: one every `1 / holdFps` seconds while a slide holds and `fadeFps` a second
35
+ * during a fade. The frames add up to exactly the slides' total, so the file is as long as the app said.
36
+ */
37
+ export function buildTimeline(durations, options = {}) {
38
+ const steps = {
39
+ holdMs: Math.max(1, Math.round(1000 / (options.holdFps ?? 1))),
40
+ fadeFps: options.fadeFps ?? 12
41
+ };
42
+ const wantedFadeMs = toMs(options.fadeSeconds ?? 0);
43
+ const ms = durations.map((seconds) => toMs(seconds));
44
+ const totalMs = ms.reduce((sum, value) => sum + value, 0);
45
+ const raw = [];
46
+ let startMs = 0;
47
+ for (const [index, slideMs] of ms.entries()) {
48
+ raw.push(...slideFrames(index, startMs, slideMs, fadeLength(ms, index, wantedFadeMs), steps));
49
+ startMs += slideMs;
50
+ }
51
+ const frames = raw.map((frame, index) => {
52
+ const nextMs = raw[index + 1]?.atMs ?? totalMs;
53
+ return {
54
+ timestamp: frame.atMs / 1000,
55
+ duration: (nextMs - frame.atMs) / 1000,
56
+ from: frame.from,
57
+ to: frame.to,
58
+ mix: frame.mix
59
+ };
60
+ });
61
+ return {
62
+ frames,
63
+ totalSeconds: totalMs / 1000,
64
+ at(seconds) {
65
+ let found = frames[0];
66
+ for (const frame of frames) {
67
+ if (frame.timestamp > seconds + 1e-9) {
68
+ break;
69
+ }
70
+ found = frame;
71
+ }
72
+ if (!found) {
73
+ throw new RangeError("The timeline has no frames");
74
+ }
75
+ return found;
76
+ }
77
+ };
78
+ }
79
+ /** What stops these slide lengths from making a slideshow under `limits`; empty when they are fine. */
80
+ export function slideshowIssues(durations, limits) {
81
+ if (durations.length === 0) {
82
+ return [{ kind: "no-slides" }];
83
+ }
84
+ const issues = [];
85
+ const { maxSlideSeconds, maxSlides, maxTotalSeconds, minSlideSeconds, minTotalSeconds } = limits;
86
+ const total = durations.reduce((sum, seconds) => sum + seconds, 0);
87
+ if (maxSlides !== undefined && durations.length > maxSlides) {
88
+ issues.push({ kind: "too-many-slides", limit: maxSlides });
89
+ }
90
+ for (const [index, seconds] of durations.entries()) {
91
+ if (minSlideSeconds !== undefined && seconds < minSlideSeconds) {
92
+ issues.push({ kind: "slide-too-short", index, limit: minSlideSeconds });
93
+ }
94
+ if (maxSlideSeconds !== undefined && seconds > maxSlideSeconds) {
95
+ issues.push({ kind: "slide-too-long", index, limit: maxSlideSeconds });
96
+ }
97
+ }
98
+ if (minTotalSeconds !== undefined && total < minTotalSeconds) {
99
+ issues.push({ kind: "total-too-short", limit: minTotalSeconds });
100
+ }
101
+ if (maxTotalSeconds !== undefined && total > maxTotalSeconds) {
102
+ issues.push({ kind: "total-too-long", limit: maxTotalSeconds });
103
+ }
104
+ return issues;
105
+ }
@@ -0,0 +1,35 @@
1
+ import { type VideoCodec } from "./encoding";
2
+ import { type Size } from "./sizes";
3
+ export type { VideoCodec } from "./encoding";
4
+ export interface TranscodeOptions {
5
+ /** Tried in order. Default `["av1", "vp9"]`. */
6
+ readonly codecs?: readonly VideoCodec[];
7
+ /** The largest output, turned to the source's orientation. Default 1920 by 1080. */
8
+ readonly maxSize?: Size;
9
+ /** The highest frame rate; a slower source keeps its own. Default 30. */
10
+ readonly maxFps?: number;
11
+ /** Video bits per second. Default: mediabunny's medium quality. */
12
+ readonly bitrate?: number;
13
+ /** Default `"keep"`, encoded as Opus. */
14
+ readonly audio?: "keep" | "drop";
15
+ readonly signal?: AbortSignal;
16
+ /** 0 to 1, from the codec actually in use: it restarts at 0 when the next codec is tried. */
17
+ readonly onProgress?: (fraction: number) => void;
18
+ }
19
+ export interface TranscodeResult {
20
+ readonly blob: Blob;
21
+ readonly codec: VideoCodec;
22
+ readonly width: number;
23
+ readonly height: number;
24
+ }
25
+ /**
26
+ * Whether this browser can encode any of `codecs` (default `["av1", "vp9"]`). Never throws: it is false
27
+ * when mediabunny or WebCodecs is missing.
28
+ */
29
+ export declare function canTranscode(codecs?: readonly VideoCodec[]): Promise<boolean>;
30
+ /**
31
+ * Converts a video to a WebM in the browser: the first codec that works, scaled down (never up) to
32
+ * `maxSize`, capped at `maxFps`, always re-encoded. Rejects with a `MediaError`: `unreadable`, `no-video`
33
+ * (before anything is encoded), `unsupported`, `encode-failed` or `cancelled`.
34
+ */
35
+ export declare function transcodeVideo(file: Blob, options?: TranscodeOptions): Promise<TranscodeResult>;
@@ -0,0 +1,132 @@
1
+ import { canEncode, DEFAULT_CODECS, hasVideoEncoder, qualityFor, withFirstCodec } from "./encoding";
2
+ import { MediaError, toMediaError } from "./errors";
3
+ import { loadMediabunny } from "./load-mediabunny";
4
+ import { fitWithin } from "./sizes";
5
+ /**
6
+ * Whether this browser can encode any of `codecs` (default `["av1", "vp9"]`). Never throws: it is false
7
+ * when mediabunny or WebCodecs is missing.
8
+ */
9
+ export async function canTranscode(codecs = DEFAULT_CODECS) {
10
+ if (!hasVideoEncoder()) {
11
+ return false;
12
+ }
13
+ try {
14
+ const mediabunny = await loadMediabunny();
15
+ const size = { width: 1280, height: 720 };
16
+ const results = await Promise.all(codecs.map((codec) => canEncode(mediabunny, codec, { size, bitrate: undefined })));
17
+ return results.includes(true);
18
+ }
19
+ catch {
20
+ return false;
21
+ }
22
+ }
23
+ async function planFor(input, options) {
24
+ const track = await input.getPrimaryVideoTrack();
25
+ if (!track) {
26
+ throw new MediaError("no-video");
27
+ }
28
+ const [width, height, stats] = await Promise.all([
29
+ track.getDisplayWidth(),
30
+ track.getDisplayHeight(),
31
+ track.computePacketStats(120)
32
+ ]);
33
+ const maxFps = options.maxFps ?? 30;
34
+ const fps = stats.averagePacketRate;
35
+ return {
36
+ size: fitWithin({ width, height }, options.maxSize ?? { width: 1920, height: 1080 }),
37
+ frameRate: Number.isFinite(fps) && fps > maxFps + 0.5 ? maxFps : undefined
38
+ };
39
+ }
40
+ /** Runs the conversion, and stops it the moment the signal aborts. */
41
+ async function execute(conversion, signal) {
42
+ const stop = () => void conversion.cancel().catch(() => undefined);
43
+ signal?.addEventListener("abort", stop, { once: true });
44
+ try {
45
+ if (signal?.aborted) {
46
+ stop();
47
+ }
48
+ await conversion.execute();
49
+ }
50
+ finally {
51
+ signal?.removeEventListener("abort", stop);
52
+ }
53
+ }
54
+ /** Converts with one codec. Throws whatever goes wrong, raw: the caller decides what that means. */
55
+ async function convertWith(mediabunny, input, codec, plan, options) {
56
+ const output = new mediabunny.Output({
57
+ format: new mediabunny.WebMOutputFormat(),
58
+ target: new mediabunny.BufferTarget()
59
+ });
60
+ try {
61
+ const conversion = await mediabunny.Conversion.init({
62
+ input,
63
+ output,
64
+ video: {
65
+ codec,
66
+ ...plan.size,
67
+ fit: "fill",
68
+ forceTranscode: true,
69
+ quality: qualityFor(mediabunny, options.bitrate),
70
+ ...(plan.frameRate === undefined ? {} : { frameRate: plan.frameRate })
71
+ },
72
+ audio: options.audio === "drop" ? { discard: true } : { codec: "opus" }
73
+ });
74
+ if (!conversion.isValid) {
75
+ const reasons = conversion.discardedTracks.map((track) => track.reason);
76
+ throw new Error("The conversion is not valid", { cause: reasons });
77
+ }
78
+ conversion.onProgress = (fraction) => options.onProgress?.(fraction);
79
+ await execute(conversion, options.signal);
80
+ if (!output.target.buffer) {
81
+ throw new Error("The conversion made no file");
82
+ }
83
+ return new Blob([output.target.buffer], { type: "video/webm" });
84
+ }
85
+ catch (error) {
86
+ void output.cancel().catch(() => undefined);
87
+ throw error;
88
+ }
89
+ }
90
+ /**
91
+ * Converts a video to a WebM in the browser: the first codec that works, scaled down (never up) to
92
+ * `maxSize`, capped at `maxFps`, always re-encoded. Rejects with a `MediaError`: `unreadable`, `no-video`
93
+ * (before anything is encoded), `unsupported`, `encode-failed` or `cancelled`.
94
+ */
95
+ export async function transcodeVideo(file, options = {}) {
96
+ const { signal } = options;
97
+ if (signal?.aborted) {
98
+ throw new MediaError("cancelled");
99
+ }
100
+ try {
101
+ if (!hasVideoEncoder()) {
102
+ throw new MediaError("unsupported");
103
+ }
104
+ const mediabunny = await loadMediabunny();
105
+ const input = new mediabunny.Input({
106
+ source: new mediabunny.BlobSource(file),
107
+ formats: mediabunny.ALL_FORMATS
108
+ });
109
+ try {
110
+ const plan = await planFor(input, options).catch((error) => {
111
+ throw toMediaError(error, "unreadable", signal);
112
+ });
113
+ return await withFirstCodec({
114
+ mediabunny,
115
+ codecs: options.codecs ?? DEFAULT_CODECS,
116
+ needs: { size: plan.size, bitrate: options.bitrate, frameRate: plan.frameRate },
117
+ signal,
118
+ run: async (codec) => {
119
+ options.onProgress?.(0);
120
+ const blob = await convertWith(mediabunny, input, codec, plan, options);
121
+ return { blob, codec, ...plan.size };
122
+ }
123
+ });
124
+ }
125
+ finally {
126
+ input.dispose();
127
+ }
128
+ }
129
+ catch (error) {
130
+ throw toMediaError(error, "encode-failed", signal);
131
+ }
132
+ }
@@ -0,0 +1,21 @@
1
+ export interface UploadOptions {
2
+ /** Default `"PUT"`. */
3
+ readonly method?: "PUT" | "POST";
4
+ /** Send exactly the headers a signed URL was signed with: any other breaks the signature. */
5
+ readonly headers?: Readonly<Record<string, string>>;
6
+ readonly signal?: AbortSignal;
7
+ /** No default: with none set, a stalled upload waits until the signal aborts. */
8
+ readonly timeoutMs?: number;
9
+ /** 0 to 1, or null when the browser can't tell the total. */
10
+ readonly onProgress?: (fraction: number | null) => void;
11
+ }
12
+ export interface UploadResult {
13
+ readonly status: number;
14
+ readonly body: string;
15
+ }
16
+ /**
17
+ * Sends `body` to a (signed) URL and always settles. 2xx resolves; rejects with a `MediaError`:
18
+ * `upload-status` (with `status`), `upload-network`, `upload-timeout` or `cancelled`. An already aborted
19
+ * signal rejects without sending.
20
+ */
21
+ export declare function uploadToSignedUrl(url: string, body: Blob, options?: UploadOptions): Promise<UploadResult>;
@@ -0,0 +1,54 @@
1
+ import { MediaError } from "./errors";
2
+ function openRequest(url, options) {
3
+ const request = new XMLHttpRequest();
4
+ request.open(options.method ?? "PUT", url);
5
+ for (const [name, value] of Object.entries(options.headers ?? {})) {
6
+ request.setRequestHeader(name, value);
7
+ }
8
+ if (options.timeoutMs !== undefined) {
9
+ request.timeout = options.timeoutMs;
10
+ }
11
+ return request;
12
+ }
13
+ /**
14
+ * Sends `body` to a (signed) URL and always settles. 2xx resolves; rejects with a `MediaError`:
15
+ * `upload-status` (with `status`), `upload-network`, `upload-timeout` or `cancelled`. An already aborted
16
+ * signal rejects without sending.
17
+ */
18
+ export function uploadToSignedUrl(url, body, options = {}) {
19
+ const { signal } = options;
20
+ return new Promise((resolve, reject) => {
21
+ if (signal?.aborted) {
22
+ reject(new MediaError("cancelled"));
23
+ return;
24
+ }
25
+ let request;
26
+ try {
27
+ request = openRequest(url, options);
28
+ }
29
+ catch (cause) {
30
+ // A bad URL or header name throws here, before anything is sent.
31
+ reject(new MediaError("upload-network", { cause }));
32
+ return;
33
+ }
34
+ const abort = () => request.abort();
35
+ const settle = (finish) => {
36
+ signal?.removeEventListener("abort", abort);
37
+ finish();
38
+ };
39
+ request.upload.addEventListener("progress", (event) => options.onProgress?.(event.lengthComputable ? event.loaded / event.total : null));
40
+ request.addEventListener("load", () => settle(() => request.status >= 200 && request.status < 300
41
+ ? resolve({ status: request.status, body: request.responseText })
42
+ : reject(new MediaError("upload-status", { status: request.status }))));
43
+ request.addEventListener("error", () => settle(() => reject(new MediaError("upload-network"))));
44
+ request.addEventListener("timeout", () => settle(() => reject(new MediaError("upload-timeout"))));
45
+ request.addEventListener("abort", () => settle(() => reject(new MediaError("cancelled"))));
46
+ signal?.addEventListener("abort", abort, { once: true });
47
+ try {
48
+ request.send(body);
49
+ }
50
+ catch (cause) {
51
+ settle(() => reject(new MediaError("upload-network", { cause })));
52
+ }
53
+ });
54
+ }