@vivix-labs/media-tools 1.0.0-beta.2 → 1.0.0-beta.21

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 (60) hide show
  1. package/README.md +38 -12
  2. package/dist/assets/1-1-WUUPNDJP.svg +7 -0
  3. package/dist/assets/16-9-BAFQTZK7.svg +9 -0
  4. package/dist/assets/2-3-WPG3UQBV.svg +7 -0
  5. package/dist/assets/3-2-YZTSUZ37.svg +7 -0
  6. package/dist/assets/3-4-7YROL4JU.svg +7 -0
  7. package/dist/assets/4-3-YG4LTLGD.svg +7 -0
  8. package/dist/assets/9-16-CYXX6QAR.svg +9 -0
  9. package/dist/assets/add-circle-RPMXNTWW.svg +4 -0
  10. package/dist/assets/captions-16-55I6JRWY.svg +5 -0
  11. package/dist/assets/captions-24-4YNDEZZX.svg +5 -0
  12. package/dist/assets/chevrons-up-down-KDZMS6DI.svg +3 -0
  13. package/dist/assets/collapse-diagonal-16-2IRQGCLB.svg +6 -0
  14. package/dist/assets/collapse-diagonal-24-GHD6Z54K.svg +6 -0
  15. package/dist/assets/copy-document-EF4PHM7F.svg +10 -0
  16. package/dist/assets/crop-5JXWHIPN.svg +6 -0
  17. package/dist/assets/delete-4Y3OUMEL.svg +8 -0
  18. package/dist/assets/download-16-QVS2YNPN.svg +4 -0
  19. package/dist/assets/download-24-ARCWU2MF.svg +4 -0
  20. package/dist/assets/download-VTKCEAZG.svg +6 -0
  21. package/dist/assets/expand-diagonal-16-QUIZSPJN.svg +10 -0
  22. package/dist/assets/expand-diagonal-24-XPK72ILY.svg +10 -0
  23. package/dist/assets/favorite-6GMNHJCN.svg +5 -0
  24. package/dist/assets/favorite-filled-FR74TEBM.svg +3 -0
  25. package/dist/assets/filter-JSDZZVGN.svg +5 -0
  26. package/dist/assets/freeform-E5MLUKDE.svg +18 -0
  27. package/dist/assets/fullscreen-exit-ADYOPBYH.svg +3 -0
  28. package/dist/assets/grid-16-POIO22HZ.svg +6 -0
  29. package/dist/assets/grid-24-U6IRT56K.svg +6 -0
  30. package/dist/assets/inria-serif-latin-400-italic-ZCFRMMVP.woff2 +0 -0
  31. package/dist/assets/inria-serif-latin-700-italic-UNRIXGAH.woff2 +0 -0
  32. package/dist/assets/inter-latin-900-normal-FKACR3DR.woff2 +0 -0
  33. package/dist/assets/list-16-YAVTLHXZ.svg +8 -0
  34. package/dist/assets/list-24-O6WDB6WJ.svg +8 -0
  35. package/dist/assets/original-LBKLUQVV.svg +18 -0
  36. package/dist/assets/pause-16-444PD7SY.svg +4 -0
  37. package/dist/assets/pause-24-WQXRNLW3.svg +4 -0
  38. package/dist/assets/play-16-5B2LZITW.svg +3 -0
  39. package/dist/assets/play-24-3IPXXAC4.svg +3 -0
  40. package/dist/assets/refresh-WQ3CTB57.svg +3 -0
  41. package/dist/assets/replace-PJXDOQDX.svg +3 -0
  42. package/dist/assets/{search-JUOSGQRM.svg → search-FMYQZJWA.svg} +1 -1
  43. package/dist/assets/select-items-GJZIVO37.svg +6 -0
  44. package/dist/assets/trim-LQMHHN2M.svg +9 -0
  45. package/dist/assets/upload-U5RZT5QI.svg +5 -0
  46. package/dist/assets/volume-16-ENYWJAGG.svg +5 -0
  47. package/dist/assets/volume-24-MVQ6CAXW.svg +5 -0
  48. package/dist/assets/volume-off-16-ALKG7632.svg +4 -0
  49. package/dist/assets/volume-off-24-2R4VED3N.svg +4 -0
  50. package/dist/client.bundle.js +1517 -262
  51. package/dist/client.css +2368 -181
  52. package/dist/server.d.ts +2 -1
  53. package/dist/server.js +1463 -259
  54. package/dist/shared.d.ts +513 -3
  55. package/dist/shared.js +230 -7
  56. package/{skills/SKILL.md → docs/operations.md} +7 -7
  57. package/package.json +5 -4
  58. package/studio-plugin.json +2 -5
  59. package/dist/assets/player-cover-shade-LLH6KOCQ.png +0 -0
  60. /package/{skills/references → docs}/processing.md +0 -0
package/dist/server.js CHANGED
@@ -1,10 +1,55 @@
1
1
  // packages/media-tools/src/server.ts
2
- import { join as join4 } from "path";
2
+ import { join as join5 } from "path";
3
3
  import { defineOperation } from "vivix-studio/sdk/server";
4
- import { z as z4 } from "vivix-studio/sdk/shared";
4
+ import { z as z5 } from "vivix-studio/sdk/shared";
5
+
6
+ // packages/media-tools/src/export-settings.ts
7
+ var exportProfiles = {
8
+ h264: {
9
+ label: "MP4 \xB7 H.264",
10
+ extension: "mp4",
11
+ container: "mp4",
12
+ codec: "h264",
13
+ encoder: "libx264",
14
+ audio: "aac",
15
+ crf: [18, 23, 28]
16
+ },
17
+ hevc: {
18
+ label: "MP4 \xB7 H.265",
19
+ extension: "mp4",
20
+ container: "mp4",
21
+ codec: "hevc",
22
+ encoder: "libx265",
23
+ audio: "aac",
24
+ crf: [20, 25, 30]
25
+ },
26
+ vp9: {
27
+ label: "WebM \xB7 VP9",
28
+ extension: "webm",
29
+ container: "webm",
30
+ codec: "vp9",
31
+ encoder: "libvpx-vp9",
32
+ audio: "opus",
33
+ crf: [23, 31, 39]
34
+ }
35
+ };
36
+ var exportAspects = ["source", "16:9", "9:16", "1:1", "4:3", "3:4", "21:9"];
37
+ var exportQualities = ["high", "standard", "small"];
38
+ function exportDimensions(source, aspect, resolution) {
39
+ if (aspect === "source" && resolution === "source") return source;
40
+ const [w = source.width, h = source.height] = aspect === "source" ? [] : aspect.split(":").map(Number);
41
+ const short = resolution === "source" ? Math.min(source.width, source.height) : resolution;
42
+ const even = (n) => 2 * Math.round(n / 2);
43
+ const width = w >= h ? even(short * w / h) : short;
44
+ const height = h >= w ? even(short * h / w) : short;
45
+ return Math.min(width, height) >= 2 && Math.max(width, height) <= 3840 && Math.min(width, height) <= 2160 ? { width, height } : null;
46
+ }
47
+ function exportName(name, extension) {
48
+ return `${name.trim().replace(/\.(mp4|webm)$/i, "").trim()}.${extension}`;
49
+ }
5
50
 
6
51
  // packages/media-tools/src/shared.ts
7
- import { z, PluginError } from "vivix-studio/sdk/shared";
52
+ import { z, PluginError, studioFileRef } from "vivix-studio/sdk/shared";
8
53
  var packageVersion = "0.1.22-ecommerce.20261110.1";
9
54
  var Config = z.object({
10
55
  dataInstance: z.string().min(1).default("user:data"),
@@ -22,6 +67,11 @@ var sequenceVideoInput = z.discriminatedUnion("kind", [
22
67
  sourceInput.extend({ trimEndMs: z.number().int().positive().optional() }),
23
68
  editInput
24
69
  ]);
70
+ var colorAdjustment = z.object({
71
+ brightness: z.number().finite().min(-0.5).max(0.5),
72
+ contrast: z.number().finite().min(0).max(2),
73
+ saturation: z.number().finite().min(0).max(2)
74
+ }).strict();
25
75
  var recipe = z.object({
26
76
  trim: z.object({ inMs: z.number().int().nonnegative(), outMs: z.number().int().positive() }).strict(),
27
77
  crop: z.object({
@@ -29,13 +79,18 @@ var recipe = z.object({
29
79
  y: z.number().finite().nonnegative(),
30
80
  width: z.number().finite().positive().max(1),
31
81
  height: z.number().finite().positive().max(1)
32
- }).strict()
82
+ }).strict(),
83
+ color: colorAdjustment.optional(),
84
+ speed: z.number().finite().min(0.25).max(4).optional()
33
85
  }).strict().superRefine((v, c) => {
34
86
  if (v.trim.inMs >= v.trim.outMs)
35
87
  c.addIssue({ code: "custom", message: "The selected interval must have positive duration." });
36
88
  if (v.crop.x + v.crop.width > 1 + 1e-9 || v.crop.y + v.crop.height > 1 + 1e-9)
37
89
  c.addIssue({ code: "custom", message: "The crop must remain inside the source picture." });
38
90
  });
91
+ function recipeDurationMs(value) {
92
+ return Math.max(1, Math.round((value.trim.outMs - value.trim.inMs) / (value.speed ?? 1)));
93
+ }
39
94
  var pixelRect = z.object({
40
95
  x: z.number().int().nonnegative(),
41
96
  y: z.number().int().nonnegative(),
@@ -75,15 +130,99 @@ var saveEdit = z.object({
75
130
  c.addIssue({ code: "custom", message: "An edit update requires its revision." });
76
131
  });
77
132
  var outputName = z.string().trim().min(1).max(200);
78
- var processVideo = z.object({ input: videoInput, outputName, retryOfJobId: z.uuid().optional() }).strict();
133
+ var gain = z.number().finite().min(-96).max(24);
134
+ var milliseconds = z.number().int().min(0).max(6e5);
135
+ var audioMix = z.object({
136
+ version: z.literal(1),
137
+ originalGainDb: gain.nullable().optional(),
138
+ originals: z.array(
139
+ z.object({
140
+ inputIndex: z.number().int().min(0).max(63),
141
+ gainDb: gain.nullable(),
142
+ role: z.enum(["dialogue", "ambience"]).optional()
143
+ }).strict()
144
+ ).max(64).optional(),
145
+ tracks: z.array(
146
+ z.object({
147
+ id: z.string().trim().min(1).max(128),
148
+ file: videoFileRef,
149
+ role: z.enum(["narration", "music", "sfx"]),
150
+ atMs: milliseconds,
151
+ inMs: milliseconds.optional(),
152
+ outMs: milliseconds.optional(),
153
+ gainDb: gain.optional(),
154
+ fadeInMs: milliseconds.optional(),
155
+ fadeOutMs: milliseconds.optional()
156
+ }).strict()
157
+ ).max(32),
158
+ ducking: z.boolean().optional(),
159
+ loudness: z.enum(["studio-web-v1", "off"]).optional()
160
+ }).strict();
161
+ var maxSequenceInputs = 64;
162
+ var audioQuery = z.object({ inputs: z.array(sequenceVideoInput).min(1).max(maxSequenceInputs) }).strict();
163
+ var previewQuery = audioQuery.extend({
164
+ knownRevision: z.number().int().nonnegative().optional()
165
+ });
166
+ var audioPreviewResult = z.discriminatedUnion("state", [
167
+ z.object({ state: z.literal("original"), revision: z.number() }),
168
+ z.object({ state: z.literal("unchanged") }),
169
+ z.object({ state: z.literal("preparing") }),
170
+ z.object({
171
+ state: z.literal("ready"),
172
+ revision: z.number(),
173
+ file: studioFileRef().nullable(),
174
+ segments: z.array(z.object({ startMs: z.number(), durationMs: z.number().positive() }))
175
+ })
176
+ ]);
177
+ var saveAudio = audioQuery.extend({
178
+ expectedRevision: z.number().int().nonnegative(),
179
+ mix: audioMix.nullable()
180
+ });
181
+ var remixRequest = z.object({
182
+ basis: z.enum(["sources", "master"]),
183
+ mix: audioMix,
184
+ expectedAssetRevision: z.number().int().positive(),
185
+ expectedMixRevision: z.number().int().nonnegative()
186
+ }).strict();
187
+ var processVideo = z.object({
188
+ input: videoInput,
189
+ outputName,
190
+ retryOfJobId: z.uuid().optional(),
191
+ remix: remixRequest.optional()
192
+ }).strict().refine((v) => !v.remix || v.input.kind === "source", "Remix requires a fixed source file.");
79
193
  var canvas = z.object({ width: z.number().int().min(2).max(3840), height: z.number().int().min(2).max(3840) }).strict().refine(
80
194
  (v) => v.width % 2 === 0 && v.height % 2 === 0 && Math.min(v.width, v.height) <= 2160,
81
195
  "Canvas dimensions must be even and within 3840 by 2160."
82
196
  );
197
+ var exportFormat = z.enum(
198
+ Object.keys(exportProfiles)
199
+ );
200
+ var exportSettings = z.object({
201
+ format: exportFormat,
202
+ aspect: z.enum(exportAspects),
203
+ resolution: z.union([
204
+ z.literal("source"),
205
+ z.literal(480),
206
+ z.literal(720),
207
+ z.literal(1080),
208
+ z.literal(2160)
209
+ ]),
210
+ frameRate: z.union([
211
+ z.literal("source"),
212
+ z.literal(24),
213
+ z.literal(25),
214
+ z.literal(30),
215
+ z.literal(50),
216
+ z.literal(60)
217
+ ]),
218
+ quality: z.enum(exportQualities),
219
+ audio: z.boolean()
220
+ }).strict();
83
221
  var processSequence = z.object({
84
- inputs: z.array(sequenceVideoInput).min(1).max(64),
222
+ inputs: z.array(sequenceVideoInput).min(1).max(maxSequenceInputs),
85
223
  outputName,
86
224
  canvas,
225
+ settings: exportSettings.optional(),
87
226
  retryOfJobId: z.uuid().optional()
88
227
  }).strict();
89
228
  var mediaRequest = z.discriminatedUnion("operation", [
@@ -137,7 +276,9 @@ function normalizeRecipe(raw, displayWidth, displayHeight, durationMs) {
137
276
  y: y / displayHeight,
138
277
  width: pixelRect2.width / displayWidth,
139
278
  height: pixelRect2.height / displayHeight
140
- }
279
+ },
280
+ ...value.color ? { color: { ...value.color } } : {},
281
+ ...value.speed === void 0 ? {} : { speed: value.speed }
141
282
  },
142
283
  geometry: { displayWidth, displayHeight, pixelRect: pixelRect2 }
143
284
  };
@@ -195,7 +336,7 @@ function readSavedEdit(data, raw) {
195
336
  file: value.file,
196
337
  recipe: value.recipe,
197
338
  geometry: value.geometry,
198
- effectiveDurationMs: value.recipe.trim.outMs - value.recipe.trim.inMs
339
+ effectiveDurationMs: recipeDurationMs(value.recipe)
199
340
  };
200
341
  }
201
342
 
@@ -441,6 +582,205 @@ var NativeExecutor = class {
441
582
  }
442
583
  };
443
584
 
585
+ // packages/media-tools/src/render.ts
586
+ function frameTimes(stdout) {
587
+ const result = stdout.split(/\r?\n/).map((line) => line.split(",")[0].trim()).filter(Boolean).map(Number).filter(Number.isFinite);
588
+ if (!result.length || result.some((v, i) => i > 0 && v <= result[i - 1]))
589
+ mediaError(
590
+ "SOURCE_TIMING_UNSUPPORTED",
591
+ "The source frame timestamps are missing or not increasing."
592
+ );
593
+ return result;
594
+ }
595
+ function segmentTiming(descriptor, frames) {
596
+ const origin = descriptor.metadata.startTime, start = origin + descriptor.recipe.trim.inMs / 1e3, end = origin + descriptor.recipe.trim.outMs / 1e3;
597
+ const kept = frames.filter((pts) => pts >= start - 1e-7 && pts < end - 1e-7);
598
+ if (!kept.length)
599
+ mediaError("EMPTY_VIDEO_INTERVAL", "The selected interval contains no video frame.");
600
+ const first = kept[0], last = kept.at(-1), next = frames.find((pts) => pts > last + 1e-7);
601
+ const lastDuration = next ? next - last : frames.length > 1 ? frames.at(-1) - frames.at(-2) : 1 / descriptor.metadata.frameRate;
602
+ const actualEnd = Math.min(
603
+ next ?? last + lastDuration,
604
+ origin + descriptor.metadata.durationMs / 1e3
605
+ );
606
+ const tolerance = Math.max(lastDuration, ...kept.slice(1).map((v, i) => v - kept[i]));
607
+ const speed = descriptor.recipe.speed ?? 1;
608
+ return {
609
+ start: first,
610
+ end: actualEnd,
611
+ duration: (actualEnd - first) / speed,
612
+ frames: kept.map((v) => (v - first) / speed),
613
+ tolerance: tolerance / speed
614
+ };
615
+ }
616
+ var seconds = (value) => Number(value.toFixed(9)).toString();
617
+ function tempoFilters(speed) {
618
+ const values = [];
619
+ while (speed < 0.5) {
620
+ values.push(0.5);
621
+ speed /= 0.5;
622
+ }
623
+ while (speed > 2) {
624
+ values.push(2);
625
+ speed /= 2;
626
+ }
627
+ if (speed !== 1) values.push(speed);
628
+ return values.map((value) => `atempo=${seconds(value)}`);
629
+ }
630
+ function renderArguments(inputs, output, canvas2, settings, mixedAudio) {
631
+ const profile = exportProfiles[settings?.format ?? "h264"];
632
+ const fps = typeof settings?.frameRate === "number" ? settings.frameRate : inputs.some(
633
+ ({ descriptor }) => descriptor.metadata.frameRate * (descriptor.recipe.speed ?? 1) > 60
634
+ ) ? 60 : void 0;
635
+ const clipAudio = mixedAudio === void 0 && settings?.audio !== false && inputs.some((i) => i.descriptor.metadata.hasAudio), audible = clipAudio || Boolean(mixedAudio), sequence = Boolean(canvas2), sourceRate = inputs[0]?.descriptor.metadata.audioSampleRate ?? null, audioSampleRate = audible ? mixedAudio || sequence || sourceRate === 32e3 ? 48e3 : sourceRate : null, filters = [], labels = [];
636
+ const args = ["-hide_banner", "-nostdin", "-y", "-copyts"];
637
+ for (const input of inputs) args.push("-protocol_whitelist", "file,pipe", "-i", input.path);
638
+ if (mixedAudio) args.push("-protocol_whitelist", "file,pipe", "-i", mixedAudio);
639
+ for (const [index, { descriptor, timing }] of inputs.entries()) {
640
+ const rect = descriptor.geometry.pixelRect;
641
+ const speed = descriptor.recipe.speed ?? 1;
642
+ const color = descriptor.recipe.color;
643
+ const video = [
644
+ `[${index}:v:0]trim=start=${seconds(timing.start)}:end=${seconds(timing.end)}`,
645
+ speed === 1 ? `setpts=PTS-${seconds(timing.start)}/TB` : `setpts=(PTS-${seconds(timing.start)}/TB)/${seconds(speed)}`,
646
+ "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709",
647
+ `crop=${rect.width}:${rect.height}:${rect.x}:${rect.y}`,
648
+ ...color ? [
649
+ `eq=brightness=${color.brightness}:contrast=${color.contrast}:saturation=${color.saturation}`
650
+ ] : [],
651
+ "setsar=1",
652
+ ...canvas2 ? [
653
+ `scale=${canvas2.width}:${canvas2.height}:flags=lanczos:in_color_matrix=bt709:out_color_matrix=bt709${settings ? ":force_original_aspect_ratio=decrease:force_divisible_by=2" : ""}`,
654
+ ...settings ? [`pad=${canvas2.width}:${canvas2.height}:(ow-iw)/2:(oh-ih)/2:black`, "setsar=1"] : []
655
+ ] : [],
656
+ "format=yuv420p",
657
+ "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709"
658
+ ];
659
+ filters.push(video.join(",") + `[v${index}]`);
660
+ labels.push(`[v${index}]`);
661
+ if (clipAudio) {
662
+ const channels = sequence ? 2 : descriptor.metadata.audioChannels;
663
+ let audio;
664
+ if (descriptor.metadata.hasAudio) {
665
+ const mono = sequence && descriptor.metadata.audioChannels === 1 ? ",pan=stereo|c0=c0|c1=c0" : "";
666
+ const sourceDuration = timing.end - timing.start;
667
+ audio = [
668
+ `[${index}:a:0]atrim=start=${seconds(timing.start)}:end=${seconds(timing.end)}`,
669
+ `asetpts=PTS-${seconds(timing.start)}/TB`,
670
+ `aresample=${audioSampleRate}:async=1:first_pts=0${mono}`,
671
+ `aformat=sample_fmts=fltp:channel_layouts=${channels === 1 ? "mono" : "stereo"}`,
672
+ `apad=whole_dur=${seconds(sourceDuration)}`,
673
+ `atrim=duration=${seconds(sourceDuration)}`,
674
+ ...tempoFilters(speed),
675
+ `apad=whole_dur=${seconds(timing.duration)}`,
676
+ `atrim=duration=${seconds(timing.duration)}`
677
+ ].join(",");
678
+ } else
679
+ audio = `anullsrc=r=48000:cl=stereo,atrim=duration=${seconds(timing.duration)},asetpts=PTS-STARTPTS`;
680
+ filters.push(audio + `[a${index}]`);
681
+ labels.push(`[a${index}]`);
682
+ }
683
+ }
684
+ if (inputs.length > 1) {
685
+ filters.push(
686
+ labels.join("") + `concat=n=${inputs.length}:v=1:a=${clipAudio ? 1 : 0}[video]${clipAudio ? "[audio]" : ""}`
687
+ );
688
+ }
689
+ const videoLabel = inputs.length > 1 ? "[video]" : "[v0]";
690
+ if (fps) {
691
+ filters.push(`${videoLabel}fps=fps=${fps}:start_time=0:eof_action=pass[cfr]`);
692
+ }
693
+ args.push("-filter_complex", filters.join(";"), "-map", fps ? "[cfr]" : videoLabel);
694
+ if (audible)
695
+ args.push(
696
+ "-map",
697
+ mixedAudio ? String(inputs.length) + ":a:0" : inputs.length > 1 ? "[audio]" : "[a0]",
698
+ "-c:a",
699
+ profile.audio === "opus" ? "libopus" : profile.audio,
700
+ "-b:a",
701
+ "192k"
702
+ );
703
+ else args.push("-an");
704
+ if (inputs.length > 1 && !fps && profile.container === "mp4") {
705
+ const last = inputs[inputs.length - 1].timing;
706
+ const tail = seconds(last.duration - last.frames[last.frames.length - 1]);
707
+ args.push(
708
+ "-bsf:v",
709
+ `setts=pts=PTS:dts=DTS:duration='if(gt(DURATION,0),DURATION,round(${tail}/TB))'`
710
+ );
711
+ }
712
+ args.push(
713
+ "-c:v",
714
+ profile.encoder,
715
+ "-crf",
716
+ String(profile.crf[exportQualities.indexOf(settings?.quality ?? "high")]),
717
+ ...profile.codec === "vp9" ? ["-b:v", "0", "-deadline", "good", "-cpu-used", "2"] : ["-preset", "medium"],
718
+ ...profile.codec === "hevc" ? ["-tag:v", "hvc1", "-x265-params", "pools=4"] : [],
719
+ "-threads",
720
+ "4",
721
+ "-pix_fmt",
722
+ "yuv420p",
723
+ "-fps_mode",
724
+ "passthrough",
725
+ "-enc_time_base:v",
726
+ fps ? `1:${fps}` : "1:90000",
727
+ ...profile.container === "mp4" ? ["-video_track_timescale", "90000", "-movflags", "+faststart"] : (
728
+ // Older WebM muxers otherwise move all video timestamps to offset Opus pre-roll.
729
+ ["-avoid_negative_ts", "disabled"]
730
+ ),
731
+ "-color_primaries",
732
+ "bt709",
733
+ "-color_trc",
734
+ "bt709",
735
+ "-colorspace",
736
+ "bt709",
737
+ "-metadata:s:v:0",
738
+ "rotate=0",
739
+ "-progress",
740
+ "pipe:1",
741
+ "-stats_period",
742
+ "0.5",
743
+ output
744
+ );
745
+ return {
746
+ args,
747
+ audible,
748
+ audioSampleRate,
749
+ frameRate: fps,
750
+ expectedFrames: inputs.flatMap((input, index) => {
751
+ const offset = inputs.slice(0, index).reduce((n, i) => n + i.timing.duration, 0);
752
+ return input.timing.frames.map((t) => t + offset);
753
+ }),
754
+ duration: inputs.reduce((n, i) => n + i.timing.duration, 0),
755
+ tolerance: inputs.reduce((n, i) => n + i.timing.tolerance, 0)
756
+ };
757
+ }
758
+ function validateFrameTiming(actual, timings, fps, webm = false) {
759
+ const precision = webm ? 2e-3 : 1e-3;
760
+ if (fps) {
761
+ if (actual.some((pts, index2) => Math.abs(pts - actual[0] - index2 / fps) > precision))
762
+ mediaError("OUTPUT_TIMING_MISMATCH", "The output does not have the selected frame cadence.");
763
+ return;
764
+ }
765
+ if (actual.length !== timings.reduce((total, timing) => total + timing.frames.length, 0))
766
+ mediaError("OUTPUT_TIMING_MISMATCH", "The output frame count changed.");
767
+ let index = 0, expectedStart = 0, boundaryTolerance = 0;
768
+ for (const timing of timings) {
769
+ const first = actual[index];
770
+ if (Math.abs(first - expectedStart) > boundaryTolerance + 1e-3)
771
+ mediaError(
772
+ "OUTPUT_TIMING_MISMATCH",
773
+ "The output segment boundary moved beyond the source frame allowance."
774
+ );
775
+ for (let offset = 0; offset < timing.frames.length; offset++)
776
+ if (Math.abs(actual[index + offset] - first - timing.frames[offset]) > precision)
777
+ mediaError("OUTPUT_TIMING_MISMATCH", "The output changed timing inside a source segment.");
778
+ index += timing.frames.length;
779
+ expectedStart += timing.duration;
780
+ boundaryTolerance += timing.tolerance;
781
+ }
782
+ }
783
+
444
784
  // packages/media-tools/src/video.ts
445
785
  async function executable(name) {
446
786
  const candidates = isAbsolute(name) || name.includes("/") ? [resolve(name)] : (process.env.PATH || "").split(":").map((p) => join2(p, name));
@@ -460,13 +800,19 @@ function fraction(value) {
460
800
  const [a, b] = String(value).split("/").map(Number);
461
801
  return b ? a / b : a;
462
802
  }
463
- function parseMetadata(info, file) {
803
+ function parseMetadata(info, file, output) {
464
804
  const streams = info.streams || [], videos = streams.filter((v) => v.codec_type === "video"), audios = streams.filter((v) => v.codec_type === "audio");
465
805
  if (videos.length !== 1 || audios.length > 1 || streams.some((v) => !["video", "audio"].includes(v.codec_type)))
466
- mediaError("UNSUPPORTED_MEDIA", "Use one H.264 video stream and at most one AAC audio stream.");
806
+ mediaError(
807
+ "UNSUPPORTED_MEDIA",
808
+ output ? "The exported stream layout is invalid." : "Use one H.264 video stream and at most one AAC audio stream."
809
+ );
467
810
  const video = videos[0], audio = audios[0], audioSampleRate = audio ? Number(audio.sample_rate) : null;
468
- if (!String(info.format?.format_name).split(",").includes("mp4") || video.codec_name !== "h264" || video.pix_fmt !== "yuv420p" || !["1:1", "N/A", void 0].includes(video.sample_aspect_ratio))
469
- mediaError("UNSUPPORTED_MEDIA", "Use an 8-bit square-pixel H.264 MP4 video.");
811
+ if (!String(info.format?.format_name).split(",").includes(output?.container ?? "mp4") || video.codec_name !== (output?.codec ?? "h264") || video.pix_fmt !== "yuv420p" || !["1:1", "N/A", void 0].includes(video.sample_aspect_ratio))
812
+ mediaError(
813
+ "UNSUPPORTED_MEDIA",
814
+ output ? "The exported video does not match the selected format." : "Use an 8-bit square-pixel H.264 MP4 video."
815
+ );
470
816
  const colorTags = [video.color_space, video.color_transfer, video.color_primaries];
471
817
  const missingColor = (tag) => tag === void 0 || tag === null || ["", "unknown", "unspecified", "N/A"].includes(String(tag));
472
818
  const declaredHdr = video.side_data_list?.some(
@@ -497,8 +843,11 @@ function parseMetadata(info, file) {
497
843
  "MEDIA_LIMIT_EXCEEDED",
498
844
  "Use an even-sized video up to 3840 by 2160, 60 fps, 600 seconds and 2 GiB."
499
845
  );
500
- if (audio && (audio.codec_name !== "aac" || ![1, 2].includes(audio.channels) || audioSampleRate === null || !Number.isInteger(audioSampleRate) || audioSampleRate <= 0 || !["mono", "stereo"].includes(audio.channel_layout)))
501
- mediaError("UNSUPPORTED_AUDIO", "Use one mono or stereo AAC track with a valid sample rate.");
846
+ if (audio && (audio.codec_name !== (output?.audio ?? "aac") || ![1, 2].includes(audio.channels) || audioSampleRate === null || !Number.isInteger(audioSampleRate) || audioSampleRate <= 0 || !["mono", "stereo"].includes(audio.channel_layout)))
847
+ mediaError(
848
+ "UNSUPPORTED_AUDIO",
849
+ output ? "The exported audio does not match the selected format." : "Use one mono or stereo AAC track with a valid sample rate."
850
+ );
502
851
  return metadata.parse({
503
852
  durationMs: Math.round(duration * 1e3),
504
853
  width,
@@ -529,6 +878,7 @@ var Videos = class {
529
878
  config;
530
879
  runtimeRoot;
531
880
  cache = /* @__PURE__ */ new Map();
881
+ frameCache = /* @__PURE__ */ new Map();
532
882
  toolCache;
533
883
  processing = false;
534
884
  async recoverProbes() {
@@ -589,15 +939,41 @@ var Videos = class {
589
939
  if (!/\blibx264\b/.test(encoders) || !/\baac\b/.test(encoders))
590
940
  mediaError("TOOL_UNSUPPORTED", "FFmpeg needs libx264 and AAC encoders.");
591
941
  const filters = (await this.command(ffmpeg, ["-hide_banner", "-filters"])).stdout;
592
- for (const filter of ["trim", "atrim", "crop", "scale", "concat", "aresample", "anullsrc"])
942
+ for (const filter of [
943
+ "trim",
944
+ "atrim",
945
+ "crop",
946
+ "scale",
947
+ "concat",
948
+ "aresample",
949
+ "anullsrc",
950
+ "fps",
951
+ "pad",
952
+ "eq",
953
+ "atempo"
954
+ ])
593
955
  if (!new RegExp("\\b" + filter + "\\b").test(filters))
594
956
  mediaError("TOOL_UNSUPPORTED", "FFmpeg is missing required video or audio filters.");
957
+ const muxers = (await this.command(ffmpeg, ["-hide_banner", "-muxers"])).stdout;
958
+ const exportFormats = ["h264"];
959
+ if (/\bmp4\b/.test(muxers) && /\blibx265\b/.test(encoders)) exportFormats.push("hevc");
960
+ if (/\bwebm\b/.test(muxers) && /\blibvpx-vp9\b/.test(encoders) && /\blibopus\b/.test(encoders))
961
+ exportFormats.push("vp9");
595
962
  this.toolCache = {
596
963
  ffmpeg,
597
964
  ffprobe,
598
965
  ffmpegVersion: encoder.stdout.split("\n")[0],
599
966
  ffprobeVersion: probe.stdout.split("\n")[0],
600
- profileVersion: 1
967
+ profileVersion: 1,
968
+ exportFormats,
969
+ ...["volume", "afade", "adelay", "amix", "apad", "aformat", "asetpts", "asplit"].every(
970
+ (f) => filters.split(/\s+/).includes(f)
971
+ ) ? {
972
+ audioMix: {
973
+ ducking: /\bsidechaincompress\b/.test(filters),
974
+ loudness: /\bloudnorm\b/.test(filters) && /\balimiter\b/.test(filters)
975
+ }
976
+ } : {}
601
977
  };
602
978
  return this.toolCache;
603
979
  }
@@ -614,49 +990,96 @@ var Videos = class {
614
990
  );
615
991
  }
616
992
  }
617
- file(file, includeDeleted = false) {
993
+ file(file, includeDeleted = false, copy = false) {
618
994
  if (this.data.scope.kind !== "project" || file.source.storeId !== this.data.storeId)
619
995
  mediaError("SCOPE_MISMATCH", "Video input belongs to another project store.");
620
996
  const object = this.data.get(file.source.objectId, includeDeleted), version = this.data.version(file.source), record = this.data.files(file.source).find((f) => f.fileId === file.fileId);
621
- if (object.typeId !== "studio.asset" || object.data.kind !== "video" || version.payload.kind !== "video" || !record || record.mimeType !== "video/mp4")
997
+ if (object.typeId !== "studio.asset" || object.data.kind !== "video" || version.payload.kind !== "video" || !record || record.mimeType !== "video/mp4" && !(copy && record.mimeType === "video/webm"))
622
998
  mediaError("SOURCE_NOT_VIDEO", "Select a readable fixed MP4 video from this project.");
623
999
  return { object, version, file: record };
624
1000
  }
625
- async restoreMetadata(raw) {
626
- const descriptor = editDescriptor.parse(raw), fixed = this.file(descriptor.file, true);
1001
+ async restoreMetadata(raw, copy = false) {
1002
+ const descriptor = editDescriptor.parse(raw), fixed = this.file(descriptor.file, true, copy);
627
1003
  if (fixed.file.sha256 !== descriptor.metadata.sha256 || fixed.file.sizeBytes !== descriptor.metadata.sizeBytes)
628
1004
  mediaError(
629
1005
  "SOURCE_SNAPSHOT_MISMATCH",
630
1006
  "The fixed execution metadata does not match the recorded source file."
631
1007
  );
632
1008
  const location = await this.data.location(descriptor.file.source, descriptor.file.fileId);
633
- this.cache.set(fixed.file.sha256, descriptor.metadata);
1009
+ if (!copy) this.cache.set(fixed.file.sha256, descriptor.metadata);
634
1010
  return location;
635
1011
  }
636
- async describe(file) {
637
- const fixed = this.file(file), location = await this.data.location(file.source, file.fileId), key = fixed.file.sha256;
638
- const cached = this.cache.get(key);
639
- if (cached) return cached;
1012
+ async probeLocation(absolutePath) {
640
1013
  if (this.processing || this.native.busy)
641
- mediaError("MEDIA_BUSY", "Wait for the current video before inspecting an uncached source.");
642
- const probe = await executable(this.config.ffprobePath);
643
- const result = await this.command(probe, [
1014
+ mediaError("MEDIA_BUSY", "Wait for the current media process before probing another file.");
1015
+ const result = await this.command(await executable(this.config.ffprobePath), [
644
1016
  "-v",
645
1017
  "error",
1018
+ "-protocol_whitelist",
1019
+ "file,pipe",
646
1020
  "-show_format",
647
1021
  "-show_streams",
648
1022
  "-of",
649
1023
  "json",
650
- location.absolutePath
1024
+ absolutePath
651
1025
  ]);
652
1026
  if (result.stderr.trim())
653
- mediaError("MEDIA_INVALID", "The source reported a decoding or metadata error.");
654
- let info;
1027
+ mediaError("MEDIA_INVALID", "Could not read the fixed media streams.");
655
1028
  try {
656
- info = JSON.parse(result.stdout);
1029
+ return JSON.parse(result.stdout);
657
1030
  } catch {
658
1031
  mediaError("MEDIA_INVALID", "The source metadata is invalid.");
659
1032
  }
1033
+ }
1034
+ async timedInput(descriptor, tools, copy, job) {
1035
+ const { absolutePath: path } = await this.restoreMetadata(descriptor, copy);
1036
+ const key = JSON.stringify([descriptor.metadata.sha256, tools.ffprobe, tools.ffprobeVersion]);
1037
+ let frames = this.frameCache.get(key);
1038
+ if (!frames) {
1039
+ if (!job && this.processing)
1040
+ mediaError("MEDIA_BUSY", "Wait for the current media process before probing frame times.");
1041
+ const args = [
1042
+ "-v",
1043
+ "error",
1044
+ "-select_streams",
1045
+ "v:0",
1046
+ "-show_entries",
1047
+ "frame=best_effort_timestamp_time",
1048
+ "-of",
1049
+ "csv=p=0",
1050
+ path
1051
+ ];
1052
+ const result = job ? await this.native.run(tools.ffprobe, args, { ...job, timeoutMs: 15e3 }) : await this.command(tools.ffprobe, args);
1053
+ frames = frameTimes(result.stdout);
1054
+ if (this.frameCache.size >= 64) this.frameCache.delete(this.frameCache.keys().next().value);
1055
+ this.frameCache.set(key, frames);
1056
+ }
1057
+ return { descriptor, path, timing: segmentTiming(descriptor, frames) };
1058
+ }
1059
+ async master(file) {
1060
+ const record = this.file(file, false, true);
1061
+ const info = await this.probeLocation(
1062
+ (await this.data.location(file.source, file.fileId)).absolutePath
1063
+ );
1064
+ const format = Object.keys(exportProfiles).find(
1065
+ (key) => exportProfiles[key].codec === info.streams?.find((s) => s.codec_type === "video")?.codec_name
1066
+ );
1067
+ if (!format)
1068
+ mediaError("UNSUPPORTED_MEDIA", "Choose an MP4 or WebM supported for video stream copying.");
1069
+ const metadata2 = parseMetadata(info, record.file, exportProfiles[format]);
1070
+ const normalized = normalizeRecipe(
1071
+ { crop: { x: 0, y: 0, width: 1, height: 1 }, trim: { inMs: 0, outMs: metadata2.durationMs } },
1072
+ metadata2.displayWidth,
1073
+ metadata2.displayHeight,
1074
+ metadata2.durationMs
1075
+ );
1076
+ return { format, descriptor: { format: 1, file, metadata: metadata2, ...normalized } };
1077
+ }
1078
+ async describe(file) {
1079
+ const fixed = this.file(file), location = await this.data.location(file.source, file.fileId), key = fixed.file.sha256;
1080
+ const cached = this.cache.get(key);
1081
+ if (cached) return cached;
1082
+ const info = await this.probeLocation(location.absolutePath);
660
1083
  const value = parseMetadata(info, fixed.file);
661
1084
  this.cache.set(key, value);
662
1085
  return value;
@@ -694,7 +1117,7 @@ var Videos = class {
694
1117
  file: descriptor.file,
695
1118
  recipe: descriptor.recipe,
696
1119
  geometry: descriptor.geometry,
697
- effectiveDurationMs: descriptor.recipe.trim.outMs - descriptor.recipe.trim.inMs,
1120
+ effectiveDurationMs: recipeDurationMs(descriptor.recipe),
698
1121
  editRef: saved?.editRef ?? null,
699
1122
  revision: saved?.revision ?? null,
700
1123
  name: fixed.object.data.name,
@@ -709,6 +1132,9 @@ var Videos = class {
709
1132
  }
710
1133
  };
711
1134
 
1135
+ // packages/media-tools/src/sequence-audio.ts
1136
+ import { z as z3 } from "vivix-studio/sdk/shared";
1137
+
712
1138
  // packages/media-tools/src/edits.ts
713
1139
  import { createHash } from "crypto";
714
1140
  import { z as z2 } from "vivix-studio/sdk/shared";
@@ -824,176 +1250,713 @@ var Edits = class {
824
1250
  }
825
1251
  };
826
1252
 
827
- // packages/media-tools/src/jobs.ts
828
- import { randomUUID as randomUUID3, createHash as createHash2 } from "crypto";
829
- import { createReadStream } from "fs";
830
- import { mkdir as mkdir2, rm as rm2, stat, statfs } from "fs/promises";
831
- import { join as join3 } from "path";
832
- import { z as z3 } from "vivix-studio/sdk/shared";
833
-
834
- // packages/media-tools/src/render.ts
835
- function frameTimes(stdout) {
836
- const result = stdout.split(/\r?\n/).map((line) => line.split(",")[0].trim()).filter(Boolean).map(Number).filter(Number.isFinite);
837
- if (!result.length || result.some((v, i) => i > 0 && v <= result[i - 1]))
838
- mediaError(
839
- "SOURCE_TIMING_UNSUPPORTED",
840
- "The source frame timestamps are missing or not increasing."
841
- );
842
- return result;
843
- }
844
- function segmentTiming(descriptor, frames) {
845
- const origin = descriptor.metadata.startTime, start = origin + descriptor.recipe.trim.inMs / 1e3, end = origin + descriptor.recipe.trim.outMs / 1e3;
846
- const kept = frames.filter((pts) => pts >= start - 1e-7 && pts < end - 1e-7);
847
- if (!kept.length)
848
- mediaError("EMPTY_VIDEO_INTERVAL", "The selected interval contains no video frame.");
849
- const first = kept[0], last = kept.at(-1), next = frames.find((pts) => pts > last + 1e-7);
850
- const lastDuration = next ? next - last : frames.length > 1 ? frames.at(-1) - frames.at(-2) : 1 / descriptor.metadata.frameRate;
851
- const actualEnd = Math.min(
852
- next ?? last + lastDuration,
853
- origin + descriptor.metadata.durationMs / 1e3
1253
+ // packages/media-tools/src/sequence-audio.ts
1254
+ var trackInfo = z3.object({
1255
+ file: videoFileRef,
1256
+ durationMs: z3.number().positive(),
1257
+ origin: z3.number().finite(),
1258
+ channels: z3.number().int(),
1259
+ sha256: z3.string(),
1260
+ sizeBytes: z3.number().int()
1261
+ }).strict();
1262
+ var timelineSchema = z3.array(
1263
+ z3.object({
1264
+ start: z3.number().finite(),
1265
+ end: z3.number().finite(),
1266
+ duration: z3.number().positive()
1267
+ })
1268
+ ).min(1).max(64);
1269
+ var audioSnapshot = z3.object({
1270
+ inputs: audioQuery.shape.inputs,
1271
+ sequenceKey: z3.uuid(),
1272
+ revision: z3.number().int().nonnegative(),
1273
+ mix: audioMix.nullable(),
1274
+ tracks: z3.array(trackInfo),
1275
+ timeline: timelineSchema.optional(),
1276
+ copy: z3.object({ format: exportFormat, descriptor: editDescriptor }).optional()
1277
+ }).strict();
1278
+ var recordSchema = audioQuery.extend({ mix: audioMix.nullable() });
1279
+ var audioType = {
1280
+ typeId: "media.sequence-audio",
1281
+ schemaVersion: 1,
1282
+ scopeKinds: ["project"],
1283
+ validate: (value) => recordSchema.parse(value)
1284
+ };
1285
+ function identifySequence(data, inputs, descriptors) {
1286
+ const normalized = inputs.map(
1287
+ (input, index) => input.kind === "edit" ? input : {
1288
+ kind: "source",
1289
+ file: input.file,
1290
+ trimEndMs: descriptors[index].recipe.trim.outMs
1291
+ }
854
1292
  );
855
- const tolerance = Math.max(lastDuration, ...kept.slice(1).map((v, i) => v - kept[i]));
1293
+ return bindingForInputs(data, normalized);
1294
+ }
1295
+ function bindingForInputs(data, normalized) {
1296
+ const parsed = audioQuery.parse({ inputs: normalized });
856
1297
  return {
857
- start: first,
858
- end: actualEnd,
859
- duration: actualEnd - first,
860
- frames: kept.map((v) => v - first),
861
- tolerance
1298
+ inputs: parsed.inputs,
1299
+ sequenceKey: stableUuid(["sequence-audio/1", data.scope.id, data.storeId, parsed.inputs])
862
1300
  };
863
1301
  }
864
- var seconds = (value) => Number(value.toFixed(9)).toString();
865
- function renderArguments(inputs, output, canvas2) {
866
- const audible = inputs.some((i) => i.descriptor.metadata.hasAudio), sequence = Boolean(canvas2), sourceRate = inputs[0]?.descriptor.metadata.audioSampleRate ?? null, audioSampleRate = audible ? sequence || sourceRate === 32e3 ? 48e3 : sourceRate : null, filters = [], labels = [];
867
- const args = ["-hide_banner", "-nostdin", "-y", "-copyts"];
868
- for (const input of inputs) args.push("-protocol_whitelist", "file,pipe", "-i", input.path);
869
- for (const [index, { descriptor, timing }] of inputs.entries()) {
870
- const rect = descriptor.geometry.pixelRect;
871
- const video = [
872
- `[${index}:v:0]trim=start=${seconds(timing.start)}:end=${seconds(timing.end)}`,
873
- `setpts=PTS-${seconds(timing.start)}/TB`,
874
- "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709",
875
- `crop=${rect.width}:${rect.height}:${rect.x}:${rect.y}`,
876
- "setsar=1",
877
- ...canvas2 ? [
878
- `scale=${canvas2.width}:${canvas2.height}:flags=lanczos:in_color_matrix=bt709:out_color_matrix=bt709`
879
- ] : [],
880
- "format=yuv420p",
881
- "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709"
1302
+ function readMix(data, sequenceKey) {
1303
+ try {
1304
+ const record = data.get(sequenceKey);
1305
+ if (record.typeId !== audioType.typeId)
1306
+ mediaError("TYPE_MISMATCH", "Unexpected sequence audio record.");
1307
+ return {
1308
+ sequenceKey,
1309
+ revision: record.revision,
1310
+ mix: audioMix.nullable().parse(record.data.mix)
1311
+ };
1312
+ } catch (error) {
1313
+ if (error.code !== "OBJECT_NOT_FOUND") throw error;
1314
+ return { sequenceKey, revision: 0, mix: null };
1315
+ }
1316
+ }
1317
+ function writeMix(t, binding, expected, mix) {
1318
+ const { sequenceKey, inputs } = binding;
1319
+ const old = readMix(t, sequenceKey);
1320
+ if (old.revision !== expected)
1321
+ mediaError("REVISION_CONFLICT", "Read the current sequence audio revision before editing.");
1322
+ const value = { inputs, mix };
1323
+ const row = expected ? t.update(sequenceKey, expected, value) : t.create(audioType.typeId, value, {}, sequenceKey);
1324
+ t.removeRelations(sequenceKey, "reference");
1325
+ if (mix) {
1326
+ const refs = [
1327
+ ...inputs.map((i) => i.kind === "edit" ? i.editRef : i.file.source),
1328
+ ...mix.tracks.map((v) => v.file.source)
882
1329
  ];
883
- filters.push(video.join(",") + `[v${index}]`);
884
- labels.push(`[v${index}]`);
885
- if (audible) {
886
- const channels = sequence ? 2 : descriptor.metadata.audioChannels;
887
- let audio;
888
- if (descriptor.metadata.hasAudio) {
889
- const mono = sequence && descriptor.metadata.audioChannels === 1 ? ",pan=stereo|c0=c0|c1=c0" : "";
890
- audio = `[${index}:a:0]atrim=start=${seconds(timing.start)}:end=${seconds(timing.end)},asetpts=PTS-${seconds(timing.start)}/TB,aresample=${audioSampleRate}:async=1:first_pts=0${mono},aformat=sample_fmts=fltp:channel_layouts=${channels === 1 ? "mono" : "stereo"},apad=whole_dur=${seconds(timing.duration)},atrim=duration=${seconds(timing.duration)}`;
891
- } else
892
- audio = `anullsrc=r=48000:cl=stereo,atrim=duration=${seconds(timing.duration)},asetpts=PTS-STARTPTS`;
893
- filters.push(audio + `[a${index}]`);
894
- labels.push(`[a${index}]`);
1330
+ for (const ref of new Map(refs.map((r) => [r.versionId, r])).values())
1331
+ t.relation(sequenceKey, null, ref, "reference");
1332
+ }
1333
+ return { sequenceKey, revision: row.revision, mix };
1334
+ }
1335
+ function checkMixTools(tools, mix) {
1336
+ if (!tools.audioMix || mix.ducking !== false && !tools.audioMix.ducking || mix.loudness !== "off" && !tools.audioMix.loudness)
1337
+ mediaError("TOOL_UNSUPPORTED", "The configured FFmpeg lacks a required audio mixing filter.");
1338
+ }
1339
+ function fixedAudio(data, file, includeDeleted = false) {
1340
+ const obj = data.get(file.source.objectId, includeDeleted);
1341
+ const version = data.version(file.source);
1342
+ const record = data.files(file.source).find((f) => f.fileId === file.fileId && f.role === "primary");
1343
+ if (obj.typeId !== "studio.asset" || !["audio", "video"].includes(obj.data.kind) || version.payload.kind !== obj.data.kind || !record)
1344
+ mediaError(
1345
+ "INVALID_AUDIO_SOURCE",
1346
+ "Select a fixed primary audio or video file in this project."
1347
+ );
1348
+ return record;
1349
+ }
1350
+ var SequenceAudio = class {
1351
+ constructor(videos) {
1352
+ this.videos = videos;
1353
+ }
1354
+ videos;
1355
+ trackCache = /* @__PURE__ */ new Map();
1356
+ get data() {
1357
+ return this.videos.data;
1358
+ }
1359
+ async descriptors(inputs, allowMaster = false) {
1360
+ const result = [];
1361
+ for (const input of inputs) {
1362
+ if (allowMaster && input.kind === "source" && inputs.length === 1) {
1363
+ try {
1364
+ result.push(await this.videos.descriptor(input));
1365
+ continue;
1366
+ } catch (error) {
1367
+ if (!["SOURCE_NOT_VIDEO", "UNSUPPORTED_MEDIA"].includes(error?.code))
1368
+ throw error;
1369
+ const { descriptor } = await this.videos.master(input.file);
1370
+ if (input.trimEndMs !== void 0 && input.trimEndMs !== descriptor.metadata.durationMs)
1371
+ throw error;
1372
+ result.push(descriptor);
1373
+ continue;
1374
+ }
1375
+ }
1376
+ result.push(await this.videos.descriptor(input));
895
1377
  }
1378
+ return result;
896
1379
  }
897
- if (inputs.length > 1) {
1380
+ async binding(inputs) {
1381
+ const normalized = [];
1382
+ for (const input of inputs) {
1383
+ if (input.kind === "edit") {
1384
+ readSavedEdit(this.data, input.editRef);
1385
+ normalized.push(input);
1386
+ } else {
1387
+ const { version } = this.videos.file(input.file, true, true);
1388
+ const duration = version.payload.durationMs;
1389
+ if (!Number.isSafeInteger(duration) || duration <= 0)
1390
+ return identifySequence(this.data, inputs, await this.descriptors(inputs, true));
1391
+ if (input.trimEndMs !== void 0 && input.trimEndMs > duration + Math.ceil(1e3 / (version.payload.frameRate || 60)))
1392
+ mediaError("INVALID_RECIPE", "A saved shot duration exceeds its selected video.");
1393
+ normalized.push({ ...input, trimEndMs: Math.min(input.trimEndMs ?? duration, duration) });
1394
+ }
1395
+ }
1396
+ return bindingForInputs(this.data, normalized);
1397
+ }
1398
+ async get(inputs) {
1399
+ const id = await this.binding(inputs);
1400
+ return readMix(this.data, id.sequenceKey);
1401
+ }
1402
+ async inspect(mix, descriptors, tools, pictureSeconds) {
1403
+ checkMixTools(tools, mix);
1404
+ if (pictureSeconds === void 0) {
1405
+ pictureSeconds = 0;
1406
+ for (const descriptor of descriptors)
1407
+ pictureSeconds += (await this.videos.timedInput(descriptor, tools, true)).timing.duration;
1408
+ }
1409
+ const duration = Math.round(pictureSeconds * 1e9) / 1e6;
1410
+ const bytes = new Map(descriptors.map((d) => [d.metadata.sha256, d.metadata.sizeBytes]));
1411
+ const originals = mix.originals ?? [];
1412
+ if (new Set(originals.map((i) => i.inputIndex)).size !== originals.length || originals.some((i) => i.inputIndex >= descriptors.length))
1413
+ mediaError(
1414
+ "INVALID_MIX",
1415
+ "Original audio overrides must identify distinct existing clip positions."
1416
+ );
1417
+ if (new Set(mix.tracks.map((t) => t.id)).size !== mix.tracks.length)
1418
+ mediaError("INVALID_MIX", "Audio track IDs must be unique.");
1419
+ const tracks = [];
1420
+ for (const track of mix.tracks) {
1421
+ const record = fixedAudio(this.data, track.file, true);
1422
+ let location;
1423
+ try {
1424
+ location = await this.data.location(track.file.source, track.file.fileId);
1425
+ } catch (error) {
1426
+ const code = error.code;
1427
+ if (code === "FILE_MISSING" || code === "FILE_CORRUPT")
1428
+ mediaError(code, "The fixed source of audio track " + track.id + " is unavailable.");
1429
+ throw error;
1430
+ }
1431
+ let info = this.trackCache.get(record.sha256);
1432
+ if (!info) {
1433
+ const probe = await this.videos.probeLocation(location.absolutePath);
1434
+ const streams = probe.streams.filter((s) => s.codec_type === "audio");
1435
+ const stream = streams[0];
1436
+ if (streams.length !== 1 || ![1, 2].includes(stream.channels))
1437
+ mediaError(
1438
+ "UNSUPPORTED_AUDIO",
1439
+ "Track " + track.id + " requires one mono or stereo audio stream."
1440
+ );
1441
+ const origin = Number(probe.format.start_time ?? 0);
1442
+ const durationMs = Math.round(1e3 * Number(probe.format.duration ?? stream.duration));
1443
+ if (!Number.isFinite(origin) || !Number.isSafeInteger(durationMs) || durationMs <= 0)
1444
+ mediaError("INVALID_MIX", "Unknown duration for track " + track.id + ".");
1445
+ info = {
1446
+ file: track.file,
1447
+ origin,
1448
+ durationMs,
1449
+ channels: stream.channels,
1450
+ sha256: record.sha256,
1451
+ sizeBytes: record.sizeBytes
1452
+ };
1453
+ this.trackCache.set(record.sha256, info);
1454
+ }
1455
+ bytes.set(record.sha256, record.sizeBytes);
1456
+ const start = track.inMs ?? 0, end = track.outMs ?? info.durationMs;
1457
+ const length = Math.min(end - start, duration - track.atMs);
1458
+ if (end > info.durationMs || length <= 0 || (track.fadeInMs ?? 0) + (track.fadeOutMs ?? 0) > length)
1459
+ mediaError(
1460
+ "INVALID_MIX_RANGE",
1461
+ "Review placement, trim and fades for track " + track.id + "."
1462
+ );
1463
+ tracks.push({ ...info, file: track.file });
1464
+ }
1465
+ if (duration > 6e5 || descriptors.reduce((sum, d) => sum + recipeDurationMs(d.recipe), 0) > 6e5 || [...bytes.values()].reduce((a, b) => a + b, 0) > 2147483648)
1466
+ mediaError(
1467
+ "MEDIA_LIMIT_EXCEEDED",
1468
+ "The mix exceeds the sequence duration or distinct source byte limit."
1469
+ );
1470
+ return tracks;
1471
+ }
1472
+ async prepareRemix(request, tools) {
1473
+ const remix = request.remix;
1474
+ if (request.input.kind !== "source")
1475
+ mediaError("INVALID_REFERENCE", "Remix requires a fixed video file.");
1476
+ const file = request.input.file;
1477
+ const asset = this.data.get(file.source.objectId);
1478
+ if (asset.revision !== remix.expectedAssetRevision)
1479
+ mediaError("REVISION_CONFLICT", "The target film revision has changed.");
1480
+ const copy = await this.videos.master(file);
1481
+ if (!(tools.exportFormats ?? ["h264"]).includes(copy.format))
1482
+ mediaError(
1483
+ "TOOL_UNSUPPORTED",
1484
+ "This format is unavailable for remix on the configured FFmpeg."
1485
+ );
1486
+ const metadata2 = this.data.version(file.source).metadata.media;
1487
+ let sourceInputs;
1488
+ let sourceDescriptors;
1489
+ let timeline;
1490
+ if (this.data.version(file.source).origin === "authored" && metadata2?.composition && metadata2.jobId) {
1491
+ const producer = this.data.get(metadata2.jobId);
1492
+ if (producer.typeId === "media.job" && producer.data.state === "succeeded" && sameFile(producer.data.result, file)) {
1493
+ sourceInputs = audioQuery.parse({ inputs: producer.data.snapshot.audio.inputs }).inputs;
1494
+ sourceDescriptors = z3.array(editDescriptor).parse(producer.data.snapshot.descriptors);
1495
+ timeline = timelineSchema.parse(metadata2.composition.timeline);
1496
+ if (timeline.length !== sourceInputs.length || sourceDescriptors.length !== timeline.length)
1497
+ mediaError(
1498
+ "INVALID_REFERENCE",
1499
+ "The saved composition does not match the accepted sequence."
1500
+ );
1501
+ }
1502
+ }
1503
+ if (remix.basis === "sources" && !sourceInputs)
1504
+ mediaError(
1505
+ "MIX_SOURCES_UNAVAILABLE",
1506
+ "Use master mode for a film without a saved source composition."
1507
+ );
1508
+ const selected = sourceInputs ?? [{ kind: "source", file }];
1509
+ const descriptors = sourceDescriptors ?? [copy.descriptor];
1510
+ const binding = identifySequence(this.data, selected, descriptors);
1511
+ const current = readMix(this.data, binding.sequenceKey);
1512
+ if (current.revision !== remix.expectedMixRevision)
1513
+ mediaError("REVISION_CONFLICT", "The current mix revision has changed.");
1514
+ let mix = remix.mix;
1515
+ if (remix.basis === "master" && sourceInputs) {
1516
+ if (mix.originals?.some((o) => o.inputIndex !== 0) || (mix.originals?.length ?? 0) > 1)
1517
+ mediaError("INVALID_MIX", "Master mode has one original audio stream.");
1518
+ const original = mix.originals?.[0], gain2 = original ? original.gainDb : mix.originalGainDb;
1519
+ let id = "master";
1520
+ while (mix.tracks.some((t) => t.id === id)) id += "-";
1521
+ const role = original?.role === "dialogue" ? "narration" : original?.role === "ambience" ? "music" : "sfx";
1522
+ mix = audioMix.parse({
1523
+ ...mix,
1524
+ originalGainDb: null,
1525
+ originals: [],
1526
+ tracks: [
1527
+ ...copy.descriptor.metadata.hasAudio && gain2 !== null ? [{ id, role, file, atMs: 0, gainDb: gain2 ?? 0 }] : [],
1528
+ ...mix.tracks
1529
+ ]
1530
+ });
1531
+ }
1532
+ const picture = await this.videos.timedInput(copy.descriptor, tools, true);
1533
+ const duration = timeline ? Math.min(
1534
+ picture.timing.duration,
1535
+ timeline.reduce((sum, t) => sum + t.duration, 0)
1536
+ ) : picture.timing.duration;
1537
+ const tracks = await this.inspect(mix, descriptors, tools, duration);
1538
+ return {
1539
+ descriptors,
1540
+ audio: {
1541
+ ...binding,
1542
+ revision: current.revision,
1543
+ mix,
1544
+ tracks,
1545
+ copy,
1546
+ ...timeline ? { timeline } : {}
1547
+ }
1548
+ };
1549
+ }
1550
+ async set(input, call) {
1551
+ if (!call.requestKey || call.requestKey.length > 128)
1552
+ mediaError("INVALID_REQUEST_KEY", "Supply a stable write request key.");
1553
+ const op = "media.sequence.audio.set";
1554
+ const replay = this.data.receipt(op, input, call);
1555
+ if (replay) return replay.result;
1556
+ requireWritable(this.data);
1557
+ const binding = await this.binding(input.inputs);
1558
+ if (input.mix) {
1559
+ const descriptors = await this.descriptors(input.inputs, true);
1560
+ await this.inspect(input.mix, descriptors, await this.videos.tools());
1561
+ }
1562
+ return this.data.operation(op, input, call, (t) => {
1563
+ requireWritable(this.data);
1564
+ return writeMix(t, binding, input.expectedRevision, input.mix);
1565
+ });
1566
+ }
1567
+ };
1568
+
1569
+ // packages/media-tools/src/audio-preview.ts
1570
+ import { randomUUID as randomUUID3 } from "crypto";
1571
+ import { readFile as readFile2, rm as rm3 } from "fs/promises";
1572
+ import { join as join3 } from "path";
1573
+ import { Readable } from "stream";
1574
+
1575
+ // packages/media-tools/src/mix-render.ts
1576
+ import { rename as rename2, rm as rm2 } from "fs/promises";
1577
+ var seconds2 = (value) => Number(value.toFixed(9));
1578
+ function mixGraph(clips, mix, tracks, trackPaths, duration) {
1579
+ const args = ["-hide_banner", "-nostdin", "-y", "-copyts"];
1580
+ const paths = /* @__PURE__ */ new Map();
1581
+ const filters = [], voice = [], background = [], other = [];
1582
+ let count = 0;
1583
+ function place(path, origin, sourceLength, length, at2, channels, gain2, role, speed, fadeIn = 0, fadeOut = 0) {
1584
+ if (length <= 0)
1585
+ mediaError("INVALID_MIX_RANGE", "An audio item falls outside the rendered picture.");
1586
+ let index = paths.get(path);
1587
+ if (index === void 0) {
1588
+ index = paths.size;
1589
+ paths.set(path, index);
1590
+ args.push("-protocol_whitelist", "file,pipe", "-i", path);
1591
+ }
1592
+ const label = "part" + count++;
1593
+ const chain = [
1594
+ "[" + index + ":a:0]atrim=start=" + seconds2(origin) + ":end=" + seconds2(origin + sourceLength),
1595
+ "asetpts=PTS-(" + seconds2(origin) + ")/TB",
1596
+ "aresample=48000:async=1:first_pts=0",
1597
+ ...channels === 1 ? ["pan=stereo|c0=c0|c1=c0"] : [],
1598
+ "aformat=sample_fmts=fltp:channel_layouts=stereo",
1599
+ "apad=whole_dur=" + seconds2(sourceLength),
1600
+ "atrim=duration=" + seconds2(sourceLength),
1601
+ ...tempoFilters(speed),
1602
+ "apad=whole_dur=" + seconds2(length),
1603
+ "atrim=duration=" + seconds2(length),
1604
+ "volume=" + gain2 + "dB"
1605
+ ];
1606
+ if (fadeIn) chain.push("afade=t=in:d=" + seconds2(fadeIn));
1607
+ if (fadeOut)
1608
+ chain.push(
1609
+ "afade=t=out:st=" + seconds2(Math.max(0, length - fadeOut)) + ":d=" + seconds2(fadeOut)
1610
+ );
1611
+ chain.push("adelay=" + Math.round(at2 * 48e3) + "S:all=1");
1612
+ filters.push(chain.join(",") + "[" + label + "]");
1613
+ const bus = role === "dialogue" || role === "narration" ? voice : role === "music" || role === "ambience" ? background : other;
1614
+ bus.push("[" + label + "]");
1615
+ }
1616
+ let at = 0;
1617
+ for (const [index, { path, descriptor, timing }] of clips.entries()) {
1618
+ const original = mix.originals?.find((o) => o.inputIndex === index);
1619
+ const gain2 = original ? original.gainDb : mix.originalGainDb;
1620
+ if (descriptor.metadata.hasAudio && gain2 !== null)
1621
+ place(
1622
+ path,
1623
+ timing.start,
1624
+ timing.end - timing.start,
1625
+ timing.duration,
1626
+ at,
1627
+ descriptor.metadata.audioChannels,
1628
+ gain2 ?? 0,
1629
+ original?.role,
1630
+ descriptor.recipe.speed ?? 1
1631
+ );
1632
+ at += timing.duration;
1633
+ }
1634
+ for (const [index, track] of mix.tracks.entries()) {
1635
+ const info = tracks[index], start = (track.inMs ?? 0) / 1e3;
1636
+ const length = Math.min(
1637
+ (track.outMs ?? info.durationMs) / 1e3 - start,
1638
+ duration - track.atMs / 1e3
1639
+ );
1640
+ place(
1641
+ trackPaths[index],
1642
+ info.origin + start,
1643
+ length,
1644
+ length,
1645
+ track.atMs / 1e3,
1646
+ info.channels,
1647
+ track.gainDb ?? 0,
1648
+ track.role,
1649
+ 1,
1650
+ (track.fadeInMs ?? 0) / 1e3,
1651
+ (track.fadeOutMs ?? 0) / 1e3
1652
+ );
1653
+ }
1654
+ if (!count) return null;
1655
+ function sum(labels, name) {
898
1656
  filters.push(
899
- labels.join("") + `concat=n=${inputs.length}:v=1:a=${audible ? 1 : 0}[video]${audible ? "[audio]" : ""}`
1657
+ labels.join("") + (labels.length === 1 ? "anull" : "amix=inputs=" + labels.length + ":normalize=0") + "[" + name + "]"
900
1658
  );
901
1659
  }
902
- args.push("-filter_complex", filters.join(";"), "-map", inputs.length > 1 ? "[video]" : "[v0]");
903
- if (audible)
904
- args.push("-map", inputs.length > 1 ? "[audio]" : "[a0]", "-c:a", "aac", "-b:a", "192k");
905
- else args.push("-an");
906
- args.push(
907
- "-c:v",
908
- "libx264",
909
- "-crf",
910
- "18",
911
- "-preset",
912
- "medium",
913
- "-threads",
914
- "4",
915
- "-pix_fmt",
916
- "yuv420p",
917
- "-fps_mode",
918
- "passthrough",
919
- "-enc_time_base:v",
920
- "1:90000",
921
- "-video_track_timescale",
922
- "90000",
923
- "-color_primaries",
924
- "bt709",
925
- "-color_trc",
926
- "bt709",
927
- "-colorspace",
928
- "bt709",
929
- "-metadata:s:v:0",
930
- "rotate=0",
931
- "-movflags",
932
- "+faststart",
933
- "-progress",
934
- "pipe:1",
935
- "-stats_period",
936
- "0.5",
937
- output
1660
+ if (mix.ducking !== false && voice.length && background.length) {
1661
+ sum(voice, "voice");
1662
+ sum(background, "background");
1663
+ filters.push("[voice]apad=whole_dur=" + seconds2(duration) + ",asplit=2[speech][key]");
1664
+ filters.push(
1665
+ "[background][key]sidechaincompress=threshold=0.025:ratio=6:attack=20:release=250[ducked]"
1666
+ );
1667
+ sum(["[speech]", "[ducked]", ...other], "sum");
1668
+ } else sum([...voice, ...background, ...other], "sum");
1669
+ filters.push(
1670
+ "[sum]apad=whole_dur=" + seconds2(duration) + ",atrim=duration=" + seconds2(duration) + "[mix]"
1671
+ );
1672
+ return { args, filters };
1673
+ }
1674
+ var norm = "loudnorm=I=-16:LRA=11:TP=-1.5";
1675
+ function levels(stderr) {
1676
+ const values = /\{\s*"input_i"[^}]+\}/.exec(stderr);
1677
+ if (!values)
1678
+ mediaError("LOUDNESS_MEASUREMENT_FAILED", "FFmpeg did not return a loudness report.");
1679
+ return JSON.parse(values[0]);
1680
+ }
1681
+ async function measureOutput(native, ffmpeg, path, options) {
1682
+ const result = await native.run(
1683
+ ffmpeg,
1684
+ [
1685
+ "-hide_banner",
1686
+ "-nostdin",
1687
+ "-i",
1688
+ path,
1689
+ "-vn",
1690
+ "-af",
1691
+ norm + ":print_format=json",
1692
+ "-f",
1693
+ "null",
1694
+ "-"
1695
+ ],
1696
+ options
938
1697
  );
1698
+ const m = levels(result.stderr);
939
1699
  return {
940
- args,
941
- audible,
942
- audioSampleRate,
943
- expectedFrames: inputs.flatMap((input, index) => {
944
- const offset = inputs.slice(0, index).reduce((n, i) => n + i.timing.duration, 0);
945
- return input.timing.frames.map((t) => t + offset);
946
- }),
947
- duration: inputs.reduce((n, i) => n + i.timing.duration, 0),
948
- tolerance: inputs.reduce((n, i) => n + i.timing.tolerance, 0)
1700
+ integratedLUFS: Number.isFinite(Number(m.input_i)) ? Number(m.input_i) : null,
1701
+ truePeakDbTP: Number.isFinite(Number(m.input_tp)) ? Number(m.input_tp) : null
949
1702
  };
950
1703
  }
951
- function validateFrameTiming(actual, timings) {
952
- if (actual.length !== timings.reduce((total, timing) => total + timing.frames.length, 0))
953
- mediaError("OUTPUT_TIMING_MISMATCH", "The output frame count changed.");
954
- let index = 0, expectedStart = 0, boundaryTolerance = 0;
955
- for (const timing of timings) {
956
- const first = actual[index];
957
- if (Math.abs(first - expectedStart) > boundaryTolerance + 1e-3)
1704
+ async function renderAudio(native, ffmpeg, clips, audio, paths, duration, output, options) {
1705
+ const graph = mixGraph(clips, audio.mix, audio.tracks, paths, duration);
1706
+ if (!graph) return null;
1707
+ let finish = "anull";
1708
+ if (audio.mix.loudness !== "off") {
1709
+ const measurement = await native.run(
1710
+ ffmpeg,
1711
+ [
1712
+ ...graph.args,
1713
+ "-filter_complex",
1714
+ [...graph.filters, "[mix]" + norm + ":print_format=json[out]"].join(";"),
1715
+ "-map",
1716
+ "[out]",
1717
+ "-f",
1718
+ "null",
1719
+ "-"
1720
+ ],
1721
+ options
1722
+ );
1723
+ const m = levels(measurement.stderr);
1724
+ const within = (value, min, max) => Number(value) >= min && Number(value) <= max;
1725
+ if (within(m.input_i, -99, 0) && within(m.input_tp, -99, 99) && within(m.input_lra, 0, 99) && within(m.input_thresh, -99, 0) && within(m.target_offset, -99, 99)) {
1726
+ finish = norm + ":measured_I=" + Number(m.input_i) + ":measured_TP=" + Number(m.input_tp) + ":measured_LRA=" + Number(m.input_lra) + ":measured_thresh=" + Number(m.input_thresh) + ":offset=" + Number(m.target_offset) + ":linear=true";
1727
+ } else if (m.input_tp === "-inf") return null;
1728
+ else if (Number.isFinite(Number(m.input_i))) finish = norm;
1729
+ else finish = "alimiter=limit=0.84:level=0:latency=1";
1730
+ }
1731
+ await native.run(
1732
+ ffmpeg,
1733
+ [
1734
+ ...graph.args,
1735
+ "-filter_complex",
1736
+ // loudnorm can leave its output layout unspecified on FFmpeg 5.1.
1737
+ [
1738
+ ...graph.filters,
1739
+ "[mix]" + finish + ",aformat=sample_rates=48000:channel_layouts=stereo[out]"
1740
+ ].join(";"),
1741
+ "-map",
1742
+ "[out]",
1743
+ "-c:a",
1744
+ "pcm_f32le",
1745
+ output
1746
+ ],
1747
+ { ...options, outputPath: output, maxOutputBytes: 240 * 1024 * 1024 }
1748
+ );
1749
+ return output;
1750
+ }
1751
+ function copyPicture(path, start, mixed, profile, output, gainDb = 0) {
1752
+ return [
1753
+ "-hide_banner",
1754
+ "-nostdin",
1755
+ "-y",
1756
+ "-copyts",
1757
+ ...path ? ["-protocol_whitelist", "file,pipe", "-i", path] : [],
1758
+ ...mixed ? ["-itsoffset", String(start), "-protocol_whitelist", "file,pipe", "-i", mixed] : [],
1759
+ ...path ? ["-map", "0:v:0", "-c:v", "copy"] : ["-vn"],
1760
+ ...mixed ? [
1761
+ "-map",
1762
+ path ? "1:a:0" : "0:a:0",
1763
+ ...gainDb ? ["-af", "volume=" + gainDb + "dB"] : [],
1764
+ "-c:a",
1765
+ profile.audio === "opus" ? "libopus" : "aac",
1766
+ "-b:a",
1767
+ "192k"
1768
+ ] : ["-an"],
1769
+ "-avoid_negative_ts",
1770
+ "disabled",
1771
+ ...profile.container === "mp4" ? ["-movflags", "+faststart"] : [],
1772
+ output
1773
+ ];
1774
+ }
1775
+ async function verifyMixLoudness(native, ffmpeg, output, pcm, start, profile, options, audioOnly = false) {
1776
+ let measured = await measureOutput(native, ffmpeg, output, options);
1777
+ if (measured.truePeakDbTP !== null) {
1778
+ const peakRoom = -1.7 - measured.truePeakDbTP;
1779
+ const delta = measured.integratedLUFS === null ? 0 : -16 - measured.integratedLUFS;
1780
+ const gain2 = measured.truePeakDbTP > -1.5 || Math.abs(delta) > 1 ? Math.min(peakRoom, delta) : 0;
1781
+ if (Math.abs(gain2) > 0.01) {
1782
+ const corrected = output + ".level." + profile.extension;
1783
+ try {
1784
+ await native.run(
1785
+ ffmpeg,
1786
+ copyPicture(audioOnly ? null : output, start, pcm, profile, corrected, gain2),
1787
+ {
1788
+ ...options,
1789
+ outputPath: corrected,
1790
+ maxOutputBytes: 2147483648
1791
+ }
1792
+ );
1793
+ measured = await measureOutput(native, ffmpeg, corrected, options);
1794
+ await rename2(corrected, output);
1795
+ } finally {
1796
+ if (!native.recoveryRequired) await rm2(corrected, { force: true });
1797
+ }
1798
+ }
1799
+ if (measured.truePeakDbTP !== null && measured.truePeakDbTP > -1.5)
958
1800
  mediaError(
959
- "OUTPUT_TIMING_MISMATCH",
960
- "The output segment boundary moved beyond the source frame allowance."
1801
+ "OUTPUT_LOUDNESS_MISMATCH",
1802
+ "The encoded mix exceeded the true peak ceiling after correction."
961
1803
  );
962
- for (let offset = 0; offset < timing.frames.length; offset++)
963
- if (Math.abs(actual[index + offset] - first - timing.frames[offset]) > 1e-3)
964
- mediaError("OUTPUT_TIMING_MISMATCH", "The output changed timing inside a source segment.");
965
- index += timing.frames.length;
966
- expectedStart += timing.duration;
967
- boundaryTolerance += timing.tolerance;
968
1804
  }
1805
+ const status = measured.integratedLUFS === null ? "unmeasurable" : Math.abs(measured.integratedLUFS + 16) > 1 ? "peak-limited" : "measured";
1806
+ return { ...measured, status };
969
1807
  }
970
1808
 
1809
+ // packages/media-tools/src/audio-preview.ts
1810
+ var AudioPreviews = class {
1811
+ constructor(videos, transfers) {
1812
+ this.videos = videos;
1813
+ this.transfers = transfers;
1814
+ this.mixes = new SequenceAudio(videos);
1815
+ }
1816
+ videos;
1817
+ transfers;
1818
+ mixes;
1819
+ cache = /* @__PURE__ */ new Map();
1820
+ pending;
1821
+ failure;
1822
+ abort = new AbortController();
1823
+ async read(inputs, knownRevision) {
1824
+ const { mix, sequenceKey, revision } = await this.mixes.get(inputs);
1825
+ if (knownRevision === revision) return { state: "unchanged" };
1826
+ if (!mix) return { state: "original", revision };
1827
+ const key = sequenceKey + ":" + revision;
1828
+ const sound = this.cache.get(key);
1829
+ if (sound) {
1830
+ const file = sound.bytes ? await this.transfers.exposeStream(
1831
+ Readable.toWeb(Readable.from([sound.bytes])),
1832
+ { name: "sequence-preview.m4a", mediaType: "audio/mp4", sizeBytes: sound.bytes.length }
1833
+ ) : null;
1834
+ return { state: "ready", revision, file, segments: sound.segments };
1835
+ }
1836
+ if (this.failure?.key === key) {
1837
+ const { error } = this.failure;
1838
+ this.failure = void 0;
1839
+ throw error;
1840
+ }
1841
+ if (!this.pending) {
1842
+ this.abort.signal.throwIfAborted();
1843
+ this.pending = this.render(inputs, mix, sequenceKey, revision).then(
1844
+ (sound2) => {
1845
+ if (this.cache.size >= 2) this.cache.delete(this.cache.keys().next().value);
1846
+ this.cache.set(key, sound2);
1847
+ },
1848
+ (error) => {
1849
+ this.failure = { key, error };
1850
+ }
1851
+ ).finally(() => {
1852
+ this.pending = void 0;
1853
+ });
1854
+ }
1855
+ return { state: "preparing" };
1856
+ }
1857
+ async render(inputs, mix, sequenceKey, revision) {
1858
+ const videos = this.videos;
1859
+ if (videos.native.recoveryRequired)
1860
+ mediaError("RECOVERY_REQUIRED", "Restart the preview after the previous worker has closed.");
1861
+ const tools = await videos.tools();
1862
+ const descriptors = await this.mixes.descriptors(inputs);
1863
+ const clips = [];
1864
+ for (const descriptor of descriptors)
1865
+ clips.push(await videos.timedInput(descriptor, tools, false));
1866
+ const duration = clips.reduce((sum, clip) => sum + clip.timing.duration, 0);
1867
+ const tracks = await this.mixes.inspect(mix, descriptors, tools, duration);
1868
+ const paths = [];
1869
+ for (const { file } of tracks)
1870
+ paths.push((await videos.data.location(file.source, file.fileId)).absolutePath);
1871
+ const token = randomUUID3(), directory = join3(videos.runtimeRoot, "probes", token);
1872
+ const options = {
1873
+ directory,
1874
+ jobId: "probe",
1875
+ executionToken: token,
1876
+ signal: this.abort.signal,
1877
+ timeoutMs: Math.min(18e5, Math.max(12e4, duration * 1e4))
1878
+ };
1879
+ const segments = clips.map(({ timing, descriptor }) => ({
1880
+ startMs: (timing.start - descriptor.metadata.startTime) * 1e3,
1881
+ durationMs: timing.duration * 1e3
1882
+ }));
1883
+ try {
1884
+ const pcm = await renderAudio(
1885
+ videos.native,
1886
+ tools.ffmpeg,
1887
+ clips,
1888
+ { inputs, mix, tracks, sequenceKey, revision },
1889
+ paths,
1890
+ duration,
1891
+ join3(directory, "mix.wav"),
1892
+ options
1893
+ );
1894
+ if (!pcm) return { bytes: null, segments };
1895
+ const output = join3(directory, "sound.m4a");
1896
+ const profile = exportProfiles.h264;
1897
+ await videos.native.run(tools.ffmpeg, copyPicture(null, 0, pcm, profile, output), {
1898
+ ...options,
1899
+ outputPath: output,
1900
+ maxOutputBytes: 32 * 1024 ** 2
1901
+ });
1902
+ if (mix.loudness !== "off")
1903
+ await verifyMixLoudness(
1904
+ videos.native,
1905
+ tools.ffmpeg,
1906
+ output,
1907
+ pcm,
1908
+ 0,
1909
+ profile,
1910
+ options,
1911
+ true
1912
+ );
1913
+ return { bytes: await readFile2(output), segments };
1914
+ } finally {
1915
+ if (!videos.native.recoveryRequired) await rm3(directory, { recursive: true, force: true });
1916
+ }
1917
+ }
1918
+ async dispose() {
1919
+ this.abort.abort();
1920
+ await this.pending;
1921
+ await this.videos.native.dispose();
1922
+ this.cache.clear();
1923
+ }
1924
+ };
1925
+
971
1926
  // packages/media-tools/src/jobs.ts
972
- var toolsSchema = z3.object({
973
- ffmpeg: z3.string(),
974
- ffprobe: z3.string(),
975
- ffmpegVersion: z3.string(),
976
- ffprobeVersion: z3.string(),
977
- profileVersion: z3.literal(1)
1927
+ import { randomUUID as randomUUID4, createHash as createHash2 } from "crypto";
1928
+ import { createReadStream } from "fs";
1929
+ import { mkdir as mkdir2, rm as rm4, stat, statfs } from "fs/promises";
1930
+ import { join as join4 } from "path";
1931
+ import { z as z4 } from "vivix-studio/sdk/shared";
1932
+ var toolsSchema = z4.object({
1933
+ ffmpeg: z4.string(),
1934
+ ffprobe: z4.string(),
1935
+ ffmpegVersion: z4.string(),
1936
+ ffprobeVersion: z4.string(),
1937
+ profileVersion: z4.literal(1),
1938
+ exportFormats: z4.array(exportFormat).optional(),
1939
+ audioMix: z4.object({ ducking: z4.boolean(), loudness: z4.boolean() }).optional()
978
1940
  }).strict();
979
- var snapshot = z3.object({
1941
+ var snapshot = z4.object({
980
1942
  request: mediaRequest,
981
- descriptors: z3.array(editDescriptor).min(1).max(64),
1943
+ audio: audioSnapshot.optional(),
1944
+ descriptors: z4.array(editDescriptor).min(1).max(64),
982
1945
  tools: toolsSchema
983
1946
  }).strict();
984
- var jobData = z3.object({
985
- state: z3.enum(jobStates),
986
- kind: z3.enum(["video", "sequence"]),
987
- namespace: z3.string(),
1947
+ var jobData = z4.object({
1948
+ state: z4.enum(jobStates),
1949
+ kind: z4.enum(["video", "sequence"]),
1950
+ namespace: z4.string(),
988
1951
  snapshot,
989
- progress: z3.number().min(0).max(1).nullable(),
990
- cancelRequested: z3.boolean(),
1952
+ progress: z4.number().min(0).max(1).nullable(),
1953
+ cancelRequested: z4.boolean(),
991
1954
  result: videoFileRef.nullable(),
992
- error: z3.object({ code: z3.string(), message: z3.string() }).strict().nullable(),
993
- executionToken: z3.uuid().nullable(),
994
- publicationKey: z3.string().nullable(),
995
- stagingFileId: z3.uuid().nullable(),
996
- cleanupPending: z3.boolean()
1955
+ error: z4.object({ code: z4.string(), message: z4.string() }).strict().nullable(),
1956
+ executionToken: z4.uuid().nullable(),
1957
+ publicationKey: z4.string().nullable(),
1958
+ stagingFileId: z4.uuid().nullable(),
1959
+ cleanupPending: z4.boolean()
997
1960
  }).strict();
998
1961
  var jobType = {
999
1962
  typeId: "media.job",
@@ -1031,6 +1994,7 @@ var Jobs = class {
1031
1994
  this.publisher = publisher;
1032
1995
  this.runtimeRoot = runtimeRoot;
1033
1996
  this.namespace = namespace;
1997
+ this.mixes = new SequenceAudio(videos);
1034
1998
  }
1035
1999
  data;
1036
2000
  videos;
@@ -1044,6 +2008,7 @@ var Jobs = class {
1044
2008
  blocked = false;
1045
2009
  failure;
1046
2010
  submissions = /* @__PURE__ */ new Map();
2011
+ mixes;
1047
2012
  call(key) {
1048
2013
  return { scope: this.data.scope, actor: { kind: "local-user", id: "local" }, requestKey: key };
1049
2014
  }
@@ -1147,11 +2112,13 @@ var Jobs = class {
1147
2112
  }
1148
2113
  async accept(request, call) {
1149
2114
  requireWritable(this.data);
2115
+ if (this.active && terminal(this.record(this.active.id).data.state)) await this.active.finished;
1150
2116
  if (this.disposed || this.blocked || this.native.recoveryRequired)
1151
2117
  mediaError("RECOVERY_REQUIRED", "Media execution is stopped or waiting for safe cleanup.");
1152
2118
  if (this.rows().filter((row) => !terminal(row.data.state)).length >= 50)
1153
2119
  mediaError("MEDIA_QUEUE_FULL", "The project already has 50 unfinished media tasks.");
1154
- let descriptors, tools;
2120
+ let descriptors, tools, audio;
2121
+ const mixes = this.mixes;
1155
2122
  if (request.input.retryOfJobId) {
1156
2123
  const old = this.record(request.input.retryOfJobId), original = old.data.snapshot.request;
1157
2124
  if (!["failed", "canceled", "interrupted"].includes(old.data.state))
@@ -1169,9 +2136,12 @@ var Jobs = class {
1169
2136
  "RETRY_INPUT_CONFLICT",
1170
2137
  "A retry must keep the original ordered inputs, output name and configuration."
1171
2138
  );
2139
+ audio = old.data.snapshot.audio ? audioSnapshot.parse(old.data.snapshot.audio) : void 0;
1172
2140
  descriptors = clone(old.data.snapshot.descriptors);
1173
2141
  tools = clone(old.data.snapshot.tools);
1174
- for (const descriptor of descriptors) await this.videos.restoreMetadata(descriptor);
2142
+ if (!audio?.timeline)
2143
+ for (const descriptor of descriptors)
2144
+ await this.videos.restoreMetadata(descriptor, Boolean(audio?.copy));
1175
2145
  for (const executable2 of [tools.ffmpeg, tools.ffprobe]) {
1176
2146
  try {
1177
2147
  const { access: access2 } = await import("fs/promises");
@@ -1185,21 +2155,58 @@ var Jobs = class {
1185
2155
  }
1186
2156
  } else {
1187
2157
  const inputs = request.operation === "video.process" ? [request.input.input] : request.input.inputs;
1188
- descriptors = [];
1189
- for (const input of inputs) descriptors.push(await this.videos.descriptor(input));
1190
2158
  tools = await this.videos.tools();
2159
+ if (request.operation === "video.process" && request.input.remix) {
2160
+ if (!this.publisher.audioMixVersion)
2161
+ mediaError("ASSET_SERVICE_UNAVAILABLE", "The publisher does not support film remix.");
2162
+ ({ descriptors, audio } = await mixes.prepareRemix(request.input, tools));
2163
+ } else {
2164
+ descriptors = await mixes.descriptors(inputs);
2165
+ if (request.operation === "sequence.process" && !this.publisher.audioMixVersion && request.input.settings?.audio !== false) {
2166
+ const binding = identifySequence(this.data, inputs, descriptors);
2167
+ if (readMix(this.data, binding.sequenceKey).mix)
2168
+ mediaError(
2169
+ "ASSET_SERVICE_UNAVAILABLE",
2170
+ "Upgrade the publisher to export the saved sequence mix."
2171
+ );
2172
+ }
2173
+ if (request.operation === "sequence.process" && this.publisher.audioMixVersion) {
2174
+ const identity = identifySequence(this.data, inputs, descriptors);
2175
+ do {
2176
+ const current = readMix(this.data, identity.sequenceKey);
2177
+ const mix = request.input.settings?.audio === false ? null : current.mix;
2178
+ const tracks = mix ? await mixes.inspect(mix, descriptors, tools) : [];
2179
+ audio = { ...identity, revision: current.revision, mix, tracks };
2180
+ } while (readMix(this.data, identity.sequenceKey).revision !== audio.revision);
2181
+ }
2182
+ }
1191
2183
  }
2184
+ if (descriptors.reduce((total, d) => total + recipeDurationMs(d.recipe), 0) > 6e5)
2185
+ mediaError("MEDIA_LIMIT_EXCEEDED", "The edited duration exceeds 600 seconds.");
1192
2186
  if (request.operation === "sequence.process") {
1193
2187
  const canvas2 = request.input.canvas, bytes = /* @__PURE__ */ new Map();
2188
+ const settings = request.input.settings;
2189
+ if (settings) {
2190
+ if (!(tools.exportFormats ?? ["h264"]).includes(settings.format))
2191
+ mediaError(
2192
+ "TOOL_UNSUPPORTED",
2193
+ "The configured FFmpeg cannot export the selected format."
2194
+ );
2195
+ if (!exportDimensions(canvas2, settings.aspect, settings.resolution))
2196
+ mediaError(
2197
+ "MEDIA_LIMIT_EXCEEDED",
2198
+ "The selected aspect ratio and resolution exceed 3840 by 2160."
2199
+ );
2200
+ }
1194
2201
  let duration = 0;
1195
2202
  for (const d of descriptors) {
1196
2203
  const rect = d.geometry.pixelRect;
1197
- if (rect.width * canvas2.height !== rect.height * canvas2.width)
2204
+ if (!settings && rect.width * canvas2.height !== rect.height * canvas2.width)
1198
2205
  mediaError(
1199
2206
  "SEQUENCE_GEOMETRY_MISMATCH",
1200
2207
  "Every selected crop must have exactly the project output aspect ratio."
1201
2208
  );
1202
- duration += d.recipe.trim.outMs - d.recipe.trim.inMs;
2209
+ duration += recipeDurationMs(d.recipe);
1203
2210
  bytes.set(d.metadata.sha256, d.metadata.sizeBytes);
1204
2211
  }
1205
2212
  if (duration > 6e5 || [...bytes.values()].reduce((a, b) => a + b, 0) > 2147483648)
@@ -1208,11 +2215,23 @@ var Jobs = class {
1208
2215
  "The sequence exceeds 600 seconds or 2 GiB of distinct source media."
1209
2216
  );
1210
2217
  }
1211
- const id = randomUUID3(), data = {
2218
+ if (audio?.copy) {
2219
+ const files = [
2220
+ ...descriptors.map((d) => d.metadata),
2221
+ ...audio.tracks,
2222
+ audio.copy.descriptor.metadata
2223
+ ];
2224
+ if ([...new Map(files.map((f) => [f.sha256, f.sizeBytes])).values()].reduce(
2225
+ (a, b) => a + b,
2226
+ 0
2227
+ ) > 2147483648)
2228
+ mediaError("MEDIA_LIMIT_EXCEEDED", "Remix exceeds 2 GiB of distinct source files.");
2229
+ }
2230
+ const id = randomUUID4(), data = {
1212
2231
  state: "queued",
1213
2232
  kind: request.operation === "video.process" ? "video" : "sequence",
1214
2233
  namespace: this.namespace,
1215
- snapshot: { request, descriptors, tools },
2234
+ snapshot: { request, descriptors, tools, ...audio ? { audio } : {} },
1216
2235
  progress: null,
1217
2236
  cancelRequested: false,
1218
2237
  result: null,
@@ -1228,7 +2247,14 @@ var Jobs = class {
1228
2247
  call,
1229
2248
  (t) => {
1230
2249
  requireWritable(this.data);
2250
+ if (audio && !request.input.retryOfJobId && readMix(t, audio.sequenceKey).revision !== audio.revision)
2251
+ mediaError("REVISION_CONFLICT", "The mix changed during submission.");
1231
2252
  t.create("media.job", data, {}, id);
2253
+ for (const source of [
2254
+ ...audio?.tracks.map((t2) => t2.file.source) ?? [],
2255
+ ...audio?.copy ? [audio.copy.descriptor.file.source] : []
2256
+ ])
2257
+ t.relation(id, null, source, "reference");
1232
2258
  const protectedRefs = /* @__PURE__ */ new Set();
1233
2259
  for (const [index, descriptor] of descriptors.entries()) {
1234
2260
  const source = descriptor.file.source, sourceKey = canonical(source);
@@ -1236,7 +2262,7 @@ var Jobs = class {
1236
2262
  t.relation(id, null, source, "reference");
1237
2263
  protectedRefs.add(sourceKey);
1238
2264
  }
1239
- const selected = request.operation === "video.process" ? request.input.input : request.input.inputs[index];
2265
+ const selected = audio ? audio.inputs[index] : request.operation === "video.process" ? request.input.input : request.input.inputs[index];
1240
2266
  if (selected.kind === "edit" && !protectedRefs.has(canonical(selected.editRef))) {
1241
2267
  t.relation(id, null, selected.editRef, "reference");
1242
2268
  protectedRefs.add(canonical(selected.editRef));
@@ -1333,7 +2359,7 @@ var Jobs = class {
1333
2359
  this.videos.processing = this.blocked;
1334
2360
  }
1335
2361
  directory(id, token) {
1336
- return join3(this.runtimeRoot, "attempts", z3.uuid().parse(id), z3.uuid().parse(token));
2362
+ return join4(this.runtimeRoot, "attempts", z4.uuid().parse(id), z4.uuid().parse(token));
1337
2363
  }
1338
2364
  wake() {
1339
2365
  if (this.pumping || this.disposed || this.blocked || this.native.recoveryRequired) return;
@@ -1354,13 +2380,20 @@ var Jobs = class {
1354
2380
  (value) => value.data.state === "queued" && !value.data.cancelRequested
1355
2381
  );
1356
2382
  if (!row) return;
1357
- await this.execute(row.objectId);
2383
+ const abort = new AbortController();
2384
+ const finished = this.execute(row.objectId, abort);
2385
+ this.active = { id: row.objectId, abort, finished };
2386
+ try {
2387
+ await finished;
2388
+ } finally {
2389
+ this.active = void 0;
2390
+ }
1358
2391
  }
1359
2392
  }
1360
- async execute(id) {
1361
- const token = randomUUID3(), abort = new AbortController();
1362
- this.active = { id, abort };
2393
+ async execute(id, abort) {
2394
+ const token = randomUUID4();
1363
2395
  this.videos.processing = true;
2396
+ let audioPath;
1364
2397
  let output, confirmed = true;
1365
2398
  try {
1366
2399
  const initial = this.record(id);
@@ -1377,7 +2410,14 @@ var Jobs = class {
1377
2410
  );
1378
2411
  const d = row.data, directory = this.directory(id, token);
1379
2412
  await mkdir2(directory, { recursive: true });
1380
- output = join3(directory, "output.mp4");
2413
+ const sequence = d.snapshot.request.operation === "sequence.process" ? d.snapshot.request.input : void 0;
2414
+ const settings = sequence?.settings;
2415
+ const targetCanvas = sequence && (settings ? exportDimensions(sequence.canvas, settings.aspect, settings.resolution) : sequence.canvas);
2416
+ if (targetCanvas === null)
2417
+ mediaError("MEDIA_LIMIT_EXCEEDED", "The selected output size is unavailable.");
2418
+ const audio = d.snapshot.audio, copy = audio?.copy;
2419
+ const profile = exportProfiles[copy?.format ?? settings?.format ?? "h264"];
2420
+ output = join4(directory, `output.${profile.extension}`);
1381
2421
  const space = await statfs(directory);
1382
2422
  if (Number(space.bavail) * Number(space.bsize) < 4.5 * 1024 ** 3)
1383
2423
  mediaError(
@@ -1386,40 +2426,58 @@ var Jobs = class {
1386
2426
  );
1387
2427
  const commandOptions = { directory, jobId: id, executionToken: token, signal: abort.signal };
1388
2428
  await this.videos.verifyTools(d.snapshot.tools, commandOptions);
1389
- const inputs = [], frameCache = /* @__PURE__ */ new Map();
1390
- for (const descriptor of d.snapshot.descriptors) {
1391
- const location = await this.videos.restoreMetadata(descriptor);
1392
- let frames = frameCache.get(descriptor.metadata.sha256);
1393
- if (!frames) {
1394
- const result = await this.native.run(
1395
- d.snapshot.tools.ffprobe,
1396
- [
1397
- "-v",
1398
- "error",
1399
- "-select_streams",
1400
- "v:0",
1401
- "-show_entries",
1402
- "frame=best_effort_timestamp_time",
1403
- "-of",
1404
- "csv=p=0",
1405
- location.absolutePath
1406
- ],
1407
- { ...commandOptions, timeoutMs: 15e3 }
1408
- );
1409
- frames = frameTimes(result.stdout);
1410
- frameCache.set(descriptor.metadata.sha256, frames);
2429
+ const inputs = [];
2430
+ const timedInput = (descriptor) => this.videos.timedInput(descriptor, d.snapshot.tools, Boolean(copy), commandOptions);
2431
+ for (const [index, descriptor] of d.snapshot.descriptors.entries()) {
2432
+ if (audio?.timeline && audio.mix) {
2433
+ const override = audio.mix.originals?.find((o) => o.inputIndex === index);
2434
+ const gain2 = override ? override.gainDb : audio.mix.originalGainDb;
2435
+ const path = descriptor.metadata.hasAudio && gain2 !== null ? (await this.videos.restoreMetadata(descriptor, true)).absolutePath : "";
2436
+ inputs.push({
2437
+ descriptor,
2438
+ path,
2439
+ timing: { ...audio.timeline[index], frames: [], tolerance: 0 }
2440
+ });
2441
+ } else inputs.push(await timedInput(descriptor));
2442
+ }
2443
+ const picture = copy ? await timedInput(copy.descriptor) : void 0;
2444
+ const duration = picture?.timing.duration ?? inputs.reduce((n, i) => n + i.timing.duration, 0);
2445
+ const mixOptions = {
2446
+ ...commandOptions,
2447
+ timeoutMs: Math.min(18e5, Math.max(12e4, duration * 1e4))
2448
+ };
2449
+ let mixed;
2450
+ if (audio?.mix) {
2451
+ const paths = [];
2452
+ for (const track of audio.tracks) {
2453
+ const file = fixedAudio(this.data, track.file, true);
2454
+ if (file.sha256 !== track.sha256 || file.sizeBytes !== track.sizeBytes)
2455
+ mediaError(
2456
+ "SOURCE_SNAPSHOT_MISMATCH",
2457
+ "A fixed audio source no longer matches its snapshot."
2458
+ );
2459
+ paths.push((await this.data.location(track.file.source, track.file.fileId)).absolutePath);
1411
2460
  }
1412
- inputs.push({
1413
- descriptor,
1414
- path: location.absolutePath,
1415
- timing: segmentTiming(descriptor, frames)
1416
- });
2461
+ audioPath = join4(directory, "mixed.wav");
2462
+ mixed = await renderAudio(
2463
+ this.native,
2464
+ d.snapshot.tools.ffmpeg,
2465
+ inputs,
2466
+ audio,
2467
+ paths,
2468
+ duration,
2469
+ audioPath,
2470
+ mixOptions
2471
+ );
1417
2472
  }
1418
- const rendered = renderArguments(
1419
- inputs,
1420
- output,
1421
- d.snapshot.request.operation === "sequence.process" ? d.snapshot.request.input.canvas : void 0
1422
- );
2473
+ const rendered = picture ? {
2474
+ args: copyPicture(picture.path, picture.timing.start, mixed, profile, output),
2475
+ duration,
2476
+ tolerance: picture.timing.tolerance,
2477
+ frameRate: void 0,
2478
+ audible: Boolean(mixed),
2479
+ audioSampleRate: mixed ? 48e3 : null
2480
+ } : renderArguments(inputs, output, targetCanvas, settings, mixed);
1423
2481
  let progressBuffer = "", lastProgress = 0;
1424
2482
  await this.native.run(d.snapshot.tools.ffmpeg, rendered.args, {
1425
2483
  ...commandOptions,
@@ -1450,6 +2508,15 @@ var Jobs = class {
1450
2508
  });
1451
2509
  abort.signal.throwIfAborted();
1452
2510
  row = this.update(id, { state: "saving", progress: 0.99 });
2511
+ const loudness = audio?.mix && mixed && audio.mix.loudness !== "off" ? await verifyMixLoudness(
2512
+ this.native,
2513
+ d.snapshot.tools.ffmpeg,
2514
+ output,
2515
+ mixed,
2516
+ picture?.timing.start ?? 0,
2517
+ profile,
2518
+ mixOptions
2519
+ ) : null;
1453
2520
  const details = await this.native.run(
1454
2521
  d.snapshot.tools.ffprobe,
1455
2522
  ["-v", "error", "-show_format", "-show_streams", "-of", "json", output],
@@ -1460,12 +2527,17 @@ var Jobs = class {
1460
2527
  const hash = createHash2("sha256");
1461
2528
  for await (const chunk of createReadStream(output, { signal: abort.signal }))
1462
2529
  hash.update(chunk);
1463
- const checked = parseMetadata(JSON.parse(details.stdout), {
1464
- sizeBytes: size,
1465
- sha256: hash.digest("hex")
1466
- });
1467
- const target = d.snapshot.request.operation === "sequence.process" ? d.snapshot.request.input.canvas : inputs[0].descriptor.geometry.pixelRect;
1468
- if (checked.colorInterpretation !== "declared-bt709" || checked.displayWidth !== target.width || checked.displayHeight !== target.height || checked.hasAudio !== rendered.audible || checked.audioSampleRate !== rendered.audioSampleRate || Math.abs(checked.durationMs / 1e3 - rendered.duration) > rendered.tolerance + 1024 / 48e3)
2530
+ const checked = parseMetadata(
2531
+ JSON.parse(details.stdout),
2532
+ {
2533
+ sizeBytes: size,
2534
+ sha256: hash.digest("hex")
2535
+ },
2536
+ settings || copy ? profile : void 0
2537
+ );
2538
+ const target = targetCanvas ?? (picture ?? inputs[0]).descriptor.geometry.pixelRect;
2539
+ const fps = rendered.frameRate;
2540
+ if (!copy && checked.colorInterpretation !== "declared-bt709" || checked.displayWidth !== target.width || checked.displayHeight !== target.height || checked.hasAudio !== rendered.audible || checked.audioSampleRate !== rendered.audioSampleRate || Math.abs(checked.durationMs / 1e3 - rendered.duration) > rendered.tolerance + 1024 / 48e3 + (fps ? 1 / fps : 0))
1469
2541
  mediaError(
1470
2542
  "OUTPUT_VALIDATION_FAILED",
1471
2543
  "The output color declaration, geometry, duration or audio does not match the fixed recipe."
@@ -1488,11 +2560,27 @@ var Jobs = class {
1488
2560
  const actualFrames = frameTimes(frameResult.stdout);
1489
2561
  validateFrameTiming(
1490
2562
  actualFrames,
1491
- inputs.map((input) => input.timing)
2563
+ (picture ? [picture] : inputs).map((input) => input.timing),
2564
+ fps,
2565
+ profile.container === "webm"
1492
2566
  );
1493
2567
  const decoded = await this.native.run(
1494
2568
  d.snapshot.tools.ffmpeg,
1495
- ["-hide_banner", "-nostdin", "-v", "error", "-i", output, "-f", "null", "-"],
2569
+ [
2570
+ "-hide_banner",
2571
+ "-nostdin",
2572
+ "-v",
2573
+ "error",
2574
+ "-i",
2575
+ output,
2576
+ "-fps_mode",
2577
+ "passthrough",
2578
+ "-enc_time_base:v",
2579
+ "1:90000",
2580
+ "-f",
2581
+ "null",
2582
+ "-"
2583
+ ],
1496
2584
  {
1497
2585
  ...commandOptions,
1498
2586
  timeoutMs: Math.min(18e5, Math.max(12e4, rendered.duration * 1e4))
@@ -1502,7 +2590,7 @@ var Jobs = class {
1502
2590
  mediaError("OUTPUT_DECODE_FAILED", "The result could not be completely decoded.");
1503
2591
  const staged = await this.data.stage(
1504
2592
  createReadStream(output),
1505
- d.snapshot.request.input.outputName + ".mp4",
2593
+ settings || copy ? exportName(d.snapshot.request.input.outputName, profile.extension) : d.snapshot.request.input.outputName + ".mp4",
1506
2594
  "local",
1507
2595
  {
1508
2596
  signal: abort.signal,
@@ -1518,17 +2606,33 @@ var Jobs = class {
1518
2606
  );
1519
2607
  row = this.update(id, { stagingFileId: staged.stagingFileId });
1520
2608
  const request = d.snapshot.request, ordered = d.snapshot.descriptors.map((descriptor, index) => {
1521
- const input = request.operation === "video.process" ? request.input.input : request.input.inputs[index];
2609
+ const input = audio ? audio.inputs[index] : request.operation === "video.process" ? request.input.input : request.input.inputs[index];
1522
2610
  return {
1523
2611
  file: descriptor.file,
1524
2612
  editRef: input.kind === "edit" ? input.editRef : null,
1525
2613
  recipe: descriptor.recipe
1526
2614
  };
1527
2615
  });
2616
+ const remix = request.operation === "video.process" ? request.input.remix : void 0;
2617
+ const appendTo = remix && copy ? { base: copy.descriptor.file, expectedRevision: remix.expectedAssetRevision } : void 0;
2618
+ let offset = 0;
2619
+ const segments = inputs.map(({ timing, descriptor }) => {
2620
+ const start = offset;
2621
+ offset += timing.duration;
2622
+ return {
2623
+ atMs: Math.round(start * 1e3),
2624
+ endMs: Math.round(offset * 1e3),
2625
+ sourceInMs: Math.round((timing.start - descriptor.metadata.startTime) * 1e3),
2626
+ sourceOutMs: Math.round((timing.end - descriptor.metadata.startTime) * 1e3),
2627
+ speed: descriptor.recipe.speed ?? 1
2628
+ };
2629
+ });
1528
2630
  await this.publisher.importDerivedVideo(
1529
2631
  {
1530
2632
  stagingFileId: staged.stagingFileId,
1531
2633
  inputs: ordered,
2634
+ ...audio ? { audioSources: audio.tracks.map((t) => t.file) } : {},
2635
+ ...appendTo ? { appendTo } : {},
1532
2636
  outputName: request.input.outputName,
1533
2637
  publicationKey: row.data.publicationKey,
1534
2638
  completion: { jobId: id, expectedRevision: row.revision, executionToken: token },
@@ -1536,7 +2640,39 @@ var Jobs = class {
1536
2640
  kind: d.kind,
1537
2641
  jobId: id,
1538
2642
  inputs: ordered,
1539
- canvas: request.operation === "sequence.process" ? request.input.canvas : null,
2643
+ canvas: targetCanvas ?? null,
2644
+ ...audio ? {
2645
+ composition: {
2646
+ version: 1,
2647
+ sequenceKey: audio.sequenceKey,
2648
+ inputs: audio.inputs,
2649
+ revision: audio.revision + (remix ? 1 : 0),
2650
+ mix: audio.mix,
2651
+ segments,
2652
+ timeline: inputs.map(({ timing: { start, end, duration: duration2 } }) => ({
2653
+ start,
2654
+ end,
2655
+ duration: duration2
2656
+ })),
2657
+ audioEnabled: settings?.audio !== false,
2658
+ loudness,
2659
+ base: appendTo?.base ?? null,
2660
+ tracks: audio.mix?.tracks.map((track, i) => {
2661
+ const start = track.inMs ?? 0;
2662
+ const length = Math.min(
2663
+ (track.outMs ?? audio.tracks[i].durationMs) - start,
2664
+ Math.round(duration * 1e3) - track.atMs
2665
+ );
2666
+ return {
2667
+ id: track.id,
2668
+ atMs: track.atMs,
2669
+ endMs: track.atMs + length,
2670
+ sourceInMs: start,
2671
+ sourceOutMs: start + length
2672
+ };
2673
+ }) ?? []
2674
+ }
2675
+ } : {},
1540
2676
  tools: {
1541
2677
  ffmpegVersion: d.snapshot.tools.ffmpegVersion,
1542
2678
  ffprobeVersion: d.snapshot.tools.ffprobeVersion,
@@ -1554,6 +2690,7 @@ var Jobs = class {
1554
2690
  const current = t.get(id);
1555
2691
  if (current.data.state !== "saving" || current.revision !== row.revision || current.data.executionToken !== token || current.data.cancelRequested)
1556
2692
  mediaError("STALE_EXECUTION", "The execution is no longer authorized to publish.");
2693
+ if (remix && audio) writeMix(t, audio, remix.expectedMixRevision, audio.mix);
1557
2694
  const completed = t.update(id, current.revision, {
1558
2695
  ...current.data,
1559
2696
  state: "succeeded",
@@ -1604,9 +2741,10 @@ var Jobs = class {
1604
2741
  this.native.quarantine();
1605
2742
  }
1606
2743
  } finally {
1607
- if (confirmed && output) await rm2(output, { force: true }).catch(() => {
2744
+ if (confirmed && audioPath) await rm4(audioPath, { force: true }).catch(() => {
2745
+ });
2746
+ if (confirmed && output) await rm4(output, { force: true }).catch(() => {
1608
2747
  });
1609
- this.active = void 0;
1610
2748
  this.videos.processing = this.blocked;
1611
2749
  }
1612
2750
  }
@@ -1654,62 +2792,125 @@ async function activate(ctx) {
1654
2792
  );
1655
2793
  projects.add(ctx.project.id);
1656
2794
  activeProjects.set(workspace, projects);
2795
+ let data;
1657
2796
  try {
1658
- const data = workspace.bind({
2797
+ data = workspace.bind({
1659
2798
  scope: { kind: "project", id: ctx.project.id },
1660
2799
  ownerPackage: "@vivix/media-tools",
1661
2800
  packageVersion,
1662
2801
  actorId: "local",
1663
2802
  access: ["data.workspace"]
1664
2803
  });
1665
- data.register(editType);
1666
- data.register(jobType);
1667
- const runtimeRoot = join4(
2804
+ const boundData = data;
2805
+ boundData.register(audioType);
2806
+ boundData.register(editType);
2807
+ boundData.register(jobType);
2808
+ const runtimeRoot = join5(
1668
2809
  ctx.project.root,
1669
2810
  ".vivix",
1670
2811
  "runtime",
1671
2812
  "media-tools",
1672
2813
  ctx.config.executionNamespace
1673
- ), native = new NativeExecutor(), videos = new Videos(data, native, ctx.config, runtimeRoot), edits = new Edits(data, videos), jobs = new Jobs(
1674
- data,
2814
+ ), native = new NativeExecutor(), videos = new Videos(boundData, native, ctx.config, runtimeRoot), edits = new Edits(boundData, videos), jobs = new Jobs(
2815
+ boundData,
1675
2816
  videos,
1676
2817
  native,
1677
2818
  studio.derivedVideos,
1678
2819
  runtimeRoot,
1679
2820
  ctx.config.executionNamespace
1680
2821
  );
2822
+ const previewVideos = new Videos(
2823
+ boundData,
2824
+ new NativeExecutor(),
2825
+ ctx.config,
2826
+ join5(runtimeRoot, "audio-preview")
2827
+ );
2828
+ await previewVideos.recoverProbes();
2829
+ const previews = new AudioPreviews(previewVideos, ctx.transfers);
1681
2830
  let active = true;
1682
2831
  const ensureActive = () => {
1683
2832
  if (!active) mediaError("SERVICE_STOPPED", "This media-tools instance has stopped.");
1684
2833
  };
1685
- ctx.onDispose(async () => {
2834
+ ctx.onDispose?.(async () => {
1686
2835
  active = false;
1687
2836
  try {
1688
- await jobs.dispose();
2837
+ await Promise.all([jobs.dispose(), previews.dispose()]);
1689
2838
  } finally {
2839
+ boundData.dispose?.();
1690
2840
  projects.delete(ctx.project.id);
1691
2841
  }
1692
2842
  });
1693
- const handle = (id, schema, action, write = false) => ctx.handle(
2843
+ const handle = (id, schema, action, write = false, description = "Project-scoped fixed video edits and durable native media tasks.", output = z5.unknown()) => ctx.handle(
1694
2844
  defineOperation({
1695
2845
  id,
1696
2846
  title: id,
1697
- description: "Project-scoped fixed video edits and durable native media tasks.",
2847
+ description,
1698
2848
  input: schema,
1699
- output: z4.unknown(),
2849
+ output,
1700
2850
  effects: write ? ["write"] : ["read"],
1701
2851
  confirm: "none"
1702
2852
  }),
1703
2853
  (input, call) => {
1704
2854
  ensureActive();
1705
- return action(input, { ...call, scope: data.scope });
2855
+ return action(input, { ...call, scope: boundData.scope });
1706
2856
  }
1707
2857
  );
2858
+ const mixes = jobs.mixes;
2859
+ handle(
2860
+ "sequence.audio.preview",
2861
+ previewQuery,
2862
+ ({ inputs, knownRevision }) => previews.read(inputs, knownRevision),
2863
+ false,
2864
+ "Preview the saved sequence mix on its rendered picture timeline.",
2865
+ audioPreviewResult
2866
+ );
2867
+ const mixPublisher = studio.derivedVideos.audioMixVersion === 1;
2868
+ handle("export.capabilities", z5.object({}).strict(), async () => {
2869
+ const tools = await videos.tools();
2870
+ return {
2871
+ formats: tools.exportFormats ?? ["h264"],
2872
+ ...mixPublisher && tools.audioMix ? {
2873
+ audioMix: {
2874
+ version: 1,
2875
+ ...tools.audioMix,
2876
+ remixFormats: tools.exportFormats ?? ["h264"]
2877
+ }
2878
+ } : {}
2879
+ };
2880
+ });
2881
+ const mixResult = z5.object({
2882
+ sequenceKey: z5.uuid(),
2883
+ revision: z5.number().int().nonnegative(),
2884
+ mix: saveAudio.shape.mix
2885
+ });
2886
+ handle(
2887
+ "sequence.audio.get",
2888
+ audioQuery,
2889
+ ({ inputs }) => mixes.get(inputs),
2890
+ false,
2891
+ "Read the saved mix and revision for ordered fixed picture inputs.",
2892
+ mixResult
2893
+ );
2894
+ handle(
2895
+ "sequence.audio.set",
2896
+ saveAudio,
2897
+ (input, call) => {
2898
+ if (!mixPublisher)
2899
+ mediaError(
2900
+ "ASSET_SERVICE_UNAVAILABLE",
2901
+ "The configured publisher does not support sequence audio."
2902
+ );
2903
+ return mixes.set(input, call);
2904
+ },
2905
+ true,
2906
+ "Save or clear the mix used by Include audio on subsequent exports of this cut.",
2907
+ mixResult
2908
+ );
1708
2909
  handle("video.resolve", videoInput, (input) => videos.resolve(input));
1709
- handle("edits.get", z4.object({ editRef: versionRef }).strict(), async (input) => {
2910
+ handle("edits.get", z5.object({ editRef: versionRef }).strict(), async (input) => {
1710
2911
  const saved = edits.get(input.editRef);
1711
- await data.location(input.editRef);
1712
- await data.location(saved.file.source, saved.file.fileId);
2912
+ await boundData.location(input.editRef);
2913
+ await boundData.location(saved.file.source, saved.file.fileId);
1713
2914
  return saved;
1714
2915
  });
1715
2916
  handle("edits.save", saveEdit, (input, call) => edits.save(input, call), true);
@@ -1717,31 +2918,33 @@ async function activate(ctx) {
1717
2918
  "video.process",
1718
2919
  processVideo,
1719
2920
  (input, call) => jobs.submit({ operation: "video.process", input }, call),
1720
- true
2921
+ true,
2922
+ "Process a fixed video, or remix and adopt a new version of the target film."
1721
2923
  );
1722
2924
  handle(
1723
2925
  "sequence.process",
1724
2926
  processSequence,
1725
2927
  (input, call) => jobs.submit({ operation: "sequence.process", input }, call),
1726
- true
2928
+ true,
2929
+ "Export ordered pictures with the saved sequence mix when audio is enabled."
1727
2930
  );
1728
- handle("jobs.get", z4.object({ jobId: z4.uuid() }).strict(), (input) => jobs.get(input.jobId));
2931
+ handle("jobs.get", z5.object({ jobId: z5.uuid() }).strict(), (input) => jobs.get(input.jobId));
1729
2932
  handle("jobs.list", jobsQuery, (input, call) => jobs.list(input, call.actor));
1730
2933
  handle(
1731
2934
  "jobs.cancel",
1732
- z4.object({ jobId: z4.uuid() }).strict(),
2935
+ z5.object({ jobId: z5.uuid() }).strict(),
1733
2936
  (input, call) => jobs.cancel(input.jobId, call),
1734
2937
  true
1735
2938
  );
1736
2939
  const service = {
1737
2940
  capabilityVersion: "media-tools/1",
1738
- storeId: data.storeId,
2941
+ storeId: boundData.storeId,
1739
2942
  projectId: ctx.project.id,
1740
2943
  getEdit: async (ref) => {
1741
2944
  ensureActive();
1742
2945
  const saved = edits.get(versionRef.parse(ref));
1743
- await data.location(ref);
1744
- await data.location(saved.file.source, saved.file.fileId);
2946
+ await boundData.location(ref);
2947
+ await boundData.location(saved.file.source, saved.file.fileId);
1745
2948
  return saved;
1746
2949
  },
1747
2950
  resolve: (input) => {
@@ -1752,6 +2955,7 @@ async function activate(ctx) {
1752
2955
  ctx.provide(service);
1753
2956
  await jobs.start();
1754
2957
  } catch (error) {
2958
+ data?.dispose?.();
1755
2959
  projects.delete(ctx.project.id);
1756
2960
  throw error;
1757
2961
  }