@effing/ffs 0.1.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.
@@ -0,0 +1,1190 @@
1
+ // src/motion.ts
2
+ function getEasingExpression(tNormExpr, easingType) {
3
+ switch (easingType) {
4
+ case "ease-in":
5
+ return `pow(${tNormExpr},2)`;
6
+ case "ease-out":
7
+ return `(1-pow(1-(${tNormExpr}),2))`;
8
+ case "ease-in-out":
9
+ return `if(lt(${tNormExpr},0.5),2*pow(${tNormExpr},2),1-pow(-2*(${tNormExpr})+2,2)/2)`;
10
+ case "linear":
11
+ default:
12
+ return `(${tNormExpr})`;
13
+ }
14
+ }
15
+ function processSlideMotion(motion, relativeTimeExpr) {
16
+ const duration = motion.duration ?? 1;
17
+ const distance = motion.distance ?? 1;
18
+ const reverse = motion.reverse ?? false;
19
+ const easing = motion.easing ?? "linear";
20
+ const tNormExpr = `(${relativeTimeExpr})/${duration}`;
21
+ const easedProgressExpr = getEasingExpression(tNormExpr, easing);
22
+ const finalTimeFactorExpr = reverse ? easedProgressExpr : `(1-(${easedProgressExpr}))`;
23
+ let activeX;
24
+ let activeY;
25
+ let initialX;
26
+ let initialY;
27
+ let finalX;
28
+ let finalY;
29
+ switch (motion.direction) {
30
+ case "left": {
31
+ const offsetXLeft = `${distance}*W`;
32
+ activeX = `(${offsetXLeft})*${finalTimeFactorExpr}`;
33
+ activeY = "0";
34
+ initialX = reverse ? "0" : offsetXLeft;
35
+ initialY = "0";
36
+ finalX = reverse ? offsetXLeft : "0";
37
+ finalY = "0";
38
+ break;
39
+ }
40
+ case "right": {
41
+ const offsetXRight = `-${distance}*W`;
42
+ activeX = `(${offsetXRight})*${finalTimeFactorExpr}`;
43
+ activeY = "0";
44
+ initialX = reverse ? "0" : offsetXRight;
45
+ initialY = "0";
46
+ finalX = reverse ? offsetXRight : "0";
47
+ finalY = "0";
48
+ break;
49
+ }
50
+ case "up": {
51
+ const offsetYUp = `${distance}*H`;
52
+ activeX = "0";
53
+ activeY = `(${offsetYUp})*${finalTimeFactorExpr}`;
54
+ initialX = "0";
55
+ initialY = reverse ? "0" : offsetYUp;
56
+ finalX = "0";
57
+ finalY = reverse ? offsetYUp : "0";
58
+ break;
59
+ }
60
+ case "down": {
61
+ const offsetYDown = `-${distance}*H`;
62
+ activeX = "0";
63
+ activeY = `(${offsetYDown})*${finalTimeFactorExpr}`;
64
+ initialX = "0";
65
+ initialY = reverse ? "0" : offsetYDown;
66
+ finalX = "0";
67
+ finalY = reverse ? offsetYDown : "0";
68
+ break;
69
+ }
70
+ }
71
+ return { initialX, initialY, activeX, activeY, finalX, finalY, duration };
72
+ }
73
+ function processBounceMotion(motion, relativeTimeExpr) {
74
+ const amplitude = motion.amplitude ?? 0.5;
75
+ const duration = motion.duration ?? 1;
76
+ const initialY = `-overlay_h*${amplitude}`;
77
+ const finalY = "0";
78
+ const tNormExpr = `(${relativeTimeExpr})/${duration}`;
79
+ const activeBounceExpression = `if(lt(${tNormExpr},0.363636),${initialY}+overlay_h*${amplitude}*(7.5625*${tNormExpr}*${tNormExpr}),if(lt(${tNormExpr},0.727273),${initialY}+overlay_h*${amplitude}*(7.5625*(${tNormExpr}-0.545455)*(${tNormExpr}-0.545455)+0.75),if(lt(${tNormExpr},0.909091),${initialY}+overlay_h*${amplitude}*(7.5625*(${tNormExpr}-0.818182)*(${tNormExpr}-0.818182)+0.9375),if(lt(${tNormExpr},0.954545),${initialY}+overlay_h*${amplitude}*(7.5625*(${tNormExpr}-0.954545)*(${tNormExpr}-0.954545)+0.984375),${finalY}))))`;
80
+ return {
81
+ initialX: "0",
82
+ initialY,
83
+ activeX: "0",
84
+ activeY: activeBounceExpression,
85
+ // This expression now scales with duration
86
+ finalX: "0",
87
+ finalY,
88
+ duration
89
+ // Return the actual duration used
90
+ };
91
+ }
92
+ function processShakeMotion(motion, relativeTimeExpr) {
93
+ const intensity = motion.intensity ?? 10;
94
+ const frequency = motion.frequency ?? 4;
95
+ const duration = motion.duration ?? 1;
96
+ const activeX = `${intensity}*sin(${relativeTimeExpr}*PI*${frequency})`;
97
+ const activeY = `${intensity}*cos(${relativeTimeExpr}*PI*${frequency})`;
98
+ return {
99
+ initialX: "0",
100
+ initialY: "0",
101
+ activeX,
102
+ activeY,
103
+ finalX: "0",
104
+ finalY: "0",
105
+ duration
106
+ };
107
+ }
108
+ function processMotion(delay, motion) {
109
+ if (!motion) return "x=0:y=0";
110
+ const start = delay + (motion.start ?? 0);
111
+ const relativeTimeExpr = `(t-${start})`;
112
+ let components;
113
+ switch (motion.type) {
114
+ case "bounce":
115
+ components = processBounceMotion(motion, relativeTimeExpr);
116
+ break;
117
+ case "shake":
118
+ components = processShakeMotion(motion, relativeTimeExpr);
119
+ break;
120
+ case "slide":
121
+ components = processSlideMotion(motion, relativeTimeExpr);
122
+ break;
123
+ default:
124
+ motion;
125
+ throw new Error(
126
+ `Unsupported motion type: ${motion.type}`
127
+ );
128
+ }
129
+ const motionEndTime = start + components.duration;
130
+ const xArg = `if(lt(t,${start}),${components.initialX},if(lt(t,${motionEndTime}),${components.activeX},${components.finalX}))`;
131
+ const yArg = `if(lt(t,${start}),${components.initialY},if(lt(t,${motionEndTime}),${components.activeY},${components.finalY}))`;
132
+ return `x='${xArg}':y='${yArg}'`;
133
+ }
134
+
135
+ // src/effect.ts
136
+ function processFadeIn(effect, _frameRate, _frameWidth, _frameHeight) {
137
+ return `fade=t=in:st=${effect.start}:d=${effect.duration}:alpha=1`;
138
+ }
139
+ function processFadeOut(effect, _frameRate, _frameWidth, _frameHeight) {
140
+ return `fade=t=out:st=${effect.start}:d=${effect.duration}:alpha=1`;
141
+ }
142
+ function processSaturateIn(effect, _frameRate, _frameWidth, _frameHeight) {
143
+ return `hue='s=max(0,min(1,(t-${effect.start})/${effect.duration}))'`;
144
+ }
145
+ function processSaturateOut(effect, _frameRate, _frameWidth, _frameHeight) {
146
+ return `hue='s=max(0,min(1,(${effect.start + effect.duration}-t)/${effect.duration}))'`;
147
+ }
148
+ function processScroll(effect, frameRate, _frameWidth, _frameHeight) {
149
+ const distance = effect.distance ?? 1;
150
+ const scroll = distance / (1 + distance);
151
+ const speed = scroll / (effect.duration * frameRate);
152
+ switch (effect.direction) {
153
+ case "left":
154
+ return `scroll=h=${speed}`;
155
+ case "right":
156
+ return `scroll=hpos=${1 - scroll}:h=-${speed}`;
157
+ case "up":
158
+ return `scroll=v=${speed}`;
159
+ case "down":
160
+ return `scroll=vpos=${1 - scroll}:v=-${speed}`;
161
+ }
162
+ }
163
+ function processEffect(effect, frameRate, frameWidth, frameHeight) {
164
+ switch (effect.type) {
165
+ case "fade-in":
166
+ return processFadeIn(effect, frameRate, frameWidth, frameHeight);
167
+ case "fade-out":
168
+ return processFadeOut(effect, frameRate, frameWidth, frameHeight);
169
+ case "saturate-in":
170
+ return processSaturateIn(effect, frameRate, frameWidth, frameHeight);
171
+ case "saturate-out":
172
+ return processSaturateOut(effect, frameRate, frameWidth, frameHeight);
173
+ case "scroll":
174
+ return processScroll(effect, frameRate, frameWidth, frameHeight);
175
+ default:
176
+ effect;
177
+ throw new Error(
178
+ `Unsupported effect type: ${effect.type}`
179
+ );
180
+ }
181
+ }
182
+ function processEffects(effects, frameRate, frameWidth, frameHeight) {
183
+ if (!effects || effects.length === 0) return "";
184
+ const filters = [];
185
+ for (const effect of effects) {
186
+ const filter = processEffect(effect, frameRate, frameWidth, frameHeight);
187
+ filters.push(filter);
188
+ }
189
+ return filters.join(",");
190
+ }
191
+
192
+ // src/ffmpeg.ts
193
+ import { spawn } from "child_process";
194
+ import { pipeline } from "stream";
195
+ import fs from "fs/promises";
196
+ import os from "os";
197
+ import path from "path";
198
+ import pathToFFmpeg from "ffmpeg-static";
199
+ import tar from "tar-stream";
200
+ import { createWriteStream } from "fs";
201
+ import { promisify } from "util";
202
+ var pump = promisify(pipeline);
203
+ var FFmpegCommand = class {
204
+ globalArgs;
205
+ inputs;
206
+ filterComplex;
207
+ outputArgs;
208
+ constructor(globalArgs, inputs, filterComplex, outputArgs) {
209
+ this.globalArgs = globalArgs;
210
+ this.inputs = inputs;
211
+ this.filterComplex = filterComplex;
212
+ this.outputArgs = outputArgs;
213
+ }
214
+ buildArgs(inputResolver) {
215
+ const inputArgs = [];
216
+ for (const input of this.inputs) {
217
+ if (input.type === "color") {
218
+ inputArgs.push(...input.preArgs);
219
+ } else if (input.type === "animation") {
220
+ inputArgs.push(
221
+ ...input.preArgs,
222
+ "-i",
223
+ path.join(inputResolver(input), "frame_%05d")
224
+ );
225
+ } else {
226
+ inputArgs.push(...input.preArgs, "-i", inputResolver(input));
227
+ }
228
+ }
229
+ const args = [
230
+ ...this.globalArgs,
231
+ ...inputArgs,
232
+ "-filter_complex",
233
+ this.filterComplex,
234
+ ...this.outputArgs
235
+ ];
236
+ return args;
237
+ }
238
+ };
239
+ var FFmpegRunner = class {
240
+ command;
241
+ ffmpegProc;
242
+ constructor(command) {
243
+ this.command = command;
244
+ }
245
+ async run(sourceResolver, imageTransformer) {
246
+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "ffs-"));
247
+ const fileMapping = /* @__PURE__ */ new Map();
248
+ const sourceCache = /* @__PURE__ */ new Map();
249
+ const fetchAndSaveSource = async (input, inputName) => {
250
+ const stream = await sourceResolver({
251
+ type: input.type,
252
+ src: input.source
253
+ });
254
+ if (input.type === "animation") {
255
+ const extractionDir = path.join(tempDir, inputName);
256
+ await fs.mkdir(extractionDir, { recursive: true });
257
+ const extract = tar.extract();
258
+ const extractPromise = new Promise((resolve, reject) => {
259
+ extract.on("entry", async (header, stream2, next) => {
260
+ if (header.name.startsWith("frame_")) {
261
+ const transformedStream = imageTransformer ? await imageTransformer(stream2) : stream2;
262
+ const outputPath = path.join(extractionDir, header.name);
263
+ const writeStream = createWriteStream(outputPath);
264
+ transformedStream.pipe(writeStream);
265
+ writeStream.on("finish", next);
266
+ writeStream.on("error", reject);
267
+ }
268
+ });
269
+ extract.on("finish", resolve);
270
+ extract.on("error", reject);
271
+ });
272
+ stream.pipe(extract);
273
+ await extractPromise;
274
+ return extractionDir;
275
+ } else if (input.type === "image" && imageTransformer) {
276
+ const tempFile = path.join(tempDir, inputName);
277
+ const transformedStream = await imageTransformer(stream);
278
+ const writeStream = createWriteStream(tempFile);
279
+ transformedStream.on("error", (e) => writeStream.destroy(e));
280
+ await pump(transformedStream, writeStream);
281
+ return tempFile;
282
+ } else {
283
+ const tempFile = path.join(tempDir, inputName);
284
+ const writeStream = createWriteStream(tempFile);
285
+ stream.on("error", (e) => writeStream.destroy(e));
286
+ await pump(stream, writeStream);
287
+ return tempFile;
288
+ }
289
+ };
290
+ await Promise.all(
291
+ this.command.inputs.map(async (input) => {
292
+ if (input.type === "color") return;
293
+ const inputName = `ffmpeg_input_${input.index.toString().padStart(3, "0")}`;
294
+ const shouldCache = input.source.startsWith("#");
295
+ if (shouldCache) {
296
+ let fetchPromise = sourceCache.get(input.source);
297
+ if (!fetchPromise) {
298
+ fetchPromise = fetchAndSaveSource(input, inputName);
299
+ sourceCache.set(input.source, fetchPromise);
300
+ }
301
+ const filePath = await fetchPromise;
302
+ fileMapping.set(input.index, filePath);
303
+ } else {
304
+ const filePath = await fetchAndSaveSource(input, inputName);
305
+ fileMapping.set(input.index, filePath);
306
+ }
307
+ })
308
+ );
309
+ const finalArgs = this.command.buildArgs((input) => {
310
+ const filePath = fileMapping.get(input.index);
311
+ if (!filePath)
312
+ throw new Error(`File for input index ${input.index} not found`);
313
+ return filePath;
314
+ });
315
+ const ffmpegProc = spawn(process.env.FFMPEG ?? pathToFFmpeg, finalArgs);
316
+ ffmpegProc.stderr.on("data", (data) => {
317
+ console.error(data.toString());
318
+ });
319
+ ffmpegProc.on("close", async () => {
320
+ try {
321
+ await fs.rm(tempDir, { recursive: true, force: true });
322
+ } catch (err) {
323
+ console.error("Error removing temp directory:", err);
324
+ }
325
+ });
326
+ this.ffmpegProc = ffmpegProc;
327
+ return ffmpegProc.stdout;
328
+ }
329
+ close() {
330
+ if (this.ffmpegProc) {
331
+ this.ffmpegProc.kill("SIGTERM");
332
+ this.ffmpegProc = void 0;
333
+ }
334
+ }
335
+ };
336
+
337
+ // src/transition.ts
338
+ function processTransition(transition) {
339
+ switch (transition.type) {
340
+ case "fade": {
341
+ if ("through" in transition) {
342
+ return `fade${transition.through}`;
343
+ }
344
+ const easing = transition.easing ?? "linear";
345
+ return {
346
+ linear: "fade",
347
+ "ease-in": "fadeslow",
348
+ "ease-out": "fadefast"
349
+ }[easing];
350
+ }
351
+ case "barn": {
352
+ const orientation = transition.orientation ?? "horizontal";
353
+ const mode = transition.mode ?? "open";
354
+ const prefix = orientation === "vertical" ? "vert" : "horz";
355
+ return `${prefix}${mode}`;
356
+ }
357
+ case "circle": {
358
+ const mode = transition.mode ?? "open";
359
+ return `circle${mode}`;
360
+ }
361
+ case "wipe":
362
+ case "slide":
363
+ case "smooth": {
364
+ const direction = transition.direction ?? "left";
365
+ return `${transition.type}${direction}`;
366
+ }
367
+ case "slice": {
368
+ const direction = transition.direction ?? "left";
369
+ const prefix = {
370
+ left: "hl",
371
+ right: "hr",
372
+ up: "vu",
373
+ down: "vd"
374
+ }[direction];
375
+ return `${prefix}${transition.type}`;
376
+ }
377
+ case "zoom": {
378
+ return "zoomin";
379
+ }
380
+ case "dissolve":
381
+ case "pixelize":
382
+ case "radial":
383
+ return transition.type;
384
+ default:
385
+ transition;
386
+ throw new Error(
387
+ `Unsupported transition type: ${transition.type}`
388
+ );
389
+ }
390
+ }
391
+
392
+ // src/render.ts
393
+ import { Readable } from "stream";
394
+ import { createReadStream as createReadStream2 } from "fs";
395
+ import sharp from "sharp";
396
+
397
+ // src/fetch.ts
398
+ import { fetch, Agent } from "undici";
399
+ async function ffsFetch(url, options) {
400
+ const {
401
+ method,
402
+ body,
403
+ headers,
404
+ headersTimeout = 3e5,
405
+ // 5 minutes
406
+ bodyTimeout = 3e5
407
+ // 5 minutes
408
+ } = options ?? {};
409
+ const agent = new Agent({ headersTimeout, bodyTimeout });
410
+ return fetch(url, {
411
+ method,
412
+ body,
413
+ headers: { "User-Agent": "FFS (+https://effing.dev/ffs)", ...headers },
414
+ dispatcher: agent
415
+ });
416
+ }
417
+
418
+ // src/render.ts
419
+ import { fileURLToPath } from "url";
420
+
421
+ // src/cache.ts
422
+ import {
423
+ S3Client,
424
+ PutObjectCommand,
425
+ GetObjectCommand,
426
+ HeadObjectCommand,
427
+ DeleteObjectCommand
428
+ } from "@aws-sdk/client-s3";
429
+ import { Upload } from "@aws-sdk/lib-storage";
430
+ import fs2 from "fs/promises";
431
+ import { createReadStream, createWriteStream as createWriteStream2, existsSync } from "fs";
432
+ import { pipeline as pipeline2 } from "stream/promises";
433
+ import path2 from "path";
434
+ import os2 from "os";
435
+ import crypto from "crypto";
436
+ var S3CacheStorage = class {
437
+ client;
438
+ bucket;
439
+ prefix;
440
+ ttlMs;
441
+ constructor(options) {
442
+ this.client = new S3Client({
443
+ endpoint: options.endpoint,
444
+ region: options.region ?? "auto",
445
+ credentials: options.accessKeyId ? {
446
+ accessKeyId: options.accessKeyId,
447
+ secretAccessKey: options.secretAccessKey
448
+ } : void 0,
449
+ forcePathStyle: !!options.endpoint
450
+ });
451
+ this.bucket = options.bucket;
452
+ this.prefix = options.prefix ?? "";
453
+ this.ttlMs = options.ttlMs ?? 60 * 60 * 1e3;
454
+ }
455
+ getExpires() {
456
+ return new Date(Date.now() + this.ttlMs);
457
+ }
458
+ getFullKey(key) {
459
+ return `${this.prefix}${key}`;
460
+ }
461
+ async put(key, stream) {
462
+ const upload = new Upload({
463
+ client: this.client,
464
+ params: {
465
+ Bucket: this.bucket,
466
+ Key: this.getFullKey(key),
467
+ Body: stream,
468
+ Expires: this.getExpires()
469
+ }
470
+ });
471
+ await upload.done();
472
+ }
473
+ async getStream(key) {
474
+ try {
475
+ const response = await this.client.send(
476
+ new GetObjectCommand({
477
+ Bucket: this.bucket,
478
+ Key: this.getFullKey(key)
479
+ })
480
+ );
481
+ return response.Body;
482
+ } catch (err) {
483
+ const error = err;
484
+ if (error.name === "NoSuchKey" || error.$metadata?.httpStatusCode === 404) {
485
+ return null;
486
+ }
487
+ throw err;
488
+ }
489
+ }
490
+ async exists(key) {
491
+ try {
492
+ await this.client.send(
493
+ new HeadObjectCommand({
494
+ Bucket: this.bucket,
495
+ Key: this.getFullKey(key)
496
+ })
497
+ );
498
+ return true;
499
+ } catch (err) {
500
+ const error = err;
501
+ if (error.name === "NotFound" || error.$metadata?.httpStatusCode === 404) {
502
+ return false;
503
+ }
504
+ throw err;
505
+ }
506
+ }
507
+ async existsMany(keys) {
508
+ const results = await Promise.all(
509
+ keys.map(async (key) => [key, await this.exists(key)])
510
+ );
511
+ return new Map(results);
512
+ }
513
+ async delete(key) {
514
+ try {
515
+ await this.client.send(
516
+ new DeleteObjectCommand({
517
+ Bucket: this.bucket,
518
+ Key: this.getFullKey(key)
519
+ })
520
+ );
521
+ } catch (err) {
522
+ const error = err;
523
+ if (error.name === "NoSuchKey" || error.$metadata?.httpStatusCode === 404) {
524
+ return;
525
+ }
526
+ throw err;
527
+ }
528
+ }
529
+ async putJson(key, data) {
530
+ await this.client.send(
531
+ new PutObjectCommand({
532
+ Bucket: this.bucket,
533
+ Key: this.getFullKey(key),
534
+ Body: JSON.stringify(data),
535
+ ContentType: "application/json",
536
+ Expires: this.getExpires()
537
+ })
538
+ );
539
+ }
540
+ async getJson(key) {
541
+ try {
542
+ const response = await this.client.send(
543
+ new GetObjectCommand({
544
+ Bucket: this.bucket,
545
+ Key: this.getFullKey(key)
546
+ })
547
+ );
548
+ const body = await response.Body?.transformToString();
549
+ if (!body) return null;
550
+ return JSON.parse(body);
551
+ } catch (err) {
552
+ const error = err;
553
+ if (error.name === "NoSuchKey" || error.$metadata?.httpStatusCode === 404) {
554
+ return null;
555
+ }
556
+ throw err;
557
+ }
558
+ }
559
+ close() {
560
+ }
561
+ };
562
+ var LocalCacheStorage = class {
563
+ baseDir;
564
+ initialized = false;
565
+ cleanupInterval;
566
+ ttlMs;
567
+ constructor(baseDir, ttlMs = 60 * 60 * 1e3) {
568
+ this.baseDir = baseDir ?? path2.join(os2.tmpdir(), "ffs-cache");
569
+ this.ttlMs = ttlMs;
570
+ this.cleanupInterval = setInterval(() => {
571
+ this.cleanupExpired().catch(console.error);
572
+ }, 3e5);
573
+ }
574
+ /**
575
+ * Remove files older than TTL
576
+ */
577
+ async cleanupExpired() {
578
+ if (!this.initialized) return;
579
+ const now = Date.now();
580
+ await this.cleanupDir(this.baseDir, now);
581
+ }
582
+ async cleanupDir(dir, now) {
583
+ let entries;
584
+ try {
585
+ entries = await fs2.readdir(dir, { withFileTypes: true });
586
+ } catch {
587
+ return;
588
+ }
589
+ for (const entry of entries) {
590
+ const fullPath = path2.join(dir, entry.name);
591
+ if (entry.isDirectory()) {
592
+ await this.cleanupDir(fullPath, now);
593
+ try {
594
+ await fs2.rmdir(fullPath);
595
+ } catch {
596
+ }
597
+ } else if (entry.isFile()) {
598
+ try {
599
+ const stat = await fs2.stat(fullPath);
600
+ if (now - stat.mtimeMs > this.ttlMs) {
601
+ await fs2.rm(fullPath, { force: true });
602
+ }
603
+ } catch {
604
+ }
605
+ }
606
+ }
607
+ }
608
+ async ensureDir(filePath) {
609
+ await fs2.mkdir(path2.dirname(filePath), { recursive: true });
610
+ this.initialized = true;
611
+ }
612
+ filePath(key) {
613
+ return path2.join(this.baseDir, key);
614
+ }
615
+ tmpPathFor(finalPath) {
616
+ const rand = crypto.randomBytes(8).toString("hex");
617
+ return `${finalPath}.tmp-${process.pid}-${rand}`;
618
+ }
619
+ async put(key, stream) {
620
+ const fp = this.filePath(key);
621
+ await this.ensureDir(fp);
622
+ const tmpPath = this.tmpPathFor(fp);
623
+ try {
624
+ const writeStream = createWriteStream2(tmpPath);
625
+ await pipeline2(stream, writeStream);
626
+ await fs2.rename(tmpPath, fp);
627
+ } catch (err) {
628
+ await fs2.rm(tmpPath, { force: true }).catch(() => {
629
+ });
630
+ throw err;
631
+ }
632
+ }
633
+ async getStream(key) {
634
+ const fp = this.filePath(key);
635
+ if (!existsSync(fp)) return null;
636
+ return createReadStream(fp);
637
+ }
638
+ async exists(key) {
639
+ try {
640
+ await fs2.access(this.filePath(key));
641
+ return true;
642
+ } catch {
643
+ return false;
644
+ }
645
+ }
646
+ async existsMany(keys) {
647
+ const results = await Promise.all(
648
+ keys.map(async (key) => [key, await this.exists(key)])
649
+ );
650
+ return new Map(results);
651
+ }
652
+ async delete(key) {
653
+ await fs2.rm(this.filePath(key), { force: true });
654
+ }
655
+ async putJson(key, data) {
656
+ const fp = this.filePath(key);
657
+ await this.ensureDir(fp);
658
+ const tmpPath = this.tmpPathFor(fp);
659
+ try {
660
+ await fs2.writeFile(tmpPath, JSON.stringify(data));
661
+ await fs2.rename(tmpPath, fp);
662
+ } catch (err) {
663
+ await fs2.rm(tmpPath, { force: true }).catch(() => {
664
+ });
665
+ throw err;
666
+ }
667
+ }
668
+ async getJson(key) {
669
+ try {
670
+ const content = await fs2.readFile(this.filePath(key), "utf-8");
671
+ return JSON.parse(content);
672
+ } catch {
673
+ return null;
674
+ }
675
+ }
676
+ close() {
677
+ if (this.cleanupInterval) {
678
+ clearInterval(this.cleanupInterval);
679
+ this.cleanupInterval = void 0;
680
+ }
681
+ }
682
+ };
683
+ function createCacheStorage() {
684
+ const ttlMs = process.env.FFS_CACHE_TTL_MS ? parseInt(process.env.FFS_CACHE_TTL_MS, 10) : 60 * 60 * 1e3;
685
+ if (process.env.FFS_CACHE_BUCKET) {
686
+ return new S3CacheStorage({
687
+ endpoint: process.env.FFS_CACHE_ENDPOINT,
688
+ region: process.env.FFS_CACHE_REGION ?? "auto",
689
+ bucket: process.env.FFS_CACHE_BUCKET,
690
+ prefix: process.env.FFS_CACHE_PREFIX,
691
+ accessKeyId: process.env.FFS_CACHE_ACCESS_KEY,
692
+ secretAccessKey: process.env.FFS_CACHE_SECRET_KEY,
693
+ ttlMs
694
+ });
695
+ }
696
+ return new LocalCacheStorage(process.env.FFS_CACHE_LOCAL_DIR, ttlMs);
697
+ }
698
+ function hashUrl(url) {
699
+ return crypto.createHash("sha256").update(url).digest("hex").slice(0, 16);
700
+ }
701
+ function sourceCacheKey(url) {
702
+ return `sources/${hashUrl(url)}`;
703
+ }
704
+ function warmupJobCacheKey(jobId) {
705
+ return `jobs/warmup/${jobId}.json`;
706
+ }
707
+ function renderJobCacheKey(jobId) {
708
+ return `jobs/render/${jobId}.json`;
709
+ }
710
+ var cacheKeys = {
711
+ source: sourceCacheKey,
712
+ warmupJob: warmupJobCacheKey,
713
+ renderJob: renderJobCacheKey
714
+ };
715
+
716
+ // src/render.ts
717
+ var EffieRenderer = class {
718
+ effieData;
719
+ ffmpegRunner;
720
+ allowLocalFiles;
721
+ cacheStorage;
722
+ constructor(effieData, options) {
723
+ this.effieData = effieData;
724
+ this.allowLocalFiles = options?.allowLocalFiles ?? false;
725
+ this.cacheStorage = options?.cacheStorage;
726
+ }
727
+ async fetchSource(src) {
728
+ if (src.startsWith("#")) {
729
+ const sourceName = src.slice(1);
730
+ if (!(sourceName in this.effieData.sources)) {
731
+ throw new Error(`Named source "${sourceName}" not found`);
732
+ }
733
+ src = this.effieData.sources[sourceName];
734
+ }
735
+ if (src.startsWith("data:")) {
736
+ const commaIndex = src.indexOf(",");
737
+ if (commaIndex === -1) {
738
+ throw new Error("Invalid data URL");
739
+ }
740
+ const meta = src.slice(5, commaIndex);
741
+ const isBase64 = meta.endsWith(";base64");
742
+ const data = src.slice(commaIndex + 1);
743
+ const buffer = isBase64 ? Buffer.from(data, "base64") : Buffer.from(decodeURIComponent(data));
744
+ return Readable.from(buffer);
745
+ }
746
+ if (src.startsWith("file:")) {
747
+ if (!this.allowLocalFiles) {
748
+ throw new Error(
749
+ "Local file paths are not allowed. Use allowLocalFiles option for trusted operations."
750
+ );
751
+ }
752
+ return createReadStream2(fileURLToPath(src));
753
+ }
754
+ if (this.cacheStorage) {
755
+ const cachedStream = await this.cacheStorage.getStream(
756
+ cacheKeys.source(src)
757
+ );
758
+ if (cachedStream) {
759
+ return cachedStream;
760
+ }
761
+ }
762
+ const response = await ffsFetch(src, {
763
+ headersTimeout: 10 * 60 * 1e3,
764
+ // 10 minutes
765
+ bodyTimeout: 20 * 60 * 1e3
766
+ // 20 minutes
767
+ });
768
+ if (!response.ok) {
769
+ throw new Error(
770
+ `Failed to fetch ${src}: ${response.status} ${response.statusText}`
771
+ );
772
+ }
773
+ if (!response.body) {
774
+ throw new Error(`No body for ${src}`);
775
+ }
776
+ return Readable.fromWeb(response.body);
777
+ }
778
+ buildAudioFilter({
779
+ duration,
780
+ volume,
781
+ fadeIn,
782
+ fadeOut
783
+ }) {
784
+ const filters = [];
785
+ if (volume !== void 0) {
786
+ filters.push(`volume=${volume}`);
787
+ }
788
+ if (fadeIn !== void 0) {
789
+ filters.push(`afade=type=in:start_time=0:duration=${fadeIn}`);
790
+ }
791
+ if (fadeOut !== void 0) {
792
+ filters.push(
793
+ `afade=type=out:start_time=${duration - fadeOut}:duration=${fadeOut}`
794
+ );
795
+ }
796
+ return filters.length ? filters.join(",") : "anull";
797
+ }
798
+ getFrameDimensions(scaleFactor) {
799
+ return {
800
+ frameWidth: Math.floor(this.effieData.width * scaleFactor / 2) * 2,
801
+ frameHeight: Math.floor(this.effieData.height * scaleFactor / 2) * 2
802
+ };
803
+ }
804
+ /**
805
+ * Builds an FFmpeg input for a background (global or segment).
806
+ */
807
+ buildBackgroundInput(background, inputIndex, frameWidth, frameHeight) {
808
+ if (background.type === "image") {
809
+ return {
810
+ index: inputIndex,
811
+ source: background.source,
812
+ preArgs: ["-loop", "1", "-framerate", this.effieData.fps.toString()],
813
+ type: "image"
814
+ };
815
+ } else if (background.type === "video") {
816
+ return {
817
+ index: inputIndex,
818
+ source: background.source,
819
+ preArgs: ["-stream_loop", "-1"],
820
+ type: "video"
821
+ };
822
+ }
823
+ return {
824
+ index: inputIndex,
825
+ source: "",
826
+ preArgs: [
827
+ "-f",
828
+ "lavfi",
829
+ "-i",
830
+ `color=${background.color}:size=${frameWidth}x${frameHeight}:rate=${this.effieData.fps}`
831
+ ],
832
+ type: "color"
833
+ };
834
+ }
835
+ buildOutputArgs(outputFilename) {
836
+ return [
837
+ "-map",
838
+ "[outv]",
839
+ "-map",
840
+ "[outa]",
841
+ "-c:v",
842
+ "libx264",
843
+ "-r",
844
+ this.effieData.fps.toString(),
845
+ "-pix_fmt",
846
+ "yuv420p",
847
+ "-preset",
848
+ "fast",
849
+ "-crf",
850
+ "28",
851
+ "-c:a",
852
+ "aac",
853
+ "-movflags",
854
+ "frag_keyframe+empty_moov",
855
+ "-f",
856
+ "mp4",
857
+ outputFilename
858
+ ];
859
+ }
860
+ buildLayerInput(layer, duration, inputIndex) {
861
+ let preArgs = [];
862
+ if (layer.type === "image") {
863
+ preArgs = [
864
+ "-loop",
865
+ "1",
866
+ "-t",
867
+ duration.toString(),
868
+ "-framerate",
869
+ this.effieData.fps.toString()
870
+ ];
871
+ } else if (layer.type === "animation") {
872
+ preArgs = ["-f", "image2", "-framerate", this.effieData.fps.toString()];
873
+ }
874
+ return {
875
+ index: inputIndex,
876
+ source: layer.source,
877
+ preArgs,
878
+ type: layer.type
879
+ };
880
+ }
881
+ /**
882
+ * Builds filter chain for all layers in a segment.
883
+ * @param segment - The segment containing layers
884
+ * @param bgLabel - Label for the background input (e.g., "bg_seg0" or "bg_seg")
885
+ * @param labelPrefix - Prefix for generated labels (e.g., "seg0_" or "")
886
+ * @param layerInputOffset - Starting input index for layers
887
+ * @param frameWidth - Frame width for nullsrc
888
+ * @param frameHeight - Frame height for nullsrc
889
+ * @param outputLabel - Label for the final video output
890
+ * @returns Array of filter parts to add to the filter chain
891
+ */
892
+ buildLayerFilters(segment, bgLabel, labelPrefix, layerInputOffset, frameWidth, frameHeight, outputLabel) {
893
+ const filterParts = [];
894
+ let currentVidLabel = bgLabel;
895
+ for (let l = 0; l < segment.layers.length; l++) {
896
+ const inputIdx = layerInputOffset + l;
897
+ const layerLabel = `${labelPrefix}layer${l}`;
898
+ const layer = segment.layers[l];
899
+ const effectChain = layer.effects ? processEffects(
900
+ layer.effects,
901
+ this.effieData.fps,
902
+ frameWidth,
903
+ frameHeight
904
+ ) : "";
905
+ filterParts.push(
906
+ `[${inputIdx}:v]trim=start=0:duration=${segment.duration},${effectChain ? effectChain + "," : ""}setsar=1,setpts=PTS-STARTPTS[${layerLabel}]`
907
+ );
908
+ let overlayInputLabel = layerLabel;
909
+ const delay = layer.delay ?? 0;
910
+ if (delay > 0) {
911
+ filterParts.push(
912
+ `nullsrc=size=${frameWidth}x${frameHeight}:duration=${delay},setpts=PTS-STARTPTS[null_${layerLabel}]`
913
+ );
914
+ filterParts.push(
915
+ `[null_${layerLabel}][${layerLabel}]concat=n=2:v=1:a=0[delayed_${layerLabel}]`
916
+ );
917
+ overlayInputLabel = `delayed_${layerLabel}`;
918
+ }
919
+ const overlayOutputLabel = `${labelPrefix}tmp${l}`;
920
+ const offset = layer.motion ? processMotion(delay, layer.motion) : "0:0";
921
+ const fromTime = layer.from ?? 0;
922
+ const untilTime = layer.until ?? segment.duration;
923
+ filterParts.push(
924
+ `[${currentVidLabel}][${overlayInputLabel}]overlay=${offset}:enable='between(t,${fromTime},${untilTime})',fps=${this.effieData.fps}[${overlayOutputLabel}]`
925
+ );
926
+ currentVidLabel = overlayOutputLabel;
927
+ }
928
+ filterParts.push(`[${currentVidLabel}]null[${outputLabel}]`);
929
+ return filterParts;
930
+ }
931
+ /**
932
+ * Applies xfade/concat transitions between video segments.
933
+ * Modifies videoSegmentLabels in place to update labels after transitions.
934
+ * @param filterParts - Array to append filter parts to
935
+ * @param videoSegmentLabels - Array of video segment labels (modified in place)
936
+ */
937
+ applyTransitions(filterParts, videoSegmentLabels) {
938
+ let transitionOffset = 0;
939
+ this.effieData.segments.forEach((segment, i) => {
940
+ if (i === 0) {
941
+ transitionOffset = segment.duration;
942
+ return;
943
+ }
944
+ const combineLabel = `[vid_com${i}]`;
945
+ if (!segment.transition) {
946
+ transitionOffset += segment.duration;
947
+ filterParts.push(
948
+ `${videoSegmentLabels[i - 1]}${videoSegmentLabels[i]}concat=n=2:v=1:a=0,fps=${this.effieData.fps}${combineLabel}`
949
+ );
950
+ videoSegmentLabels[i] = combineLabel;
951
+ return;
952
+ }
953
+ const transitionName = processTransition(segment.transition);
954
+ const transitionDuration = segment.transition.duration;
955
+ transitionOffset -= transitionDuration;
956
+ filterParts.push(
957
+ `${videoSegmentLabels[i - 1]}${videoSegmentLabels[i]}xfade=transition=${transitionName}:duration=${transitionDuration}:offset=${transitionOffset}${combineLabel}`
958
+ );
959
+ videoSegmentLabels[i] = combineLabel;
960
+ transitionOffset += segment.duration;
961
+ });
962
+ filterParts.push(`${videoSegmentLabels.at(-1)}null[outv]`);
963
+ }
964
+ /**
965
+ * Applies general audio mixing: concats segment audio and mixes with global audio if present.
966
+ * @param filterParts - Array to append filter parts to
967
+ * @param audioSegmentLabels - Array of audio segment labels to concat
968
+ * @param totalDuration - Total duration for audio trimming
969
+ * @param generalAudioInputIndex - Input index for general audio (if present)
970
+ */
971
+ applyGeneralAudio(filterParts, audioSegmentLabels, totalDuration, generalAudioInputIndex) {
972
+ if (this.effieData.audio) {
973
+ const audioSeek = this.effieData.audio.seek ?? 0;
974
+ const generalAudioFilter = this.buildAudioFilter({
975
+ duration: totalDuration,
976
+ volume: this.effieData.audio.volume,
977
+ fadeIn: this.effieData.audio.fadeIn,
978
+ fadeOut: this.effieData.audio.fadeOut
979
+ });
980
+ filterParts.push(
981
+ `[${generalAudioInputIndex}:a]atrim=start=${audioSeek}:duration=${totalDuration},${generalAudioFilter},asetpts=PTS-STARTPTS[general_audio]`
982
+ );
983
+ filterParts.push(
984
+ `${audioSegmentLabels.join("")}concat=n=${this.effieData.segments.length}:v=0:a=1,atrim=start=0:duration=${totalDuration}[segments_audio]`
985
+ );
986
+ filterParts.push(
987
+ `[general_audio][segments_audio]amix=inputs=2:duration=longest[outa]`
988
+ );
989
+ } else {
990
+ filterParts.push(
991
+ `${audioSegmentLabels.join("")}concat=n=${this.effieData.segments.length}:v=0:a=1[outa]`
992
+ );
993
+ }
994
+ }
995
+ buildFFmpegCommand(outputFilename, scaleFactor = 1) {
996
+ const globalArgs = ["-y", "-loglevel", "error"];
997
+ const inputs = [];
998
+ let inputIndex = 0;
999
+ const { frameWidth, frameHeight } = this.getFrameDimensions(scaleFactor);
1000
+ const backgroundSeek = this.effieData.background.type === "video" ? this.effieData.background.seek ?? 0 : 0;
1001
+ inputs.push(
1002
+ this.buildBackgroundInput(
1003
+ this.effieData.background,
1004
+ inputIndex,
1005
+ frameWidth,
1006
+ frameHeight
1007
+ )
1008
+ );
1009
+ const globalBgInputIdx = inputIndex;
1010
+ inputIndex++;
1011
+ const segmentBgInputIndices = [];
1012
+ for (const segment of this.effieData.segments) {
1013
+ if (segment.background) {
1014
+ inputs.push(
1015
+ this.buildBackgroundInput(
1016
+ segment.background,
1017
+ inputIndex,
1018
+ frameWidth,
1019
+ frameHeight
1020
+ )
1021
+ );
1022
+ segmentBgInputIndices.push(inputIndex);
1023
+ inputIndex++;
1024
+ } else {
1025
+ segmentBgInputIndices.push(null);
1026
+ }
1027
+ }
1028
+ for (const segment of this.effieData.segments) {
1029
+ for (const layer of segment.layers) {
1030
+ inputs.push(this.buildLayerInput(layer, segment.duration, inputIndex));
1031
+ inputIndex++;
1032
+ }
1033
+ }
1034
+ for (const segment of this.effieData.segments) {
1035
+ if (segment.audio) {
1036
+ inputs.push({
1037
+ index: inputIndex,
1038
+ source: segment.audio.source,
1039
+ preArgs: [],
1040
+ type: "audio"
1041
+ });
1042
+ inputIndex++;
1043
+ }
1044
+ }
1045
+ if (this.effieData.audio) {
1046
+ inputs.push({
1047
+ index: inputIndex,
1048
+ source: this.effieData.audio.source,
1049
+ preArgs: [],
1050
+ type: "audio"
1051
+ });
1052
+ inputIndex++;
1053
+ }
1054
+ const numSegmentBgInputs = segmentBgInputIndices.filter(
1055
+ (i) => i !== null
1056
+ ).length;
1057
+ const numVideoInputs = 1 + numSegmentBgInputs + this.effieData.segments.reduce((sum, seg) => sum + seg.layers.length, 0);
1058
+ let audioCounter = 0;
1059
+ let currentTime = 0;
1060
+ let layerInputOffset = 1 + numSegmentBgInputs;
1061
+ const filterParts = [];
1062
+ const videoSegmentLabels = [];
1063
+ const audioSegmentLabels = [];
1064
+ for (let segIdx = 0; segIdx < this.effieData.segments.length; segIdx++) {
1065
+ const segment = this.effieData.segments[segIdx];
1066
+ const bgLabel = `bg_seg${segIdx}`;
1067
+ if (segment.background) {
1068
+ const segBgInputIdx = segmentBgInputIndices[segIdx];
1069
+ const segBgSeek = segment.background.type === "video" ? segment.background.seek ?? 0 : 0;
1070
+ filterParts.push(
1071
+ `[${segBgInputIdx}:v]fps=${this.effieData.fps},scale=${frameWidth}x${frameHeight},trim=start=${segBgSeek}:duration=${segment.duration},setpts=PTS-STARTPTS[${bgLabel}]`
1072
+ );
1073
+ } else {
1074
+ filterParts.push(
1075
+ `[${globalBgInputIdx}:v]fps=${this.effieData.fps},scale=${frameWidth}x${frameHeight},trim=start=${backgroundSeek + currentTime}:duration=${segment.duration},setpts=PTS-STARTPTS[${bgLabel}]`
1076
+ );
1077
+ }
1078
+ const vidLabel = `vid_seg${segIdx}`;
1079
+ filterParts.push(
1080
+ ...this.buildLayerFilters(
1081
+ segment,
1082
+ bgLabel,
1083
+ `seg${segIdx}_`,
1084
+ layerInputOffset,
1085
+ frameWidth,
1086
+ frameHeight,
1087
+ vidLabel
1088
+ )
1089
+ );
1090
+ layerInputOffset += segment.layers.length;
1091
+ videoSegmentLabels.push(`[${vidLabel}]`);
1092
+ const nextSegment = this.effieData.segments[segIdx + 1];
1093
+ const transitionDuration = nextSegment?.transition?.duration ?? 0;
1094
+ const realDuration = Math.max(
1095
+ 1e-3,
1096
+ segment.duration - transitionDuration
1097
+ );
1098
+ if (segment.audio) {
1099
+ const audioInputIndex = numVideoInputs + audioCounter;
1100
+ const audioFilter = this.buildAudioFilter({
1101
+ duration: realDuration,
1102
+ volume: segment.audio.volume,
1103
+ fadeIn: segment.audio.fadeIn,
1104
+ fadeOut: segment.audio.fadeOut
1105
+ });
1106
+ filterParts.push(
1107
+ `[${audioInputIndex}:a]atrim=start=0:duration=${realDuration},${audioFilter},asetpts=PTS-STARTPTS[aud_seg${segIdx}]`
1108
+ );
1109
+ audioCounter++;
1110
+ } else {
1111
+ filterParts.push(
1112
+ `anullsrc=r=44100:cl=stereo,atrim=start=0:duration=${realDuration},asetpts=PTS-STARTPTS[aud_seg${segIdx}]`
1113
+ );
1114
+ }
1115
+ audioSegmentLabels.push(`[aud_seg${segIdx}]`);
1116
+ currentTime += realDuration;
1117
+ }
1118
+ this.applyGeneralAudio(
1119
+ filterParts,
1120
+ audioSegmentLabels,
1121
+ currentTime,
1122
+ numVideoInputs + audioCounter
1123
+ );
1124
+ this.applyTransitions(filterParts, videoSegmentLabels);
1125
+ const filterComplex = filterParts.join(";");
1126
+ const outputArgs = this.buildOutputArgs(outputFilename);
1127
+ return new FFmpegCommand(globalArgs, inputs, filterComplex, outputArgs);
1128
+ }
1129
+ createImageTransformer(scaleFactor) {
1130
+ return async (imageStream) => {
1131
+ if (scaleFactor === 1) return imageStream;
1132
+ const sharpTransformer = sharp();
1133
+ imageStream.on("error", (err) => {
1134
+ if (!sharpTransformer.destroyed) {
1135
+ sharpTransformer.destroy(err);
1136
+ }
1137
+ });
1138
+ sharpTransformer.on("error", (err) => {
1139
+ if (!imageStream.destroyed) {
1140
+ imageStream.destroy(err);
1141
+ }
1142
+ });
1143
+ imageStream.pipe(sharpTransformer);
1144
+ try {
1145
+ const metadata = await sharpTransformer.metadata();
1146
+ const imageWidth = metadata.width ?? this.effieData.width;
1147
+ const imageHeight = metadata.height ?? this.effieData.height;
1148
+ return sharpTransformer.resize({
1149
+ width: Math.floor(imageWidth * scaleFactor),
1150
+ height: Math.floor(imageHeight * scaleFactor)
1151
+ });
1152
+ } catch (error) {
1153
+ if (!sharpTransformer.destroyed) {
1154
+ sharpTransformer.destroy(error);
1155
+ }
1156
+ throw error;
1157
+ }
1158
+ };
1159
+ }
1160
+ /**
1161
+ * Renders the effie data to a video stream.
1162
+ * @param scaleFactor - Scale factor for output dimensions
1163
+ */
1164
+ async render(scaleFactor = 1) {
1165
+ const ffmpegCommand = this.buildFFmpegCommand("-", scaleFactor);
1166
+ this.ffmpegRunner = new FFmpegRunner(ffmpegCommand);
1167
+ return this.ffmpegRunner.run(
1168
+ async ({ src }) => this.fetchSource(src),
1169
+ this.createImageTransformer(scaleFactor)
1170
+ );
1171
+ }
1172
+ close() {
1173
+ if (this.ffmpegRunner) {
1174
+ this.ffmpegRunner.close();
1175
+ }
1176
+ }
1177
+ };
1178
+
1179
+ export {
1180
+ processMotion,
1181
+ processEffects,
1182
+ FFmpegCommand,
1183
+ FFmpegRunner,
1184
+ processTransition,
1185
+ ffsFetch,
1186
+ createCacheStorage,
1187
+ cacheKeys,
1188
+ EffieRenderer
1189
+ };
1190
+ //# sourceMappingURL=chunk-RNE6TKMF.js.map