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

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 +1444 -252
  51. package/dist/client.css +2368 -181
  52. package/dist/server.d.ts +1 -1
  53. package/dist/server.js +257 -63
  54. package/dist/shared.d.ts +188 -3
  55. package/dist/shared.js +86 -3
  56. package/{skills/SKILL.md → docs/operations.md} +7 -7
  57. package/package.json +5 -4
  58. package/studio-plugin.json +1 -4
  59. package/dist/assets/player-cover-shade-LLH6KOCQ.png +0 -0
  60. /package/{skills/references → docs}/processing.md +0 -0
package/dist/server.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { ServerContext } from 'vivix-studio/sdk/server';
2
2
  import { MediaToolsConfig } from './shared.js';
3
3
  export { Config } from './shared.js';
4
- import 'vivix-studio/sdk/shared';
5
4
  import 'react';
5
+ import 'vivix-studio/sdk/shared';
6
6
  import '@vivix-labs/ui-system';
7
7
 
8
8
  declare const dependencies: (config: MediaToolsConfig) => string[];
package/dist/server.js CHANGED
@@ -3,6 +3,51 @@ import { join as join4 } from "path";
3
3
  import { defineOperation } from "vivix-studio/sdk/server";
4
4
  import { z as z4 } from "vivix-studio/sdk/shared";
5
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
+ }
50
+
6
51
  // packages/media-tools/src/shared.ts
7
52
  import { z, PluginError } from "vivix-studio/sdk/shared";
8
53
  var packageVersion = "0.1.22-ecommerce.20261110.1";
@@ -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(),
@@ -80,10 +135,35 @@ var canvas = z.object({ width: z.number().int().min(2).max(3840), height: z.numb
80
135
  (v) => v.width % 2 === 0 && v.height % 2 === 0 && Math.min(v.width, v.height) <= 2160,
81
136
  "Canvas dimensions must be even and within 3840 by 2160."
82
137
  );
138
+ var exportFormat = z.enum(
139
+ Object.keys(exportProfiles)
140
+ );
141
+ var exportSettings = z.object({
142
+ format: exportFormat,
143
+ aspect: z.enum(exportAspects),
144
+ resolution: z.union([
145
+ z.literal("source"),
146
+ z.literal(480),
147
+ z.literal(720),
148
+ z.literal(1080),
149
+ z.literal(2160)
150
+ ]),
151
+ frameRate: z.union([
152
+ z.literal("source"),
153
+ z.literal(24),
154
+ z.literal(25),
155
+ z.literal(30),
156
+ z.literal(50),
157
+ z.literal(60)
158
+ ]),
159
+ quality: z.enum(exportQualities),
160
+ audio: z.boolean()
161
+ }).strict();
83
162
  var processSequence = z.object({
84
163
  inputs: z.array(sequenceVideoInput).min(1).max(64),
85
164
  outputName,
86
165
  canvas,
166
+ settings: exportSettings.optional(),
87
167
  retryOfJobId: z.uuid().optional()
88
168
  }).strict();
89
169
  var mediaRequest = z.discriminatedUnion("operation", [
@@ -137,7 +217,9 @@ function normalizeRecipe(raw, displayWidth, displayHeight, durationMs) {
137
217
  y: y / displayHeight,
138
218
  width: pixelRect2.width / displayWidth,
139
219
  height: pixelRect2.height / displayHeight
140
- }
220
+ },
221
+ ...value.color ? { color: { ...value.color } } : {},
222
+ ...value.speed === void 0 ? {} : { speed: value.speed }
141
223
  },
142
224
  geometry: { displayWidth, displayHeight, pixelRect: pixelRect2 }
143
225
  };
@@ -195,7 +277,7 @@ function readSavedEdit(data, raw) {
195
277
  file: value.file,
196
278
  recipe: value.recipe,
197
279
  geometry: value.geometry,
198
- effectiveDurationMs: value.recipe.trim.outMs - value.recipe.trim.inMs
280
+ effectiveDurationMs: recipeDurationMs(value.recipe)
199
281
  };
200
282
  }
201
283
 
@@ -460,13 +542,19 @@ function fraction(value) {
460
542
  const [a, b] = String(value).split("/").map(Number);
461
543
  return b ? a / b : a;
462
544
  }
463
- function parseMetadata(info, file) {
545
+ function parseMetadata(info, file, output) {
464
546
  const streams = info.streams || [], videos = streams.filter((v) => v.codec_type === "video"), audios = streams.filter((v) => v.codec_type === "audio");
465
547
  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.");
548
+ mediaError(
549
+ "UNSUPPORTED_MEDIA",
550
+ output ? "The exported stream layout is invalid." : "Use one H.264 video stream and at most one AAC audio stream."
551
+ );
467
552
  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.");
553
+ 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))
554
+ mediaError(
555
+ "UNSUPPORTED_MEDIA",
556
+ output ? "The exported video does not match the selected format." : "Use an 8-bit square-pixel H.264 MP4 video."
557
+ );
470
558
  const colorTags = [video.color_space, video.color_transfer, video.color_primaries];
471
559
  const missingColor = (tag) => tag === void 0 || tag === null || ["", "unknown", "unspecified", "N/A"].includes(String(tag));
472
560
  const declaredHdr = video.side_data_list?.some(
@@ -497,8 +585,11 @@ function parseMetadata(info, file) {
497
585
  "MEDIA_LIMIT_EXCEEDED",
498
586
  "Use an even-sized video up to 3840 by 2160, 60 fps, 600 seconds and 2 GiB."
499
587
  );
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.");
588
+ 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)))
589
+ mediaError(
590
+ "UNSUPPORTED_AUDIO",
591
+ output ? "The exported audio does not match the selected format." : "Use one mono or stereo AAC track with a valid sample rate."
592
+ );
502
593
  return metadata.parse({
503
594
  durationMs: Math.round(duration * 1e3),
504
595
  width,
@@ -589,15 +680,33 @@ var Videos = class {
589
680
  if (!/\blibx264\b/.test(encoders) || !/\baac\b/.test(encoders))
590
681
  mediaError("TOOL_UNSUPPORTED", "FFmpeg needs libx264 and AAC encoders.");
591
682
  const filters = (await this.command(ffmpeg, ["-hide_banner", "-filters"])).stdout;
592
- for (const filter of ["trim", "atrim", "crop", "scale", "concat", "aresample", "anullsrc"])
683
+ for (const filter of [
684
+ "trim",
685
+ "atrim",
686
+ "crop",
687
+ "scale",
688
+ "concat",
689
+ "aresample",
690
+ "anullsrc",
691
+ "fps",
692
+ "pad",
693
+ "eq",
694
+ "atempo"
695
+ ])
593
696
  if (!new RegExp("\\b" + filter + "\\b").test(filters))
594
697
  mediaError("TOOL_UNSUPPORTED", "FFmpeg is missing required video or audio filters.");
698
+ const muxers = (await this.command(ffmpeg, ["-hide_banner", "-muxers"])).stdout;
699
+ const exportFormats = ["h264"];
700
+ if (/\bmp4\b/.test(muxers) && /\blibx265\b/.test(encoders)) exportFormats.push("hevc");
701
+ if (/\bwebm\b/.test(muxers) && /\blibvpx-vp9\b/.test(encoders) && /\blibopus\b/.test(encoders))
702
+ exportFormats.push("vp9");
595
703
  this.toolCache = {
596
704
  ffmpeg,
597
705
  ffprobe,
598
706
  ffmpegVersion: encoder.stdout.split("\n")[0],
599
707
  ffprobeVersion: probe.stdout.split("\n")[0],
600
- profileVersion: 1
708
+ profileVersion: 1,
709
+ exportFormats
601
710
  };
602
711
  return this.toolCache;
603
712
  }
@@ -694,7 +803,7 @@ var Videos = class {
694
803
  file: descriptor.file,
695
804
  recipe: descriptor.recipe,
696
805
  geometry: descriptor.geometry,
697
- effectiveDurationMs: descriptor.recipe.trim.outMs - descriptor.recipe.trim.inMs,
806
+ effectiveDurationMs: recipeDurationMs(descriptor.recipe),
698
807
  editRef: saved?.editRef ?? null,
699
808
  revision: saved?.revision ?? null,
700
809
  name: fixed.object.data.name,
@@ -853,29 +962,53 @@ function segmentTiming(descriptor, frames) {
853
962
  origin + descriptor.metadata.durationMs / 1e3
854
963
  );
855
964
  const tolerance = Math.max(lastDuration, ...kept.slice(1).map((v, i) => v - kept[i]));
965
+ const speed = descriptor.recipe.speed ?? 1;
856
966
  return {
857
967
  start: first,
858
968
  end: actualEnd,
859
- duration: actualEnd - first,
860
- frames: kept.map((v) => v - first),
861
- tolerance
969
+ duration: (actualEnd - first) / speed,
970
+ frames: kept.map((v) => (v - first) / speed),
971
+ tolerance: tolerance / speed
862
972
  };
863
973
  }
864
974
  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 = [];
975
+ function tempoFilters(speed) {
976
+ const values = [];
977
+ while (speed < 0.5) {
978
+ values.push(0.5);
979
+ speed /= 0.5;
980
+ }
981
+ while (speed > 2) {
982
+ values.push(2);
983
+ speed /= 2;
984
+ }
985
+ if (speed !== 1) values.push(speed);
986
+ return values.map((value) => `atempo=${seconds(value)}`);
987
+ }
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 = [];
867
994
  const args = ["-hide_banner", "-nostdin", "-y", "-copyts"];
868
995
  for (const input of inputs) args.push("-protocol_whitelist", "file,pipe", "-i", input.path);
869
996
  for (const [index, { descriptor, timing }] of inputs.entries()) {
870
997
  const rect = descriptor.geometry.pixelRect;
998
+ const speed = descriptor.recipe.speed ?? 1;
999
+ const color = descriptor.recipe.color;
871
1000
  const video = [
872
1001
  `[${index}:v:0]trim=start=${seconds(timing.start)}:end=${seconds(timing.end)}`,
873
- `setpts=PTS-${seconds(timing.start)}/TB`,
1002
+ speed === 1 ? `setpts=PTS-${seconds(timing.start)}/TB` : `setpts=(PTS-${seconds(timing.start)}/TB)/${seconds(speed)}`,
874
1003
  "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709",
875
1004
  `crop=${rect.width}:${rect.height}:${rect.x}:${rect.y}`,
1005
+ ...color ? [
1006
+ `eq=brightness=${color.brightness}:contrast=${color.contrast}:saturation=${color.saturation}`
1007
+ ] : [],
876
1008
  "setsar=1",
877
1009
  ...canvas2 ? [
878
- `scale=${canvas2.width}:${canvas2.height}:flags=lanczos:in_color_matrix=bt709:out_color_matrix=bt709`
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"] : []
879
1012
  ] : [],
880
1013
  "format=yuv420p",
881
1014
  "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709"
@@ -887,7 +1020,18 @@ function renderArguments(inputs, output, canvas2) {
887
1020
  let audio;
888
1021
  if (descriptor.metadata.hasAudio) {
889
1022
  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)}`;
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(",");
891
1035
  } else
892
1036
  audio = `anullsrc=r=48000:cl=stereo,atrim=duration=${seconds(timing.duration)},asetpts=PTS-STARTPTS`;
893
1037
  filters.push(audio + `[a${index}]`);
@@ -899,17 +1043,28 @@ function renderArguments(inputs, output, canvas2) {
899
1043
  labels.join("") + `concat=n=${inputs.length}:v=1:a=${audible ? 1 : 0}[video]${audible ? "[audio]" : ""}`
900
1044
  );
901
1045
  }
902
- args.push("-filter_complex", filters.join(";"), "-map", inputs.length > 1 ? "[video]" : "[v0]");
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]`);
1049
+ }
1050
+ args.push("-filter_complex", filters.join(";"), "-map", fps ? "[cfr]" : videoLabel);
903
1051
  if (audible)
904
- args.push("-map", inputs.length > 1 ? "[audio]" : "[a0]", "-c:a", "aac", "-b:a", "192k");
1052
+ args.push(
1053
+ "-map",
1054
+ inputs.length > 1 ? "[audio]" : "[a0]",
1055
+ "-c:a",
1056
+ profile.audio === "opus" ? "libopus" : profile.audio,
1057
+ "-b:a",
1058
+ "192k"
1059
+ );
905
1060
  else args.push("-an");
906
1061
  args.push(
907
1062
  "-c:v",
908
- "libx264",
1063
+ profile.encoder,
909
1064
  "-crf",
910
- "18",
911
- "-preset",
912
- "medium",
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"] : [],
913
1068
  "-threads",
914
1069
  "4",
915
1070
  "-pix_fmt",
@@ -917,9 +1072,11 @@ function renderArguments(inputs, output, canvas2) {
917
1072
  "-fps_mode",
918
1073
  "passthrough",
919
1074
  "-enc_time_base:v",
920
- "1:90000",
921
- "-video_track_timescale",
922
- "90000",
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
+ ),
923
1080
  "-color_primaries",
924
1081
  "bt709",
925
1082
  "-color_trc",
@@ -928,8 +1085,6 @@ function renderArguments(inputs, output, canvas2) {
928
1085
  "bt709",
929
1086
  "-metadata:s:v:0",
930
1087
  "rotate=0",
931
- "-movflags",
932
- "+faststart",
933
1088
  "-progress",
934
1089
  "pipe:1",
935
1090
  "-stats_period",
@@ -940,6 +1095,7 @@ function renderArguments(inputs, output, canvas2) {
940
1095
  args,
941
1096
  audible,
942
1097
  audioSampleRate,
1098
+ frameRate: fps,
943
1099
  expectedFrames: inputs.flatMap((input, index) => {
944
1100
  const offset = inputs.slice(0, index).reduce((n, i) => n + i.timing.duration, 0);
945
1101
  return input.timing.frames.map((t) => t + offset);
@@ -948,7 +1104,13 @@ function renderArguments(inputs, output, canvas2) {
948
1104
  tolerance: inputs.reduce((n, i) => n + i.timing.tolerance, 0)
949
1105
  };
950
1106
  }
951
- function validateFrameTiming(actual, timings) {
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
+ }
952
1114
  if (actual.length !== timings.reduce((total, timing) => total + timing.frames.length, 0))
953
1115
  mediaError("OUTPUT_TIMING_MISMATCH", "The output frame count changed.");
954
1116
  let index = 0, expectedStart = 0, boundaryTolerance = 0;
@@ -960,7 +1122,7 @@ function validateFrameTiming(actual, timings) {
960
1122
  "The output segment boundary moved beyond the source frame allowance."
961
1123
  );
962
1124
  for (let offset = 0; offset < timing.frames.length; offset++)
963
- if (Math.abs(actual[index + offset] - first - timing.frames[offset]) > 1e-3)
1125
+ if (Math.abs(actual[index + offset] - first - timing.frames[offset]) > precision)
964
1126
  mediaError("OUTPUT_TIMING_MISMATCH", "The output changed timing inside a source segment.");
965
1127
  index += timing.frames.length;
966
1128
  expectedStart += timing.duration;
@@ -974,7 +1136,8 @@ var toolsSchema = z3.object({
974
1136
  ffprobe: z3.string(),
975
1137
  ffmpegVersion: z3.string(),
976
1138
  ffprobeVersion: z3.string(),
977
- profileVersion: z3.literal(1)
1139
+ profileVersion: z3.literal(1),
1140
+ exportFormats: z3.array(exportFormat).optional()
978
1141
  }).strict();
979
1142
  var snapshot = z3.object({
980
1143
  request: mediaRequest,
@@ -1189,17 +1352,32 @@ var Jobs = class {
1189
1352
  for (const input of inputs) descriptors.push(await this.videos.descriptor(input));
1190
1353
  tools = await this.videos.tools();
1191
1354
  }
1355
+ if (descriptors.reduce((total, d) => total + recipeDurationMs(d.recipe), 0) > 6e5)
1356
+ mediaError("MEDIA_LIMIT_EXCEEDED", "The edited duration exceeds 600 seconds.");
1192
1357
  if (request.operation === "sequence.process") {
1193
1358
  const canvas2 = request.input.canvas, bytes = /* @__PURE__ */ new Map();
1359
+ const settings = request.input.settings;
1360
+ if (settings) {
1361
+ if (!(tools.exportFormats ?? ["h264"]).includes(settings.format))
1362
+ mediaError(
1363
+ "TOOL_UNSUPPORTED",
1364
+ "The configured FFmpeg cannot export the selected format."
1365
+ );
1366
+ if (!exportDimensions(canvas2, settings.aspect, settings.resolution))
1367
+ mediaError(
1368
+ "MEDIA_LIMIT_EXCEEDED",
1369
+ "The selected aspect ratio and resolution exceed 3840 by 2160."
1370
+ );
1371
+ }
1194
1372
  let duration = 0;
1195
1373
  for (const d of descriptors) {
1196
1374
  const rect = d.geometry.pixelRect;
1197
- if (rect.width * canvas2.height !== rect.height * canvas2.width)
1375
+ if (!settings && rect.width * canvas2.height !== rect.height * canvas2.width)
1198
1376
  mediaError(
1199
1377
  "SEQUENCE_GEOMETRY_MISMATCH",
1200
1378
  "Every selected crop must have exactly the project output aspect ratio."
1201
1379
  );
1202
- duration += d.recipe.trim.outMs - d.recipe.trim.inMs;
1380
+ duration += recipeDurationMs(d.recipe);
1203
1381
  bytes.set(d.metadata.sha256, d.metadata.sizeBytes);
1204
1382
  }
1205
1383
  if (duration > 6e5 || [...bytes.values()].reduce((a, b) => a + b, 0) > 2147483648)
@@ -1377,7 +1555,13 @@ var Jobs = class {
1377
1555
  );
1378
1556
  const d = row.data, directory = this.directory(id, token);
1379
1557
  await mkdir2(directory, { recursive: true });
1380
- output = join3(directory, "output.mp4");
1558
+ const sequence = d.snapshot.request.operation === "sequence.process" ? d.snapshot.request.input : void 0;
1559
+ const settings = sequence?.settings;
1560
+ const targetCanvas = sequence && (settings ? exportDimensions(sequence.canvas, settings.aspect, settings.resolution) : sequence.canvas);
1561
+ if (targetCanvas === null)
1562
+ mediaError("MEDIA_LIMIT_EXCEEDED", "The selected output size is unavailable.");
1563
+ const profile = exportProfiles[settings?.format ?? "h264"];
1564
+ output = join3(directory, `output.${profile.extension}`);
1381
1565
  const space = await statfs(directory);
1382
1566
  if (Number(space.bavail) * Number(space.bsize) < 4.5 * 1024 ** 3)
1383
1567
  mediaError(
@@ -1415,11 +1599,7 @@ var Jobs = class {
1415
1599
  timing: segmentTiming(descriptor, frames)
1416
1600
  });
1417
1601
  }
1418
- const rendered = renderArguments(
1419
- inputs,
1420
- output,
1421
- d.snapshot.request.operation === "sequence.process" ? d.snapshot.request.input.canvas : void 0
1422
- );
1602
+ const rendered = renderArguments(inputs, output, targetCanvas, settings);
1423
1603
  let progressBuffer = "", lastProgress = 0;
1424
1604
  await this.native.run(d.snapshot.tools.ffmpeg, rendered.args, {
1425
1605
  ...commandOptions,
@@ -1460,12 +1640,17 @@ var Jobs = class {
1460
1640
  const hash = createHash2("sha256");
1461
1641
  for await (const chunk of createReadStream(output, { signal: abort.signal }))
1462
1642
  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)
1643
+ const checked = parseMetadata(
1644
+ JSON.parse(details.stdout),
1645
+ {
1646
+ sizeBytes: size,
1647
+ sha256: hash.digest("hex")
1648
+ },
1649
+ settings ? profile : void 0
1650
+ );
1651
+ const target = targetCanvas ?? inputs[0].descriptor.geometry.pixelRect;
1652
+ 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))
1469
1654
  mediaError(
1470
1655
  "OUTPUT_VALIDATION_FAILED",
1471
1656
  "The output color declaration, geometry, duration or audio does not match the fixed recipe."
@@ -1488,7 +1673,9 @@ var Jobs = class {
1488
1673
  const actualFrames = frameTimes(frameResult.stdout);
1489
1674
  validateFrameTiming(
1490
1675
  actualFrames,
1491
- inputs.map((input) => input.timing)
1676
+ inputs.map((input) => input.timing),
1677
+ fps,
1678
+ profile.container === "webm"
1492
1679
  );
1493
1680
  const decoded = await this.native.run(
1494
1681
  d.snapshot.tools.ffmpeg,
@@ -1502,7 +1689,7 @@ var Jobs = class {
1502
1689
  mediaError("OUTPUT_DECODE_FAILED", "The result could not be completely decoded.");
1503
1690
  const staged = await this.data.stage(
1504
1691
  createReadStream(output),
1505
- d.snapshot.request.input.outputName + ".mp4",
1692
+ settings ? exportName(d.snapshot.request.input.outputName, profile.extension) : d.snapshot.request.input.outputName + ".mp4",
1506
1693
  "local",
1507
1694
  {
1508
1695
  signal: abort.signal,
@@ -1536,7 +1723,7 @@ var Jobs = class {
1536
1723
  kind: d.kind,
1537
1724
  jobId: id,
1538
1725
  inputs: ordered,
1539
- canvas: request.operation === "sequence.process" ? request.input.canvas : null,
1726
+ canvas: targetCanvas ?? null,
1540
1727
  tools: {
1541
1728
  ffmpegVersion: d.snapshot.tools.ffmpegVersion,
1542
1729
  ffprobeVersion: d.snapshot.tools.ffprobeVersion,
@@ -1654,24 +1841,26 @@ async function activate(ctx) {
1654
1841
  );
1655
1842
  projects.add(ctx.project.id);
1656
1843
  activeProjects.set(workspace, projects);
1844
+ let data;
1657
1845
  try {
1658
- const data = workspace.bind({
1846
+ data = workspace.bind({
1659
1847
  scope: { kind: "project", id: ctx.project.id },
1660
1848
  ownerPackage: "@vivix/media-tools",
1661
1849
  packageVersion,
1662
1850
  actorId: "local",
1663
1851
  access: ["data.workspace"]
1664
1852
  });
1665
- data.register(editType);
1666
- data.register(jobType);
1853
+ const boundData = data;
1854
+ boundData.register(editType);
1855
+ boundData.register(jobType);
1667
1856
  const runtimeRoot = join4(
1668
1857
  ctx.project.root,
1669
1858
  ".vivix",
1670
1859
  "runtime",
1671
1860
  "media-tools",
1672
1861
  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,
1862
+ ), native = new NativeExecutor(), videos = new Videos(boundData, native, ctx.config, runtimeRoot), edits = new Edits(boundData, videos), jobs = new Jobs(
1863
+ boundData,
1675
1864
  videos,
1676
1865
  native,
1677
1866
  studio.derivedVideos,
@@ -1682,11 +1871,12 @@ async function activate(ctx) {
1682
1871
  const ensureActive = () => {
1683
1872
  if (!active) mediaError("SERVICE_STOPPED", "This media-tools instance has stopped.");
1684
1873
  };
1685
- ctx.onDispose(async () => {
1874
+ ctx.onDispose?.(async () => {
1686
1875
  active = false;
1687
1876
  try {
1688
1877
  await jobs.dispose();
1689
1878
  } finally {
1879
+ boundData.dispose?.();
1690
1880
  projects.delete(ctx.project.id);
1691
1881
  }
1692
1882
  });
@@ -1702,14 +1892,17 @@ async function activate(ctx) {
1702
1892
  }),
1703
1893
  (input, call) => {
1704
1894
  ensureActive();
1705
- return action(input, { ...call, scope: data.scope });
1895
+ return action(input, { ...call, scope: boundData.scope });
1706
1896
  }
1707
1897
  );
1898
+ handle("export.capabilities", z4.object({}).strict(), async () => ({
1899
+ formats: (await videos.tools()).exportFormats ?? ["h264"]
1900
+ }));
1708
1901
  handle("video.resolve", videoInput, (input) => videos.resolve(input));
1709
1902
  handle("edits.get", z4.object({ editRef: versionRef }).strict(), async (input) => {
1710
1903
  const saved = edits.get(input.editRef);
1711
- await data.location(input.editRef);
1712
- await data.location(saved.file.source, saved.file.fileId);
1904
+ await boundData.location(input.editRef);
1905
+ await boundData.location(saved.file.source, saved.file.fileId);
1713
1906
  return saved;
1714
1907
  });
1715
1908
  handle("edits.save", saveEdit, (input, call) => edits.save(input, call), true);
@@ -1735,13 +1928,13 @@ async function activate(ctx) {
1735
1928
  );
1736
1929
  const service = {
1737
1930
  capabilityVersion: "media-tools/1",
1738
- storeId: data.storeId,
1931
+ storeId: boundData.storeId,
1739
1932
  projectId: ctx.project.id,
1740
1933
  getEdit: async (ref) => {
1741
1934
  ensureActive();
1742
1935
  const saved = edits.get(versionRef.parse(ref));
1743
- await data.location(ref);
1744
- await data.location(saved.file.source, saved.file.fileId);
1936
+ await boundData.location(ref);
1937
+ await boundData.location(saved.file.source, saved.file.fileId);
1745
1938
  return saved;
1746
1939
  },
1747
1940
  resolve: (input) => {
@@ -1752,6 +1945,7 @@ async function activate(ctx) {
1752
1945
  ctx.provide(service);
1753
1946
  await jobs.start();
1754
1947
  } catch (error) {
1948
+ data?.dispose?.();
1755
1949
  projects.delete(ctx.project.id);
1756
1950
  throw error;
1757
1951
  }