@auscera/cleoedits 0.0.0-stage → 0.1.0
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/README.md +62 -2
- package/cli.mjs +149 -0
- package/lib/dependencies.mjs +384 -0
- package/lib/run.mjs +114 -0
- package/lib/workspace.mjs +167 -0
- package/package.json +240 -3
- package/workspace/.agents/skills/cleoedits/SKILL.md +29 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/audiogram.json +41 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/facebook.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/linkedin.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/podcast.json +23 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/reels.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/shorts.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/tiktok.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/x.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/youtube-shorts.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/youtube.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/assets/LICENSE-SimpleIcons +30 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/assets/logos.json +1 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Anton-Regular.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/ArchivoBlack-Regular.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/InstrumentSerif-Italic.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Inter.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/LICENSE-PermanentMarker.txt +202 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Montserrat.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Anton.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-ArchivoBlack.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-InstrumentSerif.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Inter.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Montserrat.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-PlayfairDisplay.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Poppins.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-SpaceMono.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/PermanentMarker-Regular.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/PlayfairDisplay-Italic.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/PlayfairDisplay.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Poppins-Black.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Poppins-Bold.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Poppins-ExtraBold.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/SpaceMono-Bold.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/LICENSE-MediaPipe +218 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/LICENSE-YuNet +21 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/NOTICE.md +4 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/selfie_segmenter.tflite +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/yunet.onnx +0 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/LICENSE +21 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/audio-app-ui/STYLE.md +65 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/blueprint/STYLE.md +53 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/blueprint/index.html +328 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/blueprint/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/data-story/STYLE.md +65 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/data-story/index.html +575 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/design-app-ui/STYLE.md +68 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/editor-ui/STYLE.md +73 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/editorial-paper/STYLE.md +54 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/editorial-paper/index.html +189 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/editorial-paper/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/explainer-diagram/STYLE.md +64 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/explainer-diagram/index.html +620 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/graphite-ui/STYLE.md +55 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/graphite-ui/index.html +238 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/graphite-ui/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/growing-city/STYLE.md +66 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/growing-city/index.html +602 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/ink-line/STYLE.md +66 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/ink-line/index.html +777 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/midnight-grid/STYLE.md +56 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/midnight-grid/index.html +186 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/midnight-grid/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/motion-app-ui/STYLE.md +68 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-cut/STYLE.md +56 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-cut/index.html +244 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-cut/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-world/STYLE.md +67 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-world/index.html +663 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/particle-field/STYLE.md +59 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/particle-field/index.html +395 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/poster-pop/STYLE.md +52 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/poster-pop/index.html +194 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/poster-pop/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/risograph/STYLE.md +58 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/risograph/index.html +242 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/risograph/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-grid/STYLE.md +53 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-grid/index.html +138 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-grid/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-kinetic/STYLE.md +63 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-kinetic/index.html +599 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/time-travel/STYLE.md +65 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/time-travel/index.html +1297 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/weather-widget/STYLE.md +69 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/weather-widget/index.html +674 -0
- package/workspace/.agents/skills/cleoedits/references/audio-clearervoice-elevenlabs.md +11 -0
- package/workspace/.agents/skills/cleoedits/references/ffmpeg-and-reels.md +15 -0
- package/workspace/.agents/skills/cleoedits/references/hyperframes-workflows.md +13 -0
- package/workspace/.agents/skills/cleoedits/references/kdenlive-cli-and-mcp.md +12 -0
- package/workspace/.agents/skills/cleoedits/references/motion-design-pipeline.md +7 -0
- package/workspace/.agents/skills/cleoedits/references/motion-taste-emil.md +5 -0
- package/workspace/.agents/skills/cleoedits/references/playwright-demo-capture.md +9 -0
- package/workspace/.agents/skills/cleoedits/references/remotion-workflows.md +13 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/LICENSE +21 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_ass_overlay.py +399 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/__init__.py +235 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/alpha.py +560 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/asr.py +1237 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/color.py +540 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/decision.py +2452 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/drawtext.py +290 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/emit.py +1309 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/emoji.py +518 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/fonts.py +875 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/pacing.py +263 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/pacing_edit.py +432 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/probe.py +1613 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/runner.py +3994 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/text.py +73 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/timeline.py +721 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/wrap.py +981 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_contract.py +2454 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_platforms.py +258 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_review.html +754 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_review.py +258 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_smartcut.py +450 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/audio.py +867 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/background.py +136 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/batch.py +1409 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/broll.py +282 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/caption.py +2207 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/check.py +815 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/color.py +695 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/crop.py +91 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/cropdetect.py +214 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/cut.py +2076 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/deinterlace.py +90 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/denoise.py +94 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/export.py +1033 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/fit.py +729 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/freeze.py +197 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/graphics.py +920 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/grid.py +235 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/insert.py +142 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/join.py +1083 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/look.py +475 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/loop.py +395 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/loudness.py +397 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/metadata.py +416 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/multicam.py +414 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/overlay.py +766 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/pad.py +121 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/probe.py +145 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/proxy.py +93 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/redact.py +162 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/render.py +2424 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/report.py +354 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/reverse.py +114 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/scenes.py +439 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/sequence.py +285 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/silence.py +945 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/speedramp.py +193 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/sphere.py +137 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/stabilize.py +141 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/straighten.py +120 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/sync.py +500 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/verify.py +411 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/waveform.py +502 -0
- package/workspace/.agents/skills/cleoedits/scripts/kdenlive_builder.py +284 -0
- package/workspace/.agents/skills/cleoedits/scripts/motion/LICENSE-claude-motion +21 -0
- package/workspace/.agents/skills/cleoedits/scripts/motion/LICENSE-motion-design +21 -0
- package/workspace/.agents/skills/cleoedits/scripts/motion/_media.py +43 -0
- package/workspace/.agents/skills/cleoedits/scripts/motion/pacing_check.py +90 -0
- package/workspace/.agents/skills/cleoedits/scripts/motion/storyboard.py +77 -0
- package/workspace/.agents/skills/cleoedits/scripts/reel_effects/LICENSE +26 -0
- package/workspace/.agents/skills/cleoedits/scripts/reel_effects/fx.py +2717 -0
- package/workspace/.agents/skills/cleoedits/scripts/reel_effects/logos.py +194 -0
- package/workspace/.agents/skills/cleoedits/scripts/reel_effects/sfx.py +105 -0
- package/workspace/.agents/skills/cleoedits/scripts/reel_effects/trim.py +99 -0
- package/workspace/.agents/skills/cleoedits/scripts/reel_effects/words.py +60 -0
- package/workspace/.claude/commands/blender-3d.md +12 -0
- package/workspace/.claude/commands/business-short-form-reels.md +12 -0
- package/workspace/.claude/commands/color-grade.md +12 -0
- package/workspace/.claude/commands/cutout-grid-reel.md +12 -0
- package/workspace/.claude/commands/depth-ui-reel.md +12 -0
- package/workspace/.claude/commands/explainer-panel-reel.md +12 -0
- package/workspace/.claude/commands/freeze-frame.md +12 -0
- package/workspace/.claude/commands/glass-graph.md +12 -0
- package/workspace/.claude/commands/over-the-shoulder.md +12 -0
- package/workspace/.claude/commands/personal-short-form-reels.md +12 -0
- package/workspace/.claude/commands/ranking-format.md +12 -0
- package/workspace/.claude/commands/relight.md +12 -0
- package/workspace/.claude/commands/reverse-engineer.md +12 -0
- package/workspace/.claude/commands/text-behind.md +12 -0
- package/workspace/.claude/commands/tier-list.md +12 -0
- package/workspace/.claude-plugin/plugin.json +8 -0
- package/workspace/.npmignore +15 -0
- package/workspace/AGENTS.md +30 -0
- package/workspace/README.md +63 -0
- package/workspace/assets/fonts/TikTokSans-OFL.txt +93 -0
- package/workspace/assets/fonts/TikTokSans-Variable.ttf +0 -0
- package/workspace/assets/luts/clean_warm.cube +4917 -0
- package/workspace/assets/luts/golden_hour.cube +4917 -0
- package/workspace/assets/luts/moody_dark.cube +4917 -0
- package/workspace/assets/luts/teal_orange.cube +4917 -0
- package/workspace/assets/sfx/NOTICE.txt +1 -0
- package/workspace/assets/sfx/click.wav +0 -0
- package/workspace/assets/sfx/pop.wav +0 -0
- package/workspace/assets/sfx/riser.wav +0 -0
- package/workspace/assets/sfx/whoosh.wav +0 -0
- package/workspace/generators/hyperframes/index.html +39 -0
- package/workspace/generators/hyperframes/package.json +15 -0
- package/workspace/generators/hyperframes/pnpm-lock.yaml +1181 -0
- package/workspace/generators/hyperframes/pnpm-workspace.yaml +10 -0
- package/workspace/generators/remotion/eslint.config.mjs +3 -0
- package/workspace/generators/remotion/package.json +36 -0
- package/workspace/generators/remotion/pnpm-lock.yaml +4179 -0
- package/workspace/generators/remotion/pnpm-workspace.yaml +10 -0
- package/workspace/generators/remotion/remotion.config.ts +13 -0
- package/workspace/generators/remotion/src/Root.tsx +52 -0
- package/workspace/generators/remotion/src/index.css +1 -0
- package/workspace/generators/remotion/src/index.ts +4 -0
- package/workspace/generators/remotion/tsconfig.json +15 -0
- package/workspace/pipeline/scripts/_codec.py +28 -0
- package/workspace/pipeline/scripts/ai_media_api.py +109 -0
- package/workspace/pipeline/scripts/blender_render.py +166 -0
- package/workspace/pipeline/scripts/composite.py +49 -0
- package/workspace/pipeline/scripts/melt.sh +68 -0
- package/workspace/pipeline/scripts/normalize_audio.py +39 -0
- package/workspace/pipeline/scripts/person_matte.py +216 -0
- package/workspace/pipeline/scripts/record_demo.py +69 -0
- package/workspace/pipeline/scripts/whisper_cut.py +98 -0
- package/workspace-manifest.json +908 -0
|
@@ -0,0 +1,721 @@
|
|
|
1
|
+
"""render.py project -> an editor's timeline (EDL, FCPXML, OTIO).
|
|
2
|
+
|
|
3
|
+
`render.py project.json --export-timeline edit.fcpxml|.edl|.otio` hands a rough cut to a person
|
|
4
|
+
who finishes it in Premiere, DaVinci Resolve or Final Cut. It is a translation, not a render:
|
|
5
|
+
nothing is encoded, and every decision in the file is one the project already made.
|
|
6
|
+
|
|
7
|
+
The timeline has to match what render.py itself would deliver, or the editor opens a different
|
|
8
|
+
cut than the agent showed. join.py's crossfade overlaps neighbouring clips by the transition
|
|
9
|
+
duration `d` (xfade: the last `d` s of A blend with the first `d` s of B, so the whole is `d`
|
|
10
|
+
shorter). Editors model a dissolve centred on a cut, using media beyond each clip's visible
|
|
11
|
+
range ("handles"), so each side of a dissolve is trimmed by `d/2` and the dissolve spans `d/2`
|
|
12
|
+
either side of the new cut: the same frames blend over the same span, and the total length is
|
|
13
|
+
the rendered one.
|
|
14
|
+
|
|
15
|
+
Only what an editor timeline can carry is exported: clips (with in/out and speed), the
|
|
16
|
+
transition between them, a music bed on its own audio track, and chapters as markers, on a
|
|
17
|
+
sequence of the project's frame (sized by the rule fit.py renders it with). FCPXML also states
|
|
18
|
+
how a clip of another aspect fills that frame (`adjust-conform`); EDL and OTIO cannot.
|
|
19
|
+
Everything else in the project -- captions, graphics, overlays, the silence cut, fit/crop, a
|
|
20
|
+
reframe the format cannot state, audio processing, loudness, the export preset -- is listed
|
|
21
|
+
under `not_exported`, never silently dropped.
|
|
22
|
+
"""
|
|
23
|
+
import json
|
|
24
|
+
import math
|
|
25
|
+
import os
|
|
26
|
+
import re
|
|
27
|
+
from fractions import Fraction
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
30
|
+
|
|
31
|
+
from _common.decision import MissingFpsError, aspect_ratio, frame_size, parse_time
|
|
32
|
+
from _common.emit import warn
|
|
33
|
+
from _common.probe import display_size
|
|
34
|
+
|
|
35
|
+
FORMATS = {".edl": "edl", ".fcpxml": "fcpxml", ".otio": "otio"}
|
|
36
|
+
# Common NTSC rates are stored as the exact ratio an editor expects, not as 29.97.
|
|
37
|
+
_NTSC = {23.976: Fraction(24000, 1001), 29.97: Fraction(30000, 1001), 59.94: Fraction(60000, 1001),
|
|
38
|
+
47.952: Fraction(48000, 1001), 119.88: Fraction(120000, 1001)}
|
|
39
|
+
# project keys an editor timeline cannot carry, with what the caller should know about each
|
|
40
|
+
_NOT_EXPORTED = {
|
|
41
|
+
"silence": "the silence cut (render.py measures it at render time; the timeline keeps the clips whole)",
|
|
42
|
+
"captions": "captions (burn them with render.py, or import the .srt into the editor)",
|
|
43
|
+
"graphics": "graphics (titles, lower thirds, social templates)",
|
|
44
|
+
"overlays": "overlays (logos, images, text and video layers)",
|
|
45
|
+
"fit": "fit / reframe to the delivery aspect (set the sequence frame in the editor)",
|
|
46
|
+
"audiogram": "the audiogram picture",
|
|
47
|
+
"loudness": "loudness normalisation",
|
|
48
|
+
"export": "the export preset (the editor's own export decides the delivery)",
|
|
49
|
+
"check": "the platform check",
|
|
50
|
+
"brand": "brand styles",
|
|
51
|
+
"snap": "beat snapping (the timeline uses the project's in/out as written, before any snap)",
|
|
52
|
+
}
|
|
53
|
+
# frame.fit -> the FCPXML adjust-conform type that fills the sequence the same way. blur has no
|
|
54
|
+
# conform of its own: the picture is fitted whole, and its blurred background is not exported.
|
|
55
|
+
_CONFORM = {"pad": "fit", "crop": "fill", "blur": "fit"}
|
|
56
|
+
_AUDIO_NOT_EXPORTED = ("replace", "voice", "denoise", "duck", "duck_amount", "duck_threshold", "duck_attack",
|
|
57
|
+
"duck_release", "gain", "stereo", "mono", "downmix", "stereo_widen", "effects",
|
|
58
|
+
"effects_volume", "stems", "music_volume", "fade_in", "fade_out", "music_fade_out",
|
|
59
|
+
"music_loop")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class TimelineError(ValueError):
|
|
63
|
+
"""A project that cannot be expressed as a timeline (a caller-facing `kind: input`)."""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def exact_rate(fps: float) -> Fraction:
|
|
67
|
+
for approx, exact in _NTSC.items():
|
|
68
|
+
if abs(fps - approx) < 0.01:
|
|
69
|
+
return exact
|
|
70
|
+
frac = Fraction(fps).limit_denominator(1001)
|
|
71
|
+
if frac <= 0:
|
|
72
|
+
raise TimelineError(f"frame rate {fps!r} is not usable for a timeline")
|
|
73
|
+
return frac
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _number(value: Any, what: str) -> float:
|
|
77
|
+
"""A numeric project value (a rate, a size, a speed, a transition length) as a float, or a
|
|
78
|
+
TimelineError naming it -- never float()'s traceback."""
|
|
79
|
+
try:
|
|
80
|
+
number = float(value)
|
|
81
|
+
except (TypeError, ValueError):
|
|
82
|
+
number = math.nan
|
|
83
|
+
if not math.isfinite(number):
|
|
84
|
+
raise TimelineError(f"{what}: {value!r} is not a number")
|
|
85
|
+
return number
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _seconds(value: Any, what: str, fps: Optional[float]) -> float:
|
|
89
|
+
"""A project time read with the grammar render.py's own stages read it (time_arg()): seconds,
|
|
90
|
+
mm:ss, hh:mm:ss.ms, or hh:mm:ss:ff at `fps` or its own @fps. A value it refuses is a
|
|
91
|
+
TimelineError, so `--json` gets a `kind: input` document, not a traceback and empty stdout."""
|
|
92
|
+
try:
|
|
93
|
+
seconds = parse_time(str(value), fps)
|
|
94
|
+
except MissingFpsError as exc:
|
|
95
|
+
raise TimelineError(f"{what}: {exc}")
|
|
96
|
+
except ValueError as exc:
|
|
97
|
+
raise TimelineError(f"{what}: {exc} (use seconds, mm:ss, hh:mm:ss.ms, or hh:mm:ss:ff at the "
|
|
98
|
+
"source's fps or with an explicit @fps suffix)")
|
|
99
|
+
if not math.isfinite(seconds):
|
|
100
|
+
raise TimelineError(f"{what}: {value!r} is not a time")
|
|
101
|
+
return seconds
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _picture(meta: Dict[str, Any]) -> Optional[Tuple[int, int]]:
|
|
105
|
+
"""A source's displayed width x height, as fit.py reads it: rotation metadata swaps them, and
|
|
106
|
+
non-square pixels are squared at the display aspect (probe.display_size(), #411)."""
|
|
107
|
+
w, h = display_size(meta.get("video") or {})
|
|
108
|
+
if not (w and h):
|
|
109
|
+
return None
|
|
110
|
+
return (w, h)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
_TC = re.compile(r"^(\d{2}):(\d{2}):(\d{2})[:;.](\d{2,3})$")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _drop_frame(drop: Optional[bool], rate: Fraction) -> bool:
|
|
117
|
+
"""Drop-frame counting applies to the NTSC rates only (29.97 and 59.94)."""
|
|
118
|
+
return bool(drop) and rate.denominator == 1001 and round(float(rate)) in (30, 60)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def start_tc_frames(tc: Dict[str, Any], rate: Fraction) -> int:
|
|
122
|
+
"""A source's start timecode (probe()'s `timecode`: {value, drop_frame}) as a frame count at
|
|
123
|
+
its own `rate`, drop-frame counted where it is one; 0 when the source has none (#414). A
|
|
124
|
+
label that does not exist at that rate (frame 29 at 25 fps, or a frame drop-frame counting
|
|
125
|
+
skips) is read as none, as probe() skips a malformed tag, rather than as a shifted start."""
|
|
126
|
+
m = _TC.match(str((tc or {}).get("value") or "").strip())
|
|
127
|
+
if not m:
|
|
128
|
+
return 0
|
|
129
|
+
h, mi, se, fr = (int(g) for g in m.groups())
|
|
130
|
+
nominal = int(round(float(rate)))
|
|
131
|
+
if mi > 59 or se > 59 or fr >= nominal:
|
|
132
|
+
return 0
|
|
133
|
+
frames = ((h * 60 + mi) * 60 + se) * nominal + fr
|
|
134
|
+
if _drop_frame(tc.get("drop_frame"), rate):
|
|
135
|
+
if se == 0 and mi % 10 and fr < nominal // 15:
|
|
136
|
+
return 0
|
|
137
|
+
minutes = h * 60 + mi
|
|
138
|
+
frames -= (nominal // 15) * (minutes - minutes // 10)
|
|
139
|
+
return frames
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _tc_label(frames: int, rate: Fraction, drop: bool) -> str:
|
|
143
|
+
"""`frames` as hh:mm:ss:ff at the nominal integer rate; drop-frame (`;`) for an NTSC source
|
|
144
|
+
whose own timecode is drop-frame, so the label is the one the media itself shows. Timecode
|
|
145
|
+
wraps at 24 hours as the media's own does (output_timecode_args() counts the same day): a
|
|
146
|
+
source starting at 23:59:50:00 is labelled 00:00:00:00 ten seconds in, not 24:00:00:00, which
|
|
147
|
+
no editor reads (A266)."""
|
|
148
|
+
nominal = int(round(float(rate)))
|
|
149
|
+
if not _drop_frame(drop, rate):
|
|
150
|
+
return _tc(frames % (nominal * 86400), nominal) if nominal >= 1 else _tc(frames, nominal)
|
|
151
|
+
d = nominal // 15
|
|
152
|
+
frames %= (nominal * 600 - d * 9) * 144
|
|
153
|
+
per_10, per_min = nominal * 600 - d * 9, nominal * 60 - d
|
|
154
|
+
tens, rem = divmod(frames, per_10)
|
|
155
|
+
frames += d * 9 * tens + (d * ((rem - d) // per_min) if rem > d else 0)
|
|
156
|
+
return _tc(frames, nominal)[:-3] + ";" + _tc(frames, nominal)[-2:]
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def output_timecode_args(meta: Dict[str, Any], first_frame: Optional[float], rate: Optional[float] = None) -> List[str]:
|
|
160
|
+
"""The arguments that give an output the start timecode of the source frame it starts on:
|
|
161
|
+
`first_frame` seconds after the source picture's first frame (negative: a head the tool
|
|
162
|
+
added), or None to write no start timecode at all (a join, whose later frames no single start
|
|
163
|
+
label describes). A tool that moves the start of the picture used to write the source's own
|
|
164
|
+
start timecode unchanged: FFmpeg copies the video stream's `timecode` tag, and the MOV/MP4
|
|
165
|
+
muxer rebuilds a tmcd track from it, so a cut from 1 s was stamped 01:00:00:00 for frame 30.
|
|
166
|
+
Both the stream and the container tag are set (Matroska keeps a stale stream tag otherwise;
|
|
167
|
+
MXF reads the container's). Nothing for a source without a start timecode. The label also
|
|
168
|
+
goes on STATE.expected_timecode, which source_carry compares the written file with: an
|
|
169
|
+
MXF, which always writes one, reads 00:00:00:00 when none is wanted and is listed as dropped.
|
|
170
|
+
`rate` is the frame rate the output is delivered at when the tool changes it (fit --fps, a
|
|
171
|
+
VFR source conformed to a constant rate), None for the source's own: the source's label is
|
|
172
|
+
read at the source's rate and the output's is counted at the output's, so 01:00:00:12 at 25
|
|
173
|
+
fps (0.48 s past the hour) is 01:00:00:24 at 50."""
|
|
174
|
+
from _common.runner import STATE
|
|
175
|
+
tc = (meta or {}).get("timecode") or {}
|
|
176
|
+
fps = ((meta or {}).get("video") or {}).get("fps")
|
|
177
|
+
if not tc.get("value") or not fps:
|
|
178
|
+
return []
|
|
179
|
+
label = ""
|
|
180
|
+
if first_frame is not None:
|
|
181
|
+
src_rate = exact_rate(float(fps))
|
|
182
|
+
out_rate = exact_rate(float(rate)) if rate else src_rate
|
|
183
|
+
drop = _drop_frame(tc.get("drop_frame"), out_rate)
|
|
184
|
+
nominal = round(float(out_rate))
|
|
185
|
+
if nominal >= 1:
|
|
186
|
+
day = (nominal * 600 - (nominal // 15) * 9) * 144 if drop else nominal * 86400
|
|
187
|
+
# the source label and the offset to the first frame, both in output frames, rounded
|
|
188
|
+
# once: 00:00:00:02 at 25 fps plus 0.08 s is 4.8 frames at 30, so frame 5, not 2 + 2
|
|
189
|
+
pos = (Fraction(start_tc_frames(tc, src_rate)) / src_rate
|
|
190
|
+
+ Fraction(first_frame).limit_denominator(1000000)) * out_rate
|
|
191
|
+
label = _tc_label(math.floor(pos + Fraction(1, 2)) % day, out_rate, drop)
|
|
192
|
+
# below 1 fps no frame count can name a frame: the label is removed, as when the first
|
|
193
|
+
# frame is unknown, rather than divide by a zero-length day
|
|
194
|
+
STATE.expected_timecode = label
|
|
195
|
+
return ["-metadata:s:v:0", f"timecode={label}", "-metadata", f"timecode={label}"]
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def build(proj: Dict[str, Any], probes: Dict[str, Dict[str, Any]], rel) -> Dict[str, Any]:
|
|
199
|
+
"""The editor-neutral timeline: every time in frames at `rate`.
|
|
200
|
+
|
|
201
|
+
`probes` maps each resolved clip/music path to its probe(); `rel` resolves a project path
|
|
202
|
+
the way render.py does. Raises TimelineError for what an editor timeline cannot represent."""
|
|
203
|
+
clips_in = proj.get("clips") or []
|
|
204
|
+
if not clips_in:
|
|
205
|
+
raise TimelineError("project.clips is empty")
|
|
206
|
+
for i, c in enumerate(clips_in):
|
|
207
|
+
if not isinstance(c, dict) or not c.get("src"):
|
|
208
|
+
raise TimelineError(f"clips[{i}]: no src")
|
|
209
|
+
frame = proj.get("frame") or {}
|
|
210
|
+
first = probes[rel(clips_in[0]["src"])]
|
|
211
|
+
frame_fps = _number(frame["fps"], "frame.fps") if frame.get("fps") else None
|
|
212
|
+
fps = frame_fps or (first.get("video") or {}).get("fps")
|
|
213
|
+
if not fps:
|
|
214
|
+
raise TimelineError("no frame rate: the first clip has no video stream and project.frame.fps is not set")
|
|
215
|
+
rate = exact_rate(float(fps))
|
|
216
|
+
# The sequence is the project's frame sized by fit.py's rule (render.py has already filled an
|
|
217
|
+
# aspect-only frame from the export preset), so {aspect 16:9, width 1920} is 1920x1080
|
|
218
|
+
# whatever the source's height -- the size the render's fit stage delivers. No frame at all
|
|
219
|
+
# is the first clip's own picture, which is what the render keeps.
|
|
220
|
+
aspect = frame.get("aspect")
|
|
221
|
+
ratio = aspect_ratio(aspect) if aspect else None
|
|
222
|
+
if aspect and ratio is None:
|
|
223
|
+
raise TimelineError(f"frame.aspect {aspect!r}: use W:H with whole numbers, like 16:9 (fit.py refuses it too)")
|
|
224
|
+
want_w, want_h = (int(_number(frame[k], f"frame.{k}")) if frame.get(k) else None for k in ("width", "height"))
|
|
225
|
+
if (want_w or 0) < 0 or (want_h or 0) < 0:
|
|
226
|
+
raise TimelineError(f"frame width/height must be positive, got {frame.get('width')!r} x {frame.get('height')!r}")
|
|
227
|
+
src_w, src_h = _picture(first) or (1920, 1080)
|
|
228
|
+
fit_mode = str(frame.get("fit") or "pad")
|
|
229
|
+
if ratio is None and not want_w and not want_h and not (fit_mode == "crop" and len(clips_in) > 1):
|
|
230
|
+
width, height = src_w, src_h
|
|
231
|
+
else:
|
|
232
|
+
width, height = frame_size(ratio, want_w, want_h, src_w, src_h)
|
|
233
|
+
if fit_mode not in _CONFORM:
|
|
234
|
+
raise TimelineError(f"frame.fit {frame.get('fit')!r}: use pad, crop or blur (fit.py's --fit)")
|
|
235
|
+
|
|
236
|
+
# A half frame rounds up, floor(x + 1/2), in every count of frames here: velisa/timebase@1 TB-4,
|
|
237
|
+
# decision.py and FFmpeg's av_rescale all do, and round() took 12.5 to 12 (#638).
|
|
238
|
+
def fr(seconds: float) -> int:
|
|
239
|
+
return math.floor(Fraction(seconds).limit_denominator(1000000) * rate + Fraction(1, 2))
|
|
240
|
+
|
|
241
|
+
trans = proj.get("transition") or {}
|
|
242
|
+
t_type = str(trans.get("type", "fade")) if len(clips_in) > 1 else "none"
|
|
243
|
+
d_frames = 0 if t_type == "none" else fr(_number(trans.get("duration", 0.5), "transition.duration"))
|
|
244
|
+
notes: List[str] = []
|
|
245
|
+
if d_frames and t_type != "fade":
|
|
246
|
+
notes.append(f'transition "{t_type}" is exported as a cross dissolve: editors do not share xfade\'s other patterns')
|
|
247
|
+
|
|
248
|
+
clips: List[Dict[str, Any]] = []
|
|
249
|
+
reframed: List[str] = []
|
|
250
|
+
for i, c in enumerate(clips_in):
|
|
251
|
+
src = rel(c["src"])
|
|
252
|
+
meta = probes[src]
|
|
253
|
+
dur = float(meta.get("duration") or 0.0)
|
|
254
|
+
# in/out are on the source's own clock, as cut.py reads them: hh:mm:ss:ff at the
|
|
255
|
+
# source's fps, never frame.fps. A clip with no picture has no fps, and cut.py takes no
|
|
256
|
+
# other, so its hh:mm:ss:ff needs an @fps suffix here as in the render.
|
|
257
|
+
clip_fps = (meta.get("video") or {}).get("fps")
|
|
258
|
+
start = _seconds(c["in"], f"clips[{i}].in", clip_fps) if c.get("in") is not None else 0.0
|
|
259
|
+
if start < 0:
|
|
260
|
+
raise TimelineError(f"clips[{i}].in must not be negative, got {c['in']!r}")
|
|
261
|
+
end = _seconds(c["out"], f"clips[{i}].out", clip_fps) if c.get("out") is not None else dur
|
|
262
|
+
# as cut.py reads them (#414): an in at or past the media's end is refused, an out past it
|
|
263
|
+
# is the media's end -- the render clamps it there, so the timeline does too, and says so
|
|
264
|
+
if dur > 0 and start >= dur:
|
|
265
|
+
raise TimelineError(f"clips[{i}].in ({start:g}s) is at or past the end of {os.path.basename(src)} ({dur:.3f}s)")
|
|
266
|
+
if dur > 0 and end > dur + 1e-6:
|
|
267
|
+
notes.append(f"clips[{i}].out ({end:g}s) is past the end of {os.path.basename(src)} ({dur:.3f}s): "
|
|
268
|
+
"the clip ends at the media's end, as the render cuts it")
|
|
269
|
+
end = dur
|
|
270
|
+
if end <= start:
|
|
271
|
+
raise TimelineError(f"clip {i}: out ({end:g}) is not after in ({start:g})")
|
|
272
|
+
speed = _number(c.get("speed") or 1.0, f"clips[{i}].speed")
|
|
273
|
+
if not speed > 0:
|
|
274
|
+
raise TimelineError(f"clip {i}: speed must be positive, got {c.get('speed')!r}")
|
|
275
|
+
picture = _picture(meta)
|
|
276
|
+
reframe = bool(picture and abs(Fraction(*picture) - Fraction(width, height)) > Fraction(1, 100))
|
|
277
|
+
if reframe:
|
|
278
|
+
reframed.append(os.path.basename(src))
|
|
279
|
+
src_in, src_out = fr(start), fr(end)
|
|
280
|
+
# the source's own clock (#414): its frame rate, and its start timecode as a frame count at
|
|
281
|
+
# that rate. EDL source timecodes are counted at it (a 25 fps clip in a 29.97 sequence has
|
|
282
|
+
# no frame :29); FCPXML and OTIO start the media at it, so a conform finds the frames.
|
|
283
|
+
clip_rate = exact_rate(float(clip_fps)) if clip_fps else rate
|
|
284
|
+
tc = meta.get("timecode") or {}
|
|
285
|
+
tc_start = start_tc_frames(tc, clip_rate)
|
|
286
|
+
clips.append({"index": i, "src": os.path.abspath(src), "name": os.path.basename(src),
|
|
287
|
+
"src_in": src_in, "src_out": src_out, "speed": speed,
|
|
288
|
+
"in_seconds": Fraction(start).limit_denominator(1000000), "rate": clip_rate,
|
|
289
|
+
"tc_start": tc_start, "tc_seconds": Fraction(tc_start) / clip_rate,
|
|
290
|
+
"drop_frame": _drop_frame(tc.get("drop_frame"), clip_rate),
|
|
291
|
+
"length": math.floor(Fraction(src_out - src_in) / Fraction(speed) + Fraction(1, 2)),
|
|
292
|
+
"media_frames": fr(dur), "has_video": bool(meta.get("video")),
|
|
293
|
+
"has_audio": bool(meta.get("audio")),
|
|
294
|
+
"picture": picture, "fps": clip_fps, "reframed": reframe})
|
|
295
|
+
|
|
296
|
+
# Centre each dissolve on the cut: trim d/2 off the outgoing tail and d/2 off the incoming head.
|
|
297
|
+
half_a, half_b = d_frames // 2, d_frames - d_frames // 2
|
|
298
|
+
for i, c in enumerate(clips):
|
|
299
|
+
c["trim_head"] = half_b if (i > 0 and d_frames) else 0
|
|
300
|
+
c["trim_tail"] = half_a if (i < len(clips) - 1 and d_frames) else 0
|
|
301
|
+
visible = c["length"] - c["trim_head"] - c["trim_tail"]
|
|
302
|
+
if visible <= 0:
|
|
303
|
+
raise TimelineError(f"clip {c['index']} ({c['name']}) is shorter than its transitions")
|
|
304
|
+
c["visible"] = visible
|
|
305
|
+
pos = 0
|
|
306
|
+
for c in clips:
|
|
307
|
+
c["record_in"] = pos
|
|
308
|
+
pos += c["visible"]
|
|
309
|
+
total = pos
|
|
310
|
+
|
|
311
|
+
music = None
|
|
312
|
+
audio = proj.get("audio") or {}
|
|
313
|
+
if audio.get("music"):
|
|
314
|
+
msrc = rel(audio["music"])
|
|
315
|
+
mmeta = probes[msrc]
|
|
316
|
+
mlen = min(fr(float(mmeta.get("duration") or 0.0)), total)
|
|
317
|
+
if mlen > 0:
|
|
318
|
+
music = {"src": os.path.abspath(msrc), "name": os.path.basename(msrc), "length": mlen,
|
|
319
|
+
"media_frames": fr(float(mmeta.get("duration") or 0.0))}
|
|
320
|
+
if audio.get("music_loop"):
|
|
321
|
+
notes.append("music_loop is not exported: the bed plays once, up to the timeline's length")
|
|
322
|
+
|
|
323
|
+
markers: List[Dict[str, Any]] = []
|
|
324
|
+
chapters = proj.get("chapters")
|
|
325
|
+
if isinstance(chapters, list):
|
|
326
|
+
total_seconds = Fraction(total) / rate
|
|
327
|
+
previous: Optional[float] = None
|
|
328
|
+
for j, ch in enumerate(chapters):
|
|
329
|
+
# read as render.py's chapters stage reads it (metadata.py): a chapter list carries
|
|
330
|
+
# no fps, so hh:mm:ss:ff needs its @fps there and here alike. What metadata.py refuses
|
|
331
|
+
# is refused here too, never dropped (#414): a chapter at or past the end, or one that
|
|
332
|
+
# does not come after the one before it.
|
|
333
|
+
at_s = _seconds(ch.get("at", 0), f"chapters[{j}].at", None)
|
|
334
|
+
if at_s < 0:
|
|
335
|
+
raise TimelineError(f"chapters[{j}].at must not be negative, got {ch.get('at')!r}")
|
|
336
|
+
if previous is not None and at_s <= previous:
|
|
337
|
+
raise TimelineError(f"chapters[{j}]: the chapter at {at_s:g}s does not come after the previous one "
|
|
338
|
+
f"at {previous:g}s (metadata.py refuses it too)")
|
|
339
|
+
if at_s >= total_seconds:
|
|
340
|
+
raise TimelineError(f"chapters[{j}]: the chapter at {at_s:g}s starts at or after the end of the "
|
|
341
|
+
f"timeline ({float(total_seconds):.3f}s); metadata.py refuses it too")
|
|
342
|
+
previous = at_s
|
|
343
|
+
markers.append({"at": min(fr(at_s), total - 1), "title": str(ch.get("title") or "")})
|
|
344
|
+
elif chapters:
|
|
345
|
+
notes.append("chapters given as a file are not exported as markers; write them inline as [{at, title}]")
|
|
346
|
+
|
|
347
|
+
# A clip of another aspect than the sequence is a reframe: whether the file can state it
|
|
348
|
+
# depends on the format, so summary() adds it to not_exported per format (_reframe_note).
|
|
349
|
+
not_exported = [text for key, text in _NOT_EXPORTED.items() if proj.get(key)]
|
|
350
|
+
dropped_audio = sorted(k for k in _AUDIO_NOT_EXPORTED if audio.get(k) not in (None, False, "", 0) and k != "music")
|
|
351
|
+
if dropped_audio:
|
|
352
|
+
not_exported.append("audio processing: " + ", ".join(dropped_audio))
|
|
353
|
+
return {"name": Path(str(proj.get("output") or "timeline")).stem, "rate": rate, "width": width, "height": height,
|
|
354
|
+
"fit": fit_mode, "reframed": list(dict.fromkeys(reframed)),
|
|
355
|
+
"clips": clips, "transition": t_type if d_frames else "none", "transition_frames": d_frames,
|
|
356
|
+
"music": music, "markers": markers, "total": total, "notes": notes, "not_exported": not_exported}
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _reframe_note(tl: Dict[str, Any], fmt: str) -> List[str]:
|
|
360
|
+
"""What `not_exported` says about the clips whose picture has another aspect than the
|
|
361
|
+
sequence. FCPXML states each one's spatial conform (adjust-conform: fit for frame.fit pad,
|
|
362
|
+
fill for crop), so there only blur's blurred background is missing; EDL and OTIO have no
|
|
363
|
+
field for a conform at all, so the editor's own default decides and the caller is told."""
|
|
364
|
+
if not tl["reframed"]:
|
|
365
|
+
return []
|
|
366
|
+
names = ", ".join(tl["reframed"])
|
|
367
|
+
if fmt == "fcpxml":
|
|
368
|
+
if tl["fit"] != "blur":
|
|
369
|
+
return []
|
|
370
|
+
return [f"frame.fit blur's blurred background behind {names}: the FCPXML fits the picture into "
|
|
371
|
+
f"{tl['width']}x{tl['height']} (adjust-conform fit), leaving bars where the render blurs"]
|
|
372
|
+
return [f"the reframe to {tl['width']}x{tl['height']} (frame.fit {tl['fit']}) of {names}: "
|
|
373
|
+
"set the clips' spatial conform in the editor (fit = pad, fill = crop)"]
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
# ---------------------------------------------------------------------------------------- EDL
|
|
377
|
+
def _tc(frames: int, fps_int: int) -> str:
|
|
378
|
+
h, rem = divmod(frames, fps_int * 3600)
|
|
379
|
+
m, rem = divmod(rem, fps_int * 60)
|
|
380
|
+
s, f = divmod(rem, fps_int)
|
|
381
|
+
return f"{h:02d}:{m:02d}:{s:02d}:{f:02d}"
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
# CMX 3600 numbers events in a three-digit field, and record timecode runs from 01:00:00:00 within
|
|
385
|
+
# one 24-hour day.
|
|
386
|
+
EDL_MAX_EVENTS = 999
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _edl_text(value: Any) -> str:
|
|
390
|
+
"""Caller text (a file name, a clip or chapter name, the title) on one EDL line. The format is
|
|
391
|
+
one statement per line with no escape, so a line break -- any str.splitlines() boundary -- or
|
|
392
|
+
another control character in a name added lines, or whole events, that parse_error() then
|
|
393
|
+
accepted (A261). Each becomes a space."""
|
|
394
|
+
return "".join(" " if (ch in "\x85\u2028\u2029" or ord(ch) < 32 or ord(ch) == 127) else ch for ch in str(value))
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def to_edl(tl: Dict[str, Any]) -> str:
|
|
398
|
+
"""CMX 3600, non-drop timecode at the nominal integer rate, record starting at 01:00:00:00.
|
|
399
|
+
Every event is reel AX (the convention for file-based media) with the file named in
|
|
400
|
+
FROM CLIP NAME / SOURCE FILE comments, which Premiere and Resolve both relink from. A speed
|
|
401
|
+
change is an M2 line. A dissolve is the standard pair: a zero-length cut on the outgoing
|
|
402
|
+
source where its event ended, then a D event that brings the incoming clip in over `d`
|
|
403
|
+
frames starting at the incoming clip's own in point -- so each event's record range runs
|
|
404
|
+
from where the previous one stopped to where the next dissolve begins."""
|
|
405
|
+
fps_int = int(round(float(tl["rate"])))
|
|
406
|
+
hour = fps_int * 3600
|
|
407
|
+
rate = tl["rate"]
|
|
408
|
+
clips = tl["clips"]
|
|
409
|
+
d = tl["transition_frames"]
|
|
410
|
+
# record range of each event: starts `trim_head` before its visible start (the dissolve
|
|
411
|
+
# window), ends where the next event starts
|
|
412
|
+
starts = [c["record_in"] - c["trim_head"] for c in clips]
|
|
413
|
+
ends = starts[1:] + [tl["total"]]
|
|
414
|
+
events = len(clips) + (1 if tl["music"] else 0)
|
|
415
|
+
if events > EDL_MAX_EVENTS:
|
|
416
|
+
# A265: f"{n:03d}" wrote event 1000 as four digits, outside the field
|
|
417
|
+
raise TimelineError(f"an EDL numbers its events in three digits (at most {EDL_MAX_EVENTS}); this timeline has "
|
|
418
|
+
f"{events} -- export .fcpxml or .otio, or split the project")
|
|
419
|
+
if hour + tl["total"] > fps_int * 86400:
|
|
420
|
+
raise TimelineError(f"the timeline ({float(Fraction(tl['total']) / rate):.0f}s) runs past 24:00:00:00 when the "
|
|
421
|
+
"EDL's record starts at 01:00:00:00 -- export .fcpxml or .otio, or split the project")
|
|
422
|
+
lines = [f"TITLE: {_edl_text(tl['name'])}", "FCM: NON-DROP FRAME", ""]
|
|
423
|
+
n = 0
|
|
424
|
+
prev_src_end = ""
|
|
425
|
+
|
|
426
|
+
def src_tc(c: Dict[str, Any], seq_frames: int) -> str:
|
|
427
|
+
"""The source timecode `seq_frames` (sequence frames of source media) after the clip's in
|
|
428
|
+
point: counted at the clip's own rate from its own start timecode (#414)."""
|
|
429
|
+
own = c.get("rate") or rate
|
|
430
|
+
seconds = c.get("in_seconds", Fraction(c["src_in"]) / rate) + Fraction(seq_frames) / rate
|
|
431
|
+
return _tc_label(math.floor(seconds * own + Fraction(1, 2)) + c.get("tc_start", 0), own, c.get("drop_frame", False))
|
|
432
|
+
|
|
433
|
+
for i, c in enumerate(clips):
|
|
434
|
+
n += 1
|
|
435
|
+
chan = "B" if c["has_audio"] and c["has_video"] else ("V" if c["has_video"] else "A")
|
|
436
|
+
rec_in, rec_out = hour + starts[i], hour + ends[i]
|
|
437
|
+
s_in = src_tc(c, 0)
|
|
438
|
+
s_out = src_tc(c, math.floor((ends[i] - starts[i]) * Fraction(c["speed"]) + Fraction(1, 2)))
|
|
439
|
+
if i > 0 and d:
|
|
440
|
+
lines.append(f"{n:03d} AX {chan:<5} C {prev_src_end} {prev_src_end} "
|
|
441
|
+
f"{_tc(rec_in, fps_int)} {_tc(rec_in, fps_int)}")
|
|
442
|
+
lines.append(f"{n:03d} AX {chan:<5} D {d:03d} {s_in} {s_out} "
|
|
443
|
+
f"{_tc(rec_in, fps_int)} {_tc(rec_out, fps_int)}")
|
|
444
|
+
lines.append(f"* FROM CLIP NAME: {_edl_text(clips[i - 1]['name'])}")
|
|
445
|
+
lines.append(f"* TO CLIP NAME: {_edl_text(c['name'])}")
|
|
446
|
+
else:
|
|
447
|
+
lines.append(f"{n:03d} AX {chan:<5} C {s_in} {s_out} "
|
|
448
|
+
f"{_tc(rec_in, fps_int)} {_tc(rec_out, fps_int)}")
|
|
449
|
+
lines.append(f"* FROM CLIP NAME: {_edl_text(c['name'])}")
|
|
450
|
+
lines.append(f"* SOURCE FILE: {_edl_text(c['src'])}")
|
|
451
|
+
if abs(c["speed"] - 1.0) > 1e-6:
|
|
452
|
+
# the speed in source frames per second, at the rate the source labels are counted in
|
|
453
|
+
own_fps = int(round(float(c.get("rate") or rate)))
|
|
454
|
+
lines.append(f"M2 AX {own_fps * c['speed']:05.1f} {s_in}")
|
|
455
|
+
lines.append("")
|
|
456
|
+
prev_src_end = s_out
|
|
457
|
+
if tl["music"]:
|
|
458
|
+
n += 1
|
|
459
|
+
m = tl["music"]
|
|
460
|
+
lines.append(f"{n:03d} AX A2 C {_tc(0, fps_int)} {_tc(m['length'], fps_int)} "
|
|
461
|
+
f"{_tc(hour, fps_int)} {_tc(hour + m['length'], fps_int)}")
|
|
462
|
+
lines.append(f"* FROM CLIP NAME: {_edl_text(m['name'])}")
|
|
463
|
+
lines.append(f"* SOURCE FILE: {_edl_text(m['src'])}")
|
|
464
|
+
lines.append("")
|
|
465
|
+
for mk in tl["markers"]:
|
|
466
|
+
lines.append(f"* LOC: {_tc(hour + mk['at'], fps_int)} WHITE {_edl_text(mk['title'])}")
|
|
467
|
+
return "\n".join(lines).rstrip("\n") + "\n"
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
# ---------------------------------------------------------------------------------------- FCPXML
|
|
471
|
+
def _t(frames: int, rate: Fraction) -> str:
|
|
472
|
+
"""A rational FCPXML time: frames at `rate`, as `N/Ds` (or `Ns` when whole)."""
|
|
473
|
+
value = Fraction(frames) / rate
|
|
474
|
+
return f"{value.numerator}s" if value.denominator == 1 else f"{value.numerator}/{value.denominator}s"
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def _ts(value: Fraction) -> str:
|
|
478
|
+
"""A rational FCPXML time from seconds."""
|
|
479
|
+
return f"{value.numerator}s" if value.denominator == 1 else f"{value.numerator}/{value.denominator}s"
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def _url(path: str) -> str:
|
|
483
|
+
# pathlib builds the percent-encoded file:// URL itself (and the drive-letter form on
|
|
484
|
+
# Windows): no network-library import in scripts/, not even for quoting (see the no-fetch test)
|
|
485
|
+
return Path(os.path.abspath(path)).as_uri()
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def _xml_text(value: Any) -> str:
|
|
489
|
+
"""Caller text as XML 1.0 can hold it: a control character other than tab, line feed and
|
|
490
|
+
carriage return (and U+FFFE/U+FFFF) has no representation at all, not even escaped, so a clip
|
|
491
|
+
or chapter name carrying one made the FCPXML not well-formed (the sibling of A261). Each
|
|
492
|
+
becomes a space."""
|
|
493
|
+
return "".join(" " if ((ord(ch) < 32 and ch not in "\t\n\r") or ch in "\ufffe\uffff") else ch for ch in str(value))
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def to_fcpxml(tl: Dict[str, Any]) -> str:
|
|
497
|
+
"""FCPXML 1.10 (Final Cut Pro 10.6+, DaVinci Resolve): one library/event/project, a spine of
|
|
498
|
+
asset-clips with cross dissolves between them, the music bed as a connected clip on lane -1
|
|
499
|
+
of the first clip, chapters as chapter-markers. Speed is a linear timeMap on the clip. The
|
|
500
|
+
sequence has its own format (r1); each video asset has its source's, and a clip of another
|
|
501
|
+
aspect states its spatial conform (adjust-conform) for frame.fit."""
|
|
502
|
+
from xml.sax.saxutils import escape as _xml_escape # a heavy import chain: only an FCPXML write pays for it
|
|
503
|
+
rate = tl["rate"]
|
|
504
|
+
q = lambda s: _xml_escape(_xml_text(s), {'"': """}) # noqa: E731
|
|
505
|
+
fd = _t(1, rate)
|
|
506
|
+
res: List[str] = []
|
|
507
|
+
ids: Dict[Any, str] = {} # a format's (width, height, frameDuration) or an asset's path -> its id
|
|
508
|
+
|
|
509
|
+
def fmt(width: int, height: int, frame_duration: str) -> str:
|
|
510
|
+
key = (width, height, frame_duration)
|
|
511
|
+
if key not in ids:
|
|
512
|
+
ids[key] = f"r{len(ids) + 1}"
|
|
513
|
+
res.append(f' <format id="{ids[key]}" name="FFVideoFormat{height}p" frameDuration="{frame_duration}" '
|
|
514
|
+
f'width="{width}" height="{height}"/>')
|
|
515
|
+
return ids[key]
|
|
516
|
+
|
|
517
|
+
seq_fmt = fmt(tl["width"], tl["height"], fd) # r1: the sequence's frame
|
|
518
|
+
|
|
519
|
+
def clip_fmt(c: Dict[str, Any]) -> str:
|
|
520
|
+
# An asset describes its own media, not the sequence: with every asset on r1, a 320x180
|
|
521
|
+
# file under a 1080x1920 frame claimed to be 1080x1920, and its conform had nothing to do.
|
|
522
|
+
if not (c["has_video"] and c["picture"]):
|
|
523
|
+
return seq_fmt
|
|
524
|
+
return fmt(c["picture"][0], c["picture"][1], _t(1, exact_rate(float(c["fps"]))) if c["fps"] else fd)
|
|
525
|
+
|
|
526
|
+
def asset(path: str, name: str, frames: int, has_video: bool, has_audio: bool, format_id: str = "",
|
|
527
|
+
start: Fraction = Fraction(0)) -> str:
|
|
528
|
+
if path in ids:
|
|
529
|
+
return ids[path]
|
|
530
|
+
rid = f"r{len(ids) + 1}"
|
|
531
|
+
ids[path] = rid
|
|
532
|
+
# the media starts at its own start timecode (#414): a clip's start is counted from there
|
|
533
|
+
res.append(f' <asset id="{rid}" name="{q(name)}" start="{_ts(start)}" duration="{_t(frames, rate)}" '
|
|
534
|
+
f'hasVideo="{int(has_video)}" hasAudio="{int(has_audio)}"'
|
|
535
|
+
+ (f' format="{format_id}"' if has_video else "") + ' audioSources="1" audioChannels="2">\n'
|
|
536
|
+
f' <media-rep kind="original-media" src="{q(_url(path))}"/>\n </asset>')
|
|
537
|
+
return rid
|
|
538
|
+
|
|
539
|
+
spine: List[str] = []
|
|
540
|
+
d = tl["transition_frames"]
|
|
541
|
+
markers = list(tl["markers"])
|
|
542
|
+
for i, c in enumerate(tl["clips"]):
|
|
543
|
+
cid = clip_fmt(c)
|
|
544
|
+
base = c.get("tc_seconds", Fraction(0))
|
|
545
|
+
rid = asset(c["src"], c["name"], c["media_frames"], c["has_video"], c["has_audio"], cid, base)
|
|
546
|
+
if i > 0 and d:
|
|
547
|
+
spine.append(f' <transition name="Cross Dissolve" offset="{_t(c["record_in"] - c["trim_head"], rate)}" '
|
|
548
|
+
f'duration="{_t(d, rate)}"/>')
|
|
549
|
+
src_start = c["src_in"] + math.floor(c["trim_head"] * Fraction(c["speed"]) + Fraction(1, 2))
|
|
550
|
+
inner: List[str] = []
|
|
551
|
+
if abs(c["speed"] - 1.0) > 1e-6:
|
|
552
|
+
# timeMap maps clip-local time to source time; two linear points give a constant speed
|
|
553
|
+
inner.append(" <timeMap>")
|
|
554
|
+
inner.append(f' <timept time="0s" value="{_ts(base + Fraction(src_start) / rate)}" interp="linear"/>')
|
|
555
|
+
inner.append(f' <timept time="{_t(c["visible"], rate)}" '
|
|
556
|
+
f'value="{_ts(base + Fraction(src_start + math.floor(c["visible"] * Fraction(c["speed"]) + Fraction(1, 2))) / rate)}" interp="linear"/>')
|
|
557
|
+
inner.append(" </timeMap>")
|
|
558
|
+
start_attr = "0s"
|
|
559
|
+
else:
|
|
560
|
+
start_attr = _ts(base + Fraction(src_start) / rate)
|
|
561
|
+
# the clip's local time: the source's (from its start timecode), or 0 under a timeMap
|
|
562
|
+
local0 = base + Fraction(src_start) / rate if abs(c["speed"] - 1.0) <= 1e-6 else Fraction(0)
|
|
563
|
+
# the FCPXML 1.10 DTD's order inside an asset-clip: timeMap, then the adjust-* elements
|
|
564
|
+
# (adjust-conform), then anchored items (the music bed), then markers. Anything out of
|
|
565
|
+
# that order does not validate, and Final Cut validates what it imports against that DTD.
|
|
566
|
+
if c["reframed"]:
|
|
567
|
+
# the DTD reads a missing adjust-conform as fit, so crop has to say fill; fit is
|
|
568
|
+
# written too, so the file states the project's choice rather than a default
|
|
569
|
+
inner.append(f' <adjust-conform type="{_CONFORM[tl["fit"]]}"/>')
|
|
570
|
+
if i == 0 and tl["music"]:
|
|
571
|
+
m = tl["music"]
|
|
572
|
+
mid = asset(m["src"], m["name"], m["media_frames"], False, True)
|
|
573
|
+
inner.append(f' <asset-clip ref="{mid}" lane="-1" offset="{_ts(local0)}" name="{q(m["name"])}" '
|
|
574
|
+
f'start="0s" duration="{_t(m["length"], rate)}" audioRole="music"/>')
|
|
575
|
+
for mk in [m for m in markers if c["record_in"] <= m["at"] < c["record_in"] + c["visible"]]:
|
|
576
|
+
inner.append(f' <chapter-marker start="{_ts(local0 + Fraction(mk["at"] - c["record_in"]) / rate)}" '
|
|
577
|
+
f'duration="{fd}" value="{q(mk["title"])}"/>')
|
|
578
|
+
head = (f' <asset-clip ref="{rid}" offset="{_t(c["record_in"], rate)}" name="{q(c["name"])}" '
|
|
579
|
+
f'start="{start_attr}" duration="{_t(c["visible"], rate)}" format="{cid}" '
|
|
580
|
+
f'tcFormat="{"DF" if c.get("drop_frame") else "NDF"}"')
|
|
581
|
+
spine.append(head + (">\n" + "\n".join(inner) + "\n </asset-clip>" if inner else "/>"))
|
|
582
|
+
out = ['<?xml version="1.0" encoding="UTF-8"?>', "<!DOCTYPE fcpxml>", '<fcpxml version="1.10">',
|
|
583
|
+
" <resources>", *res, " </resources>", " <library>", f' <event name="{q(tl["name"])}">',
|
|
584
|
+
f' <project name="{q(tl["name"])}">',
|
|
585
|
+
f' <sequence format="{seq_fmt}" duration="{_t(tl["total"], rate)}" tcStart="0s" tcFormat="NDF">',
|
|
586
|
+
" <spine>", *spine, " </spine>", " </sequence>", " </project>", " </event>",
|
|
587
|
+
" </library>", "</fcpxml>"]
|
|
588
|
+
return "\n".join(out) + "\n"
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
# ---------------------------------------------------------------------------------------- OTIO
|
|
592
|
+
def _rt(frames: int, rate: Fraction) -> Dict[str, Any]:
|
|
593
|
+
return {"OTIO_SCHEMA": "RationalTime.1", "rate": float(rate), "value": float(frames)}
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def _range(start: int, dur: int, rate: Fraction) -> Dict[str, Any]:
|
|
597
|
+
return {"OTIO_SCHEMA": "TimeRange.1", "start_time": _rt(start, rate), "duration": _rt(dur, rate)}
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
def to_otio(tl: Dict[str, Any]) -> str:
|
|
601
|
+
"""OpenTimelineIO JSON (Resolve imports it natively; Premiere/Avid through OTIO's adapters):
|
|
602
|
+
a video track of clips and SMPTE dissolves, a music track, markers on the stack. Times are in
|
|
603
|
+
timeline frames; a speed change is a LinearTimeWarp effect over the clip's source range."""
|
|
604
|
+
rate = tl["rate"]
|
|
605
|
+
d = tl["transition_frames"]
|
|
606
|
+
video: List[Dict[str, Any]] = []
|
|
607
|
+
for i, c in enumerate(tl["clips"]):
|
|
608
|
+
if i > 0 and d:
|
|
609
|
+
video.append({"OTIO_SCHEMA": "Transition.1", "name": "Cross Dissolve", "metadata": {},
|
|
610
|
+
"transition_type": "SMPTE_Dissolve",
|
|
611
|
+
# OTIO: in_offset is the part before the cut, out_offset the part after
|
|
612
|
+
"in_offset": _rt(c["trim_head"], rate), "out_offset": _rt(tl["clips"][i - 1]["trim_tail"], rate)})
|
|
613
|
+
src_start = c["src_in"] + math.floor(c["trim_head"] * Fraction(c["speed"]) + Fraction(1, 2))
|
|
614
|
+
# the media's range starts at its start timecode (#414), in timeline frames
|
|
615
|
+
base = c.get("tc_seconds", Fraction(0)) * rate
|
|
616
|
+
clip = {"OTIO_SCHEMA": "Clip.2", "name": c["name"], "metadata": {}, "enabled": True,
|
|
617
|
+
# OTIO's own convention: source_range starts at the media's in point and lasts the
|
|
618
|
+
# clip's length on the timeline; a LinearTimeWarp says how fast the media runs
|
|
619
|
+
# through it (core OTIO does not rescale durations by effects).
|
|
620
|
+
"source_range": _range(base + src_start, c["visible"], rate),
|
|
621
|
+
"effects": [], "markers": [],
|
|
622
|
+
"media_references": {"DEFAULT_MEDIA": {
|
|
623
|
+
"OTIO_SCHEMA": "ExternalReference.1", "name": c["name"], "metadata": {},
|
|
624
|
+
"target_url": _url(c["src"]), "available_range": _range(base, c["media_frames"], rate),
|
|
625
|
+
"available_image_bounds": None}},
|
|
626
|
+
"active_media_reference_key": "DEFAULT_MEDIA"}
|
|
627
|
+
if abs(c["speed"] - 1.0) > 1e-6:
|
|
628
|
+
clip["effects"].append({"OTIO_SCHEMA": "LinearTimeWarp.1", "name": "speed", "metadata": {},
|
|
629
|
+
"effect_name": "LinearTimeWarp", "time_scalar": c["speed"]})
|
|
630
|
+
video.append(clip)
|
|
631
|
+
tracks = [{"OTIO_SCHEMA": "Track.1", "name": "V1", "kind": "Video", "metadata": {}, "enabled": True,
|
|
632
|
+
"source_range": None, "effects": [], "markers": [], "children": video}]
|
|
633
|
+
if tl["music"]:
|
|
634
|
+
m = tl["music"]
|
|
635
|
+
tracks.append({"OTIO_SCHEMA": "Track.1", "name": "Music", "kind": "Audio", "metadata": {}, "enabled": True,
|
|
636
|
+
"source_range": None, "effects": [], "markers": [], "children": [{
|
|
637
|
+
"OTIO_SCHEMA": "Clip.2", "name": m["name"], "metadata": {}, "enabled": True,
|
|
638
|
+
"source_range": _range(0, m["length"], rate), "effects": [], "markers": [],
|
|
639
|
+
"media_references": {"DEFAULT_MEDIA": {
|
|
640
|
+
"OTIO_SCHEMA": "ExternalReference.1", "name": m["name"], "metadata": {},
|
|
641
|
+
"target_url": _url(m["src"]), "available_range": _range(0, m["media_frames"], rate),
|
|
642
|
+
"available_image_bounds": None}},
|
|
643
|
+
"active_media_reference_key": "DEFAULT_MEDIA"}]})
|
|
644
|
+
markers = [{"OTIO_SCHEMA": "Marker.2", "name": mk["title"], "metadata": {}, "color": "RED", "comment": "",
|
|
645
|
+
"marked_range": _range(mk["at"], 0, rate)} for mk in tl["markers"]]
|
|
646
|
+
doc = {"OTIO_SCHEMA": "Timeline.1", "name": tl["name"], "metadata": {}, "global_start_time": _rt(0, rate),
|
|
647
|
+
"tracks": {"OTIO_SCHEMA": "Stack.1", "name": "tracks", "metadata": {}, "enabled": True,
|
|
648
|
+
"source_range": None, "effects": [], "markers": markers, "children": tracks}}
|
|
649
|
+
return json.dumps(doc, indent=2, ensure_ascii=False) + "\n"
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
WRITERS = {"edl": to_edl, "fcpxml": to_fcpxml, "otio": to_otio}
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
def parses(path: str, fmt: str) -> bool:
|
|
656
|
+
"""The verification step: the written file reads back as what it claims to be. A file that
|
|
657
|
+
does not is recorded with the reason (`diagnostics.warnings`, `timeline_parse_failed`: the
|
|
658
|
+
exception, or what was read instead), beside the step's `ok: false`."""
|
|
659
|
+
why = parse_error(path, fmt)
|
|
660
|
+
if why:
|
|
661
|
+
warn(f"{path} does not read back as {fmt}: {why}", "timeline_parse_failed", path=path, format=fmt, error=why)
|
|
662
|
+
return why is None
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
def _xml_root_tag(data: bytes) -> str:
|
|
666
|
+
"""The root element of a well-formed XML document, read with expat directly.
|
|
667
|
+
|
|
668
|
+
ElementTree expands entities declared in an internal DTD, and on Python 3.9/3.10 (both
|
|
669
|
+
supported) that is an entity-expansion ("billion laughs") risk on a file the tool did not
|
|
670
|
+
write. A timeline never declares an entity (to_fcpxml writes a bare `<!DOCTYPE fcpxml>`), so
|
|
671
|
+
a declaration is refused rather than expanded. Errors are ElementTree's ParseError, so a
|
|
672
|
+
failure reads the same as before."""
|
|
673
|
+
from xml.etree.ElementTree import ParseError
|
|
674
|
+
from xml.parsers import expat
|
|
675
|
+
parser = expat.ParserCreate()
|
|
676
|
+
parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_NEVER)
|
|
677
|
+
root: List[str] = []
|
|
678
|
+
|
|
679
|
+
def start(name: str, _attrs: Any) -> None:
|
|
680
|
+
if not root:
|
|
681
|
+
root.append(name)
|
|
682
|
+
|
|
683
|
+
def entity(name: str, *_rest: Any) -> None:
|
|
684
|
+
raise ParseError(f"the document declares the entity {name!r}; a timeline never declares one")
|
|
685
|
+
|
|
686
|
+
parser.StartElementHandler = start
|
|
687
|
+
parser.EntityDeclHandler = entity
|
|
688
|
+
try:
|
|
689
|
+
parser.Parse(data, True)
|
|
690
|
+
except expat.ExpatError as exc:
|
|
691
|
+
raise ParseError(str(exc)) from None
|
|
692
|
+
return root[0]
|
|
693
|
+
|
|
694
|
+
|
|
695
|
+
def parse_error(path: str, fmt: str) -> Optional[str]:
|
|
696
|
+
"""Why `path` does not read back as `fmt`, or None when it does (parses() without the record)."""
|
|
697
|
+
try:
|
|
698
|
+
text = Path(path).read_text(encoding="utf-8")
|
|
699
|
+
if fmt == "fcpxml":
|
|
700
|
+
tag = _xml_root_tag(text.encode("utf-8"))
|
|
701
|
+
return None if tag == "fcpxml" else f"the root element is <{tag}>, not <fcpxml>"
|
|
702
|
+
if fmt == "otio":
|
|
703
|
+
doc = json.loads(text)
|
|
704
|
+
schema = doc.get("OTIO_SCHEMA") if isinstance(doc, dict) else None
|
|
705
|
+
return None if schema == "Timeline.1" else f"OTIO_SCHEMA is {schema!r}, not 'Timeline.1'"
|
|
706
|
+
if not text.startswith("TITLE:"):
|
|
707
|
+
return "the first line is not TITLE:"
|
|
708
|
+
return None if any(line[:3].isdigit() for line in text.splitlines()) else "no numbered event line"
|
|
709
|
+
except (OSError, ValueError, SyntaxError) as exc:
|
|
710
|
+
return f"{type(exc).__name__}: {exc}"
|
|
711
|
+
|
|
712
|
+
|
|
713
|
+
def summary(tl: Dict[str, Any], fmt: str) -> Dict[str, Any]:
|
|
714
|
+
"""The part of the timeline a caller reads back in render.py's --json document."""
|
|
715
|
+
rate = tl["rate"]
|
|
716
|
+
return {"format": fmt, "rate": f"{rate.numerator}/{rate.denominator}" if rate.denominator != 1 else str(rate.numerator),
|
|
717
|
+
"duration": round(float(Fraction(tl["total"]) / rate), 3), "frames": tl["total"],
|
|
718
|
+
"clips": len(tl["clips"]), "transition": tl["transition"],
|
|
719
|
+
"transition_frames": tl["transition_frames"], "music": bool(tl["music"]),
|
|
720
|
+
"markers": len(tl["markers"]), "notes": tl["notes"],
|
|
721
|
+
"not_exported": tl["not_exported"] + _reframe_note(tl, fmt)}
|