cheapgen 0.1.2 → 0.2.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.
package/src/media.js ADDED
@@ -0,0 +1,231 @@
1
+ // Reads what cheapgen needs to know about a local input file without decoding it: the image
2
+ // type (from the file's first bytes, never its name), its size in bytes, and its width and height.
3
+ import fs from 'node:fs';
4
+
5
+ const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
6
+ /** JPEG markers that start a frame header (SOF0-SOF15), which carries the size. */
7
+ const isFrameMarker = (m) => m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc;
8
+ /** Markers with no length field: the fill byte, TEM, RST0-RST7 and SOI. */
9
+ const isBareMarker = (m) => m === 0x01 || (m >= 0xd0 && m <= 0xd8);
10
+
11
+ export const IMAGE_MIME = Object.freeze({ png: 'image/png', jpeg: 'image/jpeg', webp: 'image/webp' });
12
+
13
+ /** Reads up to `length` bytes at `position`; shorter when the file ends first. */
14
+ function readAt(fd, position, length) {
15
+ const buf = Buffer.alloc(length);
16
+ const n = fs.readSync(fd, buf, 0, length, position);
17
+ return n === length ? buf : buf.subarray(0, n);
18
+ }
19
+
20
+ function pngSize(fd) {
21
+ const head = readAt(fd, 8, 16);
22
+ if (head.length < 16 || head.toString('latin1', 4, 8) !== 'IHDR') return null;
23
+ return { width: head.readUInt32BE(8), height: head.readUInt32BE(12) };
24
+ }
25
+
26
+ /** The Exif orientation (1-8) from an APP1 segment's bytes, or 1 when it has none. */
27
+ function exifOrientation(seg) {
28
+ if (seg.length < 14 || seg.toString('latin1', 0, 6) !== 'Exif\0\0') return 1;
29
+ const tiff = seg.subarray(6);
30
+ const order = tiff.toString('latin1', 0, 2);
31
+ if (order !== 'II' && order !== 'MM') return 1;
32
+ const u16 = (o) => (order === 'II' ? tiff.readUInt16LE(o) : tiff.readUInt16BE(o));
33
+ const u32 = (o) => (order === 'II' ? tiff.readUInt32LE(o) : tiff.readUInt32BE(o));
34
+ const ifd = u32(4);
35
+ if (ifd + 2 > tiff.length) return 1;
36
+ const count = u16(ifd);
37
+ for (let i = 0; i < count; i += 1) {
38
+ const at = ifd + 2 + i * 12;
39
+ if (at + 12 > tiff.length) break;
40
+ if (u16(at) === 0x0112) {
41
+ const value = u16(at + 8);
42
+ return value >= 1 && value <= 8 ? value : 1;
43
+ }
44
+ }
45
+ return 1;
46
+ }
47
+
48
+ /** Walks the segments up to the frame header. Orientations 5-8 turn the picture on its side. */
49
+ function jpegSize(fd, fileBytes) {
50
+ let pos = 2;
51
+ let orientation = 1;
52
+ while (pos + 4 <= fileBytes) {
53
+ const head = readAt(fd, pos, 4);
54
+ if (head.length < 4 || head[0] !== 0xff) return null;
55
+ const marker = head[1];
56
+ if (marker === 0xff) { pos += 1; continue; }
57
+ if (isBareMarker(marker)) { pos += 2; continue; }
58
+ if (marker === 0xd9 || marker === 0xda) return null;
59
+ const length = head.readUInt16BE(2);
60
+ if (length < 2) return null;
61
+ if (isFrameMarker(marker)) {
62
+ const frame = readAt(fd, pos + 4, 5);
63
+ if (frame.length < 5) return null;
64
+ const height = frame.readUInt16BE(1);
65
+ const width = frame.readUInt16BE(3);
66
+ return orientation >= 5 ? { width: height, height: width } : { width, height };
67
+ }
68
+ if (marker === 0xe1 && orientation === 1) orientation = exifOrientation(readAt(fd, pos + 4, Math.min(length - 2, 65_533)));
69
+ pos += 2 + length;
70
+ }
71
+ return null;
72
+ }
73
+
74
+ function webpSize(fd) {
75
+ const head = readAt(fd, 12, 18);
76
+ if (head.length < 18) return null;
77
+ const chunk = head.toString('latin1', 0, 4);
78
+ const data = head.subarray(8);
79
+ if (chunk === 'VP8 ') {
80
+ if (data[3] !== 0x9d || data[4] !== 0x01 || data[5] !== 0x2a) return null;
81
+ return { width: data.readUInt16LE(6) & 0x3fff, height: data.readUInt16LE(8) & 0x3fff };
82
+ }
83
+ if (chunk === 'VP8L') {
84
+ if (data[0] !== 0x2f) return null;
85
+ const bits = data.readUInt32LE(1);
86
+ return { width: (bits & 0x3fff) + 1, height: ((bits >>> 14) & 0x3fff) + 1 };
87
+ }
88
+ if (chunk === 'VP8X') {
89
+ return { width: data.readUIntLE(4, 3) + 1, height: data.readUIntLE(7, 3) + 1 };
90
+ }
91
+ return null;
92
+ }
93
+
94
+ /**
95
+ * @param {string} filePath
96
+ * @returns {{ type: 'png'|'jpeg'|'webp', bytes: number, width: number, height: number } | null}
97
+ * null when the file isn't a PNG, JPEG or WebP image whose size can be read
98
+ */
99
+ export function probeImage(filePath) {
100
+ const fd = fs.openSync(filePath, 'r');
101
+ try {
102
+ const bytes = fs.fstatSync(fd).size;
103
+ const head = readAt(fd, 0, 12);
104
+ let type = null;
105
+ let size = null;
106
+ if (head.length >= 8 && head.subarray(0, 8).equals(PNG_SIGNATURE)) {
107
+ type = 'png';
108
+ size = pngSize(fd);
109
+ } else if (head.length >= 3 && head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff) {
110
+ type = 'jpeg';
111
+ size = jpegSize(fd, bytes);
112
+ } else if (head.length >= 12 && head.toString('latin1', 0, 4) === 'RIFF' && head.toString('latin1', 8, 12) === 'WEBP') {
113
+ type = 'webp';
114
+ size = webpSize(fd);
115
+ }
116
+ if (!type || !size || !(size.width > 0) || !(size.height > 0)) return null;
117
+ return { type, bytes, width: size.width, height: size.height };
118
+ } finally {
119
+ fs.closeSync(fd);
120
+ }
121
+ }
122
+
123
+ export const AUDIO_MIME = Object.freeze({ wav: 'audio/wav', mp3: 'audio/mpeg' });
124
+
125
+ /** Length of a WAV file: the data chunk's bytes divided by the format chunk's byte rate. */
126
+ function wavSeconds(fd, fileBytes) {
127
+ let pos = 12;
128
+ let byteRate = null;
129
+ while (pos + 8 <= fileBytes) {
130
+ const head = readAt(fd, pos, 8);
131
+ if (head.length < 8) return null;
132
+ const id = head.toString('latin1', 0, 4);
133
+ const size = head.readUInt32LE(4);
134
+ if (id === 'fmt ') {
135
+ const fmt = readAt(fd, pos + 8, 12);
136
+ if (fmt.length < 12) return null;
137
+ byteRate = fmt.readUInt32LE(8);
138
+ } else if (id === 'data') {
139
+ if (!(byteRate > 0)) return null;
140
+ // A recorder that didn't go back to fill in the size leaves 0 or the maximum: use the rest of the file.
141
+ const rest = fileBytes - (pos + 8);
142
+ const dataBytes = size === 0 || size > rest ? rest : size;
143
+ return dataBytes / byteRate;
144
+ }
145
+ pos += 8 + size + (size % 2);
146
+ }
147
+ return null;
148
+ }
149
+
150
+ const MP3_BITRATES_V1 = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320];
151
+ const MP3_BITRATES_V2 = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160];
152
+ const MP3_SAMPLE_RATES = { 3: [44100, 48000, 32000], 2: [22050, 24000, 16000], 0: [11025, 12000, 8000] };
153
+
154
+ /** The fields of an MPEG Layer III frame header, or null when the four bytes aren't one. */
155
+ function mp3Header(buf) {
156
+ if (buf.length < 4 || buf[0] !== 0xff || (buf[1] & 0xe0) !== 0xe0) return null;
157
+ const version = (buf[1] >> 3) & 3; // 3: MPEG-1, 2: MPEG-2, 0: MPEG-2.5
158
+ const layer = (buf[1] >> 1) & 3; // 1: Layer III
159
+ const bitrateIndex = buf[2] >> 4;
160
+ const rateIndex = (buf[2] >> 2) & 3;
161
+ if (version === 1 || layer !== 1 || bitrateIndex === 0 || bitrateIndex === 15 || rateIndex === 3) return null;
162
+ const mono = (buf[3] >> 6) === 3;
163
+ return {
164
+ sampleRate: MP3_SAMPLE_RATES[version][rateIndex],
165
+ kbps: (version === 3 ? MP3_BITRATES_V1 : MP3_BITRATES_V2)[bitrateIndex],
166
+ samplesPerFrame: version === 3 ? 1152 : 576,
167
+ sideInfoBytes: version === 3 ? (mono ? 17 : 32) : (mono ? 9 : 17),
168
+ hasCrc: (buf[1] & 1) === 0,
169
+ };
170
+ }
171
+
172
+ /**
173
+ * An MP3's first frame and its length. The length comes from the frame count in the first
174
+ * frame's Xing, Info or VBRI tag; a file without one has no stated length (`seconds: null`).
175
+ * Null when the file doesn't start with an MPEG Layer III frame (after an ID3v2 tag, if any).
176
+ */
177
+ function mp3Info(fd) {
178
+ let start = 0;
179
+ const tag = readAt(fd, 0, 10);
180
+ if (tag.length === 10 && tag.toString('latin1', 0, 3) === 'ID3') {
181
+ const size = ((tag[6] & 0x7f) << 21) | ((tag[7] & 0x7f) << 14) | ((tag[8] & 0x7f) << 7) | (tag[9] & 0x7f);
182
+ start = 10 + size + (tag[5] & 0x10 ? 10 : 0);
183
+ }
184
+ const frame = readAt(fd, start, 200);
185
+ const h = mp3Header(frame);
186
+ if (!h) return null;
187
+ let frames = null;
188
+ const xingAt = 4 + (h.hasCrc ? 2 : 0) + h.sideInfoBytes;
189
+ const xing = frame.toString('latin1', xingAt, xingAt + 4);
190
+ if ((xing === 'Xing' || xing === 'Info') && frame.length >= xingAt + 12 && (frame.readUInt32BE(xingAt + 4) & 1)) {
191
+ frames = frame.readUInt32BE(xingAt + 8);
192
+ } else if (frame.toString('latin1', 36, 40) === 'VBRI' && frame.length >= 54) {
193
+ frames = frame.readUInt32BE(50);
194
+ }
195
+ return { seconds: frames > 0 ? (frames * h.samplesPerFrame) / h.sampleRate : null };
196
+ }
197
+
198
+ /**
199
+ * @param {string} filePath
200
+ * @returns {{ type: 'wav'|'mp3', bytes: number, seconds: number|null } | null} `seconds` is null
201
+ * when the file doesn't state its length; null overall when it is neither WAV nor MP3
202
+ */
203
+ export function probeAudio(filePath) {
204
+ const fd = fs.openSync(filePath, 'r');
205
+ try {
206
+ const bytes = fs.fstatSync(fd).size;
207
+ const head = readAt(fd, 0, 12);
208
+ if (head.length >= 12 && head.toString('latin1', 0, 4) === 'RIFF' && head.toString('latin1', 8, 12) === 'WAVE') {
209
+ return { type: 'wav', bytes, seconds: wavSeconds(fd, bytes) };
210
+ }
211
+ const mp3 = mp3Info(fd);
212
+ return mp3 ? { type: 'mp3', bytes, seconds: mp3.seconds } : null;
213
+ } finally {
214
+ fs.closeSync(fd);
215
+ }
216
+ }
217
+
218
+ /** The ratio in `ratios` ("16:9", ...) closest to width ÷ height, compared on a log scale. */
219
+ export function nearestRatio(width, height, ratios) {
220
+ if (!(width > 0) || !(height > 0)) return null;
221
+ const target = Math.log(width / height);
222
+ let best = null;
223
+ let bestGap = Infinity;
224
+ for (const ratio of ratios) {
225
+ const [w, h] = String(ratio).split(':').map(Number);
226
+ if (!(w > 0) || !(h > 0)) continue;
227
+ const gap = Math.abs(Math.log(w / h) - target);
228
+ if (gap < bestGap - 1e-12) { best = ratio; bestGap = gap; }
229
+ }
230
+ return best;
231
+ }
@@ -27,11 +27,15 @@ function requestFor(catalog, e, cwd) {
27
27
  if (model.kind === 'video') {
28
28
  flags.res = first(e.when?.resolution) ?? (model.resolutions.includes(DEFAULTS.resolution) ? DEFAULTS.resolution : model.resolutions[0]);
29
29
  if (e.mode === 'image-to-video') flags.image = 'https://example.com/first-frame.png';
30
- } else if (e.when?.size) {
31
- flags.size = first(e.when.size);
30
+ } else {
31
+ if (e.when?.size) flags.size = first(e.when.size);
32
+ if (e.mode === 'image-edit') flags.image = ['https://example.com/input.png'];
32
33
  }
33
- if (!model.aspectRatios.includes(DEFAULTS.aspectRatio)) flags.aspect = model.aspectRatios[0];
34
- return buildCanonicalRequest(e.model, flags, catalog, { cwd, requirePrompt: false });
34
+ if (!model.aspectRatios.includes(DEFAULTS.aspectRatio) || e.mode === 'image-edit') {
35
+ flags.aspect = model.aspectRatios.includes(DEFAULTS.aspectRatio) ? DEFAULTS.aspectRatio : model.aspectRatios[0];
36
+ }
37
+ // Variant prices are checked whatever the user's setting is.
38
+ return buildCanonicalRequest(e.model, flags, catalog, { cwd, requirePrompt: false, allowVariants: true });
35
39
  }
36
40
 
37
41
  /**
@@ -100,12 +104,14 @@ async function checkOne(app, e, base, out, compare, falPrices) {
100
104
  const entry = app.catalog.models[e.model].providers[e.provider];
101
105
  if (!entry) return out('unchecked', { reason: `${e.provider} doesn't list ${e.model}` });
102
106
 
103
- if (e.provider === 'wavespeed') {
104
- const live = await ADAPTERS.wavespeed.livePrice(request, ctx, { entry });
105
- if (!live) return out('unavailable', { reason: 'WaveSpeed\'s price API didn\'t answer' });
107
+ // Both price one whole request: WaveSpeed's price API and Higgsfield's estimate endpoint.
108
+ if (e.provider === 'wavespeed' || e.provider === 'higgsfield') {
109
+ const adapter = ADAPTERS[e.provider];
110
+ const live = await adapter.livePrice(request, ctx, { entry });
111
+ if (!live) return out('unavailable', { reason: `${adapter.displayName}'s price API didn't answer` });
106
112
  if (e.pricing.type === 'perSecond') return compare(live.usd / request.duration);
107
113
  if (e.pricing.type === 'perImage') return compare(live.usd / request.count);
108
- return out('unchecked', { reason: `a ${e.pricing.type} price can't be compared with WaveSpeed's request price` });
114
+ return out('unchecked', { reason: `a ${e.pricing.type} price can't be compared with ${adapter.displayName}'s request price` });
109
115
  }
110
116
 
111
117
  if (e.provider === 'fal') {
@@ -19,6 +19,31 @@ export function frameSize(request, frameSizes) {
19
19
  */
20
20
  export function cost(pricing, request, frameSizes) {
21
21
  const count = request.count ?? 1;
22
+ return baseCost(pricing, request, frameSizes, count) + inputFee(pricing.inputFee, request) * count;
23
+ }
24
+
25
+ /**
26
+ * What the input images of an edit add to one output: a fee per image (after any free ones),
27
+ * or a fee per megapixel of input.
28
+ */
29
+ function inputFee(fee, request) {
30
+ const images = request.images;
31
+ if (!fee || !images?.length) return 0;
32
+ let usd = 0;
33
+ if (fee.usdPerImage) usd += Math.max(0, images.length - (fee.free ?? 0)) * fee.usdPerImage;
34
+ if (fee.usdPerMp) {
35
+ const mp = fee.mpDefinition ?? 1e6;
36
+ usd += images.reduce((sum, i) => sum + Math.ceil(needPixels(i) / mp - 1e-12), 0) * fee.usdPerMp;
37
+ }
38
+ return usd;
39
+ }
40
+
41
+ function needPixels(image) {
42
+ if (!(image.width > 0) || !(image.height > 0)) throw new Error('the size of an input image given as a URL is unknown');
43
+ return image.width * image.height;
44
+ }
45
+
46
+ function baseCost(pricing, request, frameSizes, count) {
22
47
  switch (pricing.type) {
23
48
  case 'perSecond':
24
49
  return pricing.usd * need(request.duration, 'duration') * count;
@@ -34,6 +59,7 @@ export function cost(pricing, request, frameSizes) {
34
59
  const mpUnit = pricing.mpDefinition ?? 1e6;
35
60
  const round = pricing.roundUp === false ? (x) => x : (x) => Math.ceil(x - 1e-12);
36
61
  const outputMp = round((w * h) / mpUnit);
62
+ if (pricing.usdPerInputMp && request.images?.length) request.images.forEach(needPixels);
37
63
  const inputMp = request.inputPixels ? round(request.inputPixels / mpUnit) : 0;
38
64
  const perImage = (pricing.usdPerRun ?? 0) + outputMp * (pricing.usdPerOutputMp ?? 0)
39
65
  + inputMp * (pricing.usdPerInputMp ?? 0);
@@ -2,6 +2,7 @@
2
2
  // API and a key, else a cached live price younger than 24 hours, else the bundled table.
3
3
  import { cost } from './formulas.js';
4
4
  import { pricedRequest } from '../request.js';
5
+ import { entryFor } from '../catalog.js';
5
6
 
6
7
  export const STALE_AFTER_DAYS = 14;
7
8
  const DAY_MS = 24 * 60 * 60 * 1000;
@@ -46,7 +47,9 @@ export function bundledPrice(catalog, providerId, request, now) {
46
47
 
47
48
  export function cacheKey(providerId, r) {
48
49
  return [providerId, r.model, r.mode, r.resolution ?? r.size, r.aspectRatio,
49
- r.autoDuration ? 'auto' : r.duration, r.audio, r.count, r.image ? 'img' : ''].join('|');
50
+ r.autoDuration ? 'auto' : r.duration, r.audio, r.count, r.image ? 'img' : '',
51
+ ...(r.images ? [`in${r.images.length}`, r.inputPixels ?? '?', r.effectiveAspect ?? '?',
52
+ r.images.map((i) => (i.isLocal ? `${i.width}x${i.height}` : 'url')).join(',')] : [])].join('|');
50
53
  }
51
54
 
52
55
  /**
@@ -66,7 +69,7 @@ export async function priceFor({ adapter, request, catalog, ctx, cache, now }) {
66
69
  const key = cacheKey(adapter.id, request);
67
70
  let live = null;
68
71
  try {
69
- live = await adapter.livePrice(request, ctx, { entry: catalog.models[request.model].providers[adapter.id],
72
+ live = await adapter.livePrice(request, ctx, { entry: entryFor(catalog, adapter.id, request),
70
73
  bundled, frameSizes: catalog.frameSizes });
71
74
  } catch { live = null; }
72
75
  if (live && typeof live.usd === 'number' && Number.isFinite(live.usd)) {
@@ -42,12 +42,18 @@ export function readError(message, status) {
42
42
 
43
43
  const MIME = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif' };
44
44
 
45
- /** Reads a local file into a Blob for multipart uploads, with a MIME type from its extension. */
46
- export function fileBlob(filePath) {
47
- const type = MIME[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream';
45
+ /**
46
+ * Reads a local file into a Blob for uploads. The MIME type is `contentType` when the caller
47
+ * read the file's type from its bytes, else it comes from the extension.
48
+ */
49
+ export function fileBlob(filePath, contentType) {
50
+ const type = contentType ?? MIME[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream';
48
51
  return { blob: new Blob([fs.readFileSync(filePath)], { type }), name: path.basename(filePath), type };
49
52
  }
50
53
 
54
+ /** What an upload is called in an error message: "the image" or "the audio file". */
55
+ export const uploadLabel = (contentType) => (contentType?.startsWith('audio/') ? 'the audio file' : 'the image');
56
+
51
57
  /** Wraps an upload so any failure counts as a clear rejection: no job exists yet. */
52
58
  export async function asRejection(what, fn) {
53
59
  try {
@@ -81,26 +87,61 @@ export function videoFields(r, { durationAsString = false, entry } = {}) {
81
87
  return fields;
82
88
  }
83
89
 
90
+ /**
91
+ * The media fields of a video request under one provider's field names (`names`: first, last,
92
+ * refImages, refAudio). A reference list with nothing in it is left out, and the entry's
93
+ * `request.referenceFields` (a task type, where the provider has one) is added to a
94
+ * reference-to-video request.
95
+ */
96
+ export function videoMedia(r, entry, names, { imageUrl, lastImageUrl, refImageUrls, refAudioUrls } = {}) {
97
+ if (r.mode === 'reference-to-video') {
98
+ return {
99
+ ...(refImageUrls?.length ? { [names.refImages]: refImageUrls } : {}),
100
+ ...(refAudioUrls?.length ? { [names.refAudio]: refAudioUrls } : {}),
101
+ ...(entry?.request?.referenceFields ?? {}),
102
+ };
103
+ }
104
+ return { ...(imageUrl ? { [names.first]: imageUrl } : {}), ...(lastImageUrl ? { [names.last]: lastImageUrl } : {}) };
105
+ }
106
+
84
107
  /**
85
108
  * Image size and aspect fields from the entry's `request` block. Without one,
86
109
  * the adapter's default size field is used and the canonical size is sent as is.
110
+ *
111
+ * An edit with aspect "auto" uses the provider's own way of following the input image
112
+ * (`edit.follow`): a value for the aspect field, no aspect field at all (`aspect: null`), or a
113
+ * size preset per canonical size. A provider with none gets the ratio worked out from the image.
87
114
  */
88
115
  export function imageFields(r, entry, defaultSizeField) {
89
116
  const req = entry?.request ?? {};
90
117
  const size = req.size ?? { field: defaultSizeField };
118
+ const auto = r.aspectRatio === 'auto';
119
+ const follow = auto ? entry?.edit?.follow : undefined;
120
+ let aspect = auto ? r.effectiveAspect : r.aspectRatio;
121
+ if (follow) aspect = Object.hasOwn(follow, 'aspect') ? follow.aspect : null;
91
122
  let value;
92
- if (size.pixels) {
123
+ if (follow?.size) {
124
+ value = follow.size[r.size] ?? r.size;
125
+ } else if (size.pixels) {
93
126
  if (!Array.isArray(r.pixels)) throw new Error(`no pixel size for ${r.model} ${r.size} ${r.aspectRatio}`);
94
127
  const [width, height] = r.pixels;
95
128
  value = size.pixels === 'object' ? { width, height } : `${width}*${height}`;
96
129
  } else {
97
130
  value = size.values?.[r.size] ?? r.size;
98
131
  }
99
- return { ...(req.aspect === false ? {} : { aspect_ratio: r.aspectRatio }), [size.field]: value };
132
+ return { ...(req.aspect === false || !aspect ? {} : { aspect_ratio: aspect }), [size.field]: value };
100
133
  }
101
134
 
102
- /** "<id>/<suffix>", or the id alone when the entry maps the mode to "". */
135
+ /** The input images of an edit, under the provider's field name; nothing for other modes. */
136
+ export const editImages = (r, entry, imageUrls) =>
137
+ (r.mode === 'image-edit' ? { [entry.edit.field]: imageUrls ?? [] } : {});
138
+
139
+ /** The provider's model id: its edit id for an edit when it has a separate one. */
140
+ export const modelId = (r, entry) => (r.mode === 'image-edit' ? entry.edit?.id ?? entry.id : entry.id);
141
+
142
+ /** "<id>/<suffix>", or the id alone when the entry maps the mode to "". An edit has its own path. */
103
143
  export function endpointPath(r, entry) {
144
+ if (r.mode === 'image-edit' && entry.edit?.id) return entry.edit.id;
104
145
  const suffix = entry.modes?.[r.mode] ?? r.mode;
105
146
  return suffix ? `${entry.id}/${suffix}` : entry.id;
106
147
  }
@@ -10,11 +10,15 @@ export class SubmitRejected extends Error {
10
10
  }
11
11
  }
12
12
 
13
- /** A job may exist and may be billed: never fall back automatically. */
13
+ /**
14
+ * A job may exist and may be billed: never fall back automatically. `details` holds anything that
15
+ * helps find the job later (for example an idempotency key); it goes in the spend log.
16
+ */
14
17
  export class SubmitUnknown extends Error {
15
- constructor(message, { status = null } = {}) {
18
+ constructor(message, { status = null, details = null } = {}) {
16
19
  super(message);
17
20
  this.name = 'SubmitUnknown';
18
21
  this.status = status;
22
+ this.details = details;
19
23
  }
20
24
  }
@@ -3,9 +3,9 @@
3
3
  // The balance needs a key with billing:usage:read; without it the balance is unknown.
4
4
  import { http, describeBody } from '../http.js';
5
5
  import { SubmitUnknown } from './errors.js';
6
- import { postJob, getJson, fileBlob, asRejection, videoFields, imageFields, endpointPath } from './common.js';
6
+ import { postJob, getJson, fileBlob, uploadLabel, asRejection, videoFields, videoMedia, imageFields, editImages, endpointPath } from './common.js';
7
7
  import { cost } from '../pricing/formulas.js';
8
- import { pricedRequest } from '../request.js';
8
+ import { pricedRequest, promptFor } from '../request.js';
9
9
 
10
10
  const QUEUE = 'https://queue.fal.run';
11
11
  const API = 'https://api.fal.ai/v1';
@@ -15,6 +15,15 @@ const auth = (ctx) => ({ Authorization: `Key ${ctx.key}` });
15
15
 
16
16
  const endpointOf = endpointPath;
17
17
 
18
+ const VIDEO_INPUTS = { first: 'image_url', last: 'end_image_url', refImages: 'image_urls', refAudio: 'audio_urls' };
19
+
20
+ /**
21
+ * The endpoint whose unit price applies. fal has one price per endpoint, and a reference
22
+ * endpoint's can't tell a request with reference video from one without; with images and audio
23
+ * only, the rate is the text-to-video one.
24
+ */
25
+ const pricedEndpoint = (r, entry) => endpointOf(r.mode === 'reference-to-video' ? { ...r, mode: 'text-to-video' } : r, entry);
26
+
18
27
  /** fal's queue status URLs use the app id: the first two segments of the endpoint. */
19
28
  const appIdOf = (endpoint) => endpoint.split('/').slice(0, 2).join('/');
20
29
 
@@ -29,7 +38,10 @@ export const hasLivePrice = (priceEntry) => priceEntry?.live?.falUnitPrice !== f
29
38
  export function liveToPricing(unit, unitPrice, bundledPricing) {
30
39
  const u = String(unit ?? '').toLowerCase();
31
40
  if (/^(second|seconds|sec)$/.test(u)) return { type: 'perSecond', usd: unitPrice };
32
- if (/^(image|images)$/.test(u)) return { type: 'perImage', usd: unitPrice };
41
+ if (/^(image|images)$/.test(u)) {
42
+ // The unit price is the output image; an input-image fee on record still applies.
43
+ return { type: 'perImage', usd: unitPrice, ...(bundledPricing?.inputFee ? { inputFee: bundledPricing.inputFee } : {}) };
44
+ }
33
45
  if (/token/.test(u) && bundledPricing?.type === 'perToken') {
34
46
  // fal's units look like "1000 tokens" or "1m tokens" (fal.ai/pricing.md).
35
47
  const per1k = /\b(1m|1 ?million|1,?000,?000)\b/.test(u) ? unitPrice / 1000
@@ -45,10 +57,13 @@ export default {
45
57
  envVar: 'FAL_KEY',
46
58
  billing: { failedJobCharged: false, validationErrorMayCharge: true },
47
59
 
48
- buildRequest(r, { entry, imageUrl }) {
60
+ buildRequest(r, inputs) {
61
+ const { entry, imageUrls } = inputs;
62
+ // fal names inputs in the prompt as @Image1, @Audio1.
49
63
  const body = r.kind === 'image'
50
- ? { prompt: r.prompt, ...imageFields(r, entry, 'resolution') }
51
- : { prompt: r.prompt, ...videoFields(r, { durationAsString: true, entry }), ...(imageUrl ? { image_url: imageUrl } : {}) };
64
+ ? { prompt: r.prompt, ...imageFields(r, entry, 'resolution'), ...editImages(r, entry, imageUrls) }
65
+ : { prompt: promptFor(r, 'plain'), ...videoFields(r, { durationAsString: true, entry }),
66
+ ...videoMedia(r, entry, VIDEO_INPUTS, inputs) };
52
67
  return { method: 'POST', url: `${QUEUE}/${endpointOf(r, entry)}`, body };
53
68
  },
54
69
 
@@ -74,7 +89,7 @@ export default {
74
89
 
75
90
  async livePrice(r, ctx, { entry, bundled, frameSizes }) {
76
91
  if (!hasLivePrice(bundled?.entry)) return null;
77
- const endpoint = endpointOf(r, entry);
92
+ const endpoint = pricedEndpoint(r, entry);
78
93
  const p = (await this.unitPrices([endpoint], ctx)).get(endpoint);
79
94
  if (!p) return null;
80
95
  const pricing = liveToPricing(p.unit, p.unitPrice, bundled?.entry?.pricing);
@@ -88,9 +103,9 @@ export default {
88
103
  return typeof balance === 'number' ? balance : null;
89
104
  },
90
105
 
91
- async upload(filePath, ctx) {
92
- return asRejection('the image to fal', async () => {
93
- const { blob, name, type } = fileBlob(filePath);
106
+ async upload(filePath, ctx, contentType) {
107
+ return asRejection(`${uploadLabel(contentType)} to fal`, async () => {
108
+ const { blob, name, type } = fileBlob(filePath, contentType);
94
109
  const init = await http(ctx, { method: 'POST', url: STORAGE, headers: auth(ctx), timeoutMs: 30_000,
95
110
  json: { content_type: type, file_name: name } });
96
111
  if (!init.ok || !init.json?.upload_url) throw new Error(`HTTP ${init.status}: ${describeBody(init)}`);
@@ -101,8 +116,9 @@ export default {
101
116
  });
102
117
  },
103
118
 
104
- async submit(r, ctx, { entry, imageUrl }) {
105
- const { url, body } = this.buildRequest(r, { entry, imageUrl });
119
+ async submit(r, ctx, inputs) {
120
+ const { entry } = inputs;
121
+ const { url, body } = this.buildRequest(r, inputs);
106
122
  const res = await postJob(ctx, { url, headers: auth(ctx), json: body });
107
123
  const j = res.json;
108
124
  if (!j?.request_id) throw new SubmitUnknown(`no request id in the response: ${describeBody(res)}`);