@lalalic/markcut 3.2.49 → 3.2.51

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lalalic/markcut",
3
- "version": "3.2.49",
3
+ "version": "3.2.51",
4
4
  "description": "Markdown-to-video engine. Describe scenes in markdown, get a rendered video.",
5
5
  "bin": {
6
6
  "markcut": "bin/markcut"
@@ -101,7 +101,12 @@ export function FolderLeaf({ stream }: { stream: FolderStream }) {
101
101
  ? <EffectWrapper stream={child as any}><FolderLeaf stream={child as any} /></EffectWrapper>
102
102
  : React.createElement(FolderLeaf, { stream: child as FolderStream });
103
103
  return (
104
- <SequenceWrap key={child.id} durationInFrames={durFrames} layout="none">
104
+ <SequenceWrap
105
+ key={child.id}
106
+ durationInFrames={durFrames}
107
+ layout="absolute-fill"
108
+ premountFor={isSeries && !allAudio ? fps : undefined}
109
+ >
105
110
  <Container
106
111
  id={child.id}
107
112
  type={child.type}
@@ -207,8 +207,10 @@ function extractMetadata(filePath) {
207
207
  }
208
208
  } catch { /* fall through */ }
209
209
 
210
- // Fallback: ffprobe
211
- if (!width || !height) {
210
+ // Always probe videos for their precise duration. ExifTool's formatted
211
+ // Duration can be "0:01:16" or "1 min 16 sec", which parseFloat misreads
212
+ // as 0 or 1 even when it has already reported valid width/height.
213
+ if (!width || !height || VIDEO_EXTS.has(extname(filePath).toLowerCase())) {
212
214
  try {
213
215
  const probe = JSON.parse(run(
214
216
  `ffprobe -v quiet -print_format json -show_format -show_streams ${shQuote(filePath)}`,
@@ -218,7 +220,8 @@ function extractMetadata(filePath) {
218
220
  const videoStream = streams.find((s) => s.codec_type === "video") || {};
219
221
  width = width || videoStream.width || 0;
220
222
  height = height || videoStream.height || 0;
221
- duration = duration || (format.duration ? parseFloat(format.duration) : null);
223
+ const probedDuration = Number(format.duration);
224
+ if (Number.isFinite(probedDuration) && probedDuration > 0) duration = probedDuration;
222
225
  created = created || format.tags?.creation_time || videoStream.tags?.creation_time || null;
223
226
  if (!location && format.tags) {
224
227
  const iso = format.tags["com.apple.quicktime.location.ISO6709"] || "";
@@ -809,6 +812,27 @@ function buildMergedCues(userHint, cues, sceneChangesMs, totalDurationMs) {
809
812
  return merged;
810
813
  }
811
814
 
815
+ /** Make a source-time-faithful, metadata-stripped clip for one VTT segment.
816
+ * Never seek a long video's uniformly sampled understanding copy with original
817
+ * timestamps, and never let an empty ffmpeg output masquerade as evidence.
818
+ */
819
+ function extractOriginalSegment(original, output, startSec, durationSec) {
820
+ if (!Number.isFinite(startSec) || startSec < 0 || !Number.isFinite(durationSec) || durationSec <= 0) {
821
+ throw new Error("Invalid source segment range");
822
+ }
823
+ const clipFilter = "scale='min(360,iw)':'min(360,ih)':force_original_aspect_ratio=decrease,pad='ceil(iw/2)*2':'ceil(ih/2)*2':-1:-1";
824
+ if (!existsSync(output) || getVideoDuration(output) <= 0) {
825
+ try { rmSync(output, { force: true }); } catch {}
826
+ run(`ffmpeg -y -i ${shQuote(original)} -ss ${startSec} -t ${durationSec} -map_metadata -1 -map_chapters -1 -vf ${shQuote(clipFilter)} -c:v libx264 -preset fast -crf 28 -an -fflags +genpts ${shQuote(output)}`, { timeout: 120_000 });
827
+ }
828
+ const actualDuration = getVideoDuration(output);
829
+ if (!Number.isFinite(actualDuration) || actualDuration <= 0) {
830
+ try { rmSync(output, { force: true }); } catch {}
831
+ throw new Error(`Cannot decode source segment at ${startSec}s for ${durationSec}s`);
832
+ }
833
+ return output;
834
+ }
835
+
812
836
  function analyzeVideo(videoPath, normInfo, normDir, prompts, context = "", userHint = "", sampleInterval = DEFAULT_VTT_SAMPLE_INTERVAL, userHints = null, skipSTT = false) {
813
837
  let ctxParts = [];
814
838
  if (context) ctxParts.push(`Context: ${context}`);
@@ -937,23 +961,18 @@ function analyzeVideo(videoPath, normInfo, normDir, prompts, context = "", userH
937
961
 
938
962
  const clipName = `${basename(normInfo.path, extname(normInfo.path))}_seg_${key}.mp4`;
939
963
  const clipOut = join(segDir, clipName);
940
- let clipPath = normInfo.path;
941
-
942
- if (!existsSync(clipOut)) {
943
- const srcForClip = existsSync(normInfo.path) ? normInfo.path : videoPath;
944
- const clipFilter = "scale='min(360,iw)':'min(360,ih)':force_original_aspect_ratio=decrease,pad='ceil(iw/2)*2':'ceil(ih/2)*2':-1:-1";
945
- try {
946
- // Use -ss after -i (output seek) for accurate duration metadata
947
- run(`ffmpeg -y -i ${shQuote(srcForClip)} -ss ${startSec} -t ${durSec} -vf ${shQuote(clipFilter)} -c:v libx264 -preset fast -crf 28 -an -fflags +genpts ${shQuote(clipOut)}`, { timeout: 120_000 });
948
- if (existsSync(clipOut)) clipPath = clipOut;
949
- } catch { /* fallback */ }
950
- } else { clipPath = clipOut; }
964
+ // Segment keys are ORIGINAL source timestamps. Long recordings have a
965
+ // uniformly sampled understanding copy whose seconds do not map 1:1 to
966
+ // the original timeline; seeking it can produce empty late segments.
967
+ // Extract from the original, then scale/strip its metadata for VTT.
968
+ const clipPath = extractOriginalSegment(videoPath, clipOut, startSec, durSec);
951
969
 
952
970
  // Use runVTT for video clips (extracts frames, then runs ITT)
953
971
  const segRawVis = runVTT(clipPath, visSegPrompt, DEFAULT_VTT_CLI, DEFAULT_ITT_CLI, sampleInterval);
954
972
  const segVisText = extractRawText(segRawVis);
955
973
  seg.vision = stripThinkBlocks(looseJSONParse(segRawVis)?.desc || segVisText.slice(0, 300) || segRawVis.slice(0, 300));
956
- try { if (clipPath !== normInfo.path) rmSync(clipPath, { force: true }); } catch {}
974
+ if (!seg.vision?.trim()) throw new Error(`Segment ${key} returned no verified visual response`);
975
+ try { rmSync(clipPath, { force: true }); } catch {}
957
976
  }
958
977
  try { rmSync(segDir, { recursive: true, force: true }); } catch {}
959
978
  perception.segments = segments;
@@ -1105,7 +1124,14 @@ async function runNormalizeAndPercept(folder, metadataPath, prompts, context, pi
1105
1124
 
1106
1125
  emitInfo(`\nšŸŽ¬ Video: ${base}${userHint ? ` (hint: "${userHint}")` : ""}`);
1107
1126
  const vidPath = join(folder, fileName);
1108
- const normInfo = normalizeVideo(vidPath, normDir, meta.duration);
1127
+ // Existing metadata.json may contain an incomplete or incorrectly parsed
1128
+ // ExifTool Duration from a previous extraction. Reconcile against the
1129
+ // original container before using it for segmentation and handoff.
1130
+ const originalDuration = getVideoDuration(vidPath);
1131
+ if (!Number.isFinite(originalDuration) || originalDuration <= 0)
1132
+ throw new Error(`Video has no usable original duration: ${fileName}`);
1133
+ meta.duration = originalDuration;
1134
+ const normInfo = normalizeVideo(vidPath, normDir, originalDuration);
1109
1135
  let perception = {};
1110
1136
  let cacheKey = "";
1111
1137
  const ctxV = context ? `Context: ${context}\n\n` : "";
@@ -1310,6 +1336,8 @@ export async function main(args) {
1310
1336
  // ═════════════════════════════════════════════════════════════════════════
1311
1337
 
1312
1338
  export {
1339
+ extractOriginalSegment,
1340
+ extractMetadata,
1313
1341
  scanMedia,
1314
1342
  buildPreviewTree,
1315
1343
  mergeLabelsIntoMetadata,
@@ -0,0 +1,29 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { mkdtempSync, rmSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { execFileSync } from "node:child_process";
6
+ import { extractMetadata, extractOriginalSegment } from "../src/vision/cli.mjs";
7
+
8
+ describe("Vision metadata long-video duration", () => {
9
+ it("uses ffprobe time instead of misreading formatted ExifTool Duration", () => {
10
+ const dir=mkdtempSync(join(tmpdir(),"markcut-duration-"));
11
+ try {
12
+ const video=join(dir,"long.mov");
13
+ execFileSync("ffmpeg",["-loglevel","error","-y","-f","lavfi","-i","color=c=blue:s=160x90:r=2:d=76.16",
14
+ "-c:v","libx264","-preset","ultrafast","-pix_fmt","yuv420p",video],{timeout:30000});
15
+ const metadata=extractMetadata(video);
16
+ expect(metadata.width).toBe(160);
17
+ expect(metadata.height).toBe(90);
18
+ expect(metadata.duration).toBeGreaterThan(76);
19
+ expect(metadata.duration).toBeLessThan(77);
20
+ const segment=join(dir,"segment.mp4");
21
+ extractOriginalSegment(video,segment,63,13);
22
+ const seconds=Number(execFileSync("ffprobe",["-v","error","-show_entries","format=duration",
23
+ "-of","default=noprint_wrappers=1:nokey=1",segment],{encoding:"utf8"}).trim());
24
+ expect(seconds).toBeGreaterThan(12);
25
+ expect(seconds).toBeLessThanOrEqual(13.5);
26
+ expect(() => extractOriginalSegment(video,join(dir,"missing.mp4"),80,5)).toThrow(/Cannot decode source segment/);
27
+ } finally {rmSync(dir,{recursive:true,force:true});}
28
+ });
29
+ });