@fungi.computer/darkroom 0.11.11 → 0.11.12

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 (90) hide show
  1. package/README.md +13 -0
  2. package/examples/standalone/README.md +52 -0
  3. package/examples/standalone/worker.ts +87 -0
  4. package/examples/standalone/wrangler.jsonc +26 -0
  5. package/package.json +7 -1
  6. package/src/app-media-contracts.ts +142 -0
  7. package/src/audio-providers/elevenlabs.ts +108 -0
  8. package/src/audio-reference-types.ts +47 -0
  9. package/src/audio-references.ts +107 -0
  10. package/src/browser-failure.ts +73 -0
  11. package/src/browser.ts +7 -0
  12. package/src/cloudflare/provider-reason.ts +89 -0
  13. package/src/cloudflare/provider.ts +405 -0
  14. package/src/cloudflare/r2-destination.ts +130 -0
  15. package/src/cloudflare/reference-images.ts +193 -0
  16. package/src/cloudflare.ts +38 -0
  17. package/src/cost-estimate.ts +129 -0
  18. package/src/daily-media-meter.ts +163 -0
  19. package/src/effect.ts +2 -0
  20. package/src/execution-error.ts +98 -0
  21. package/src/failure.ts +13 -0
  22. package/src/gateway-models.ts +304 -0
  23. package/src/gateway-wire.ts +36 -0
  24. package/src/index.ts +1454 -0
  25. package/src/media-binding.ts +260 -0
  26. package/src/media-content-type.ts +60 -0
  27. package/src/media-generation.ts +171 -0
  28. package/src/media-operation-contract.ts +173 -0
  29. package/src/media-operation-do.ts +257 -0
  30. package/src/media-operation-owner.ts +1786 -0
  31. package/src/media-operation-storage.ts +110 -0
  32. package/src/media-operation.ts +454 -0
  33. package/src/media-path.ts +8 -0
  34. package/src/media-quote.ts +34 -0
  35. package/src/media-run-lifetime.ts +5 -0
  36. package/src/media-written.ts +38 -0
  37. package/src/model-catalog.ts +1574 -0
  38. package/src/neurons.ts +6 -0
  39. package/src/node-webpmux.d.ts +12 -0
  40. package/src/provenance-bytes.ts +22 -0
  41. package/src/provenance-export.ts +126 -0
  42. package/src/provenance-jpeg.ts +83 -0
  43. package/src/provenance-png.ts +26 -0
  44. package/src/provenance-signed.ts +7 -0
  45. package/src/provenance-xmp.ts +57 -0
  46. package/src/provenance.ts +87 -0
  47. package/src/reference-image-size.ts +67 -0
  48. package/src/reference-read.ts +50 -0
  49. package/src/server.ts +711 -0
  50. package/src/video-providers/index.ts +18 -0
  51. package/src/video-providers/minimax.ts +96 -0
  52. package/src/video-providers/reference-encoding.ts +32 -0
  53. package/src/video-providers/types.ts +47 -0
  54. package/src/video-providers/unified.ts +68 -0
  55. package/test/audio-models.test.ts +428 -0
  56. package/test/audio-references.test.ts +428 -0
  57. package/test/custom-catalogue.test.ts +257 -0
  58. package/test/daily-media-meter.test.ts +287 -0
  59. package/test/failure.test.ts +190 -0
  60. package/test/fixtures/cloudflare-workers.fixture.ts +10 -0
  61. package/test/fixtures/media-operation.fixture.ts +134 -0
  62. package/test/fixtures/media-team-prompts.ts +7 -0
  63. package/test/fixtures/native-sqlite.fixture.ts +40 -0
  64. package/test/gateway-models.test.ts +712 -0
  65. package/test/media-operation-do.test.ts +1565 -0
  66. package/test/media-quote.test.ts +81 -0
  67. package/test/media-retention.test.ts +597 -0
  68. package/test/media-service.test.ts +549 -0
  69. package/test/media-team-prompts.test.ts +92 -0
  70. package/test/model-facts.test.ts +126 -0
  71. package/test/prompt-limit.test.ts +53 -0
  72. package/test/provenance-export.test.ts +144 -0
  73. package/test/provenance-images.fixture.mjs +17 -0
  74. package/test/provenance.test.ts +179 -0
  75. package/test/provider-gateway.test.ts +114 -0
  76. package/test/provider-reasons.test.ts +133 -0
  77. package/test/r2-destination.test.ts +166 -0
  78. package/test/reference-image-size.test.ts +73 -0
  79. package/test/reference-images-billing.test.ts +40 -0
  80. package/test/reference-images.test.ts +399 -0
  81. package/test/standalone.cloudflare.test.mjs +298 -0
  82. package/test/standalone.worker.mjs +70 -0
  83. package/test/transform-models.test.ts +400 -0
  84. package/test/video-capabilities.test.ts +160 -0
  85. package/test/video-contract.test.ts +533 -0
  86. package/test/video-failure-lifecycle.test.ts +177 -0
  87. package/test/video-provider.test.ts +136 -0
  88. package/test/video-wire.test.ts +251 -0
  89. package/vitest.cloudflare.config.ts +22 -0
  90. package/vitest.node.config.ts +14 -0
package/src/neurons.ts ADDED
@@ -0,0 +1,6 @@
1
+ /** Published Workers AI image rate: $0.011 per 1,000 neurons. */
2
+ export const USD_PER_1K_NEURONS = 0.011;
3
+
4
+ /** Convert a neuron estimate to milliunits, rounding up to avoid underquoting. */
5
+ export const neuronsToMilliunits = (neurons: number): number =>
6
+ Math.ceil((neurons * 11) / 10);
@@ -0,0 +1,12 @@
1
+ /** Buffer-only public API of pinned node-webpmux 3.2.1; no file or codec APIs. */
2
+ declare module "node-webpmux" {
3
+ import type { Buffer } from "node:buffer";
4
+ const webp: {
5
+ Image: new () => {
6
+ xmp: Buffer | undefined;
7
+ load(data: Buffer): Promise<void>;
8
+ save(path: null): Promise<Buffer>;
9
+ };
10
+ };
11
+ export default webp;
12
+ }
@@ -0,0 +1,22 @@
1
+ /** Byte composition only; maintained format owners parse and encode containers. */
2
+ export function joinBytes(
3
+ parts: readonly Uint8Array[],
4
+ ): Uint8Array<ArrayBuffer> {
5
+ const result = new Uint8Array(
6
+ parts.reduce((size, part) => size + part.length, 0),
7
+ );
8
+ let offset = 0;
9
+ for (const part of parts) {
10
+ result.set(part, offset);
11
+ offset += part.length;
12
+ }
13
+ return result;
14
+ }
15
+
16
+ export function startsWithBytes(bytes: Uint8Array, text: string): boolean {
17
+ const prefix = new TextEncoder().encode(text);
18
+ return (
19
+ bytes.length >= prefix.length &&
20
+ prefix.every((value, index) => bytes[index] === value)
21
+ );
22
+ }
@@ -0,0 +1,126 @@
1
+ import { DOMParser } from "@xmldom/xmldom";
2
+ import ExifReader from "exifreader";
3
+ import { createRiffContainer, parseRiff } from "@fungi.computer/ts-webp";
4
+ import { replacePngXmp } from "./provenance-png.js";
5
+ import { replaceJpegXmp } from "./provenance-jpeg.js";
6
+ import { hasC2paSignature } from "./provenance-signed.js";
7
+ import { publicProvenancePacket } from "./provenance-xmp.js";
8
+
9
+ /** The admitted Computer file read and generated output share this launch bound. */
10
+ export const maximumPrintDownloadBytes = 32 * 1024 * 1024;
11
+ /** Why a lossless public image export was refused. */
12
+ export type ProvenanceExportFailure =
13
+ "too-large" | "invalid-image" | "unsupported-format";
14
+ /** A refusal to export unsafe, unsupported or oversized image bytes. */
15
+ export class ProvenanceExportError extends Error {
16
+ /** Stable export refusal name. */
17
+ override readonly name = "ProvenanceExportError";
18
+ constructor(
19
+ /** Bounded refusal reason. */
20
+ readonly reason: ProvenanceExportFailure,
21
+ options?: ErrorOptions,
22
+ ) {
23
+ super(`Print export refused: ${reason}`, options);
24
+ }
25
+ }
26
+
27
+ function replaceWebpXmp(bytes: Uint8Array, xmp: string): Uint8Array {
28
+ const chunks = parseRiff(bytes);
29
+ // The maintained parser tolerates truncation for inspection. Export must not
30
+ // turn a partial file into an apparently successful download.
31
+ if (
32
+ chunks.some((chunk) => chunk.size !== chunk.data.length) ||
33
+ chunks.reduce(
34
+ (length, chunk) => length + 8 + chunk.size + (chunk.size % 2),
35
+ 12,
36
+ ) !== bytes.length
37
+ )
38
+ throw new Error("Incomplete extended WebP");
39
+ if (!chunks.some((chunk) => chunk.fourCC === "XMP ")) return bytes;
40
+ if (!chunks.some((chunk) => chunk.fourCC === "VP8X"))
41
+ throw new Error("XMP without extended WebP header");
42
+ let inserted = false;
43
+ return createRiffContainer(
44
+ chunks.flatMap((chunk) => {
45
+ if (chunk.fourCC !== "XMP ")
46
+ return [
47
+ {
48
+ fourCC: chunk.fourCC,
49
+ data: chunk.data,
50
+ },
51
+ ];
52
+ if (inserted) return [];
53
+ inserted = true;
54
+ return [
55
+ {
56
+ fourCC: "XMP ",
57
+ data: new TextEncoder().encode(xmp),
58
+ },
59
+ ];
60
+ }),
61
+ );
62
+ }
63
+
64
+ /** Lossless browser export. Never mutates the input or falls back to private bytes. */
65
+ export async function stripPrivateProvenance(bytes: Uint8Array): Promise<{
66
+ /** Image bytes with private provenance removed. */
67
+ bytes: Uint8Array;
68
+ /** Actual output MIME type. */
69
+ type: string;
70
+ /** Filename extension matching the output encoding. */
71
+ extension: string;
72
+ }> {
73
+ if (bytes.length > maximumPrintDownloadBytes)
74
+ throw new ProvenanceExportError("too-large");
75
+ // Embed never writes Prints XMP into a C2PA-signed image, so a signed file
76
+ // holds nothing private to remove. Export its stored bytes unchanged, which
77
+ // also keeps the provider's Content Credentials valid.
78
+ const signed = hasC2paSignature(bytes);
79
+ try {
80
+ const metadata = await ExifReader.loadView(
81
+ new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength),
82
+ {
83
+ expanded: true,
84
+ async: true,
85
+ domParser: new DOMParser(),
86
+ includeTags: { xmp: true, png: true, file: true },
87
+ decompress: { maxDecompressedSize: maximumPrintDownloadBytes },
88
+ },
89
+ );
90
+ const format = metadata.file?.FileType?.value;
91
+ if (
92
+ format !== "png" &&
93
+ format !== "jpeg" &&
94
+ format !== "webp" &&
95
+ format !== "gif"
96
+ )
97
+ throw new ProvenanceExportError("unsupported-format");
98
+ const mime = {
99
+ type: `image/${format}`,
100
+ extension: format === "jpeg" ? "jpg" : format,
101
+ };
102
+ if (signed || (format === "gif" && !metadata.xmp))
103
+ return { bytes, ...mime };
104
+ const packet = publicProvenancePacket(
105
+ metadata.xmp?._raw ?? metadata.pngText?.["XML:com.adobe.xmp"]?.value,
106
+ );
107
+ const output =
108
+ format === "png"
109
+ ? replacePngXmp(bytes, packet)
110
+ : format === "jpeg"
111
+ ? replaceJpegXmp(bytes, packet)
112
+ : format === "webp"
113
+ ? replaceWebpXmp(bytes, packet)
114
+ : undefined;
115
+ if (!output) throw new ProvenanceExportError("unsupported-format");
116
+ if (output.length > maximumPrintDownloadBytes)
117
+ throw new ProvenanceExportError("too-large");
118
+ return {
119
+ bytes: output,
120
+ ...mime,
121
+ };
122
+ } catch (cause) {
123
+ if (cause instanceof ProvenanceExportError) throw cause;
124
+ throw new ProvenanceExportError("invalid-image", { cause });
125
+ }
126
+ }
@@ -0,0 +1,83 @@
1
+ import { joinBytes, startsWithBytes } from "./provenance-bytes.js";
2
+ const jpegXmpSignature = "http://ns.adobe.com/xap/1.0/\0";
3
+ const jpegExtendedXmpSignature = "http://ns.adobe.com/xmp/extension/\0";
4
+
5
+ /** Narrow JPEG splice exception: adr-jpeg-provenance-splice. Never decode or
6
+ * rewrite scan data; walk bounded header segments and preserve their bytes. */
7
+ export function replaceJpegXmp(bytes: Uint8Array, xmp: string): Uint8Array {
8
+ const source = bytes;
9
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
10
+ if (
11
+ source.length < 4 ||
12
+ view.getUint16(0) !== 0xffd8 ||
13
+ view.getUint16(source.length - 2) !== 0xffd9
14
+ )
15
+ throw new Error("Invalid JPEG envelope");
16
+ const payload = new TextEncoder().encode(`${jpegXmpSignature}${xmp}`);
17
+ if (payload.length > 65_533)
18
+ throw new Error("XMP exceeds one JPEG APP1 segment");
19
+ const header = new Uint8Array(4);
20
+ const headerView = new DataView(header.buffer);
21
+ headerView.setUint16(0, 0xffe1);
22
+ headerView.setUint16(2, payload.length + 2);
23
+ const xmpSegment = joinBytes([header, payload]);
24
+ const segments: Uint8Array[] = [source.subarray(0, 2)];
25
+ let insertion = 1;
26
+ let leading = true;
27
+ let hasFrame = false;
28
+ let offset = 2;
29
+ while (offset + 4 <= source.length) {
30
+ const start = offset;
31
+ if (source[offset] !== 0xff) throw new Error("Invalid JPEG marker");
32
+ while (source[offset] === 0xff) offset++;
33
+ const marker = source[offset];
34
+ if (
35
+ marker === undefined ||
36
+ marker === 0 ||
37
+ marker === 0xd8 ||
38
+ marker === 0xd9
39
+ )
40
+ throw new Error("JPEG ended before its scan");
41
+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
42
+ segments.push(source.subarray(start, offset + 1));
43
+ offset++;
44
+ leading = false;
45
+ continue;
46
+ }
47
+ if (offset + 3 > source.length) throw new Error("Truncated JPEG length");
48
+ const length = view.getUint16(offset + 1);
49
+ const end = offset + 1 + length;
50
+ if (length < 2 || end > source.length)
51
+ throw new Error("Truncated JPEG segment");
52
+ if (
53
+ marker >= 0xc0 &&
54
+ marker <= 0xcf &&
55
+ ![0xc4, 0xc8, 0xcc].includes(marker)
56
+ )
57
+ hasFrame = true;
58
+ if (marker === 0xda) {
59
+ if (!hasFrame) throw new Error("JPEG has no frame");
60
+ segments.splice(insertion, 0, xmpSegment);
61
+ segments.push(source.subarray(start));
62
+ return joinBytes(segments);
63
+ }
64
+ const data = source.subarray(offset + 3, end);
65
+ const isXmp =
66
+ marker === 0xe1 &&
67
+ [jpegXmpSignature, jpegExtendedXmpSignature].some((signature) =>
68
+ startsWithBytes(data, signature),
69
+ );
70
+ if (!isXmp) {
71
+ segments.push(source.subarray(start, end));
72
+ if (
73
+ leading &&
74
+ (marker === 0xe0 ||
75
+ (marker === 0xe1 && startsWithBytes(data, "Exif\0\0")))
76
+ )
77
+ insertion = segments.length;
78
+ else leading = false;
79
+ }
80
+ offset = end;
81
+ }
82
+ throw new Error("JPEG has no scan");
83
+ }
@@ -0,0 +1,26 @@
1
+ import extractPng from "png-chunks-extract";
2
+ import encodePng from "png-chunks-encode";
3
+ import { joinBytes, startsWithBytes } from "./provenance-bytes.js";
4
+
5
+ export function replacePngXmp(bytes: Uint8Array, xmp: string): Uint8Array {
6
+ const chunks = extractPng(bytes);
7
+ const keyword = "XML:com.adobe.xmp\0";
8
+ const kept = chunks.filter(
9
+ (chunk) =>
10
+ !(
11
+ ["iTXt", "tEXt", "zTXt"].includes(chunk.name) &&
12
+ startsWithBytes(chunk.data, keyword)
13
+ ),
14
+ );
15
+ const imageIndex = kept.findIndex((chunk) => chunk.name === "IDAT");
16
+ if (imageIndex < 0) throw new Error("PNG has no image data");
17
+ kept.splice(imageIndex, 0, {
18
+ name: "iTXt",
19
+ data: joinBytes([
20
+ new TextEncoder().encode(keyword),
21
+ new Uint8Array(4),
22
+ new TextEncoder().encode(xmp),
23
+ ]),
24
+ });
25
+ return encodePng(kept);
26
+ }
@@ -0,0 +1,7 @@
1
+ /** Conservative C2PA detection shared by embed and export. This is not
2
+ * signature validation: any C2PA marker means the file is provider-signed and
3
+ * Prints leaves its bytes untouched. */
4
+ export function hasC2paSignature(bytes: Uint8Array): boolean {
5
+ const text = new TextDecoder("latin1").decode(bytes);
6
+ return text.includes("c2pa") || text.includes("caBX");
7
+ }
@@ -0,0 +1,57 @@
1
+ import { DOMParser, XMLSerializer } from "@xmldom/xmldom";
2
+
3
+ const fungiNamespace = "https://fungi.computer/ns/provenance/1.0/";
4
+ const iptcNamespace = "http://iptc.org/std/Iptc4xmpExt/2008-02-29/";
5
+ const rdfNamespace = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
6
+
7
+ /** Whitelist public identity, never copy provider or Fungi private XMP wholesale. */
8
+ export function publicProvenancePacket(packet?: string): string {
9
+ const parser = new DOMParser({
10
+ onError: () => {
11
+ throw new Error("Invalid provenance XML");
12
+ },
13
+ });
14
+ const source = packet
15
+ ? parser.parseFromString(packet, "application/xml")
16
+ : undefined;
17
+ const value = (namespace: string, name: string) => {
18
+ const element = source?.getElementsByTagNameNS(namespace, name).item(0);
19
+ if (element?.textContent) return element.textContent;
20
+ const descriptions = source?.getElementsByTagNameNS(
21
+ rdfNamespace,
22
+ "Description",
23
+ );
24
+ if (!descriptions) return undefined;
25
+ for (let index = 0; index < descriptions.length; index++) {
26
+ const attribute = descriptions
27
+ .item(index)
28
+ ?.getAttributeNS(namespace, name);
29
+ if (attribute) return attribute;
30
+ }
31
+ return undefined;
32
+ };
33
+ const output = parser.parseFromString(
34
+ '<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about=""/></rdf:RDF></x:xmpmeta>',
35
+ "application/xml",
36
+ );
37
+ const description = output
38
+ .getElementsByTagNameNS(rdfNamespace, "Description")
39
+ .item(0);
40
+ if (!description) throw new Error("Missing provenance description");
41
+ const fields = [
42
+ { namespace: fungiNamespace, name: "printId", qualified: "fungi:printId" },
43
+ {
44
+ namespace: iptcNamespace,
45
+ name: "DigitalSourceType",
46
+ qualified: "Iptc4xmpExt:DigitalSourceType",
47
+ },
48
+ ];
49
+ for (const { namespace, name, qualified } of fields) {
50
+ const text = value(namespace, name);
51
+ if (text === undefined) continue;
52
+ const element = output.createElementNS(namespace, qualified);
53
+ element.textContent = text;
54
+ description.appendChild(element);
55
+ }
56
+ return new XMLSerializer().serializeToString(output);
57
+ }
@@ -0,0 +1,87 @@
1
+ import { Buffer as NodeBuffer } from "node:buffer";
2
+ import { replacePngXmp } from "./provenance-png.js";
3
+ import { replaceJpegXmp } from "./provenance-jpeg.js";
4
+ import { hasC2paSignature } from "./provenance-signed.js";
5
+ import type { ImageFormat } from "./index.js";
6
+ import { reportCatchFailure } from "./failure.js";
7
+
8
+ /** Public file facts only; actor, namespace, billing and reference paths stay private. */
9
+ export type ProvenanceFacts = Readonly<{
10
+ printId: string;
11
+ model: string;
12
+ /**
13
+ * The prompt to publish in the file's XMP, or null to leave it out. The host
14
+ * decides per generation; a prompt is private unless the host opts in.
15
+ */
16
+ prompt: string | null;
17
+ createdAt: number;
18
+ }>;
19
+ export type ProvenanceEmbedResult =
20
+ | Readonly<{ bytes: Uint8Array; embedded: true }>
21
+ | Readonly<{
22
+ bytes: Uint8Array;
23
+ embedded: false;
24
+ reason: "unsupported-format" | "signed-image" | "invalid-image";
25
+ }>;
26
+
27
+ // The XMP builder and WebP muxer load on the first embed: a Worker that hosts
28
+ // this module never pays to evaluate them at startup.
29
+ async function packet(facts: ProvenanceFacts): Promise<string> {
30
+ const { create } = await import("xmlbuilder2");
31
+ const document = create({ invalidCharReplacement: "�" });
32
+ const description = document
33
+ .ele("adobe:ns:meta/", "x:xmpmeta")
34
+ .ele("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:RDF")
35
+ .ele("rdf:Description")
36
+ .att("rdf:about", "")
37
+ .att("xmlns:xmp", "http://ns.adobe.com/xap/1.0/")
38
+ .att("xmlns:Iptc4xmpExt", "http://iptc.org/std/Iptc4xmpExt/2008-02-29/")
39
+ .att("xmlns:fungi", "https://fungi.computer/ns/provenance/1.0/");
40
+ description
41
+ .ele("xmp:CreateDate")
42
+ .txt(new Date(facts.createdAt).toISOString());
43
+ description
44
+ .ele("Iptc4xmpExt:DigitalSourceType")
45
+ .txt(
46
+ "http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia",
47
+ );
48
+ description.ele("fungi:printId").txt(facts.printId);
49
+ description.ele("fungi:model").txt(facts.model);
50
+ if (facts.prompt !== null) description.ele("fungi:prompt").txt(facts.prompt);
51
+ return document.end({ headless: true });
52
+ }
53
+
54
+ async function embedWebp(bytes: Uint8Array, xmp: string): Promise<Uint8Array> {
55
+ const { default: webp } = await import("node-webpmux");
56
+ const image = new webp.Image();
57
+ await image.load(NodeBuffer.from(bytes));
58
+ image.xmp = NodeBuffer.from(xmp, "utf8");
59
+ return image.save(null);
60
+ }
61
+
62
+ /** Deterministic enrichment. A failed embed never replaces or loses paid bytes.
63
+ * Conservative C2PA detection preserves signed outputs unchanged rather than
64
+ * claiming their old signatures still cover a modified file. */
65
+ export async function embedProvenance(
66
+ bytes: Uint8Array,
67
+ format: ImageFormat | "mp4",
68
+ facts: ProvenanceFacts,
69
+ ): Promise<ProvenanceEmbedResult> {
70
+ if (format === "gif" || format === "mp4")
71
+ return { bytes, embedded: false, reason: "unsupported-format" };
72
+ if (hasC2paSignature(bytes))
73
+ return { bytes, embedded: false, reason: "signed-image" };
74
+ try {
75
+ const xmp = await packet(facts);
76
+ const output =
77
+ format === "png"
78
+ ? replacePngXmp(bytes, xmp)
79
+ : format === "jpeg"
80
+ ? replaceJpegXmp(bytes, xmp)
81
+ : await embedWebp(bytes, xmp);
82
+ return { bytes: output, embedded: true };
83
+ } catch (cause) {
84
+ reportCatchFailure("embed-provenance", cause);
85
+ return { bytes, embedded: false, reason: "invalid-image" };
86
+ }
87
+ }
@@ -0,0 +1,67 @@
1
+ import {
2
+ getMediaModel,
3
+ mediaModels,
4
+ MediaSettingsError,
5
+ type MediaCatalogue,
6
+ } from "./model-catalog.js";
7
+
8
+ const MIN_VIDEO_REFERENCE_DIMENSION = 320;
9
+
10
+ /** One owner for both native fitting and the resolved-reference boundary. */
11
+ function sizing(modelId: string, catalogue: MediaCatalogue) {
12
+ const model = getMediaModel(modelId, catalogue);
13
+ if (model === undefined) throw new MediaSettingsError("unknown Media model");
14
+ return model.video === null && model.input.referenceDimension !== null
15
+ ? { edge: "long" as const, dimension: model.input.referenceDimension }
16
+ : { edge: "short" as const, dimension: MIN_VIDEO_REFERENCE_DIMENSION };
17
+ }
18
+
19
+ /** Aspect-preserving native resize; only video references may be enlarged. */
20
+ export function referenceImageTransform(
21
+ modelId: string,
22
+ width: number,
23
+ height: number,
24
+ catalogue: MediaCatalogue = mediaModels,
25
+ ) {
26
+ const rule = sizing(modelId, catalogue);
27
+ const edge =
28
+ rule.edge === "short" ? Math.min(width, height) : Math.max(width, height);
29
+ const ratio =
30
+ rule.edge === "short"
31
+ ? rule.dimension / edge
32
+ : Math.min(1, rule.dimension / edge);
33
+ // A video's bounding box must not round its long edge down and squeeze
34
+ // the actual decoded short edge below the provider minimum.
35
+ const round = rule.edge === "short" ? Math.ceil : Math.round;
36
+ return {
37
+ width: Math.max(1, round(width * ratio)),
38
+ height: Math.max(1, round(height * ratio)),
39
+ // Small video frames must grow; image references must never grow.
40
+ fit: rule.edge === "short" ? ("contain" as const) : ("scale-down" as const),
41
+ };
42
+ }
43
+
44
+ /** Validate actual decoded output, rather than trusting requested resize dimensions. */
45
+ export function referenceImageSizeIsValid(
46
+ modelId: string,
47
+ width: number,
48
+ height: number,
49
+ catalogue: MediaCatalogue = mediaModels,
50
+ ): boolean {
51
+ const rule = sizing(modelId, catalogue);
52
+ return rule.edge === "short"
53
+ ? Math.min(width, height) >= rule.dimension
54
+ : Math.max(width, height) <= rule.dimension;
55
+ }
56
+
57
+ /** The encoding the selected model's fitted references are sent in. */
58
+ export function referenceImageFormat(
59
+ modelId: string,
60
+ catalogue: MediaCatalogue = mediaModels,
61
+ ) {
62
+ const model = getMediaModel(modelId, catalogue);
63
+ if (model === undefined) throw new MediaSettingsError("unknown Media model");
64
+ return model.input.referenceFormat === "webp"
65
+ ? ("image/webp" as const)
66
+ : ("image/png" as const);
67
+ }
@@ -0,0 +1,50 @@
1
+ import { MAX_AUDIO_REFERENCE_BYTES } from "./audio-reference-types.js";
2
+ import { MediaSettingsError } from "./model-catalog.js";
3
+ import { MAX_REFERENCE_BYTES, type MediaReference } from "./index.js";
4
+
5
+ /** One stored reference: its size is known before its bytes are loaded. */
6
+ export type HostReferenceSource = Readonly<{
7
+ /** Stored byte length, checked before the bytes are read. */
8
+ size: number;
9
+ /** Load the exact stored bytes. */
10
+ bytes: () => Promise<Uint8Array>;
11
+ }>;
12
+
13
+ /**
14
+ * The one owner of a host reference read's refusals. The reference must name
15
+ * the host's admitted destination, exist, be non-empty and fit the byte limit
16
+ * for its kind; anything else is a {@link MediaSettingsError} raised before
17
+ * any provider dispatch.
18
+ */
19
+ export async function readHostReference(
20
+ input: Readonly<{
21
+ reference: MediaReference;
22
+ /** The host's admitted destination identity. */
23
+ destinationId: string;
24
+ kind: "image" | "audio";
25
+ /** Open the reference path in the host's store, or null when missing. */
26
+ open: (path: string) => Promise<HostReferenceSource | null>;
27
+ }>,
28
+ ): Promise<Uint8Array> {
29
+ const { reference, kind } = input;
30
+ if (reference.computerId !== input.destinationId)
31
+ throw new MediaSettingsError("reference Computer is not selected");
32
+ const limit =
33
+ kind === "image" ? MAX_REFERENCE_BYTES : MAX_AUDIO_REFERENCE_BYTES;
34
+ const source = await input.open(reference.path);
35
+ if (source === null || source.size === 0 || source.size > limit)
36
+ throw new MediaSettingsError(
37
+ `${kind} reference is unavailable or exceeds the byte limit`,
38
+ );
39
+ const bytes = await source.bytes();
40
+ if (bytes.byteLength === 0 || bytes.byteLength > limit)
41
+ throw new MediaSettingsError(
42
+ `${kind} reference is unavailable or exceeds the byte limit`,
43
+ );
44
+ return bytes;
45
+ }
46
+
47
+ /** The filename sent with a multipart reference: the last path segment. */
48
+ export function referenceFilename(reference: MediaReference): string {
49
+ return reference.path.split("/").at(-1) ?? "reference";
50
+ }