@morshoto/framekit 0.1.0 → 0.1.5

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 (65) hide show
  1. package/README.md +42 -17
  2. package/dist-package/adapters/final-cut/typescript/src/analyzers.js +86 -2
  3. package/dist-package/adapters/final-cut/typescript/src/connection.js +5 -1
  4. package/dist-package/adapters/final-cut/typescript/src/export.js +231 -8
  5. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +70 -9
  6. package/dist-package/adapters/final-cut/typescript/src/live.js +2 -2
  7. package/dist-package/adapters/final-cut/typescript/src/native.js +1000 -100
  8. package/dist-package/adapters/final-cut/typescript/src/publisher.js +242 -30
  9. package/dist-package/adapters/final-cut/typescript/src/session.js +86 -9
  10. package/dist-package/apps/mcp-server/src/main.js +10 -1
  11. package/dist-package/apps/mcp-server/src/routing.js +172 -0
  12. package/dist-package/apps/mcp-server/src/server.js +867 -52
  13. package/dist-package/apps/mcp-server/src/version.js +34 -0
  14. package/dist-package/packages/runtime/src/application/duration-policy-service.js +6 -0
  15. package/dist-package/packages/runtime/src/application/media-analysis-service.js +473 -0
  16. package/dist-package/packages/runtime/src/application/project-service.js +146 -0
  17. package/dist-package/packages/runtime/src/application/runtime-options.js +1 -0
  18. package/dist-package/packages/runtime/src/application/transaction-store.js +12 -0
  19. package/dist-package/packages/runtime/src/audio/dialogue-normalization.js +64 -0
  20. package/dist-package/packages/runtime/src/audio/noise-reduction.js +46 -0
  21. package/dist-package/packages/runtime/src/capabilities.js +187 -1
  22. package/dist-package/packages/runtime/src/color-correction.js +48 -0
  23. package/dist-package/packages/runtime/src/context/context-engine.js +20 -6
  24. package/dist-package/packages/runtime/src/context/context-service.js +30 -0
  25. package/dist-package/packages/runtime/src/context/revision.js +3 -0
  26. package/dist-package/packages/runtime/src/domain/capabilities.js +1 -0
  27. package/dist-package/packages/runtime/src/domain/context.js +1 -0
  28. package/dist-package/packages/runtime/src/domain/diff.js +1 -0
  29. package/dist-package/packages/runtime/src/domain/duration.js +1 -0
  30. package/dist-package/packages/runtime/src/domain/editing.js +1 -0
  31. package/dist-package/packages/runtime/src/domain/index.js +12 -0
  32. package/dist-package/packages/runtime/src/domain/media.js +8 -0
  33. package/dist-package/packages/runtime/src/domain/ports.js +1 -0
  34. package/dist-package/packages/runtime/src/domain/primitives.js +1 -0
  35. package/dist-package/packages/runtime/src/domain/project.js +1 -0
  36. package/dist-package/packages/runtime/src/domain/rough-cut.js +69 -0
  37. package/dist-package/packages/runtime/src/domain/skills.js +33 -0
  38. package/dist-package/packages/runtime/src/domain/types.js +5 -1
  39. package/dist-package/packages/runtime/src/domain/verification.js +1 -0
  40. package/dist-package/packages/runtime/src/editing/dialogue-normalization-service.js +141 -0
  41. package/dist-package/packages/runtime/src/editing/duration-policy.js +187 -0
  42. package/dist-package/packages/runtime/src/editing/edit-service.js +449 -0
  43. package/dist-package/packages/runtime/src/editing/filler-removal-service.js +361 -0
  44. package/dist-package/packages/runtime/src/editing/music-service.js +85 -0
  45. package/dist-package/packages/runtime/src/index.js +14 -3
  46. package/dist-package/packages/runtime/src/planning/rough-cut.js +71 -0
  47. package/dist-package/packages/runtime/src/runtime.js +131 -826
  48. package/dist-package/packages/runtime/src/skills/builtin.js +339 -0
  49. package/dist-package/packages/runtime/src/skills/index.js +3 -0
  50. package/dist-package/packages/runtime/src/skills/registry.js +74 -0
  51. package/dist-package/packages/runtime/src/skills/requirements.js +170 -0
  52. package/dist-package/packages/runtime/src/skills/runtime.js +239 -0
  53. package/dist-package/packages/runtime/src/speech/analysis.js +301 -0
  54. package/dist-package/packages/runtime/src/speech/filler-detector.js +132 -0
  55. package/dist-package/packages/runtime/src/speech/mapping.js +227 -0
  56. package/dist-package/packages/runtime/src/speech/safe-cut-resolver.js +314 -0
  57. package/dist-package/packages/runtime/src/timeline/rational-time.js +63 -0
  58. package/dist-package/packages/runtime/src/verification/verification.js +712 -1
  59. package/dist-package/packages/testkit/src/fixture-analyzers.js +28 -0
  60. package/dist-package/packages/testkit/src/in-memory-editor.js +287 -3
  61. package/dist-package/packages/testkit/src/index.js +1 -0
  62. package/dist-package/packages/testkit/src/skill-fixtures.js +64 -0
  63. package/package.json +17 -8
  64. /package/dist-package/packages/runtime/src/{diff/diff.js → timeline/snapshot-diff.js} +0 -0
  65. /package/dist-package/packages/runtime/src/{snapshot-digest.js → timeline/snapshot-digest.js} +0 -0
@@ -0,0 +1,227 @@
1
+ import { addRationalTimes, parseRational, subtractRationalTimes } from "../timeline/rational-time.js";
2
+ /** Map validated source evidence onto one exact timeline occurrence. */
3
+ export function mapSpeechAnalysisToOccurrence(analysis, occurrence, options) {
4
+ validateOccurrence(occurrence);
5
+ if (analysis.mediaId !== occurrence.mediaId) {
6
+ throw new Error("TARGET_MISMATCH: speech analysis media does not match the timeline occurrence");
7
+ }
8
+ if (!sameRevision(analysis.revision, occurrence.revision)) {
9
+ throw new Error("STALE_CONTEXT: speech analysis revision does not match the timeline occurrence");
10
+ }
11
+ if (!analysis.sourceTimebase) {
12
+ throw new Error("ANALYSIS_INVALID: speech source timebase is required for mapping");
13
+ }
14
+ const sourceTimebase = validatePositiveRational(analysis.sourceTimebase, "ANALYSIS_INVALID", "speech source timebase");
15
+ if (occurrence.sourceTimebase !== undefined) {
16
+ const occurrenceTimebase = validatePositiveRational(occurrence.sourceTimebase, "ANALYSIS_INVALID", "occurrence source timebase");
17
+ if (!sameRational(sourceTimebase, occurrenceTimebase)) {
18
+ throw new Error("AMBIGUOUS_MAPPING: speech source timebase does not match the timeline occurrence");
19
+ }
20
+ }
21
+ const frame = validatePositiveRational(options.sequenceFrameDuration, "ANALYSIS_INVALID", "sequence frame duration");
22
+ const sourceDuration = occurrence.sourceRange.end - occurrence.sourceRange.start;
23
+ const sequenceDuration = occurrence.sequenceRange.end - occurrence.sequenceRange.start;
24
+ if (Math.abs(sourceDuration - sequenceDuration) > 0.000000001) {
25
+ throw new Error("AMBIGUOUS_MAPPING: source and sequence occurrence durations differ");
26
+ }
27
+ validateSequenceRationalRange(occurrence.sequenceRange);
28
+ return {
29
+ occurrenceId: occurrence.occurrenceId,
30
+ mediaId: occurrence.mediaId,
31
+ revision: structuredClone(occurrence.revision),
32
+ sourceRange: structuredClone(occurrence.sourceRange),
33
+ sequenceRange: structuredClone(occurrence.sequenceRange),
34
+ sourceTimebase,
35
+ sequenceFrameDuration: frame,
36
+ capability: analysis.capability,
37
+ words: mapEvidence(analysis.words, occurrence, frame, "speech word", (word) => word),
38
+ ...(analysis.vadSegments
39
+ ? { vadSegments: mapEvidence(analysis.vadSegments, occurrence, frame, "VAD segment", (segment) => segment) }
40
+ : {}),
41
+ ...(analysis.silenceSegments
42
+ ? { silenceSegments: mapEvidence(analysis.silenceSegments, occurrence, frame, "silence segment", (segment) => segment) }
43
+ : {}),
44
+ ...(analysis.protectedSegments
45
+ ? { protectedSegments: mapEvidence(analysis.protectedSegments, occurrence, frame, "protected segment", (segment) => segment) }
46
+ : {}),
47
+ };
48
+ }
49
+ /** Map one source range onto an exact timeline occurrence. */
50
+ export function mapSourceRangeToSequenceRange(sourceRange, occurrence) {
51
+ validateRange(sourceRange, "source range");
52
+ validateRange(occurrence.sourceRange, "source occurrence range");
53
+ validateRange(occurrence.sequenceRange, "sequence occurrence range");
54
+ const sourceDuration = occurrence.sourceRange.end - occurrence.sourceRange.start;
55
+ const sequenceDuration = occurrence.sequenceRange.end - occurrence.sequenceRange.start;
56
+ if (Math.abs(sourceDuration - sequenceDuration) > 0.000000001) {
57
+ throw new Error("AMBIGUOUS_MAPPING: source and sequence occurrence durations differ");
58
+ }
59
+ const relation = relationToRange(sourceRange, occurrence.sourceRange);
60
+ if (relation === "outside")
61
+ throw new Error("AMBIGUOUS_MAPPING: source range is outside the occurrence");
62
+ if (relation === "partial")
63
+ throw new Error("AMBIGUOUS_MAPPING: source range crosses the occurrence boundary");
64
+ return translateRange(sourceRange, occurrence, validateSequenceRationalRange(occurrence.sequenceRange));
65
+ }
66
+ function mapEvidence(evidence, occurrence, frame, label, clone) {
67
+ const mapped = [];
68
+ for (const value of evidence) {
69
+ const relation = relationToRange(value, occurrence.sourceRange);
70
+ if (relation === "outside")
71
+ continue;
72
+ if (relation === "partial") {
73
+ throw new Error(`AMBIGUOUS_MAPPING: ${label} crosses the occurrence source boundary`);
74
+ }
75
+ const sourceRange = { start: value.start, end: value.end };
76
+ const sequenceRange = mapSourceRangeToSequenceRange(sourceRange, occurrence);
77
+ const frameAlignedRange = alignRange(sequenceRange, frame);
78
+ if (!containsRange(occurrence.sequenceRange, frameAlignedRange)) {
79
+ throw new Error(`AMBIGUOUS_MAPPING: ${label} cannot be frame-aligned inside the occurrence`);
80
+ }
81
+ const mappedValue = {
82
+ ...("text" in value ? { word: clone(value) } : { segment: clone(value) }),
83
+ sourceRange,
84
+ sequenceRange,
85
+ frameAlignedRange,
86
+ };
87
+ mapped.push(mappedValue);
88
+ }
89
+ return mapped;
90
+ }
91
+ function translateRange(source, occurrence, sequenceStartTime) {
92
+ const offset = source.start - occurrence.sourceRange.start;
93
+ const duration = source.end - source.start;
94
+ const offsetTime = source.startTime && occurrence.sourceRange.startTime
95
+ ? subtractRationalTimes(source.startTime, occurrence.sourceRange.startTime)
96
+ : secondsToRational(offset);
97
+ return {
98
+ start: occurrence.sequenceRange.start + offset,
99
+ end: occurrence.sequenceRange.start + (source.end - occurrence.sourceRange.start),
100
+ startTime: addRationalTimes(sequenceStartTime, offsetTime),
101
+ durationTime: source.durationTime ? { ...source.durationTime } : secondsToRational(duration),
102
+ };
103
+ }
104
+ function alignRange(range, frame) {
105
+ if (!range.startTime || !range.durationTime)
106
+ throw new Error("ANALYSIS_INVALID: mapped sequence range is missing rational timing");
107
+ const start = floorToFrame(range.startTime, frame);
108
+ const end = ceilToFrame(addRationalTimes(range.startTime, range.durationTime), frame);
109
+ return {
110
+ start: rationalToNumber(start),
111
+ end: rationalToNumber(end),
112
+ startTime: start,
113
+ durationTime: subtractRational(end, start),
114
+ };
115
+ }
116
+ function validateOccurrence(occurrence) {
117
+ if (!occurrence.occurrenceId.trim())
118
+ throw new Error("ANALYSIS_INVALID: speech occurrence ID is required");
119
+ if (!occurrence.mediaId.trim())
120
+ throw new Error("ANALYSIS_INVALID: speech occurrence media ID is required");
121
+ validateRange(occurrence.sourceRange, "source occurrence range");
122
+ validateRange(occurrence.sequenceRange, "sequence occurrence range");
123
+ }
124
+ function validateSequenceRationalRange(range) {
125
+ if (!range.startTime || !range.durationTime) {
126
+ throw new Error("ANALYSIS_INVALID: sequence occurrence requires exact rational timing");
127
+ }
128
+ const start = validateRational(range.startTime, "ANALYSIS_INVALID", "sequence occurrence start time");
129
+ const duration = validatePositiveRational(range.durationTime, "ANALYSIS_INVALID", "sequence occurrence duration time");
130
+ if (Math.abs(rationalToNumber(start) - range.start) > 0.000000001
131
+ || Math.abs(rationalToNumber(duration) - (range.end - range.start)) > 0.000000001) {
132
+ throw new Error("AMBIGUOUS_MAPPING: sequence occurrence seconds and rational timing differ");
133
+ }
134
+ return start;
135
+ }
136
+ function validateRange(range, label) {
137
+ if (!Number.isFinite(range.start) || !Number.isFinite(range.end) || range.start < 0 || range.end <= range.start) {
138
+ throw new Error(`ANALYSIS_INVALID: ${label} is invalid`);
139
+ }
140
+ }
141
+ function validatePositiveRational(value, errorCode, label) {
142
+ const rational = validateRational(value, errorCode, label);
143
+ if (parseRational(rational, errorCode).value <= 0n)
144
+ throw new Error(`${errorCode}: ${label} must be positive`);
145
+ return rational;
146
+ }
147
+ function validateRational(value, errorCode, label) {
148
+ try {
149
+ parseRational(value, errorCode);
150
+ }
151
+ catch (error) {
152
+ throw new Error(`${errorCode}: ${label} is invalid: ${String(error)}`);
153
+ }
154
+ return { value: value.value, timescale: value.timescale };
155
+ }
156
+ function relationToRange(value, range) {
157
+ if (value.end <= range.start || value.start >= range.end)
158
+ return "outside";
159
+ if (value.start >= range.start && value.end <= range.end)
160
+ return "inside";
161
+ return "partial";
162
+ }
163
+ function containsRange(container, value) {
164
+ return value.start >= container.start - 0.000000001 && value.end <= container.end + 0.000000001;
165
+ }
166
+ function floorToFrame(value, frame) {
167
+ const valueParts = parseRational(value, "ANALYSIS_INVALID");
168
+ const frameParts = parseRational(frame, "ANALYSIS_INVALID");
169
+ const numerator = valueParts.value * frameParts.timescale;
170
+ const denominator = valueParts.timescale * frameParts.value;
171
+ const quotient = floorDivision(numerator, denominator);
172
+ return normalizeRational(quotient * frameParts.value, frameParts.timescale);
173
+ }
174
+ function ceilToFrame(value, frame) {
175
+ const valueParts = parseRational(value, "ANALYSIS_INVALID");
176
+ const frameParts = parseRational(frame, "ANALYSIS_INVALID");
177
+ const numerator = valueParts.value * frameParts.timescale;
178
+ const denominator = valueParts.timescale * frameParts.value;
179
+ const quotient = floorDivision(numerator + denominator - 1n, denominator);
180
+ return normalizeRational(quotient * frameParts.value, frameParts.timescale);
181
+ }
182
+ function floorDivision(numerator, denominator) {
183
+ if (numerator >= 0n)
184
+ return numerator / denominator;
185
+ return -((-numerator + denominator - 1n) / denominator);
186
+ }
187
+ function subtractRational(left, right) {
188
+ const leftParts = parseRational(left, "ANALYSIS_INVALID");
189
+ const rightParts = parseRational(right, "ANALYSIS_INVALID");
190
+ return normalizeRational(leftParts.value * rightParts.timescale - rightParts.value * leftParts.timescale, leftParts.timescale * rightParts.timescale);
191
+ }
192
+ function rationalToNumber(value) {
193
+ const parts = parseRational(value, "ANALYSIS_INVALID");
194
+ const result = Number(parts.value) / Number(parts.timescale);
195
+ if (!Number.isFinite(result))
196
+ throw new Error("ANALYSIS_INVALID: rational mapping is outside supported range");
197
+ return result;
198
+ }
199
+ function secondsToRational(seconds) {
200
+ const text = seconds.toFixed(6).replace(/0+$/, "").replace(/\.$/, "");
201
+ if (!text.includes("."))
202
+ return { value: text || "0", timescale: "1" };
203
+ const [whole, fraction = ""] = text.split(".");
204
+ const numerator = BigInt(`${whole}${fraction}`);
205
+ const denominator = 10n ** BigInt(fraction.length);
206
+ return normalizeRational(numerator, denominator);
207
+ }
208
+ function normalizeRational(value, timescale) {
209
+ const divisor = greatestCommonDivisor(value < 0n ? -value : value, timescale);
210
+ return { value: String(value / divisor), timescale: String(timescale / divisor) };
211
+ }
212
+ function greatestCommonDivisor(left, right) {
213
+ while (right !== 0n) {
214
+ const remainder = left % right;
215
+ left = right;
216
+ right = remainder;
217
+ }
218
+ return left || 1n;
219
+ }
220
+ function sameRevision(left, right) {
221
+ return left.id === right.id && left.sequence === right.sequence && left.timestamp === right.timestamp;
222
+ }
223
+ function sameRational(left, right) {
224
+ const leftParts = parseRational(left, "ANALYSIS_INVALID");
225
+ const rightParts = parseRational(right, "ANALYSIS_INVALID");
226
+ return leftParts.value * rightParts.timescale === rightParts.value * leftParts.timescale;
227
+ }
@@ -0,0 +1,314 @@
1
+ export const DEFAULT_SAFE_CUT_PRESERVE_PAUSE_MS = 700;
2
+ export const DEFAULT_SAFE_CUT_TARGET_PAUSE_MS = 500;
3
+ /** Resolve filler words to safe frame-aligned operations without mutating an editor. */
4
+ export class SafeCutResolver {
5
+ preservePauseMs;
6
+ targetPauseMs;
7
+ constructor(options = {}) {
8
+ this.preservePauseMs = options.preservePauseMs ?? DEFAULT_SAFE_CUT_PRESERVE_PAUSE_MS;
9
+ this.targetPauseMs = options.targetPauseMs ?? DEFAULT_SAFE_CUT_TARGET_PAUSE_MS;
10
+ if (!Number.isFinite(this.preservePauseMs)
11
+ || this.preservePauseMs < 0
12
+ || !Number.isFinite(this.targetPauseMs)
13
+ || this.targetPauseMs < 0
14
+ || this.targetPauseMs > this.preservePauseMs) {
15
+ throw new Error("INVALID_OPERATION: safe cut pause settings are invalid");
16
+ }
17
+ }
18
+ resolve(request) {
19
+ const evidence = createEvidence(request);
20
+ const base = {
21
+ candidateId: request.candidate.id,
22
+ occurrenceId: request.occurrence.occurrenceId,
23
+ evidence,
24
+ };
25
+ const initialReasons = [];
26
+ if (request.candidate.occurrenceId !== request.occurrence.occurrenceId) {
27
+ return { ...base, status: "SKIPPED", reasonCodes: ["AMBIGUOUS_MAPPING"] };
28
+ }
29
+ if (!isContained(request.candidate.sequenceRange, request.targetRange)) {
30
+ return { ...base, status: "SKIPPED", reasonCodes: ["OUTSIDE_TARGET_BOUND"] };
31
+ }
32
+ if (!isContained(request.candidate.sequenceRange, request.occurrence.sequenceRange)) {
33
+ return { ...base, status: "SKIPPED", reasonCodes: ["OUTSIDE_OCCURRENCE_BOUND"] };
34
+ }
35
+ if (!isSequenceMappingConsistent(request.candidate, request.occurrence)) {
36
+ return { ...base, status: "SKIPPED", reasonCodes: ["AMBIGUOUS_MAPPING"] };
37
+ }
38
+ const frame = parseRational(request.sequenceFrameDuration);
39
+ if (!frame || frame.numerator <= 0n) {
40
+ return { ...base, status: "SKIPPED", reasonCodes: ["NO_FRAME_ALIGNED_RANGE"] };
41
+ }
42
+ const words = orderWords(request.analysis.words);
43
+ if (!words) {
44
+ return { ...base, status: "SKIPPED", reasonCodes: ["OVERLAPPING_SPEECH"] };
45
+ }
46
+ const wordMatches = words.filter((word) => sameWord(word, request.candidate.word));
47
+ if (wordMatches.length !== 1) {
48
+ return { ...base, status: "SKIPPED", reasonCodes: ["AMBIGUOUS_MAPPING"] };
49
+ }
50
+ const wordIndex = words.indexOf(wordMatches[0]);
51
+ const word = wordMatches[0];
52
+ const previousWord = words[wordIndex - 1];
53
+ const nextWord = words[wordIndex + 1];
54
+ evidence.word = { ...word };
55
+ if (previousWord)
56
+ evidence.previousWord = { ...previousWord };
57
+ if (nextWord)
58
+ evidence.nextWord = { ...nextWord };
59
+ if (!request.analysis.vadSegments) {
60
+ return { ...base, status: "SKIPPED", reasonCodes: ["MISSING_VAD_EVIDENCE"] };
61
+ }
62
+ const vadSegments = validateSegments(request.analysis.vadSegments);
63
+ if (!vadSegments) {
64
+ return { ...base, status: "SKIPPED", reasonCodes: ["INVALID_VAD_EVIDENCE"] };
65
+ }
66
+ evidence.speechSegments = vadSegments.filter((segment) => segment.kind === "speech");
67
+ if (hasOverlappingSpeech(vadSegments)) {
68
+ return { ...base, status: "SKIPPED", reasonCodes: ["OVERLAPPING_SPEECH"] };
69
+ }
70
+ if (hasOverlappingSegments(vadSegments)) {
71
+ return { ...base, status: "SKIPPED", reasonCodes: ["INVALID_VAD_EVIDENCE"] };
72
+ }
73
+ if (!coversRange(evidence.speechSegments, request.candidate.sourceRange)) {
74
+ return { ...base, status: "SKIPPED", reasonCodes: ["MISSING_VAD_EVIDENCE"] };
75
+ }
76
+ const silenceSegments = validateSegments(request.analysis.silenceSegments ?? vadSegments.filter((segment) => segment.kind === "silence"));
77
+ if (!silenceSegments) {
78
+ return { ...base, status: "SKIPPED", reasonCodes: ["INVALID_SILENCE_EVIDENCE"] };
79
+ }
80
+ evidence.silenceSegments = silenceSegments;
81
+ const protectedSegments = validateSegments(request.analysis.protectedSegments ?? []);
82
+ if (!protectedSegments) {
83
+ return { ...base, status: "SKIPPED", reasonCodes: ["INVALID_PROTECTED_EVIDENCE"] };
84
+ }
85
+ evidence.protectedSegments = protectedSegments;
86
+ if (overlapsAny(protectedSegments, request.candidate.sourceRange)) {
87
+ return { ...base, status: "SKIPPED", reasonCodes: ["PROTECTED_SEGMENT_OVERLAP"] };
88
+ }
89
+ const nextStart = nextWord?.start ?? request.occurrence.sourceRange.end;
90
+ const followingPauseMs = Math.max(0, (nextStart - word.end) * 1000);
91
+ evidence.pauseBeforeCutMs = Math.max(0, (word.start - (previousWord?.end ?? word.start)) * 1000);
92
+ let sourceEnd = word.end;
93
+ let pauseReason = false;
94
+ if (followingPauseMs > this.preservePauseMs) {
95
+ const silenceEnd = silenceEndFor(silenceSegments, word.end, nextStart);
96
+ const desiredEnd = word.end + (followingPauseMs - this.targetPauseMs) / 1000;
97
+ if (silenceEnd !== undefined && silenceEnd >= desiredEnd) {
98
+ sourceEnd = Math.min(desiredEnd, nextStart);
99
+ pauseReason = true;
100
+ }
101
+ }
102
+ evidence.pauseAfterCutMs = Math.max(0, (nextStart - sourceEnd) * 1000);
103
+ if (overlapsAny(protectedSegments, { start: word.start, end: sourceEnd })) {
104
+ return { ...base, status: "SKIPPED", reasonCodes: ["PROTECTED_SEGMENT_OVERLAP"] };
105
+ }
106
+ const sourceStart = word.start;
107
+ const minimumSourceStart = previousWord
108
+ ? Math.max(previousWord.end, request.occurrence.sourceRange.start)
109
+ : request.occurrence.sourceRange.start;
110
+ const precedingSpeechEnd = evidence.speechSegments
111
+ .filter((segment) => segment.end <= word.start)
112
+ .reduce((latest, segment) => Math.max(latest, segment.end), minimumSourceStart);
113
+ const followingSpeechStart = evidence.speechSegments
114
+ .filter((segment) => segment.start >= sourceEnd)
115
+ .reduce((earliest, segment) => Math.min(earliest, segment.start), nextStart);
116
+ const sequenceStart = mapSourceToSequence(sourceStart, request.occurrence);
117
+ const sequenceEnd = mapSourceToSequence(sourceEnd, request.occurrence);
118
+ const minimumSequenceStart = Math.max(mapSourceToSequence(Math.max(minimumSourceStart, precedingSpeechEnd), request.occurrence), request.targetRange.start, request.occurrence.sequenceRange.start);
119
+ const maximumSequenceEnd = Math.min(mapSourceToSequence(Math.min(nextStart, followingSpeechStart), request.occurrence), request.targetRange.end, request.occurrence.sequenceRange.end);
120
+ const alignedStart = floorMultiple(decimalToRational(sequenceStart), frame);
121
+ const alignedEnd = ceilMultiple(decimalToRational(sequenceEnd), frame);
122
+ const safeStart = rationalToNumber(alignedStart);
123
+ const safeEnd = rationalToNumber(alignedEnd);
124
+ if (!Number.isFinite(safeStart)
125
+ || !Number.isFinite(safeEnd)
126
+ || safeEnd <= safeStart
127
+ || safeStart < minimumSequenceStart - 0.000000001
128
+ || safeEnd > maximumSequenceEnd + 0.000000001) {
129
+ return { ...base, status: "SKIPPED", reasonCodes: ["NO_FRAME_ALIGNED_RANGE"] };
130
+ }
131
+ const alignedSourceRange = {
132
+ start: request.occurrence.sourceRange.start
133
+ + (safeStart - request.occurrence.sequenceRange.start),
134
+ end: request.occurrence.sourceRange.start
135
+ + (safeEnd - request.occurrence.sequenceRange.start),
136
+ };
137
+ if (overlapsAny(protectedSegments, alignedSourceRange)) {
138
+ return { ...base, status: "SKIPPED", reasonCodes: ["PROTECTED_SEGMENT_OVERLAP"] };
139
+ }
140
+ const range = rangeFromRationals(alignedStart, subtractRationals(alignedEnd, alignedStart));
141
+ evidence.safeRange = structuredClone(range);
142
+ initialReasons.push("SAFE_BOUNDARY_RESOLVED");
143
+ if (pauseReason)
144
+ initialReasons.push("PAUSE_PRESERVED");
145
+ if (!request.candidate.eligible || request.candidate.confidence < request.candidate.confidenceThreshold) {
146
+ initialReasons.push("LOW_CONFIDENCE");
147
+ }
148
+ const status = initialReasons.includes("LOW_CONFIDENCE") ? "SUGGESTED" : "AUTO_APPLY";
149
+ return {
150
+ ...base,
151
+ status,
152
+ reasonCodes: initialReasons,
153
+ range,
154
+ operation: {
155
+ type: "ripple-delete",
156
+ timelineId: request.timelineId,
157
+ range: structuredClone(range),
158
+ reason: `remove filler candidate ${request.candidate.id}`,
159
+ },
160
+ };
161
+ }
162
+ }
163
+ function createEvidence(request) {
164
+ return {
165
+ word: { ...request.candidate.word },
166
+ speechSegments: [],
167
+ silenceSegments: [],
168
+ protectedSegments: [],
169
+ occurrenceRange: structuredClone(request.occurrence.sequenceRange),
170
+ targetRange: structuredClone(request.targetRange),
171
+ frameDuration: structuredClone(request.sequenceFrameDuration),
172
+ pauseBeforeCutMs: 0,
173
+ pauseAfterCutMs: 0,
174
+ };
175
+ }
176
+ function validateSegments(segments) {
177
+ if (!segments)
178
+ return undefined;
179
+ const ordered = segments.map((segment) => ({ ...segment })).sort((left, right) => left.start - right.start || left.end - right.end);
180
+ for (let index = 0; index < ordered.length; index += 1) {
181
+ const segment = ordered[index];
182
+ if (!Number.isFinite(segment.start)
183
+ || !Number.isFinite(segment.end)
184
+ || segment.start < 0
185
+ || segment.end <= segment.start
186
+ || !["speech", "silence", "breath", "laughter", "noise"].includes(segment.kind)) {
187
+ return undefined;
188
+ }
189
+ }
190
+ return ordered;
191
+ }
192
+ function orderWords(words) {
193
+ const ordered = words.map((word) => ({ ...word })).sort((left, right) => left.start - right.start || left.end - right.end);
194
+ return hasOverlappingWords(ordered) ? undefined : ordered;
195
+ }
196
+ function hasOverlappingWords(words) {
197
+ return words.some((word, index) => index > 0 && words[index - 1].end > word.start);
198
+ }
199
+ function hasOverlappingSpeech(segments) {
200
+ const speech = segments.filter((segment) => segment.kind === "speech");
201
+ return speech.some((segment, index) => index > 0 && speech[index - 1].end > segment.start);
202
+ }
203
+ function hasOverlappingSegments(segments) {
204
+ return segments.some((segment, index) => index > 0 && segments[index - 1].end > segment.start);
205
+ }
206
+ function coversRange(segments, range) {
207
+ return segments.some((segment) => segment.start <= range.start && segment.end >= range.end);
208
+ }
209
+ function overlapsAny(segments, range) {
210
+ return segments.some((segment) => segment.start < range.end && segment.end > range.start);
211
+ }
212
+ function silenceEndFor(segments, start, end) {
213
+ return segments
214
+ .filter((segment) => segment.kind === "silence" && segment.start <= start && segment.end >= end)
215
+ .map((segment) => segment.end)
216
+ .sort((left, right) => right - left)[0];
217
+ }
218
+ function sameWord(left, right) {
219
+ return left.text === right.text && left.start === right.start && left.end === right.end;
220
+ }
221
+ function isContained(candidate, container) {
222
+ return candidate.start >= container.start && candidate.end <= container.end;
223
+ }
224
+ function isSequenceMappingConsistent(candidate, occurrence) {
225
+ const expectedStart = mapSourceToSequence(candidate.sourceRange.start, occurrence);
226
+ const expectedEnd = mapSourceToSequence(candidate.sourceRange.end, occurrence);
227
+ return Math.abs(expectedStart - candidate.sequenceRange.start) <= 0.000001
228
+ && Math.abs(expectedEnd - candidate.sequenceRange.end) <= 0.000001;
229
+ }
230
+ function mapSourceToSequence(sourceTime, occurrence) {
231
+ return occurrence.sequenceRange.start + (sourceTime - occurrence.sourceRange.start);
232
+ }
233
+ function parseRational(time) {
234
+ if (!/^-?\d+$/.test(time.value) || !/^\d+$/.test(time.timescale))
235
+ return undefined;
236
+ const denominator = BigInt(time.timescale);
237
+ if (denominator <= 0n)
238
+ return undefined;
239
+ return normalizeRational({ numerator: BigInt(time.value), denominator });
240
+ }
241
+ function decimalToRational(value) {
242
+ const text = value.toString();
243
+ if (/[eE]/u.test(text)) {
244
+ const [coefficient, exponentText] = text.split(/[eE]/u);
245
+ const exponent = Number(exponentText);
246
+ const coefficientParts = decimalToRational(Number(coefficient));
247
+ if (exponent >= 0)
248
+ return normalizeRational({ numerator: coefficientParts.numerator * 10n ** BigInt(exponent), denominator: coefficientParts.denominator });
249
+ return normalizeRational({ numerator: coefficientParts.numerator, denominator: coefficientParts.denominator * 10n ** BigInt(-exponent) });
250
+ }
251
+ const [whole, fraction = ""] = text.split(".");
252
+ const sign = whole.startsWith("-") ? -1n : 1n;
253
+ const unsignedWhole = whole.replace(/^-/, "");
254
+ return normalizeRational({
255
+ numerator: sign * BigInt(`${unsignedWhole}${fraction}` || "0"),
256
+ denominator: 10n ** BigInt(fraction.length),
257
+ });
258
+ }
259
+ function normalizeRational(value) {
260
+ const divisor = greatestCommonDivisor(value.numerator < 0n ? -value.numerator : value.numerator, value.denominator);
261
+ return { numerator: value.numerator / divisor, denominator: value.denominator / divisor };
262
+ }
263
+ function floorMultiple(value, multiple) {
264
+ const quotient = floorDivide(value.numerator * multiple.denominator, value.denominator * multiple.numerator);
265
+ return normalizeRational({ numerator: quotient * multiple.numerator, denominator: multiple.denominator });
266
+ }
267
+ function ceilMultiple(value, multiple) {
268
+ const numerator = value.numerator * multiple.denominator;
269
+ const denominator = value.denominator * multiple.numerator;
270
+ const quotient = ceilDivide(numerator, denominator);
271
+ return normalizeRational({ numerator: quotient * multiple.numerator, denominator: multiple.denominator });
272
+ }
273
+ function floorDivide(numerator, denominator) {
274
+ if (numerator >= 0n)
275
+ return numerator / denominator;
276
+ return -((-numerator + denominator - 1n) / denominator);
277
+ }
278
+ function ceilDivide(numerator, denominator) {
279
+ if (numerator >= 0n)
280
+ return (numerator + denominator - 1n) / denominator;
281
+ return -((-numerator) / denominator);
282
+ }
283
+ function subtractRationals(left, right) {
284
+ return normalizeRational({
285
+ numerator: left.numerator * right.denominator - right.numerator * left.denominator,
286
+ denominator: left.denominator * right.denominator,
287
+ });
288
+ }
289
+ function rangeFromRationals(start, duration) {
290
+ const end = normalizeRational({
291
+ numerator: start.numerator * duration.denominator + duration.numerator * start.denominator,
292
+ denominator: start.denominator * duration.denominator,
293
+ });
294
+ return {
295
+ start: rationalToNumber(start),
296
+ end: rationalToNumber(end),
297
+ startTime: rationalToTime(start),
298
+ durationTime: rationalToTime(duration),
299
+ };
300
+ }
301
+ function rationalToNumber(value) {
302
+ return Number(value.numerator) / Number(value.denominator);
303
+ }
304
+ function rationalToTime(value) {
305
+ return { value: String(value.numerator), timescale: String(value.denominator) };
306
+ }
307
+ function greatestCommonDivisor(left, right) {
308
+ while (right !== 0n) {
309
+ const remainder = left % right;
310
+ left = right;
311
+ right = remainder;
312
+ }
313
+ return left || 1n;
314
+ }
@@ -0,0 +1,63 @@
1
+ export function parseRational(time, errorCode) {
2
+ if (!/^-?\d+$/.test(time.value) || !/^\d+$/.test(time.timescale)) {
3
+ throw new Error(`${errorCode}: rational time requires integer value and timescale`);
4
+ }
5
+ const value = BigInt(time.value);
6
+ const timescale = BigInt(time.timescale);
7
+ if (timescale <= 0n)
8
+ throw new Error(`${errorCode}: rational timescale must be positive`);
9
+ return { value, timescale };
10
+ }
11
+ export function addRationalTimes(left, right, errorCode = "ANALYSIS_INVALID") {
12
+ const leftParts = parseRational(left, errorCode);
13
+ const rightParts = parseRational(right, errorCode);
14
+ return normalizeRational(leftParts.value * rightParts.timescale + rightParts.value * leftParts.timescale, leftParts.timescale * rightParts.timescale);
15
+ }
16
+ export function subtractRationalTimes(left, right, errorCode = "ANALYSIS_INVALID") {
17
+ const leftParts = parseRational(left, errorCode);
18
+ const rightParts = parseRational(right, errorCode);
19
+ return normalizeRational(leftParts.value * rightParts.timescale - rightParts.value * leftParts.timescale, leftParts.timescale * rightParts.timescale);
20
+ }
21
+ export function isWithinClip(position, startTime, durationTime) {
22
+ const start = parseRational(startTime, "INVALID_PROJECT_STATE");
23
+ const duration = parseRational(durationTime, "INVALID_PROJECT_STATE");
24
+ if (duration.value < 0n)
25
+ throw new Error("INVALID_PROJECT_STATE: clip duration cannot be negative");
26
+ const startsBeforeOrAtPosition = start.value * position.timescale <= position.value * start.timescale;
27
+ const endValue = start.value * duration.timescale + duration.value * start.timescale;
28
+ const endTimescale = start.timescale * duration.timescale;
29
+ const positionBeforeEnd = position.value * endTimescale < endValue * position.timescale;
30
+ return startsBeforeOrAtPosition && positionBeforeEnd;
31
+ }
32
+ export function rationalDifferenceSeconds(left, right) {
33
+ const numerator = left.value * right.timescale - right.value * left.timescale;
34
+ const denominator = left.timescale * right.timescale;
35
+ const seconds = Number(numerator) / Number(denominator);
36
+ if (!Number.isFinite(seconds)) {
37
+ throw new Error("INVALID_TIMELINE_POSITION: relative media time is outside the supported analysis range");
38
+ }
39
+ return seconds;
40
+ }
41
+ function normalizeRational(value, timescale) {
42
+ const divisor = greatestCommonDivisor(value < 0n ? -value : value, timescale);
43
+ return { value: String(value / divisor), timescale: String(timescale / divisor) };
44
+ }
45
+ function greatestCommonDivisor(left, right) {
46
+ while (right !== 0n) {
47
+ const remainder = left % right;
48
+ left = right;
49
+ right = remainder;
50
+ }
51
+ return left || 1n;
52
+ }
53
+ export function translateRationalRange(clipStartTime, clipStart, sourceRange) {
54
+ if (!sourceRange.startTime || !sourceRange.durationTime) {
55
+ throw new Error("ANALYSIS_INVALID: filler range is missing rational timing");
56
+ }
57
+ return {
58
+ start: clipStart + sourceRange.start,
59
+ end: clipStart + sourceRange.end,
60
+ startTime: addRationalTimes(clipStartTime, sourceRange.startTime),
61
+ durationTime: { ...sourceRange.durationTime },
62
+ };
63
+ }