@lalalic/markcut 3.2.54 → 3.2.56

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.
@@ -7,9 +7,10 @@
7
7
  * (TTS/STT/durations)
8
8
  */
9
9
  import { execSync, spawn } from "node:child_process";
10
- import { readFileSync, writeFileSync, mkdirSync, existsSync, copyFileSync } from "node:fs";
10
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, copyFileSync, rmSync } from "node:fs";
11
11
  import { resolve, dirname, join } from "node:path";
12
12
  import { fileURLToPath } from "node:url";
13
+ import { googleMapErrorLine, nativeMapMissingKey } from "./google-map-health.mjs";
13
14
  import {
14
15
  DEFAULT_TTS_CLI, DEFAULT_STT_CLI, DEFAULT_TTI_CLI, DEFAULT_TTV_CLI,
15
16
  DEFAULT_ITT_CLI, DEFAULT_VTT_CLI, DEFAULT_AGENT_CLI, DEFAULT_EDIT_CLI,
@@ -139,6 +140,7 @@ console.log(`\n▶ Rendering → ${outputPath}`);
139
140
  let lastLoggedFrame = 0;
140
141
  let totalFrames = 0;
141
142
  let lineBuffer = "";
143
+ let googleMapFailure = "";
142
144
 
143
145
  // Parse "Rendered X/Y, time remaining: ..." or "Rendered X/Y" lines
144
146
  const progressRe = /^Rendered\s+(\d+)\/(\d+)/;
@@ -150,6 +152,7 @@ console.log(`\n▶ Rendering → ${outputPath}`);
150
152
  lineBuffer = lines.pop() || "";
151
153
  for (const line of lines) {
152
154
  if (!line) continue;
155
+ if (!googleMapFailure) googleMapFailure = googleMapErrorLine(line);
153
156
 
154
157
  const match = line.match(progressRe);
155
158
  if (match) {
@@ -186,9 +189,13 @@ console.log(`\n▶ Rendering → ${outputPath}`);
186
189
  proc.on("exit", (code) => {
187
190
  // Flush any remaining line in the buffer (non-progress lines only)
188
191
  if (lineBuffer && !lineBuffer.match(progressRe)) {
192
+ if (!googleMapFailure) googleMapFailure = googleMapErrorLine(lineBuffer);
189
193
  console.error(lineBuffer);
190
194
  }
191
- if (code === 0) {
195
+ if (code === 0 && googleMapFailure) {
196
+ rmSync(outputPath,{force:true}); // A valid MP4 container with failed Google maps is NOT a valid video.
197
+ reject(new Error(`Google Maps rendering failed: ${googleMapFailure}`));
198
+ } else if (code === 0) {
192
199
  console.log(`✓ ${outputPath}`);
193
200
  resolvePromise();
194
201
  } else {
@@ -343,7 +350,7 @@ edit=${DEFAULT_EDIT_CLI}`);
343
350
  }
344
351
 
345
352
  const final = await resolveAll(resolved, options);
346
- return compileDescriptiveRoot(final);
353
+ return compileDescriptiveRoot(final, {googleMapsApiKey:process.env.GOOGLE_MAPS_API_KEY});
347
354
  }
348
355
 
349
356
  if (filePath.endsWith(".md")) {
@@ -431,6 +438,9 @@ edit=${DEFAULT_EDIT_CLI}`);
431
438
  }
432
439
  }
433
440
 
441
+ // A Maps JS node must carry a valid key in its compiled props before Remotion starts.
442
+ // Otherwise Chrome may report ApiProjectMapError yet encode a superficially valid MP4.
443
+ if (nativeMapMissingKey(streamTree,process.env.GOOGLE_MAPS_API_KEY)) throw new Error("Google Maps view requires GOOGLE_MAPS_API_KEY; refusing an invalid map render");
434
444
  const output = args.output ? resolve(args.output) : join(ROOT, "out", "video.mp4");
435
445
  await renderOne(streamTree, output, args.verbose, renderPublicDir);
436
446
 
@@ -0,0 +1,10 @@
1
+ /** Native Google Maps render gates: prevent successful MP4 status with missing map pixels. */
2
+ const FATAL_MAP_LINE = /Google Maps JavaScript API error:|MapsRequestError.*PERMISSION_DENIED|ROUTES_COMPUTE_ROUTES.*PERMISSION_DENIED|ApiProjectMapError|ApiTargetBlockedMapError|BillingNotEnabledMapError/;
3
+ export function googleMapErrorLine(line) {
4
+ return FATAL_MAP_LINE.test(line) ? String(line).slice(0,400) : '';
5
+ }
6
+ export function nativeMapMissingKey(node, inheritedKey = '') {
7
+ if (!node || typeof node !== 'object') return false;
8
+ if (node.type === 'map' && node.mapType !== 'schematic' && !node.googleMapsApiKey && !inheritedKey) return true;
9
+ return Array.isArray(node.children) && node.children.some(child => nativeMapMissingKey(child,inheritedKey));
10
+ }
@@ -284,11 +284,16 @@ export const mapStream = base.extend({
284
284
  routeWeight: z.number().default(4),
285
285
  zoom: z.number().optional().describe("Optional fixed zoom; route view auto-fits when omitted"),
286
286
  center: z.object({ lat: z.number(), lng: z.number() }).optional().describe("map view center (defaults to first waypoint)"),
287
- mapType: z.enum(["roadmap", "satellite", "hybrid", "terrain"]).default("roadmap").describe("Google Maps style"),
287
+ mapType: z.enum(["roadmap", "satellite", "hybrid", "terrain", "schematic"]).default("roadmap").describe("Google Maps style, or deterministic offline route schematic"),
288
288
  language: z.string().optional().describe("Google Maps UI/label language, e.g. zh-CN"),
289
289
  region: z.string().optional().describe("Google Maps region code, e.g. CN"),
290
290
  travelMode: z.enum(["DRIVING", "WALKING", "BICYCLING", "TRANSIT"]).default("DRIVING").describe("Directions API travel mode"),
291
291
  routeMarker: z.string().default("🚗").describe("emoji/character for the animated traveling marker"),
292
+ routeAnimation: z.object({
293
+ startHold: z.number().min(0).optional(),
294
+ endHold: z.number().min(0).optional(),
295
+ easing: z.enum(["linear", "easeInOut"]).optional(),
296
+ }).optional().describe("Vlog route pacing: endpoint holds (seconds) and eased marker motion"),
292
297
  camera: mapCamera.optional().describe("generic camera tween (dolly/pan/tilt)"),
293
298
  cinematic: mapCinematic.optional().describe("cinematic camera behavior"),
294
299
  streetView: mapStreetView.optional().describe("immersive street view config"),
package/src/types/Map.tsx CHANGED
@@ -44,10 +44,13 @@ import {
44
44
  routePositionAtLegs,
45
45
  modeEmoji,
46
46
  routeMarkerGlyph,
47
+ pointAlongPath,
48
+ locationsForRouteFit,
47
49
  type RouteLeg,
48
50
  type RouteStopWindow,
49
51
  } from "../utils/route-legs";
50
52
  import type { MapStream, Stream } from "../schema/index";
53
+ import { SchematicRouteMap } from "./SchematicRouteMap";
51
54
 
52
55
  // API key is injected by the compiler onto the stream node (see compileLeaf in compiler.ts).
53
56
  // This fallback handles the case where Map.tsx is used directly without the compiler.
@@ -283,26 +286,8 @@ function MapChildRender({ child }: { child: Stream }): React.ReactElement | null
283
286
  return React.createElement(Renderer, { stream: child });
284
287
  }
285
288
 
286
- // ============================================================
287
- // Hide Google Maps attribution / UI text (Google logo, "Keyboard
288
- // shortcuts", "Terms", "Report a map error", "Map data ©...") from the
289
- // rendered output. Both the 2D map and Street View share the `.gm-style`
290
- // DOM, so two rules cover every view. Injected once, globally.
291
- // ============================================================
292
- let googleMapsUiHidden = false;
293
- function hideGoogleMapsUi(): void {
294
- if (googleMapsUiHidden || typeof document === "undefined") return;
295
- googleMapsUiHidden = true;
296
- const style = document.createElement("style");
297
- style.textContent = [
298
- // Attribution / copyright blocks: "Map data ©Google", "Keyboard shortcuts",
299
- // "Terms", "Report a map error" / "Report a problem".
300
- ".gm-style-cc { display: none !important; }",
301
- // Google logo link ("Google" in the bottom-left).
302
- '.gm-style a[href*="maps.google.com/maps"] { display: none !important; }',
303
- ].join("\n");
304
- document.head.appendChild(style);
305
- }
289
+ // Google Maps branding and legal attribution must remain visible in the rendered video.
290
+ // Do not hide, crop or obscure Google's copyright notices or provider logos.
306
291
 
307
292
  // Cache identical routing requests within one preview session. Scrubbing the
308
293
  // Remotion timeline remounts scenes; do not issue a billable Routes request
@@ -357,8 +342,7 @@ export function MapLeaf({ stream }: { stream: MapStream }) {
357
342
  const mapLoadContinuedRef = React.useRef(false);
358
343
 
359
344
  React.useEffect(() => {
360
- // Strip Google Maps attribution / UI text from the rendered video.
361
- hideGoogleMapsUi();
345
+ if (stream.mapType === "schematic") return;
362
346
 
363
347
  mapLoadHandleRef.current = delayRender("Waiting for map to load...");
364
348
  mapLoadContinuedRef.current = false;
@@ -379,7 +363,7 @@ export function MapLeaf({ stream }: { stream: MapStream }) {
379
363
  }
380
364
  mapLoadHandleRef.current = null;
381
365
  };
382
- }, [stream.id, start, end]);
366
+ }, [stream.id, stream.mapType, start, end]);
383
367
 
384
368
  const handleMapReady = React.useCallback(() => {
385
369
  if (!mapLoadContinuedRef.current && mapLoadHandleRef.current !== null) {
@@ -395,6 +379,17 @@ export function MapLeaf({ stream }: { stream: MapStream }) {
395
379
  stream.cinematic?.fallback === "none" &&
396
380
  (stream.cinematic.mode === "flyTo" || stream.cinematic.mode === "orbit");
397
381
 
382
+ if (stream.mapType === "schematic" && view !== "route") {
383
+ throw Error("mapType:schematic currently supports only view:route");
384
+ }
385
+ if (stream.mapType === "schematic" && view === "route") {
386
+ return (
387
+ <Sequence durationInFrames={durFrames} from={Math.floor(fps * start)} layout="none">
388
+ <SchematicRouteMap stream={stream} />
389
+ </Sequence>
390
+ );
391
+ }
392
+
398
393
  return (
399
394
  <Sequence
400
395
  durationInFrames={durFrames}
@@ -467,9 +462,16 @@ function RouteMap({
467
462
  const waypoints = stream.waypoints ?? [];
468
463
  const start = stream.start ?? 0;
469
464
  const end = stream.end ?? start + (stream.duration ?? 1);
470
- // Fit all observed stops to the video composition by default. Explicit
471
- // stream/camera center and zoom take precedence over automatic framing.
472
- const fitted = React.useMemo(() => fitRouteViewport(waypoints, width, height), [waypoints, width, height]);
465
+ // After Google Routes loads, fit its actual road geometry (which can detour
466
+ // far beyond source stops). Preserve explicit center/zoom overrides.
467
+ const [routePath, setRoutePath] = React.useState<Array<{lat: number; lng: number}>>([]);
468
+ const handleRoutePath = React.useCallback((path: Array<{lat: number; lng: number}>) => {
469
+ setRoutePath(path);
470
+ }, []);
471
+ const fitted = React.useMemo(
472
+ () => fitRouteViewport([...waypoints, ...routePath], width, height, {padding: 0.19}),
473
+ [waypoints, routePath, width, height],
474
+ );
473
475
  const fallbackCenter = stream.center ?? fitted?.center ?? waypoints[0] ?? {lat: 0, lng: 0};
474
476
  const center = {
475
477
  lat: resolveTween(frame, fps, stream.camera?.center?.lat, start, end, fallbackCenter.lat),
@@ -493,9 +495,11 @@ function RouteMap({
493
495
  travelMode={stream.travelMode ?? "DRIVING"}
494
496
  markerEmoji={stream.routeMarker ?? "🚗"}
495
497
  actionDuration={end - start}
498
+ routeAnimation={stream.routeAnimation}
496
499
  routeColor={stream.routeColor ?? "#4285F4"}
497
500
  routeWeight={stream.routeWeight ?? 4}
498
501
  children={stream.children as Stream[]}
502
+ onRoutePath={handleRoutePath}
499
503
  />
500
504
  </GoogleMap>
501
505
  );
@@ -995,19 +999,24 @@ function RouteWithMarker({
995
999
  // (✈️ 🚢 🚶 🚲 🚌 🚗).
996
1000
  // ============================================================
997
1001
  function RouteWithMarkerLegs({
998
- waypoints, travelMode, markerEmoji, actionDuration, routeColor, routeWeight, children,
1002
+ waypoints, travelMode, markerEmoji, actionDuration, routeColor, routeWeight, children, onRoutePath, routeAnimation,
999
1003
  }: {
1000
1004
  waypoints: { lat: number; lng: number; label?: string; media?: string; mode?: string }[];
1001
1005
  travelMode: string;
1002
1006
  markerEmoji: string;
1003
1007
  actionDuration: number;
1008
+ routeAnimation?: {startHold?: number; endHold?: number; easing?: "linear" | "easeInOut"};
1004
1009
  routeColor: string;
1005
1010
  routeWeight: number;
1006
1011
  children?: Stream[];
1012
+ onRoutePath?: (path: Array<{lat: number; lng: number}>) => void;
1007
1013
  }) {
1008
1014
  const legs = useRouteLegs(waypoints, travelMode);
1015
+ React.useEffect(() => {
1016
+ if (legs.length) onRoutePath?.(locationsForRouteFit([], legs));
1017
+ }, [legs, onRoutePath]);
1009
1018
  const stops = useRouteStops(children, waypoints, legs);
1010
- const position = useAnimatedPositionLegs({ legs, actionDuration, stops });
1019
+ const position = useAnimatedPositionLegs({ legs, actionDuration, stops, timing: routeAnimation });
1011
1020
  const glyph = routeMarkerGlyph(markerEmoji, position?.mode);
1012
1021
 
1013
1022
  return (
@@ -1132,17 +1141,18 @@ function useRouteLegs(
1132
1141
  // (view:"route"): returns { lat, lng, mode } for the current frame
1133
1142
  // ============================================================
1134
1143
  function useAnimatedPositionLegs({
1135
- legs, actionDuration, stops = [],
1144
+ legs, actionDuration, stops = [], timing,
1136
1145
  }: {
1137
1146
  legs: RouteLeg[];
1138
1147
  actionDuration: number;
1139
1148
  stops?: RouteStopWindow[];
1149
+ timing?: {startHold?: number; endHold?: number; easing?: "linear" | "easeInOut"};
1140
1150
  }) {
1141
1151
  const frame = useCurrentFrame();
1142
1152
  const { fps } = useVideoConfig();
1143
1153
  return React.useMemo(
1144
- () => routePositionAtLegs(legs, actionDuration, frame / fps, stops),
1145
- [legs, frame, fps, actionDuration, stops],
1154
+ () => routePositionAtLegs(legs, actionDuration, frame / fps, stops, timing),
1155
+ [legs, frame, fps, actionDuration, stops, timing],
1146
1156
  );
1147
1157
  }
1148
1158
 
@@ -1267,13 +1277,7 @@ function routePositionAt(
1267
1277
 
1268
1278
  const stepElapsed = currentInSecond - elapsedInSeconds;
1269
1279
  const stepProgress = stepElapsed / (step.duration?.value ?? 1);
1270
- const pathIdx = Math.min(
1271
- Math.max(0, Math.floor(stepProgress * step.path.length)),
1272
- step.path.length - 1,
1273
- );
1274
- const pt = step.path[pathIdx];
1275
- if (!pt) return null;
1276
- return { lat: pt.lat(), lng: pt.lng() };
1280
+ return pointAlongPath(step.path.map((p) => ({lat: p.lat(), lng: p.lng()})), stepProgress);
1277
1281
  }
1278
1282
 
1279
1283
  // ============================================================
@@ -0,0 +1,61 @@
1
+ import React from 'react';
2
+ import { AbsoluteFill, useCurrentFrame, useVideoConfig } from 'remotion';
3
+ import type { MapStream } from '../schema/index';
4
+ import { pointAtRouteProgress, projectSchematicRoute, routeSvgPath } from '../utils/schematic-route';
5
+
6
+ /** Google-independent, reproducible map chapter. No road map or actual travel track is inferred. */
7
+ export function SchematicRouteMap({stream}: {stream: MapStream}) {
8
+ const {width, height, fps} = useVideoConfig();
9
+ const frame = useCurrentFrame();
10
+ const waypoints = stream.waypoints ?? [];
11
+ const points = React.useMemo(() => projectSchematicRoute(waypoints, width, height), [waypoints, width, height]);
12
+ if (!points.length) return null;
13
+ const duration = Math.max(1, Math.round((stream.end ?? (stream.start ?? 0) + (stream.duration ?? 1)) * fps) - Math.round((stream.start ?? 0) * fps));
14
+ const progress = Math.max(0, Math.min(1, frame / Math.max(1, duration - 1)));
15
+ const marker = pointAtRouteProgress(points, progress);
16
+ const path = routeSvgPath(points);
17
+ const total = points.slice(1).reduce((sum, p, i) => sum + Math.hypot(p.x - points[i]!.x, p.y - points[i]!.y), 0);
18
+ const color = stream.routeColor ?? '#4285F4';
19
+ const headingSize = Math.round(Math.min(width * 0.06, 34));
20
+ const subtitleSize = Math.round(headingSize * .55);
21
+ const pinRadius = Math.max(8, width * .016);
22
+ const first = points[0], last = points[points.length - 1];
23
+ return <AbsoluteFill style={{backgroundColor: '#0d2032'}}>
24
+ <svg viewBox={`0 0 ${width} ${height}`} width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
25
+ <defs>
26
+ <linearGradient id="schematic-bg" x1="0" x2="1" y1="0" y2="1">
27
+ <stop offset="0" stopColor="#163450"/><stop offset="1" stopColor="#091726"/>
28
+ </linearGradient>
29
+ <pattern id="schematic-grid" width="54" height="54" patternUnits="userSpaceOnUse">
30
+ <path d="M 54 0 L 0 0 0 54" fill="none" stroke="#ffffff" strokeOpacity=".075" strokeWidth="1" />
31
+ </pattern>
32
+ </defs>
33
+ <rect width={width} height={height} fill="url(#schematic-bg)" />
34
+ <rect width={width} height={height} fill="url(#schematic-grid)" />
35
+ <text x={width * .08} y={height * .093} fontSize={headingSize} fill="#ffffff" fontWeight="700" fontFamily="sans-serif">路线示意</text>
36
+ <text x={width * .08} y={height * .14} fontSize={subtitleSize} fill="#9dc2d3" fontFamily="sans-serif">按已验证地点连接 · 非道路导航</text>
37
+ {points.length > 1 && <>
38
+ <path d={path} fill="none" stroke="#ffffff" strokeOpacity=".32" strokeWidth={Math.max(2, stream.routeWeight ?? 4)} strokeDasharray="8 8" strokeLinecap="round" strokeLinejoin="round" />
39
+ <path d={path} fill="none" stroke={color} strokeWidth={Math.max(3, stream.routeWeight ?? 4)} strokeLinecap="round" strokeLinejoin="round" strokeDasharray={`${total} ${total}`} strokeDashoffset={total * (1 - progress)} />
40
+ </>}
41
+ {points.map((p, i) => {
42
+ if (points.length > 6 && i > 0 && i < points.length - 1) return null;
43
+ const name = (p.label || (i === 0 ? '出发' : i === points.length - 1 ? '到达' : `站点${i + 1}`)).slice(0, 18);
44
+ const alignRight = p.x > width * .58;
45
+ const nearBottom = p.y > height * .77;
46
+ const labelX = p.x + (alignRight ? -pinRadius * 2 : pinRadius * 2);
47
+ return <g key={i}>
48
+ <circle cx={p.x} cy={p.y} r={pinRadius * .64} fill="#ffffff" opacity=".96" />
49
+ <circle cx={p.x} cy={p.y} r={pinRadius * .33} fill={color} />
50
+ <text x={labelX} y={p.y + (nearBottom ? -pinRadius : -pinRadius * .65)} textAnchor={alignRight ? 'end' : 'start'} fill="#f2f7fa" fontFamily="sans-serif" fontWeight="600" fontSize={Math.max(15, headingSize * .66)}>{name}</text>
51
+ </g>;
52
+ })}
53
+ <circle cx={marker.x} cy={marker.y} r={pinRadius * 2} fill={color} fillOpacity=".2" />
54
+ <circle cx={marker.x} cy={marker.y} r={pinRadius} fill={color} stroke="#ffffff" strokeWidth="3" />
55
+ <rect x={width * .08} y={height * .886} width={width * .84} height={3} rx={1.5} fill="#b9d9e6" opacity=".28" />
56
+ <rect x={width * .08} y={height * .886} width={width * .84 * progress} height={3} rx={1.5} fill={color} />
57
+ <text x={width * .08} y={height * .925} fontSize={subtitleSize} fill="#c8dee7" fontFamily="sans-serif">{(first?.label || '出发').slice(0,14)}</text>
58
+ <text x={width * .92} y={height * .925} textAnchor="end" fontSize={subtitleSize} fill="#c8dee7" fontFamily="sans-serif">{(last?.label || '到达').slice(0,14)}</text>
59
+ </svg>
60
+ </AbsoluteFill>;
61
+ }
@@ -119,6 +119,42 @@ export function modeEmoji(mode?: string): string {
119
119
  }
120
120
  }
121
121
 
122
+ /** Interpolate by actual polyline length, not array index: Routes samples are not evenly spaced. */
123
+ export function pointAlongPath(
124
+ path: readonly {lat: number; lng: number}[],
125
+ progress: number,
126
+ ): {lat: number; lng: number} | null {
127
+ if (!path.length) return null;
128
+ if (path.length === 1) return path[0]!;
129
+ const lengths = path.slice(1).map((p, i) => haversineKm(path[i]!, p));
130
+ const total = lengths.reduce((a, b) => a + b, 0);
131
+ if (total < 1e-9) return path[0]!;
132
+ let target = Math.max(0, Math.min(1, progress)) * total;
133
+ for (let i = 0; i < lengths.length; i++) {
134
+ const length = lengths[i]!;
135
+ if (target <= length || i === lengths.length - 1) {
136
+ const a = path[i]!, b = path[i + 1]!;
137
+ const ratio = length ? Math.min(1, Math.max(0, target / length)) : 0;
138
+ const deltaLng = ((b.lng - a.lng + 540) % 360) - 180;
139
+ const lng = ((a.lng + deltaLng * ratio + 540) % 360) - 180;
140
+ return {lat: a.lat + (b.lat - a.lat) * ratio, lng};
141
+ }
142
+ target -= length;
143
+ }
144
+ return path[path.length - 1]!;
145
+ }
146
+
147
+ /** The whole Google road path must fit, including detours outside recorded GPS bounds. */
148
+ export function locationsForRouteFit(
149
+ waypoints: readonly {lat: number; lng: number}[],
150
+ legs: readonly RouteLeg[],
151
+ ): {lat: number; lng: number}[] {
152
+ return [
153
+ ...waypoints,
154
+ ...legs.flatMap(leg => leg.steps.flatMap(step => step.path)),
155
+ ];
156
+ }
157
+
122
158
  /** Position within one leg at normalized progress t ∈ [0,1] (step-timed). */
123
159
  export function positionAlongLeg(
124
160
  leg: RouteLeg,
@@ -131,11 +167,7 @@ export function positionAlongLeg(
131
167
  if (currentInSecond <= acc + step.durationSec) {
132
168
  const stepElapsed = currentInSecond - acc;
133
169
  const stepProgress = step.durationSec > 0 ? stepElapsed / step.durationSec : 0;
134
- const idx = Math.min(
135
- Math.max(0, Math.floor(stepProgress * step.path.length)),
136
- step.path.length - 1,
137
- );
138
- return step.path[idx] ?? null;
170
+ return pointAlongPath(step.path, stepProgress);
139
171
  }
140
172
  acc += step.durationSec;
141
173
  }
@@ -169,6 +201,7 @@ export function routePositionAtLegs(
169
201
  actionDuration: number,
170
202
  seconds: number,
171
203
  stops: RouteStopWindow[] = [],
204
+ timing: {startHold?: number; endHold?: number; easing?: "linear" | "easeInOut"} = {},
172
205
  ): { lat: number; lng: number; mode: string } | null {
173
206
  if (legs.length === 0) return null;
174
207
 
@@ -184,11 +217,17 @@ export function routePositionAtLegs(
184
217
  if (seconds >= s.toSec) dwellBefore += s.toSec - s.fromSec;
185
218
  else if (seconds > s.fromSec) dwellBefore += seconds - s.fromSec;
186
219
  }
187
- const driveTime = Math.max(0, seconds - dwellBefore);
220
+ const startHold = Math.max(0, Math.min(actionDuration * 0.4, timing.startHold ?? 0));
221
+ const endHold = Math.max(0, Math.min(actionDuration * 0.4, timing.endHold ?? 0));
222
+ const driveTime = Math.max(0, seconds - dwellBefore - startHold);
188
223
  const totalDwell = stops.reduce((s, st) => s + (st.toSec - st.fromSec), 0);
189
- const driveBudget = Math.max(0.1, actionDuration - totalDwell);
224
+ const driveBudget = Math.max(0.1, actionDuration - totalDwell - startHold - endHold);
190
225
  const total = legs.reduce((s, l) => s + l.durationSec, 0);
191
- const currentInSecond = driveTime * (total / driveBudget);
226
+ const progress = Math.max(0, Math.min(1, driveTime / driveBudget));
227
+ // Ease the full motion only when no authored intermediate dwell windows need exact arrival times.
228
+ const eased = timing.easing === "easeInOut" && stops.length === 0
229
+ ? progress * progress * (3 - 2 * progress) : progress;
230
+ const currentInSecond = eased * total;
192
231
  let acc = 0;
193
232
  for (const leg of legs) {
194
233
  if (currentInSecond <= acc + leg.durationSec) {
@@ -0,0 +1,56 @@
1
+ /** Deterministic offline projection for route visuals; connecting samples is illustrative, not road geometry. */
2
+ export interface RoutePoint { lat: number; lng: number; label?: string }
3
+ export interface ScreenPoint { x: number; y: number; label?: string }
4
+
5
+ function mercatorY(lat: number): number {
6
+ const r = Math.max(-85, Math.min(85, lat)) * Math.PI / 180;
7
+ return Math.log(Math.tan(Math.PI / 4 + r / 2));
8
+ }
9
+
10
+ export function projectSchematicRoute(points: RoutePoint[], width: number, height: number): ScreenPoint[] {
11
+ if (!points.length) return [];
12
+ const map = points.map((p, i) => {
13
+ if (!Number.isFinite(p.lat) || !Number.isFinite(p.lng) || Math.abs(p.lat) > 90 || Math.abs(p.lng) > 180)
14
+ throw Error(`Invalid route coordinate at index ${i}`);
15
+ return { x: p.lng, y: -mercatorY(p.lat), label: p.label };
16
+ });
17
+ // Unwrap the antimeridian so nearby points at +179/-179 do not span the world.
18
+ for (let i = 1; i < map.length; i++) {
19
+ const prev = map[i - 1]!.x;
20
+ const original = map[i]!.x;
21
+ map[i]!.x = prev + ((((original - prev + 540) % 360) + 360) % 360) - 180;
22
+ }
23
+ let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
24
+ for (const p of map) {
25
+ minX = Math.min(minX, p.x); maxX = Math.max(maxX, p.x);
26
+ minY = Math.min(minY, p.y); maxY = Math.max(maxY, p.y);
27
+ }
28
+ const spreadX = Math.max(1e-6, maxX - minX), spreadY = Math.max(1e-6, maxY - minY);
29
+ const insetX = width * 0.17, insetY = height * 0.23;
30
+ const scale = Math.min((width - 2 * insetX) / spreadX, (height - 2 * insetY) / spreadY);
31
+ const cx = (minX + maxX) / 2, cy = (minY + maxY) / 2;
32
+ return map.map(p => ({x: width / 2 + (p.x - cx) * scale, y: height / 2 + (p.y - cy) * scale, label: p.label}));
33
+ }
34
+
35
+ export function pointAtRouteProgress(points: ScreenPoint[], progress: number): ScreenPoint {
36
+ if (!points.length) throw Error('Route requires at least one waypoint');
37
+ if (points.length === 1) return points[0]!;
38
+ const distances = points.slice(1).map((p, i) => Math.hypot(p.x - points[i]!.x, p.y - points[i]!.y));
39
+ const total = distances.reduce((a, b) => a + b, 0);
40
+ if (total < 1e-6) return points[0]!;
41
+ let remaining = Math.max(0, Math.min(1, progress)) * total;
42
+ for (let i = 0; i < distances.length; i++) {
43
+ const length = distances[i]!;
44
+ if (remaining <= length || i === distances.length - 1) {
45
+ const f = length > 0 ? Math.min(1, remaining / length) : 0;
46
+ return { x: points[i]!.x + (points[i + 1]!.x - points[i]!.x) * f,
47
+ y: points[i]!.y + (points[i + 1]!.y - points[i]!.y) * f };
48
+ }
49
+ remaining -= length;
50
+ }
51
+ return points[points.length - 1]!;
52
+ }
53
+
54
+ export function routeSvgPath(points: ScreenPoint[]): string {
55
+ return points.map((p, i) => `${i ? 'L' : 'M'} ${p.x.toFixed(2)} ${p.y.toFixed(2)}`).join(' ');
56
+ }
@@ -0,0 +1,13 @@
1
+ import {it,expect} from 'vitest';
2
+ import {parseMarkdownDescriptive} from '../src/descriptive/markdown';
3
+ const base='# video\nwidth:540 height:960 fps:12\n\n## Scene\nlayout:parallel\n';
4
+ it('rejects malformed Google Street View literal instead of silently losing its location',()=>{
5
+ const broken=base+'- map view:streetview duration:2 streetView:{location:{lat:45.33,lng:-75.88}}}\n';
6
+ expect(()=>parseMarkdownDescriptive(broken)).toThrow(/invalid structured streetView/);
7
+ });
8
+ it('preserves valid Google Street View location and camera tween',()=>{
9
+ const good=base+'- map view:streetview duration:2 streetView:{location:{lat:45.33,lng:-75.88},radius:70,pov:{heading:tween(100,190,easeInOut)}}\n';
10
+ const doc=parseMarkdownDescriptive(good), sv=(doc.children[0] as any).children[0].streetView;
11
+ expect(sv.location).toEqual({lat:45.33,lng:-75.88});
12
+ expect(sv.pov.heading.__tween).toEqual([100,190,'easeInOut']);
13
+ });
@@ -0,0 +1,9 @@
1
+ import {it,expect} from 'vitest';
2
+ import {parseMarkdownDescriptive} from '../src/descriptive/markdown';
3
+ import {compileDescriptiveRoot} from '../src/descriptive/compiler';
4
+ it('routes Google visual timing through descriptive schema and native map stream',()=>{
5
+ const input='# video\nwidth:540 height:960 fps:24\n\n## Route\nlayout:parallel\n- map view:route mapType:roadmap duration:8 routeAnimation:{startHold:0.6,endHold:0.8,easing:easeInOut} waypoints:[45,-76,"A";45.1,-75.9,"B"]';
6
+ const root=compileDescriptiveRoot(parseMarkdownDescriptive(input));
7
+ const map=(root.children[0] as any).children[0];
8
+ expect(map.routeAnimation).toEqual({startHold:0.6,endHold:0.8,easing:'easeInOut'});
9
+ });
@@ -7,12 +7,12 @@ function harness(remoteData?:any, fetchOverride?:(url:string)=>Promise<any>, too
7
7
  const messages:any[]=[];
8
8
  const listeners:Record<string,Array<(evt:any)=>void>>={};
9
9
  const element=()=>({value:'',textContent:'',onclick:null as null|(()=>void),oninput:null as null|(()=>void),
10
- disabled:false,hidden:false,type:'',children:[] as any[],listeners:{} as Record<string,Function>,
10
+ disabled:false,hidden:false,type:'',style:{display:''},children:[] as any[],listeners:{} as Record<string,Function>,
11
11
  addEventListener(type:string,listener:Function){this.listeners[type]=listener},
12
12
  replaceChildren(){this.children=[]},append(...items:any[]){this.children.push(...items)}
13
13
  });
14
14
  const nodes:Record<string,ReturnType<typeof element>>={
15
- feedback:element(),status:element(),'path-label':element(),'video-md-version':element(),'interactive-ui':element(),approve:element(),changes:element(),'save-spot':element(),'remove-spot':element(),'comment-target':element(),'comment-mode':element(),'overall-mode':element(),'review-delivery-mode':element()
15
+ feedback:element(),status:element(),'path-label':element(),'video-md-version':element(),'interactive-ui':element(),'comment-entry':element(),approve:element(),changes:element(),'save-spot':element(),'remove-spot':element(),'comment-target':element(),'comment-mode':element(),'overall-mode':element(),'review-delivery-mode':element()
16
16
  };
17
17
  nodes['comment-mode'].value='spot';
18
18
  let dispatch:(message:any,source?:any)=>void;
@@ -35,6 +35,23 @@ function harness(remoteData?:any, fetchOverride?:(url:string)=>Promise<any>, too
35
35
  const nextTick=()=>new Promise(resolve=>setTimeout(resolve,0));
36
36
 
37
37
  describe('MCP Remotion bridge',()=>{
38
+ it('readonly input displays playback without review controls or messages',async()=>{
39
+ const h=harness();
40
+ h.dispatch({method:'ui/notifications/tool-input',params:{arguments:{path:'/tmp/read-only.md',readonly:true}}});
41
+ h.result({id:'view',revisionId:'r-view',contentHash:'a'.repeat(64),path:'/tmp/read-only.md',
42
+ review:{delivery:'text',readonly:true},compiled:{children:[{name:'Scene'}]}});
43
+ await nextTick();
44
+ expect(h.nodes['review-delivery-mode'].textContent).toBe('Read-only mode');
45
+ expect(h.nodes['interactive-ui'].hidden).toBe(false);
46
+ expect(h.nodes['comment-entry'].style.display).toBe('none');
47
+ expect(h.nodes.approve.style.display).toBe('none');
48
+ expect(h.nodes.changes.style.display).toBe('none');
49
+ expect(h.nodes.approve.disabled).toBe(true);
50
+ h.nodes.approve.onclick?.();
51
+ h.nodes.changes.onclick?.();
52
+ expect(h.messages.filter(m=>m.method==='ui/message'||m.method==='tools/call')).toHaveLength(0);
53
+ });
54
+
38
55
  it('hydrates scenes from NeoY when ChatGPT does not deliver tool-result',async()=>{
39
56
  const path='https://neoy.qili2.com/files/markcut-review/video-a-v4.md';
40
57
  const data={id:'remote',revisionId:'remote-r1',contentHash:'sha',path,requestedPath:path,compiled:{children:[{type:'scene'}]}};
@@ -41,6 +41,10 @@ describe('Markcut Remotion MCP App',()=>{
41
41
  expect(audio).toContain('ctx.decodeAudioData(bytes)');
42
42
  expect(audio).toContain("p.addEventListener('play',play)");
43
43
  });
44
+ it('publishes v46 while retaining v45 as a compatible alias',()=>{
45
+ expect(RESOURCE_URI).toBe('ui://markcut/video-preview-v46.html');
46
+ expect(LEGACY_RESOURCE_URIS).toContain('ui://markcut/video-preview-v45.html');
47
+ });
44
48
  it('registers latest resource at startup and aliases previous URIs',()=>{
45
49
  for(const uri of [RESOURCE_URI,...LEGACY_RESOURCE_URIS]){
46
50
  const result=buildPreviewResourceResult(uri);
@@ -73,6 +77,8 @@ describe('Markcut Remotion MCP App',()=>{
73
77
  it('includes a local audio track for Remotion playback',async()=>{
74
78
  const dir=await mkdtemp(join(tmpdir(),'markcut-audio-'));
75
79
  try {
80
+ await writeFile(join(dir,'.ghost.markcut.md'),'# video\n');
81
+ expect(await readPreviewAudio(join(dir,'.ghost.markcut.md'))).toEqual({});
76
82
  await writeFile(join(dir,'clip.md'),'# video\naudio: sample.wav\n');
77
83
  await writeFile(join(dir,'sample.wav'),Buffer.from([82,73,70,70]));
78
84
  const media=await readPreviewAudio(join(dir,'clip.md'));
@@ -0,0 +1,39 @@
1
+ import {describe,it,expect} from 'vitest';
2
+ import {nativeMapMissingKey,googleMapErrorLine} from '../src/render/google-map-health.mjs';
3
+ import {readFileSync,writeFileSync,mkdtempSync,rmSync} from 'node:fs';
4
+ import {tmpdir} from 'node:os';
5
+ import {join,resolve} from 'node:path';
6
+ import {spawnSync} from 'node:child_process';
7
+
8
+ describe('Google Maps native rendering safeguards',()=>{
9
+ it('detects unkeyed native maps at any depth but not schematic maps',()=>{
10
+ const root={type:'root',children:[{type:'scene',children:[{type:'map',view:'streetview',mapType:'roadmap'}]}]};
11
+ expect(nativeMapMissingKey(root,'')).toBe(true);
12
+ expect(nativeMapMissingKey(root,'enabled')).toBe(false);
13
+ expect(nativeMapMissingKey({...root,children:[{type:'scene',children:[{type:'map',view:'route',mapType:'schematic'}]}]},'')).toBe(false);
14
+ });
15
+ it('recognizes fatal Maps JS and Routes errors, not benign warnings',()=>{
16
+ for(const line of [
17
+ '[console.error] Google Maps JavaScript API error: ApiProjectMapError',
18
+ 'MapsRequestError: ROUTES_COMPUTE_ROUTES: PERMISSION_DENIED: denied',
19
+ 'Google Maps JavaScript API error: BillingNotEnabledMapError',
20
+ ]) expect(googleMapErrorLine(line)).toBeTruthy();
21
+ expect(googleMapErrorLine('Google Maps JavaScript API warning: NoApiKeys')).toBe('');
22
+ });
23
+ it('fails before rendering and producing a false success MP4 without Google key',()=>{
24
+ const dir=mkdtempSync(join(tmpdir(),'markcut-google-key-'));
25
+ try{
26
+ const md=join(dir,'video.md'),mp4=join(dir,'out.mp4');
27
+ writeFileSync(md,'# video\nseed:1\nwidth:320 height:320 fps:10 layout:series\n\n## Map\nlayout:parallel\n- map view:overview mapType:roadmap center:{lat:45,lng:-75} duration:1\n');
28
+ const result=spawnSync(process.execPath,[resolve('bin/markcut'),'render',md,'--output',mp4],{
29
+ encoding:'utf8',cwd:process.cwd(),timeout:30000,env:{...process.env,GOOGLE_MAPS_API_KEY:''}
30
+ });
31
+ expect(result.status).not.toBe(0);
32
+ expect(result.stderr+result.stdout).toMatch(/requires GOOGLE_MAPS_API_KEY/);
33
+ }finally{rmSync(dir,{recursive:true,force:true});}
34
+ });
35
+ it('injects Maps key explicitly on Markdown CLI compile path',()=>{
36
+ const text=readFileSync(resolve('src/render/cli.mjs'),'utf8');
37
+ expect(text).toMatch(/compileDescriptiveRoot\(final,\s*\{googleMapsApiKey:process\.env\.GOOGLE_MAPS_API_KEY\}\)/);
38
+ });
39
+ });
@@ -188,3 +188,37 @@ describe('routeMarkerGlyph',()=>{
188
188
  expect(routeMarkerGlyph('🚗','DRIVING')).toBe('🚗');
189
189
  });
190
190
  });
191
+
192
+ describe('natural road-video polyline interpolation and fit', () => {
193
+ it('interpolates by distance, not by the uneven vertex count', async () => {
194
+ const {pointAlongPath} = await import('../src/utils/route-legs');
195
+ const path=[{lat:45,lng:-76},{lat:45,lng:-75.999},{lat:45,lng:-75.99}];
196
+ const mid=pointAlongPath(path,0.5)!;
197
+ expect(mid.lng).toBeCloseTo(-75.995,3);
198
+ expect(pointAlongPath(path,1)!.lng).toBeCloseTo(-75.99,5);
199
+ });
200
+ it('fits full Google road detour, not only filmed GPS endpoints', async () => {
201
+ const {locationsForRouteFit} = await import('../src/utils/route-legs');
202
+ const {fitRouteViewport} = await import('../src/utils/map-viewport');
203
+ const gps=[{lat:45,lng:-76},{lat:45,lng:-75.99}];
204
+ const route=[{mode:'DRIVING',from:gps[0]!,to:gps[1]!,durationSec:90,
205
+ steps:[{durationSec:90,path:[gps[0]!,{lat:45.1,lng:-75.995},gps[1]!]}]}];
206
+ const before=fitRouteViewport(gps,540,960,{padding:0.19})!;
207
+ const after=fitRouteViewport(locationsForRouteFit(gps,route),540,960,{padding:0.19})!;
208
+ expect(after.zoom).toBeLessThan(before.zoom);
209
+ expect(after.center.lat).toBeGreaterThan(before.center.lat);
210
+ });
211
+ });
212
+
213
+ describe('video route animation timing',()=>{
214
+ it('holds on the source start/end GPS location and eases movement in between',async()=>{
215
+ const {routePositionAtLegs}=await import('../src/utils/route-legs');
216
+ const from={lat:45,lng:-76},to={lat:45,lng:-75.99};
217
+ const legs=[{mode:'WALKING',from,to,durationSec:200,steps:[{durationSec:200,path:[from,to]}]}];
218
+ const config={startHold:0.6,endHold:0.8,easing:'easeInOut' as const};
219
+ expect(routePositionAtLegs(legs,8,.3,[],config)?.lng).toBeCloseTo(-76,4);
220
+ expect(routePositionAtLegs(legs,8,7.6,[],config)?.lng).toBeCloseTo(-75.99,4);
221
+ expect(routePositionAtLegs(legs,8,.9,[],config)!.lng).toBeLessThan(-75.999);
222
+ expect(routePositionAtLegs(legs,8,4,[],config)!.lng).toBeGreaterThan(-76);
223
+ });
224
+ });