@vivix-labs/media-tools 1.0.0-beta.20 → 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.
package/dist/server.js CHANGED
@@ -1,7 +1,7 @@
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
5
 
6
6
  // packages/media-tools/src/export-settings.ts
7
7
  var exportProfiles = {
@@ -49,7 +49,7 @@ function exportName(name, extension) {
49
49
  }
50
50
 
51
51
  // packages/media-tools/src/shared.ts
52
- import { z, PluginError } from "vivix-studio/sdk/shared";
52
+ import { z, PluginError, studioFileRef } from "vivix-studio/sdk/shared";
53
53
  var packageVersion = "0.1.22-ecommerce.20261110.1";
54
54
  var Config = z.object({
55
55
  dataInstance: z.string().min(1).default("user:data"),
@@ -130,7 +130,66 @@ var saveEdit = z.object({
130
130
  c.addIssue({ code: "custom", message: "An edit update requires its revision." });
131
131
  });
132
132
  var outputName = z.string().trim().min(1).max(200);
133
- 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.");
134
193
  var canvas = z.object({ width: z.number().int().min(2).max(3840), height: z.number().int().min(2).max(3840) }).strict().refine(
135
194
  (v) => v.width % 2 === 0 && v.height % 2 === 0 && Math.min(v.width, v.height) <= 2160,
136
195
  "Canvas dimensions must be even and within 3840 by 2160."
@@ -160,7 +219,7 @@ var exportSettings = z.object({
160
219
  audio: z.boolean()
161
220
  }).strict();
162
221
  var processSequence = z.object({
163
- inputs: z.array(sequenceVideoInput).min(1).max(64),
222
+ inputs: z.array(sequenceVideoInput).min(1).max(maxSequenceInputs),
164
223
  outputName,
165
224
  canvas,
166
225
  settings: exportSettings.optional(),
@@ -523,6 +582,205 @@ var NativeExecutor = class {
523
582
  }
524
583
  };
525
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
+
526
784
  // packages/media-tools/src/video.ts
527
785
  async function executable(name) {
528
786
  const candidates = isAbsolute(name) || name.includes("/") ? [resolve(name)] : (process.env.PATH || "").split(":").map((p) => join2(p, name));
@@ -620,6 +878,7 @@ var Videos = class {
620
878
  config;
621
879
  runtimeRoot;
622
880
  cache = /* @__PURE__ */ new Map();
881
+ frameCache = /* @__PURE__ */ new Map();
623
882
  toolCache;
624
883
  processing = false;
625
884
  async recoverProbes() {
@@ -706,7 +965,15 @@ var Videos = class {
706
965
  ffmpegVersion: encoder.stdout.split("\n")[0],
707
966
  ffprobeVersion: probe.stdout.split("\n")[0],
708
967
  profileVersion: 1,
709
- exportFormats
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
+ } : {}
710
977
  };
711
978
  return this.toolCache;
712
979
  }
@@ -723,49 +990,96 @@ var Videos = class {
723
990
  );
724
991
  }
725
992
  }
726
- file(file, includeDeleted = false) {
993
+ file(file, includeDeleted = false, copy = false) {
727
994
  if (this.data.scope.kind !== "project" || file.source.storeId !== this.data.storeId)
728
995
  mediaError("SCOPE_MISMATCH", "Video input belongs to another project store.");
729
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);
730
- 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"))
731
998
  mediaError("SOURCE_NOT_VIDEO", "Select a readable fixed MP4 video from this project.");
732
999
  return { object, version, file: record };
733
1000
  }
734
- async restoreMetadata(raw) {
735
- 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);
736
1003
  if (fixed.file.sha256 !== descriptor.metadata.sha256 || fixed.file.sizeBytes !== descriptor.metadata.sizeBytes)
737
1004
  mediaError(
738
1005
  "SOURCE_SNAPSHOT_MISMATCH",
739
1006
  "The fixed execution metadata does not match the recorded source file."
740
1007
  );
741
1008
  const location = await this.data.location(descriptor.file.source, descriptor.file.fileId);
742
- this.cache.set(fixed.file.sha256, descriptor.metadata);
1009
+ if (!copy) this.cache.set(fixed.file.sha256, descriptor.metadata);
743
1010
  return location;
744
1011
  }
745
- async describe(file) {
746
- const fixed = this.file(file), location = await this.data.location(file.source, file.fileId), key = fixed.file.sha256;
747
- const cached = this.cache.get(key);
748
- if (cached) return cached;
1012
+ async probeLocation(absolutePath) {
749
1013
  if (this.processing || this.native.busy)
750
- mediaError("MEDIA_BUSY", "Wait for the current video before inspecting an uncached source.");
751
- const probe = await executable(this.config.ffprobePath);
752
- 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), [
753
1016
  "-v",
754
1017
  "error",
1018
+ "-protocol_whitelist",
1019
+ "file,pipe",
755
1020
  "-show_format",
756
1021
  "-show_streams",
757
1022
  "-of",
758
1023
  "json",
759
- location.absolutePath
1024
+ absolutePath
760
1025
  ]);
761
1026
  if (result.stderr.trim())
762
- mediaError("MEDIA_INVALID", "The source reported a decoding or metadata error.");
763
- let info;
1027
+ mediaError("MEDIA_INVALID", "Could not read the fixed media streams.");
764
1028
  try {
765
- info = JSON.parse(result.stdout);
1029
+ return JSON.parse(result.stdout);
766
1030
  } catch {
767
1031
  mediaError("MEDIA_INVALID", "The source metadata is invalid.");
768
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);
769
1083
  const value = parseMetadata(info, fixed.file);
770
1084
  this.cache.set(key, value);
771
1085
  return value;
@@ -818,6 +1132,9 @@ var Videos = class {
818
1132
  }
819
1133
  };
820
1134
 
1135
+ // packages/media-tools/src/sequence-audio.ts
1136
+ import { z as z3 } from "vivix-studio/sdk/shared";
1137
+
821
1138
  // packages/media-tools/src/edits.ts
822
1139
  import { createHash } from "crypto";
823
1140
  import { z as z2 } from "vivix-studio/sdk/shared";
@@ -933,230 +1250,713 @@ var Edits = class {
933
1250
  }
934
1251
  };
935
1252
 
936
- // packages/media-tools/src/jobs.ts
937
- import { randomUUID as randomUUID3, createHash as createHash2 } from "crypto";
938
- import { createReadStream } from "fs";
939
- import { mkdir as mkdir2, rm as rm2, stat, statfs } from "fs/promises";
940
- import { join as join3 } from "path";
941
- import { z as z3 } from "vivix-studio/sdk/shared";
942
-
943
- // packages/media-tools/src/render.ts
944
- function frameTimes(stdout) {
945
- const result = stdout.split(/\r?\n/).map((line) => line.split(",")[0].trim()).filter(Boolean).map(Number).filter(Number.isFinite);
946
- if (!result.length || result.some((v, i) => i > 0 && v <= result[i - 1]))
947
- mediaError(
948
- "SOURCE_TIMING_UNSUPPORTED",
949
- "The source frame timestamps are missing or not increasing."
950
- );
951
- return result;
952
- }
953
- function segmentTiming(descriptor, frames) {
954
- const origin = descriptor.metadata.startTime, start = origin + descriptor.recipe.trim.inMs / 1e3, end = origin + descriptor.recipe.trim.outMs / 1e3;
955
- const kept = frames.filter((pts) => pts >= start - 1e-7 && pts < end - 1e-7);
956
- if (!kept.length)
957
- mediaError("EMPTY_VIDEO_INTERVAL", "The selected interval contains no video frame.");
958
- const first = kept[0], last = kept.at(-1), next = frames.find((pts) => pts > last + 1e-7);
959
- const lastDuration = next ? next - last : frames.length > 1 ? frames.at(-1) - frames.at(-2) : 1 / descriptor.metadata.frameRate;
960
- const actualEnd = Math.min(
961
- next ?? last + lastDuration,
962
- 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
+ }
963
1292
  );
964
- const tolerance = Math.max(lastDuration, ...kept.slice(1).map((v, i) => v - kept[i]));
965
- const speed = descriptor.recipe.speed ?? 1;
1293
+ return bindingForInputs(data, normalized);
1294
+ }
1295
+ function bindingForInputs(data, normalized) {
1296
+ const parsed = audioQuery.parse({ inputs: normalized });
966
1297
  return {
967
- start: first,
968
- end: actualEnd,
969
- duration: (actualEnd - first) / speed,
970
- frames: kept.map((v) => (v - first) / speed),
971
- tolerance: tolerance / speed
1298
+ inputs: parsed.inputs,
1299
+ sequenceKey: stableUuid(["sequence-audio/1", data.scope.id, data.storeId, parsed.inputs])
972
1300
  };
973
1301
  }
974
- var seconds = (value) => Number(value.toFixed(9)).toString();
975
- function tempoFilters(speed) {
976
- const values = [];
977
- while (speed < 0.5) {
978
- values.push(0.5);
979
- speed /= 0.5;
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 };
980
1315
  }
981
- while (speed > 2) {
982
- values.push(2);
983
- speed /= 2;
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)
1329
+ ];
1330
+ for (const ref of new Map(refs.map((r) => [r.versionId, r])).values())
1331
+ t.relation(sequenceKey, null, ref, "reference");
984
1332
  }
985
- if (speed !== 1) values.push(speed);
986
- return values.map((value) => `atempo=${seconds(value)}`);
1333
+ return { sequenceKey, revision: row.revision, mix };
987
1334
  }
988
- function renderArguments(inputs, output, canvas2, settings) {
989
- const profile = exportProfiles[settings?.format ?? "h264"];
990
- const fps = typeof settings?.frameRate === "number" ? settings.frameRate : inputs.some(
991
- ({ descriptor }) => descriptor.metadata.frameRate * (descriptor.recipe.speed ?? 1) > 60
992
- ) ? 60 : void 0;
993
- const audible = settings?.audio !== false && 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 = [];
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));
1377
+ }
1378
+ return result;
1379
+ }
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) {
994
1579
  const args = ["-hide_banner", "-nostdin", "-y", "-copyts"];
995
- for (const input of inputs) args.push("-protocol_whitelist", "file,pipe", "-i", input.path);
996
- for (const [index, { descriptor, timing }] of inputs.entries()) {
997
- const rect = descriptor.geometry.pixelRect;
998
- const speed = descriptor.recipe.speed ?? 1;
999
- const color = descriptor.recipe.color;
1000
- const video = [
1001
- `[${index}:v:0]trim=start=${seconds(timing.start)}:end=${seconds(timing.end)}`,
1002
- speed === 1 ? `setpts=PTS-${seconds(timing.start)}/TB` : `setpts=(PTS-${seconds(timing.start)}/TB)/${seconds(speed)}`,
1003
- "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709",
1004
- `crop=${rect.width}:${rect.height}:${rect.x}:${rect.y}`,
1005
- ...color ? [
1006
- `eq=brightness=${color.brightness}:contrast=${color.contrast}:saturation=${color.saturation}`
1007
- ] : [],
1008
- "setsar=1",
1009
- ...canvas2 ? [
1010
- `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" : ""}`,
1011
- ...settings ? [`pad=${canvas2.width}:${canvas2.height}:(ow-iw)/2:(oh-ih)/2:black`, "setsar=1"] : []
1012
- ] : [],
1013
- "format=yuv420p",
1014
- "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709"
1015
- ];
1016
- filters.push(video.join(",") + `[v${index}]`);
1017
- labels.push(`[v${index}]`);
1018
- if (audible) {
1019
- const channels = sequence ? 2 : descriptor.metadata.audioChannels;
1020
- let audio;
1021
- if (descriptor.metadata.hasAudio) {
1022
- const mono = sequence && descriptor.metadata.audioChannels === 1 ? ",pan=stereo|c0=c0|c1=c0" : "";
1023
- const sourceDuration = timing.end - timing.start;
1024
- audio = [
1025
- `[${index}:a:0]atrim=start=${seconds(timing.start)}:end=${seconds(timing.end)}`,
1026
- `asetpts=PTS-${seconds(timing.start)}/TB`,
1027
- `aresample=${audioSampleRate}:async=1:first_pts=0${mono}`,
1028
- `aformat=sample_fmts=fltp:channel_layouts=${channels === 1 ? "mono" : "stereo"}`,
1029
- `apad=whole_dur=${seconds(sourceDuration)}`,
1030
- `atrim=duration=${seconds(sourceDuration)}`,
1031
- ...tempoFilters(speed),
1032
- `apad=whole_dur=${seconds(timing.duration)}`,
1033
- `atrim=duration=${seconds(timing.duration)}`
1034
- ].join(",");
1035
- } else
1036
- audio = `anullsrc=r=48000:cl=stereo,atrim=duration=${seconds(timing.duration)},asetpts=PTS-STARTPTS`;
1037
- filters.push(audio + `[a${index}]`);
1038
- labels.push(`[a${index}]`);
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);
1039
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 + "]");
1040
1615
  }
1041
- if (inputs.length > 1) {
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) {
1042
1656
  filters.push(
1043
- 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 + "]"
1044
1658
  );
1045
1659
  }
1046
- const videoLabel = inputs.length > 1 ? "[video]" : "[v0]";
1047
- if (fps) {
1048
- filters.push(`${videoLabel}fps=fps=${fps}:start_time=0:eof_action=pass[cfr]`);
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
1697
+ );
1698
+ const m = levels(result.stderr);
1699
+ return {
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
1702
+ };
1703
+ }
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";
1049
1730
  }
1050
- args.push("-filter_complex", filters.join(";"), "-map", fps ? "[cfr]" : videoLabel);
1051
- if (audible)
1052
- args.push(
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(";"),
1053
1741
  "-map",
1054
- inputs.length > 1 ? "[audio]" : "[a0]",
1742
+ "[out]",
1055
1743
  "-c:a",
1056
- profile.audio === "opus" ? "libopus" : profile.audio,
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",
1057
1766
  "-b:a",
1058
1767
  "192k"
1059
- );
1060
- else args.push("-an");
1061
- args.push(
1062
- "-c:v",
1063
- profile.encoder,
1064
- "-crf",
1065
- String(profile.crf[exportQualities.indexOf(settings?.quality ?? "high")]),
1066
- ...profile.codec === "vp9" ? ["-b:v", "0", "-deadline", "good", "-cpu-used", "2"] : ["-preset", "medium"],
1067
- ...profile.codec === "hevc" ? ["-tag:v", "hvc1", "-x265-params", "pools=4"] : [],
1068
- "-threads",
1069
- "4",
1070
- "-pix_fmt",
1071
- "yuv420p",
1072
- "-fps_mode",
1073
- "passthrough",
1074
- "-enc_time_base:v",
1075
- fps ? `1:${fps}` : "1:90000",
1076
- ...profile.container === "mp4" ? ["-video_track_timescale", "90000", "-movflags", "+faststart"] : (
1077
- // Older WebM muxers otherwise move all video timestamps to offset Opus pre-roll.
1078
- ["-avoid_negative_ts", "disabled"]
1079
- ),
1080
- "-color_primaries",
1081
- "bt709",
1082
- "-color_trc",
1083
- "bt709",
1084
- "-colorspace",
1085
- "bt709",
1086
- "-metadata:s:v:0",
1087
- "rotate=0",
1088
- "-progress",
1089
- "pipe:1",
1090
- "-stats_period",
1091
- "0.5",
1768
+ ] : ["-an"],
1769
+ "-avoid_negative_ts",
1770
+ "disabled",
1771
+ ...profile.container === "mp4" ? ["-movflags", "+faststart"] : [],
1092
1772
  output
1093
- );
1094
- return {
1095
- args,
1096
- audible,
1097
- audioSampleRate,
1098
- frameRate: fps,
1099
- expectedFrames: inputs.flatMap((input, index) => {
1100
- const offset = inputs.slice(0, index).reduce((n, i) => n + i.timing.duration, 0);
1101
- return input.timing.frames.map((t) => t + offset);
1102
- }),
1103
- duration: inputs.reduce((n, i) => n + i.timing.duration, 0),
1104
- tolerance: inputs.reduce((n, i) => n + i.timing.tolerance, 0)
1105
- };
1773
+ ];
1106
1774
  }
1107
- function validateFrameTiming(actual, timings, fps, webm = false) {
1108
- const precision = webm ? 2e-3 : 1e-3;
1109
- if (fps) {
1110
- if (actual.some((pts, index2) => Math.abs(pts - actual[0] - index2 / fps) > precision))
1111
- mediaError("OUTPUT_TIMING_MISMATCH", "The output does not have the selected frame cadence.");
1112
- return;
1113
- }
1114
- if (actual.length !== timings.reduce((total, timing) => total + timing.frames.length, 0))
1115
- mediaError("OUTPUT_TIMING_MISMATCH", "The output frame count changed.");
1116
- let index = 0, expectedStart = 0, boundaryTolerance = 0;
1117
- for (const timing of timings) {
1118
- const first = actual[index];
1119
- if (Math.abs(first - expectedStart) > boundaryTolerance + 1e-3)
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)
1120
1800
  mediaError(
1121
- "OUTPUT_TIMING_MISMATCH",
1122
- "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."
1123
1803
  );
1124
- for (let offset = 0; offset < timing.frames.length; offset++)
1125
- if (Math.abs(actual[index + offset] - first - timing.frames[offset]) > precision)
1126
- mediaError("OUTPUT_TIMING_MISMATCH", "The output changed timing inside a source segment.");
1127
- index += timing.frames.length;
1128
- expectedStart += timing.duration;
1129
- boundaryTolerance += timing.tolerance;
1130
1804
  }
1805
+ const status = measured.integratedLUFS === null ? "unmeasurable" : Math.abs(measured.integratedLUFS + 16) > 1 ? "peak-limited" : "measured";
1806
+ return { ...measured, status };
1131
1807
  }
1132
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
+
1133
1926
  // packages/media-tools/src/jobs.ts
1134
- var toolsSchema = z3.object({
1135
- ffmpeg: z3.string(),
1136
- ffprobe: z3.string(),
1137
- ffmpegVersion: z3.string(),
1138
- ffprobeVersion: z3.string(),
1139
- profileVersion: z3.literal(1),
1140
- exportFormats: z3.array(exportFormat).optional()
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()
1141
1940
  }).strict();
1142
- var snapshot = z3.object({
1941
+ var snapshot = z4.object({
1143
1942
  request: mediaRequest,
1144
- descriptors: z3.array(editDescriptor).min(1).max(64),
1943
+ audio: audioSnapshot.optional(),
1944
+ descriptors: z4.array(editDescriptor).min(1).max(64),
1145
1945
  tools: toolsSchema
1146
1946
  }).strict();
1147
- var jobData = z3.object({
1148
- state: z3.enum(jobStates),
1149
- kind: z3.enum(["video", "sequence"]),
1150
- namespace: z3.string(),
1947
+ var jobData = z4.object({
1948
+ state: z4.enum(jobStates),
1949
+ kind: z4.enum(["video", "sequence"]),
1950
+ namespace: z4.string(),
1151
1951
  snapshot,
1152
- progress: z3.number().min(0).max(1).nullable(),
1153
- cancelRequested: z3.boolean(),
1952
+ progress: z4.number().min(0).max(1).nullable(),
1953
+ cancelRequested: z4.boolean(),
1154
1954
  result: videoFileRef.nullable(),
1155
- error: z3.object({ code: z3.string(), message: z3.string() }).strict().nullable(),
1156
- executionToken: z3.uuid().nullable(),
1157
- publicationKey: z3.string().nullable(),
1158
- stagingFileId: z3.uuid().nullable(),
1159
- 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()
1160
1960
  }).strict();
1161
1961
  var jobType = {
1162
1962
  typeId: "media.job",
@@ -1194,6 +1994,7 @@ var Jobs = class {
1194
1994
  this.publisher = publisher;
1195
1995
  this.runtimeRoot = runtimeRoot;
1196
1996
  this.namespace = namespace;
1997
+ this.mixes = new SequenceAudio(videos);
1197
1998
  }
1198
1999
  data;
1199
2000
  videos;
@@ -1207,6 +2008,7 @@ var Jobs = class {
1207
2008
  blocked = false;
1208
2009
  failure;
1209
2010
  submissions = /* @__PURE__ */ new Map();
2011
+ mixes;
1210
2012
  call(key) {
1211
2013
  return { scope: this.data.scope, actor: { kind: "local-user", id: "local" }, requestKey: key };
1212
2014
  }
@@ -1310,11 +2112,13 @@ var Jobs = class {
1310
2112
  }
1311
2113
  async accept(request, call) {
1312
2114
  requireWritable(this.data);
2115
+ if (this.active && terminal(this.record(this.active.id).data.state)) await this.active.finished;
1313
2116
  if (this.disposed || this.blocked || this.native.recoveryRequired)
1314
2117
  mediaError("RECOVERY_REQUIRED", "Media execution is stopped or waiting for safe cleanup.");
1315
2118
  if (this.rows().filter((row) => !terminal(row.data.state)).length >= 50)
1316
2119
  mediaError("MEDIA_QUEUE_FULL", "The project already has 50 unfinished media tasks.");
1317
- let descriptors, tools;
2120
+ let descriptors, tools, audio;
2121
+ const mixes = this.mixes;
1318
2122
  if (request.input.retryOfJobId) {
1319
2123
  const old = this.record(request.input.retryOfJobId), original = old.data.snapshot.request;
1320
2124
  if (!["failed", "canceled", "interrupted"].includes(old.data.state))
@@ -1332,9 +2136,12 @@ var Jobs = class {
1332
2136
  "RETRY_INPUT_CONFLICT",
1333
2137
  "A retry must keep the original ordered inputs, output name and configuration."
1334
2138
  );
2139
+ audio = old.data.snapshot.audio ? audioSnapshot.parse(old.data.snapshot.audio) : void 0;
1335
2140
  descriptors = clone(old.data.snapshot.descriptors);
1336
2141
  tools = clone(old.data.snapshot.tools);
1337
- 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));
1338
2145
  for (const executable2 of [tools.ffmpeg, tools.ffprobe]) {
1339
2146
  try {
1340
2147
  const { access: access2 } = await import("fs/promises");
@@ -1348,9 +2155,31 @@ var Jobs = class {
1348
2155
  }
1349
2156
  } else {
1350
2157
  const inputs = request.operation === "video.process" ? [request.input.input] : request.input.inputs;
1351
- descriptors = [];
1352
- for (const input of inputs) descriptors.push(await this.videos.descriptor(input));
1353
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
+ }
1354
2183
  }
1355
2184
  if (descriptors.reduce((total, d) => total + recipeDurationMs(d.recipe), 0) > 6e5)
1356
2185
  mediaError("MEDIA_LIMIT_EXCEEDED", "The edited duration exceeds 600 seconds.");
@@ -1386,11 +2215,23 @@ var Jobs = class {
1386
2215
  "The sequence exceeds 600 seconds or 2 GiB of distinct source media."
1387
2216
  );
1388
2217
  }
1389
- 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 = {
1390
2231
  state: "queued",
1391
2232
  kind: request.operation === "video.process" ? "video" : "sequence",
1392
2233
  namespace: this.namespace,
1393
- snapshot: { request, descriptors, tools },
2234
+ snapshot: { request, descriptors, tools, ...audio ? { audio } : {} },
1394
2235
  progress: null,
1395
2236
  cancelRequested: false,
1396
2237
  result: null,
@@ -1406,7 +2247,14 @@ var Jobs = class {
1406
2247
  call,
1407
2248
  (t) => {
1408
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.");
1409
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");
1410
2258
  const protectedRefs = /* @__PURE__ */ new Set();
1411
2259
  for (const [index, descriptor] of descriptors.entries()) {
1412
2260
  const source = descriptor.file.source, sourceKey = canonical(source);
@@ -1414,7 +2262,7 @@ var Jobs = class {
1414
2262
  t.relation(id, null, source, "reference");
1415
2263
  protectedRefs.add(sourceKey);
1416
2264
  }
1417
- 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];
1418
2266
  if (selected.kind === "edit" && !protectedRefs.has(canonical(selected.editRef))) {
1419
2267
  t.relation(id, null, selected.editRef, "reference");
1420
2268
  protectedRefs.add(canonical(selected.editRef));
@@ -1511,7 +2359,7 @@ var Jobs = class {
1511
2359
  this.videos.processing = this.blocked;
1512
2360
  }
1513
2361
  directory(id, token) {
1514
- 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));
1515
2363
  }
1516
2364
  wake() {
1517
2365
  if (this.pumping || this.disposed || this.blocked || this.native.recoveryRequired) return;
@@ -1532,13 +2380,20 @@ var Jobs = class {
1532
2380
  (value) => value.data.state === "queued" && !value.data.cancelRequested
1533
2381
  );
1534
2382
  if (!row) return;
1535
- 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
+ }
1536
2391
  }
1537
2392
  }
1538
- async execute(id) {
1539
- const token = randomUUID3(), abort = new AbortController();
1540
- this.active = { id, abort };
2393
+ async execute(id, abort) {
2394
+ const token = randomUUID4();
1541
2395
  this.videos.processing = true;
2396
+ let audioPath;
1542
2397
  let output, confirmed = true;
1543
2398
  try {
1544
2399
  const initial = this.record(id);
@@ -1560,8 +2415,9 @@ var Jobs = class {
1560
2415
  const targetCanvas = sequence && (settings ? exportDimensions(sequence.canvas, settings.aspect, settings.resolution) : sequence.canvas);
1561
2416
  if (targetCanvas === null)
1562
2417
  mediaError("MEDIA_LIMIT_EXCEEDED", "The selected output size is unavailable.");
1563
- const profile = exportProfiles[settings?.format ?? "h264"];
1564
- output = join3(directory, `output.${profile.extension}`);
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}`);
1565
2421
  const space = await statfs(directory);
1566
2422
  if (Number(space.bavail) * Number(space.bsize) < 4.5 * 1024 ** 3)
1567
2423
  mediaError(
@@ -1570,36 +2426,58 @@ var Jobs = class {
1570
2426
  );
1571
2427
  const commandOptions = { directory, jobId: id, executionToken: token, signal: abort.signal };
1572
2428
  await this.videos.verifyTools(d.snapshot.tools, commandOptions);
1573
- const inputs = [], frameCache = /* @__PURE__ */ new Map();
1574
- for (const descriptor of d.snapshot.descriptors) {
1575
- const location = await this.videos.restoreMetadata(descriptor);
1576
- let frames = frameCache.get(descriptor.metadata.sha256);
1577
- if (!frames) {
1578
- const result = await this.native.run(
1579
- d.snapshot.tools.ffprobe,
1580
- [
1581
- "-v",
1582
- "error",
1583
- "-select_streams",
1584
- "v:0",
1585
- "-show_entries",
1586
- "frame=best_effort_timestamp_time",
1587
- "-of",
1588
- "csv=p=0",
1589
- location.absolutePath
1590
- ],
1591
- { ...commandOptions, timeoutMs: 15e3 }
1592
- );
1593
- frames = frameTimes(result.stdout);
1594
- 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);
1595
2460
  }
1596
- inputs.push({
1597
- descriptor,
1598
- path: location.absolutePath,
1599
- timing: segmentTiming(descriptor, frames)
1600
- });
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
+ );
1601
2472
  }
1602
- const rendered = renderArguments(inputs, output, targetCanvas, settings);
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);
1603
2481
  let progressBuffer = "", lastProgress = 0;
1604
2482
  await this.native.run(d.snapshot.tools.ffmpeg, rendered.args, {
1605
2483
  ...commandOptions,
@@ -1630,6 +2508,15 @@ var Jobs = class {
1630
2508
  });
1631
2509
  abort.signal.throwIfAborted();
1632
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;
1633
2520
  const details = await this.native.run(
1634
2521
  d.snapshot.tools.ffprobe,
1635
2522
  ["-v", "error", "-show_format", "-show_streams", "-of", "json", output],
@@ -1646,11 +2533,11 @@ var Jobs = class {
1646
2533
  sizeBytes: size,
1647
2534
  sha256: hash.digest("hex")
1648
2535
  },
1649
- settings ? profile : void 0
2536
+ settings || copy ? profile : void 0
1650
2537
  );
1651
- const target = targetCanvas ?? inputs[0].descriptor.geometry.pixelRect;
2538
+ const target = targetCanvas ?? (picture ?? inputs[0]).descriptor.geometry.pixelRect;
1652
2539
  const fps = rendered.frameRate;
1653
- 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 + (fps ? 1 / fps : 0))
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))
1654
2541
  mediaError(
1655
2542
  "OUTPUT_VALIDATION_FAILED",
1656
2543
  "The output color declaration, geometry, duration or audio does not match the fixed recipe."
@@ -1673,13 +2560,27 @@ var Jobs = class {
1673
2560
  const actualFrames = frameTimes(frameResult.stdout);
1674
2561
  validateFrameTiming(
1675
2562
  actualFrames,
1676
- inputs.map((input) => input.timing),
2563
+ (picture ? [picture] : inputs).map((input) => input.timing),
1677
2564
  fps,
1678
2565
  profile.container === "webm"
1679
2566
  );
1680
2567
  const decoded = await this.native.run(
1681
2568
  d.snapshot.tools.ffmpeg,
1682
- ["-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
+ ],
1683
2584
  {
1684
2585
  ...commandOptions,
1685
2586
  timeoutMs: Math.min(18e5, Math.max(12e4, rendered.duration * 1e4))
@@ -1689,7 +2590,7 @@ var Jobs = class {
1689
2590
  mediaError("OUTPUT_DECODE_FAILED", "The result could not be completely decoded.");
1690
2591
  const staged = await this.data.stage(
1691
2592
  createReadStream(output),
1692
- settings ? exportName(d.snapshot.request.input.outputName, profile.extension) : d.snapshot.request.input.outputName + ".mp4",
2593
+ settings || copy ? exportName(d.snapshot.request.input.outputName, profile.extension) : d.snapshot.request.input.outputName + ".mp4",
1693
2594
  "local",
1694
2595
  {
1695
2596
  signal: abort.signal,
@@ -1705,17 +2606,33 @@ var Jobs = class {
1705
2606
  );
1706
2607
  row = this.update(id, { stagingFileId: staged.stagingFileId });
1707
2608
  const request = d.snapshot.request, ordered = d.snapshot.descriptors.map((descriptor, index) => {
1708
- 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];
1709
2610
  return {
1710
2611
  file: descriptor.file,
1711
2612
  editRef: input.kind === "edit" ? input.editRef : null,
1712
2613
  recipe: descriptor.recipe
1713
2614
  };
1714
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
+ });
1715
2630
  await this.publisher.importDerivedVideo(
1716
2631
  {
1717
2632
  stagingFileId: staged.stagingFileId,
1718
2633
  inputs: ordered,
2634
+ ...audio ? { audioSources: audio.tracks.map((t) => t.file) } : {},
2635
+ ...appendTo ? { appendTo } : {},
1719
2636
  outputName: request.input.outputName,
1720
2637
  publicationKey: row.data.publicationKey,
1721
2638
  completion: { jobId: id, expectedRevision: row.revision, executionToken: token },
@@ -1724,6 +2641,38 @@ var Jobs = class {
1724
2641
  jobId: id,
1725
2642
  inputs: ordered,
1726
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
+ } : {},
1727
2676
  tools: {
1728
2677
  ffmpegVersion: d.snapshot.tools.ffmpegVersion,
1729
2678
  ffprobeVersion: d.snapshot.tools.ffprobeVersion,
@@ -1741,6 +2690,7 @@ var Jobs = class {
1741
2690
  const current = t.get(id);
1742
2691
  if (current.data.state !== "saving" || current.revision !== row.revision || current.data.executionToken !== token || current.data.cancelRequested)
1743
2692
  mediaError("STALE_EXECUTION", "The execution is no longer authorized to publish.");
2693
+ if (remix && audio) writeMix(t, audio, remix.expectedMixRevision, audio.mix);
1744
2694
  const completed = t.update(id, current.revision, {
1745
2695
  ...current.data,
1746
2696
  state: "succeeded",
@@ -1791,9 +2741,10 @@ var Jobs = class {
1791
2741
  this.native.quarantine();
1792
2742
  }
1793
2743
  } finally {
1794
- 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(() => {
1795
2747
  });
1796
- this.active = void 0;
1797
2748
  this.videos.processing = this.blocked;
1798
2749
  }
1799
2750
  }
@@ -1851,9 +2802,10 @@ async function activate(ctx) {
1851
2802
  access: ["data.workspace"]
1852
2803
  });
1853
2804
  const boundData = data;
2805
+ boundData.register(audioType);
1854
2806
  boundData.register(editType);
1855
2807
  boundData.register(jobType);
1856
- const runtimeRoot = join4(
2808
+ const runtimeRoot = join5(
1857
2809
  ctx.project.root,
1858
2810
  ".vivix",
1859
2811
  "runtime",
@@ -1867,6 +2819,14 @@ async function activate(ctx) {
1867
2819
  runtimeRoot,
1868
2820
  ctx.config.executionNamespace
1869
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);
1870
2830
  let active = true;
1871
2831
  const ensureActive = () => {
1872
2832
  if (!active) mediaError("SERVICE_STOPPED", "This media-tools instance has stopped.");
@@ -1874,19 +2834,19 @@ async function activate(ctx) {
1874
2834
  ctx.onDispose?.(async () => {
1875
2835
  active = false;
1876
2836
  try {
1877
- await jobs.dispose();
2837
+ await Promise.all([jobs.dispose(), previews.dispose()]);
1878
2838
  } finally {
1879
2839
  boundData.dispose?.();
1880
2840
  projects.delete(ctx.project.id);
1881
2841
  }
1882
2842
  });
1883
- 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(
1884
2844
  defineOperation({
1885
2845
  id,
1886
2846
  title: id,
1887
- description: "Project-scoped fixed video edits and durable native media tasks.",
2847
+ description,
1888
2848
  input: schema,
1889
- output: z4.unknown(),
2849
+ output,
1890
2850
  effects: write ? ["write"] : ["read"],
1891
2851
  confirm: "none"
1892
2852
  }),
@@ -1895,11 +2855,59 @@ async function activate(ctx) {
1895
2855
  return action(input, { ...call, scope: boundData.scope });
1896
2856
  }
1897
2857
  );
1898
- handle("export.capabilities", z4.object({}).strict(), async () => ({
1899
- formats: (await videos.tools()).exportFormats ?? ["h264"]
1900
- }));
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
+ );
1901
2909
  handle("video.resolve", videoInput, (input) => videos.resolve(input));
1902
- handle("edits.get", z4.object({ editRef: versionRef }).strict(), async (input) => {
2910
+ handle("edits.get", z5.object({ editRef: versionRef }).strict(), async (input) => {
1903
2911
  const saved = edits.get(input.editRef);
1904
2912
  await boundData.location(input.editRef);
1905
2913
  await boundData.location(saved.file.source, saved.file.fileId);
@@ -1910,19 +2918,21 @@ async function activate(ctx) {
1910
2918
  "video.process",
1911
2919
  processVideo,
1912
2920
  (input, call) => jobs.submit({ operation: "video.process", input }, call),
1913
- true
2921
+ true,
2922
+ "Process a fixed video, or remix and adopt a new version of the target film."
1914
2923
  );
1915
2924
  handle(
1916
2925
  "sequence.process",
1917
2926
  processSequence,
1918
2927
  (input, call) => jobs.submit({ operation: "sequence.process", input }, call),
1919
- true
2928
+ true,
2929
+ "Export ordered pictures with the saved sequence mix when audio is enabled."
1920
2930
  );
1921
- 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));
1922
2932
  handle("jobs.list", jobsQuery, (input, call) => jobs.list(input, call.actor));
1923
2933
  handle(
1924
2934
  "jobs.cancel",
1925
- z4.object({ jobId: z4.uuid() }).strict(),
2935
+ z5.object({ jobId: z5.uuid() }).strict(),
1926
2936
  (input, call) => jobs.cancel(input.jobId, call),
1927
2937
  true
1928
2938
  );