datacut 0.1.0__py3-none-any.whl
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.
- datacut/__init__.py +121 -0
- datacut/__main__.py +122 -0
- datacut/animation/__init__.py +0 -0
- datacut/animation/animation.py +336 -0
- datacut/animation/composition.py +258 -0
- datacut/animation/creation.py +315 -0
- datacut/animation/fading.py +328 -0
- datacut/animation/growing.py +90 -0
- datacut/animation/indication.py +608 -0
- datacut/animation/movement.py +165 -0
- datacut/animation/numbers.py +92 -0
- datacut/animation/physics.py +453 -0
- datacut/animation/rotation.py +95 -0
- datacut/animation/specialized.py +956 -0
- datacut/animation/transform.py +505 -0
- datacut/animation/transform_matching_parts.py +343 -0
- datacut/animation/update.py +95 -0
- datacut/camera/__init__.py +0 -0
- datacut/camera/camera.py +795 -0
- datacut/camera/camera_frame.py +320 -0
- datacut/camera/cinematography.py +1166 -0
- datacut/config.py +479 -0
- datacut/constants.py +160 -0
- datacut/css/__init__.py +189 -0
- datacut/css/easing.py +328 -0
- datacut/css/engine.py +1727 -0
- datacut/css/gradients.py +678 -0
- datacut/css/motion.py +1615 -0
- datacut/css/parser.py +741 -0
- datacut/css/presets.py +143 -0
- datacut/css/shader_fill.py +703 -0
- datacut/css/values.py +650 -0
- datacut/default_config.yml +224 -0
- datacut/event_handler/__init__.py +6 -0
- datacut/event_handler/event_dispatcher.py +161 -0
- datacut/event_handler/event_listner.py +31 -0
- datacut/event_handler/event_type.py +11 -0
- datacut/event_handler/picking.py +111 -0
- datacut/event_keys.py +53 -0
- datacut/extract_scene.py +200 -0
- datacut/layout/__init__.py +39 -0
- datacut/layout/components.py +425 -0
- datacut/layout/containers.py +1520 -0
- datacut/logger.py +13 -0
- datacut/mobject/__init__.py +0 -0
- datacut/mobject/boolean_ops.py +168 -0
- datacut/mobject/changing.py +209 -0
- datacut/mobject/coordinate_systems.py +1056 -0
- datacut/mobject/fractals.py +348 -0
- datacut/mobject/frame.py +80 -0
- datacut/mobject/functions.py +147 -0
- datacut/mobject/geometry.py +1834 -0
- datacut/mobject/gltf.py +243 -0
- datacut/mobject/interactive.py +906 -0
- datacut/mobject/lights.py +366 -0
- datacut/mobject/materials.py +207 -0
- datacut/mobject/matrix.py +570 -0
- datacut/mobject/mesh3d.py +2288 -0
- datacut/mobject/mobject.py +2885 -0
- datacut/mobject/mobject_update_utils.py +123 -0
- datacut/mobject/model.py +543 -0
- datacut/mobject/number_line.py +517 -0
- datacut/mobject/numbers.py +441 -0
- datacut/mobject/probability.py +536 -0
- datacut/mobject/shape_matchers.py +161 -0
- datacut/mobject/subtitles.py +260 -0
- datacut/mobject/svg/__init__.py +0 -0
- datacut/mobject/svg/brace.py +356 -0
- datacut/mobject/svg/drawings.py +1041 -0
- datacut/mobject/svg/old_tex_mobject.py +335 -0
- datacut/mobject/svg/path_cache.py +155 -0
- datacut/mobject/svg/special_tex.py +216 -0
- datacut/mobject/svg/string_mobject.py +622 -0
- datacut/mobject/svg/svg_mobject.py +657 -0
- datacut/mobject/svg/svg_parse.py +437 -0
- datacut/mobject/svg/tex_mobject.py +499 -0
- datacut/mobject/svg/text_mobject.py +702 -0
- datacut/mobject/svg/typst_mobject.py +864 -0
- datacut/mobject/three_dimensions.py +686 -0
- datacut/mobject/types/__init__.py +0 -0
- datacut/mobject/types/dot_cloud.py +220 -0
- datacut/mobject/types/image_mobject.py +130 -0
- datacut/mobject/types/point_cloud_mobject.py +138 -0
- datacut/mobject/types/shader_mobject.py +268 -0
- datacut/mobject/types/surface.py +848 -0
- datacut/mobject/types/vectorized_mobject.py +1749 -0
- datacut/mobject/types/video_mobject.py +3902 -0
- datacut/mobject/value_tracker.py +110 -0
- datacut/mobject/vector_field.py +585 -0
- datacut/module_loader.py +176 -0
- datacut/reactive/__init__.py +25 -0
- datacut/reactive/signals.py +610 -0
- datacut/renderer/__init__.py +4 -0
- datacut/renderer/drawing.py +1066 -0
- datacut/renderer/gpu.py +800 -0
- datacut/renderer/material.py +88 -0
- datacut/renderer/pipeline.py +179 -0
- datacut/renderer/post_process.py +577 -0
- datacut/renderer/renderer.py +1285 -0
- datacut/renderer/shader_source.py +146 -0
- datacut/renderer/shared_buffer.py +185 -0
- datacut/renderer/texture.py +217 -0
- datacut/renderer/uniform_block.py +118 -0
- datacut/scene/__init__.py +0 -0
- datacut/scene/incremental.py +233 -0
- datacut/scene/interactive_scene.py +758 -0
- datacut/scene/performance.py +226 -0
- datacut/scene/presentation_scene.py +783 -0
- datacut/scene/recording.py +541 -0
- datacut/scene/safe_zones.py +323 -0
- datacut/scene/scene.py +2849 -0
- datacut/scene/scene_embed.py +277 -0
- datacut/scene/scene_file_writer.py +1014 -0
- datacut/scene/scene_task.py +183 -0
- datacut/scene/sfx.py +164 -0
- datacut/scene/sound.py +702 -0
- datacut/scene/sound_clip.py +580 -0
- datacut/scene/timeline.py +1689 -0
- datacut/scene/transcript.py +503 -0
- datacut/shaders/fill.wgsl +107 -0
- datacut/shaders/fill_depth.wgsl +198 -0
- datacut/shaders/image.wgsl +25 -0
- datacut/shaders/inserts/NOTE.md +16 -0
- datacut/shaders/inserts/clip_test.wgsl +14 -0
- datacut/shaders/inserts/complex_functions.wgsl +20 -0
- datacut/shaders/inserts/fill_color.wgsl +10 -0
- datacut/shaders/inserts/finalize_color.wgsl +44 -0
- datacut/shaders/inserts/frame_uniforms.wgsl +37 -0
- datacut/shaders/inserts/frame_units.wgsl +18 -0
- datacut/shaders/inserts/image_quad.wgsl +28 -0
- datacut/shaders/inserts/mobject_uniforms.wgsl +11 -0
- datacut/shaders/inserts/project_point.wgsl +44 -0
- datacut/shaders/inserts/quad_corners.wgsl +12 -0
- datacut/shaders/inserts/read_data.wgsl +33 -0
- datacut/shaders/inserts/surface_mesh.wgsl +106 -0
- datacut/shaders/mandelbrot_fractal.wgsl +100 -0
- datacut/shaders/mesh.wgsl +474 -0
- datacut/shaders/newton_fractal.wgsl +200 -0
- datacut/shaders/present.wgsl +62 -0
- datacut/shaders/stroke.wgsl +1141 -0
- datacut/shaders/stroke_depth.wgsl +1136 -0
- datacut/shaders/surface.wgsl +40 -0
- datacut/shaders/textured_surface.wgsl +59 -0
- datacut/shaders/true_dot.wgsl +78 -0
- datacut/shaders/video.wgsl +42 -0
- datacut/tex_templates.yml +736 -0
- datacut/transcribe.py +32 -0
- datacut/typing.py +412 -0
- datacut/utils/__init__.py +0 -0
- datacut/utils/bezier.py +467 -0
- datacut/utils/browser_audio.py +423 -0
- datacut/utils/browser_code_transform.py +1293 -0
- datacut/utils/browser_completions.py +2255 -0
- datacut/utils/browser_fonts.py +143 -0
- datacut/utils/browser_pathops.py +47 -0
- datacut/utils/browser_scheduler.py +18 -0
- datacut/utils/browser_typst.py +82 -0
- datacut/utils/cache.py +34 -0
- datacut/utils/cinematic_vfx.py +779 -0
- datacut/utils/color.py +203 -0
- datacut/utils/debug.py +46 -0
- datacut/utils/dict_ops.py +22 -0
- datacut/utils/directories.py +55 -0
- datacut/utils/editor_signatures.py +1806 -0
- datacut/utils/editor_thumbnails.py +769 -0
- datacut/utils/family_ops.py +48 -0
- datacut/utils/file_ops.py +65 -0
- datacut/utils/images.py +52 -0
- datacut/utils/iterables.py +216 -0
- datacut/utils/native.py +280 -0
- datacut/utils/paths.py +83 -0
- datacut/utils/rate_functions.py +154 -0
- datacut/utils/render_geometry.py +186 -0
- datacut/utils/simple_functions.py +99 -0
- datacut/utils/sounds.py +43 -0
- datacut/utils/space_ops.py +460 -0
- datacut/utils/structured_array.py +256 -0
- datacut/utils/svg_export.py +102 -0
- datacut/utils/tex.py +139 -0
- datacut/utils/tex_file_writing.py +164 -0
- datacut/utils/tex_to_symbol_count.py +186 -0
- datacut/utils/typst_file_writing.py +205 -0
- datacut/utils/vfx_presets.py +4543 -0
- datacut/utils/visual_css.py +737 -0
- datacut/utils/visual_editor.py +4292 -0
- datacut/utils/window_audio.py +760 -0
- datacut/window.py +910 -0
- datacut-0.1.0.dist-info/METADATA +226 -0
- datacut-0.1.0.dist-info/RECORD +193 -0
- datacut-0.1.0.dist-info/WHEEL +5 -0
- datacut-0.1.0.dist-info/entry_points.txt +2 -0
- datacut-0.1.0.dist-info/licenses/LICENSE.md +21 -0
- datacut-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1014 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import platform
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess as sp
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
if sys.platform != "emscripten":
|
|
11
|
+
from pydub import AudioSegment
|
|
12
|
+
else:
|
|
13
|
+
AudioSegment = None
|
|
14
|
+
from tqdm.auto import tqdm as ProgressDisplay
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from datacut.logger import log
|
|
18
|
+
from datacut.mobject.mobject import Mobject
|
|
19
|
+
from datacut.utils.file_ops import guarantee_existence
|
|
20
|
+
from datacut.camera.camera import FrameStream
|
|
21
|
+
from datacut.scene.sound import Sound
|
|
22
|
+
from datacut.scene.sound_clip import SoundClip
|
|
23
|
+
from datacut.scene.sound_clip import duck_keys_for
|
|
24
|
+
from datacut.utils.sounds import get_full_sound_file_path
|
|
25
|
+
|
|
26
|
+
from typing import TYPE_CHECKING
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from PIL.Image import Image
|
|
30
|
+
|
|
31
|
+
from datacut.scene.scene import Scene
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# Named ways of encoding a movie, see the --quality flag. Set before the scene runs, so that
|
|
35
|
+
# what the scene sets of its own, its crf say, still has the last word.
|
|
36
|
+
QUALITY_PROFILES: dict[str, dict] = {
|
|
37
|
+
# Quick to write and small, to look at what was made
|
|
38
|
+
"preview": dict(video_codec="libx264", pixel_format="yuv420p", crf=28, preset="veryfast"),
|
|
39
|
+
# For uploading: little lost, playing everywhere, and playable before it has all arrived
|
|
40
|
+
"youtube": dict(
|
|
41
|
+
video_codec="libx264", pixel_format="yuv420p", crf=16, preset="slow",
|
|
42
|
+
container_flags=["-movflags", "+faststart"],
|
|
43
|
+
),
|
|
44
|
+
# For editing further: ProRes 422 HQ, ten bits, as Resolve, Premiere and Final Cut take it
|
|
45
|
+
"master": dict(
|
|
46
|
+
video_codec="prores_ks", pixel_format="yuv422p10le", crf=None, preset=None,
|
|
47
|
+
movie_flags=["-profile:v", "3", "-vendor", "apl0"], movie_file_extension=".mov",
|
|
48
|
+
note="ProRes for editing, which Windows' own player does not open",
|
|
49
|
+
),
|
|
50
|
+
# With the background left transparent, to be laid over other footage: ProRes 4444 with its
|
|
51
|
+
# alpha, ten bits, as Resolve, Premiere and Final Cut take it
|
|
52
|
+
"alpha": dict(
|
|
53
|
+
video_codec="prores_ks", pixel_format="yuva444p10le", crf=None, preset=None,
|
|
54
|
+
movie_flags=["-profile:v", "4", "-vendor", "apl0"], movie_file_extension=".mov",
|
|
55
|
+
transparent=True, png_mode="RGBA",
|
|
56
|
+
note="ProRes 4444 with a transparent background, for laying over other footage",
|
|
57
|
+
),
|
|
58
|
+
# Every pixel exactly as drawn, as rgb, for measuring against
|
|
59
|
+
"lossless": dict(
|
|
60
|
+
video_codec="libx264rgb", pixel_format="rgb24", crf=0, preset="veryfast", encoder="cpu",
|
|
61
|
+
note="exact rgb, which players decoding on the graphics card do not open",
|
|
62
|
+
),
|
|
63
|
+
}
|
|
64
|
+
# Pixel formats the graphics cards' H.264 encoders take
|
|
65
|
+
HARDWARE_PIXEL_FORMATS = ("yuv420p", "nv12", "yuv444p")
|
|
66
|
+
# The H.264 encoders tried, in order, see hardware_h264_encoder
|
|
67
|
+
HARDWARE_H264_ENCODERS = ("h264_nvenc", "h264_amf", "h264_qsv")
|
|
68
|
+
_hardware_h264: dict[str, str | None] = {}
|
|
69
|
+
# x264's presets, as NVENC's, which run p1, fastest, to p7, best
|
|
70
|
+
NVENC_PRESETS = {
|
|
71
|
+
"ultrafast": "p1", "superfast": "p1", "veryfast": "p2", "faster": "p3", "fast": "p4",
|
|
72
|
+
"medium": "p5", "slow": "p6", "slower": "p7", "veryslow": "p7", "placebo": "p7",
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def hardware_h264_encoder(ffmpeg_bin: str = "ffmpeg") -> str | None:
|
|
77
|
+
"""
|
|
78
|
+
The first of the graphics card's H.264 encoders ffmpeg has which encodes here, found by
|
|
79
|
+
having each encode a few frames, once a run. None where there is none.
|
|
80
|
+
"""
|
|
81
|
+
if ffmpeg_bin in _hardware_h264:
|
|
82
|
+
return _hardware_h264[ffmpeg_bin]
|
|
83
|
+
found = None
|
|
84
|
+
for codec in HARDWARE_H264_ENCODERS:
|
|
85
|
+
try:
|
|
86
|
+
result = sp.run(
|
|
87
|
+
[ffmpeg_bin, "-v", "error", "-f", "lavfi", "-i", "color=size=256x256:rate=30",
|
|
88
|
+
"-frames:v", "3", "-c:v", codec, "-f", "null", "-"],
|
|
89
|
+
capture_output=True, timeout=20,
|
|
90
|
+
)
|
|
91
|
+
except (OSError, sp.TimeoutExpired):
|
|
92
|
+
continue
|
|
93
|
+
if result.returncode == 0:
|
|
94
|
+
found = codec
|
|
95
|
+
break
|
|
96
|
+
_hardware_h264[ffmpeg_bin] = found
|
|
97
|
+
return found
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def hardware_quality_options(codec: str, crf: int | None, preset: str | None) -> list[str]:
|
|
101
|
+
"""crf and preset, as x264 has them, in a graphics card encoder's own terms"""
|
|
102
|
+
quality = 23 if crf is None else int(crf)
|
|
103
|
+
if codec == "h264_nvenc":
|
|
104
|
+
options = ["-preset", NVENC_PRESETS.get(preset or "medium", "p5")]
|
|
105
|
+
if quality <= 0:
|
|
106
|
+
return options + ["-tune", "lossless"]
|
|
107
|
+
# No B-frames: NVENC gives them a coarser quantizer than the P-frames around them, and
|
|
108
|
+
# what changes little from a frame to the next, a thin stroke being drawn or something
|
|
109
|
+
# fading in, is dropped in them and caught up at the next P-frame, every fourth frame,
|
|
110
|
+
# so that it moves at a quarter of the frame rate
|
|
111
|
+
return options + ["-tune", "hq", "-rc", "vbr", "-cq", str(quality), "-b:v", "0", "-bf", "0"]
|
|
112
|
+
if codec == "h264_amf":
|
|
113
|
+
return ["-quality", "quality", "-rc", "cqp",
|
|
114
|
+
"-qp_i", str(quality), "-qp_p", str(quality), "-qp_b", str(quality)]
|
|
115
|
+
if codec == "h264_qsv":
|
|
116
|
+
return ["-global_quality", str(max(quality, 1))]
|
|
117
|
+
return []
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# What a movie says of its colors. Left unsaid, ffmpeg turns rgb into yuv as BT.601 has it, while
|
|
121
|
+
# players take a movie saying nothing, of HD size, to be BT.709, and turn it back into rgb by
|
|
122
|
+
# another reckoning than it was made with: reds and oranges go towards yellow, and every color's
|
|
123
|
+
# saturation shifts. Made as BT.709, see open_movie_pipe, and said to be, it is seen as drawn.
|
|
124
|
+
COLOR_TAGS = [
|
|
125
|
+
"-colorspace", "bt709", "-color_primaries", "bt709",
|
|
126
|
+
"-color_trc", "bt709", "-color_range", "tv",
|
|
127
|
+
]
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def chapter_file_name(name: str, limit: int = 60) -> str:
|
|
131
|
+
"""A chapter's name made fit to name a file with"""
|
|
132
|
+
import re
|
|
133
|
+
name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "", name).strip().rstrip(".")
|
|
134
|
+
return (name[:limit].rstrip() or "Chapter")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class SceneFileWriter(object):
|
|
138
|
+
def __init__(
|
|
139
|
+
self,
|
|
140
|
+
scene: Scene,
|
|
141
|
+
write_to_movie: bool = False,
|
|
142
|
+
subdivide_output: bool = False,
|
|
143
|
+
png_mode: str = "RGBA",
|
|
144
|
+
save_last_frame: bool = False,
|
|
145
|
+
movie_file_extension: str = ".mp4",
|
|
146
|
+
# Where should this be written
|
|
147
|
+
output_directory: str = ".",
|
|
148
|
+
file_name: str | None = None,
|
|
149
|
+
open_file_upon_completion: bool = False,
|
|
150
|
+
show_file_location_upon_completion: bool = False,
|
|
151
|
+
quiet: bool = False,
|
|
152
|
+
total_frames: int = 0,
|
|
153
|
+
progress_description_len: int = 40,
|
|
154
|
+
# Name of the binary used for ffmpeg
|
|
155
|
+
ffmpeg_bin: str = "ffmpeg",
|
|
156
|
+
video_codec: str = "libx264",
|
|
157
|
+
pixel_format: str = "yuv420p",
|
|
158
|
+
# How hard the encoder should try, where zero means keep every pixel exactly. Left
|
|
159
|
+
# unsaid the encoder's default stands, which throws away a good deal, so it is worth
|
|
160
|
+
# setting for anything a frame will be measured against.
|
|
161
|
+
crf: int | None = None,
|
|
162
|
+
preset: str | None = "fast",
|
|
163
|
+
saturation: float = 1.0,
|
|
164
|
+
gamma: float = 1.0,
|
|
165
|
+
# How the movie is encoded, named, see QUALITY_PROFILES; what the scene sets of its
|
|
166
|
+
# own, its crf say, still has the last word
|
|
167
|
+
quality: str | None = None,
|
|
168
|
+
# Where H.264 is encoded: "auto", on the graphics card's encoder where there is one
|
|
169
|
+
# and on the processor otherwise, "gpu" or "cpu", see hardware_h264_encoder
|
|
170
|
+
encoder: str = "auto",
|
|
171
|
+
# Every play and wait a chapter of the movie, and each written on its own too
|
|
172
|
+
chapters: bool = False,
|
|
173
|
+
# Only chapters which could have changed drawn again, see datacut.scene.incremental
|
|
174
|
+
incremental: bool = False,
|
|
175
|
+
# Only this stretch of the scene, (start, end) in seconds, end below zero for the end
|
|
176
|
+
time_range: tuple[float, float] | None = None,
|
|
177
|
+
):
|
|
178
|
+
self.scene: Scene = scene
|
|
179
|
+
self.encoder = encoder
|
|
180
|
+
self.quality = quality
|
|
181
|
+
# The ffmpeg encoder the movie was written with, once it is known, see video_options
|
|
182
|
+
self.encoder_used: str | None = None
|
|
183
|
+
# Said to the encoder, and to the file every time it is written, see QUALITY_PROFILES
|
|
184
|
+
self.movie_flags: list[str] = []
|
|
185
|
+
self.container_flags: list[str] = []
|
|
186
|
+
# The background left transparent whatever the scene sets, see Scene.draw_frame
|
|
187
|
+
self.transparent = False
|
|
188
|
+
self.chapters = chapters
|
|
189
|
+
self.incremental = incremental
|
|
190
|
+
# The pieces of the movie, see begin_chapter: (path, frames written, taken from before)
|
|
191
|
+
self.pieces: list[list] = []
|
|
192
|
+
self.piece_dry = False
|
|
193
|
+
self.time_range = time_range
|
|
194
|
+
if time_range is not None:
|
|
195
|
+
start, end = time_range
|
|
196
|
+
# A movie of its own, rather than in place of the whole scene's
|
|
197
|
+
# A decimal comma, a point being taken for the start of an extension
|
|
198
|
+
span = (f"{start:g}s-{end:g}s" if end >= 0 else f"{start:g}s-end").replace(".", ",")
|
|
199
|
+
file_name = f"{file_name or str(scene)}_{span}"
|
|
200
|
+
self.write_to_movie = write_to_movie
|
|
201
|
+
self.subdivide_output = subdivide_output
|
|
202
|
+
self.png_mode = png_mode
|
|
203
|
+
self.save_last_frame = save_last_frame
|
|
204
|
+
self.movie_file_extension = movie_file_extension
|
|
205
|
+
self.output_directory = output_directory
|
|
206
|
+
self.file_name = file_name
|
|
207
|
+
self.open_file_upon_completion = open_file_upon_completion
|
|
208
|
+
self.show_file_location_upon_completion = show_file_location_upon_completion
|
|
209
|
+
self.quiet = quiet
|
|
210
|
+
self.total_frames = total_frames
|
|
211
|
+
self.progress_description_len = progress_description_len
|
|
212
|
+
self.ffmpeg_bin = ffmpeg_bin
|
|
213
|
+
self.video_codec = video_codec
|
|
214
|
+
self.pixel_format = pixel_format
|
|
215
|
+
self.crf = crf
|
|
216
|
+
self.preset = preset
|
|
217
|
+
if quality is not None:
|
|
218
|
+
self.apply_quality(quality)
|
|
219
|
+
self.saturation = saturation
|
|
220
|
+
self.gamma = gamma
|
|
221
|
+
|
|
222
|
+
# State during file writing
|
|
223
|
+
self.writing_process: sp.Popen | None = None
|
|
224
|
+
self.progress_display: ProgressDisplay | None = None
|
|
225
|
+
self.ended_with_interrupt: bool = False
|
|
226
|
+
self.output_time: float = 0.0
|
|
227
|
+
self.audio_time_offset: float = 0.0
|
|
228
|
+
self.audio_events: list[tuple[float, object, float | None]] = []
|
|
229
|
+
# Every sound added, for what is asked of them after, see apply_sound_clip_changes
|
|
230
|
+
self.sound_clips: list[SoundClip] = []
|
|
231
|
+
# What the whole of the audio is put through before it goes in the movie, see
|
|
232
|
+
# Scene.set_master_audio
|
|
233
|
+
self.master_audio = None
|
|
234
|
+
# How subtitles are grouped, None for none to be written, see Scene.enable_subtitles
|
|
235
|
+
self.subtitle_options: dict | None = None
|
|
236
|
+
|
|
237
|
+
self.init_output_directories()
|
|
238
|
+
self.init_audio()
|
|
239
|
+
|
|
240
|
+
# Output directories and files
|
|
241
|
+
def init_output_directories(self) -> None:
|
|
242
|
+
if self.save_last_frame:
|
|
243
|
+
self.image_file_path = self.init_image_file_path()
|
|
244
|
+
if self.write_to_movie:
|
|
245
|
+
self.movie_file_path = self.init_movie_file_path()
|
|
246
|
+
if self.subdivide_output:
|
|
247
|
+
self.partial_movie_directory = self.init_partial_movie_directory()
|
|
248
|
+
|
|
249
|
+
def init_image_file_path(self) -> Path:
|
|
250
|
+
return self.get_output_file_rootname().with_suffix(".png")
|
|
251
|
+
|
|
252
|
+
def init_movie_file_path(self) -> Path:
|
|
253
|
+
return self.get_output_file_rootname().with_suffix(self.movie_file_extension)
|
|
254
|
+
|
|
255
|
+
def init_partial_movie_directory(self):
|
|
256
|
+
return guarantee_existence(self.get_output_file_rootname())
|
|
257
|
+
|
|
258
|
+
def get_output_file_rootname(self) -> Path:
|
|
259
|
+
return Path(
|
|
260
|
+
guarantee_existence(self.output_directory),
|
|
261
|
+
self.get_output_file_name()
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
def get_output_file_name(self) -> str:
|
|
265
|
+
if self.file_name:
|
|
266
|
+
return self.file_name
|
|
267
|
+
# Otherwise, use the name of the scene, potentially
|
|
268
|
+
# appending animation numbers
|
|
269
|
+
name = str(self.scene)
|
|
270
|
+
saan = self.scene.start_at_animation_number
|
|
271
|
+
eaan = self.scene.end_at_animation_number
|
|
272
|
+
if saan is not None:
|
|
273
|
+
name += f"_{saan}"
|
|
274
|
+
if eaan is not None:
|
|
275
|
+
name += f"_{eaan}"
|
|
276
|
+
return name
|
|
277
|
+
|
|
278
|
+
# Directory getters
|
|
279
|
+
def get_image_file_path(self) -> str:
|
|
280
|
+
return self.image_file_path
|
|
281
|
+
|
|
282
|
+
def get_next_partial_movie_path(self) -> str:
|
|
283
|
+
result = Path(self.partial_movie_directory, f"{self.scene.num_plays:05}")
|
|
284
|
+
return result.with_suffix(self.movie_file_extension)
|
|
285
|
+
|
|
286
|
+
def get_movie_file_path(self) -> str:
|
|
287
|
+
return self.movie_file_path
|
|
288
|
+
|
|
289
|
+
# Sound
|
|
290
|
+
def init_audio(self) -> None:
|
|
291
|
+
self.includes_sound: bool = False
|
|
292
|
+
|
|
293
|
+
def create_audio_segment(self) -> None:
|
|
294
|
+
if sys.platform == "emscripten":
|
|
295
|
+
return
|
|
296
|
+
self.audio_segment = AudioSegment.silent()
|
|
297
|
+
|
|
298
|
+
def add_audio_segment(
|
|
299
|
+
self,
|
|
300
|
+
new_segment: AudioSegment,
|
|
301
|
+
time: float | None = None,
|
|
302
|
+
gain_to_background: float | None = None
|
|
303
|
+
) -> None:
|
|
304
|
+
if not self.includes_sound:
|
|
305
|
+
self.includes_sound = True
|
|
306
|
+
self.create_audio_segment()
|
|
307
|
+
segment = self.audio_segment
|
|
308
|
+
curr_end = segment.duration_seconds
|
|
309
|
+
if time is None:
|
|
310
|
+
time = curr_end
|
|
311
|
+
if time < 0:
|
|
312
|
+
raise Exception("Adding sound at timestamp < 0")
|
|
313
|
+
|
|
314
|
+
new_end = time + new_segment.duration_seconds
|
|
315
|
+
diff = new_end - curr_end
|
|
316
|
+
if diff > 0:
|
|
317
|
+
segment = segment.append(
|
|
318
|
+
AudioSegment.silent(int(np.ceil(diff * 1000))),
|
|
319
|
+
crossfade=0,
|
|
320
|
+
)
|
|
321
|
+
self.audio_segment = segment.overlay(
|
|
322
|
+
new_segment,
|
|
323
|
+
position=int(1000 * time),
|
|
324
|
+
gain_during_overlay=gain_to_background,
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
def add_sound(
|
|
328
|
+
self,
|
|
329
|
+
sound_file: str | Sound | AudioSegment,
|
|
330
|
+
time: float | None = None,
|
|
331
|
+
gain: float | None = None,
|
|
332
|
+
gain_to_background: float | None = None,
|
|
333
|
+
fade_in: float = 0.0,
|
|
334
|
+
fade_out: float = 0.0,
|
|
335
|
+
voice: bool = False,
|
|
336
|
+
duck: bool | float = False,
|
|
337
|
+
scene_start: float | None = None,
|
|
338
|
+
loop: bool | int = False,
|
|
339
|
+
transcription: dict | None = None,
|
|
340
|
+
transcript=None,
|
|
341
|
+
) -> SoundClip:
|
|
342
|
+
"""
|
|
343
|
+
Mixes a sound in at `time`, and hands back the SoundClip which can change it later,
|
|
344
|
+
see datacut.scene.sound_clip, where what fade_in, fade_out, voice and duck mean is
|
|
345
|
+
set out. The sound is a file's name, a Sound, or a pydub AudioSegment.
|
|
346
|
+
`scene_start` is where it starts on the scene's clock, which is what its
|
|
347
|
+
later changes are timed against, `time` by default. `loop` plays it over and over,
|
|
348
|
+
until stopped or the scene ends for True, or that many times in all.
|
|
349
|
+
"""
|
|
350
|
+
if sys.platform == "emscripten":
|
|
351
|
+
# Browser audio is handled by BrowserAudio. Scene.add_sound() records
|
|
352
|
+
# the event without decoding it through pydub/audioop.
|
|
353
|
+
return SoundClip(
|
|
354
|
+
source=sound_file, scene_start=scene_start or time or 0.0,
|
|
355
|
+
transcription=transcription, transcript=transcript,
|
|
356
|
+
)
|
|
357
|
+
if isinstance(sound_file, Sound):
|
|
358
|
+
new_segment = sound_file.to_segment()
|
|
359
|
+
elif isinstance(sound_file, AudioSegment):
|
|
360
|
+
new_segment = sound_file
|
|
361
|
+
else:
|
|
362
|
+
file_path = get_full_sound_file_path(sound_file)
|
|
363
|
+
new_segment = AudioSegment.from_file(file_path)
|
|
364
|
+
if gain:
|
|
365
|
+
new_segment = new_segment.apply_gain(gain)
|
|
366
|
+
clip = SoundClip(
|
|
367
|
+
self, new_segment,
|
|
368
|
+
scene_start=(time if scene_start is None else scene_start) or 0.0,
|
|
369
|
+
fade_in=fade_in, fade_out=fade_out, voice=voice, duck=duck, loop=loop,
|
|
370
|
+
source=sound_file, transcription=transcription, transcript=transcript,
|
|
371
|
+
)
|
|
372
|
+
# What can be known now, its fades, goes in now; the very segment where there are none
|
|
373
|
+
new_segment = clip.processed()
|
|
374
|
+
scene_time = time
|
|
375
|
+
if scene_time is not None:
|
|
376
|
+
self.audio_events.append((scene_time, new_segment, gain_to_background))
|
|
377
|
+
clip.event = self.audio_events[-1]
|
|
378
|
+
time = scene_time - self.audio_time_offset
|
|
379
|
+
self.sound_clips.append(clip)
|
|
380
|
+
self.add_audio_segment(new_segment, time, gain_to_background)
|
|
381
|
+
return clip
|
|
382
|
+
|
|
383
|
+
def apply_sound_clip_changes(self) -> None:
|
|
384
|
+
"""
|
|
385
|
+
Mixes in what was asked of sounds after they were added: changes of volume, stopping
|
|
386
|
+
them, and ducking under narration, which depends on every voice the scene went on to
|
|
387
|
+
add. Each such sound's event is replaced by the sound as it is now to be heard, and the
|
|
388
|
+
audio mixed again from the events, as VideoMobject does with what it changes.
|
|
389
|
+
|
|
390
|
+
Run again, it does nothing but what has changed since. Scenes asking none of this
|
|
391
|
+
leave their audio as it is. Audio replayed after a seek, see replay_audio_from, is
|
|
392
|
+
mixed again from the events like the rest.
|
|
393
|
+
"""
|
|
394
|
+
clips = [c for c in self.sound_clips if not c.is_null and c.event is not None]
|
|
395
|
+
if not clips:
|
|
396
|
+
return
|
|
397
|
+
# A sound looping until the scene ends loops until now, which is the end of it once
|
|
398
|
+
# the scene is over, before anything is reckoned from how long the sounds play
|
|
399
|
+
now = float(self.scene.get_time())
|
|
400
|
+
for clip in clips:
|
|
401
|
+
if clip.loops_until_end:
|
|
402
|
+
clip.loop_until = now - clip.scene_start
|
|
403
|
+
voices = [c for c in clips if c.voice]
|
|
404
|
+
replacements = {}
|
|
405
|
+
for clip in clips:
|
|
406
|
+
duck = duck_keys_for(clip, voices) if clip.duck_gain is not None else []
|
|
407
|
+
state = (
|
|
408
|
+
tuple(clip.gain_keys), clip.stop_at, clip.stop_fade, tuple(duck),
|
|
409
|
+
clip.loop_until, len(clip.edits),
|
|
410
|
+
)
|
|
411
|
+
applied = getattr(clip, "_applied_state", None)
|
|
412
|
+
if applied is None:
|
|
413
|
+
# As added, which is what was mixed in then
|
|
414
|
+
applied = ((), None, 0.0, (), None, 0)
|
|
415
|
+
if state == applied:
|
|
416
|
+
continue
|
|
417
|
+
clip._applied_state = state
|
|
418
|
+
ev_time, _, gain_bg = clip.event
|
|
419
|
+
replacements[id(clip.event)] = (clip, (ev_time, clip.processed(duck), gain_bg))
|
|
420
|
+
if not replacements:
|
|
421
|
+
return
|
|
422
|
+
new_events = []
|
|
423
|
+
for ev in self.audio_events:
|
|
424
|
+
found = replacements.get(id(ev))
|
|
425
|
+
if found is None:
|
|
426
|
+
new_events.append(ev)
|
|
427
|
+
continue
|
|
428
|
+
clip, replacement = found
|
|
429
|
+
clip.event = replacement
|
|
430
|
+
new_events.append(replacement)
|
|
431
|
+
self.audio_events = new_events
|
|
432
|
+
self.includes_sound = False
|
|
433
|
+
self.create_audio_segment()
|
|
434
|
+
for ev_time, seg, gain_bg in self.audio_events:
|
|
435
|
+
self.add_audio_segment(seg, ev_time - self.audio_time_offset, gain_bg)
|
|
436
|
+
|
|
437
|
+
def get_output_time(self) -> float:
|
|
438
|
+
return self.output_time
|
|
439
|
+
|
|
440
|
+
def set_audio_time_offset(self, offset: float) -> None:
|
|
441
|
+
self.audio_time_offset = offset
|
|
442
|
+
|
|
443
|
+
def replay_audio_from(self, scene_time: float) -> None:
|
|
444
|
+
"""Replay audio events from the requested scene time on the output timeline."""
|
|
445
|
+
output_start = self.output_time
|
|
446
|
+
|
|
447
|
+
for event_time, segment, gain_to_background in self.audio_events:
|
|
448
|
+
# The event already finished before the seek.
|
|
449
|
+
if event_time + segment.duration_seconds <= scene_time:
|
|
450
|
+
continue
|
|
451
|
+
|
|
452
|
+
# If the event started before the seek, discard the part that has
|
|
453
|
+
# already elapsed and play the remaining portion immediately.
|
|
454
|
+
if event_time < scene_time:
|
|
455
|
+
elapsed = scene_time - event_time
|
|
456
|
+
segment = segment[int(elapsed * 1000):]
|
|
457
|
+
output_time = output_start
|
|
458
|
+
else:
|
|
459
|
+
output_time = output_start + event_time - scene_time
|
|
460
|
+
|
|
461
|
+
self.add_audio_segment(segment, output_time, gain_to_background)
|
|
462
|
+
|
|
463
|
+
# Writers
|
|
464
|
+
def writes_in_pieces(self) -> bool:
|
|
465
|
+
return self.incremental and self.write_to_movie and not self.subdivide_output
|
|
466
|
+
|
|
467
|
+
def begin(self) -> None:
|
|
468
|
+
if self.writes_in_pieces():
|
|
469
|
+
# Written a chapter at a time, see begin_chapter
|
|
470
|
+
return
|
|
471
|
+
if not self.subdivide_output and self.write_to_movie:
|
|
472
|
+
# Opened with the first frame rather than now, so that how the movie is encoded,
|
|
473
|
+
# its crf or pixel format, may still be set in the scene's setup or construct
|
|
474
|
+
self.pending_movie_path = self.get_movie_file_path()
|
|
475
|
+
|
|
476
|
+
# Pieces, see datacut.scene.incremental
|
|
477
|
+
|
|
478
|
+
def pieces_dir(self) -> Path:
|
|
479
|
+
movie = Path(self.get_movie_file_path())
|
|
480
|
+
folder = Path(movie.parent, ".incremental", movie.stem)
|
|
481
|
+
guarantee_existence(folder)
|
|
482
|
+
return folder
|
|
483
|
+
|
|
484
|
+
def piece_settings(self) -> tuple:
|
|
485
|
+
camera = self.scene.camera
|
|
486
|
+
return (
|
|
487
|
+
tuple(camera.get_pixel_shape()), camera.fps, getattr(camera, "samples", None),
|
|
488
|
+
self.video_codec, self.pixel_format, self.crf, self.preset, self.quality,
|
|
489
|
+
self.encoder, self.saturation, self.gamma, self.movie_file_extension,
|
|
490
|
+
self.transparent, tuple(self.movie_flags),
|
|
491
|
+
)
|
|
492
|
+
|
|
493
|
+
def end_piece(self) -> None:
|
|
494
|
+
if self.pieces and not self.pieces[-1][2] and self.writing_process is not None:
|
|
495
|
+
self.close_movie_pipe(final=False)
|
|
496
|
+
self.piece_dry = False
|
|
497
|
+
self.scene.dry_run = False
|
|
498
|
+
|
|
499
|
+
def begin_chapter(self, animations: list) -> None:
|
|
500
|
+
"""
|
|
501
|
+
A chapter is about to be played: written as a piece of its own, or, if a piece with
|
|
502
|
+
the same fingerprint was written before, played without being drawn and that piece
|
|
503
|
+
used, see datacut.scene.incremental
|
|
504
|
+
"""
|
|
505
|
+
if not self.writes_in_pieces():
|
|
506
|
+
return
|
|
507
|
+
self.end_piece()
|
|
508
|
+
if self.scene.skip_animations:
|
|
509
|
+
return
|
|
510
|
+
from datacut.scene.incremental import chapter_key
|
|
511
|
+
key = chapter_key(self.scene, animations, self.piece_settings())
|
|
512
|
+
path = str(Path(self.pieces_dir(), key[:32] + self.movie_file_extension))
|
|
513
|
+
cached = os.path.exists(path)
|
|
514
|
+
self.pieces.append([path, 0, cached])
|
|
515
|
+
if cached:
|
|
516
|
+
self.piece_dry = True
|
|
517
|
+
self.scene.dry_run = True
|
|
518
|
+
else:
|
|
519
|
+
self.open_movie_pipe(path)
|
|
520
|
+
|
|
521
|
+
def finish_pieces(self) -> None:
|
|
522
|
+
"""The pieces put together, without encoding them again, as the movie"""
|
|
523
|
+
self.end_piece()
|
|
524
|
+
used = [p for p in self.pieces if p[1] > 0]
|
|
525
|
+
movie = self.get_movie_file_path()
|
|
526
|
+
folder = self.pieces_dir()
|
|
527
|
+
if not used:
|
|
528
|
+
return
|
|
529
|
+
list_path = Path(folder, "pieces.txt")
|
|
530
|
+
with open(list_path, "w", encoding="utf-8") as file:
|
|
531
|
+
for path, _, _ in used:
|
|
532
|
+
file.write("file '" + str(path).replace("\\", "/").replace("'", "'\\''") + "'\n")
|
|
533
|
+
stem, ext = os.path.splitext(movie)
|
|
534
|
+
temp = stem + "_temp" + ext
|
|
535
|
+
sp.call([
|
|
536
|
+
self.ffmpeg_bin, "-y", "-loglevel", "error", "-f", "concat", "-safe", "0",
|
|
537
|
+
"-i", str(list_path), "-c", "copy", *self.container_flags, temp,
|
|
538
|
+
])
|
|
539
|
+
os.remove(list_path)
|
|
540
|
+
shutil.move(temp, movie)
|
|
541
|
+
self.movie_file_path = movie
|
|
542
|
+
if not self.ended_with_interrupt:
|
|
543
|
+
# Pieces no longer part of the scene go
|
|
544
|
+
keep = {os.path.normcase(os.path.abspath(p[0])) for p in self.pieces}
|
|
545
|
+
for name in os.listdir(folder):
|
|
546
|
+
full = os.path.normcase(os.path.abspath(os.path.join(folder, name)))
|
|
547
|
+
if name.endswith(self.movie_file_extension) and full not in keep:
|
|
548
|
+
os.remove(full)
|
|
549
|
+
if not self.quiet:
|
|
550
|
+
reused = sum(1 for p in used if p[2])
|
|
551
|
+
log.info(
|
|
552
|
+
f"Incremental: {len(used) - reused} of {len(used)} chapters drawn, "
|
|
553
|
+
f"{reused} taken from before"
|
|
554
|
+
)
|
|
555
|
+
|
|
556
|
+
def open_pending_movie_pipe(self) -> None:
|
|
557
|
+
path = getattr(self, "pending_movie_path", None)
|
|
558
|
+
if path is not None and self.writing_process is None:
|
|
559
|
+
self.pending_movie_path = None
|
|
560
|
+
self.open_movie_pipe(path)
|
|
561
|
+
|
|
562
|
+
def begin_animation(self) -> None:
|
|
563
|
+
if self.subdivide_output and self.write_to_movie:
|
|
564
|
+
self.open_movie_pipe(self.get_next_partial_movie_path())
|
|
565
|
+
|
|
566
|
+
def end_animation(self) -> None:
|
|
567
|
+
if self.subdivide_output and self.write_to_movie:
|
|
568
|
+
self.close_movie_pipe()
|
|
569
|
+
|
|
570
|
+
def finish(self) -> None:
|
|
571
|
+
if not self.subdivide_output and self.write_to_movie:
|
|
572
|
+
if self.writes_in_pieces():
|
|
573
|
+
self.finish_pieces()
|
|
574
|
+
if self.progress_display is not None:
|
|
575
|
+
self.progress_display.close()
|
|
576
|
+
self.progress_display = None
|
|
577
|
+
else:
|
|
578
|
+
self.close_movie_pipe()
|
|
579
|
+
if self.includes_sound:
|
|
580
|
+
self.add_sound_to_video()
|
|
581
|
+
summary = self.scene.performance.summary() if hasattr(self.scene, "performance") else None
|
|
582
|
+
if summary and not self.quiet:
|
|
583
|
+
log.info(f"Written at {summary}, encoded by {self.encoder_used}")
|
|
584
|
+
if not self.ended_with_interrupt:
|
|
585
|
+
if self.time_range is not None:
|
|
586
|
+
self.cut_to_time_range()
|
|
587
|
+
if self.chapters:
|
|
588
|
+
self.write_chapters()
|
|
589
|
+
self.print_file_ready_message(self.get_movie_file_path())
|
|
590
|
+
self.write_subtitles()
|
|
591
|
+
if self.save_last_frame:
|
|
592
|
+
self.scene.update_frame(force_draw=True)
|
|
593
|
+
self.save_final_image(self.scene.get_image())
|
|
594
|
+
if self.should_open_file():
|
|
595
|
+
self.open_file()
|
|
596
|
+
|
|
597
|
+
def open_movie_pipe(self, file_path: str) -> None:
|
|
598
|
+
stem, ext = os.path.splitext(file_path)
|
|
599
|
+
self.final_file_path = file_path
|
|
600
|
+
self.temp_file_path = stem + "_temp" + ext
|
|
601
|
+
|
|
602
|
+
fps = self.scene.camera.fps
|
|
603
|
+
width, height = self.scene.camera.get_pixel_shape()
|
|
604
|
+
|
|
605
|
+
# Frames come back a row at a time from the top, as a texture is laid out
|
|
606
|
+
command = [
|
|
607
|
+
self.ffmpeg_bin,
|
|
608
|
+
'-y', # overwrite output file if it exists
|
|
609
|
+
'-f', 'rawvideo',
|
|
610
|
+
'-s', f'{width}x{height}', # size of one frame
|
|
611
|
+
'-pix_fmt', 'rgba',
|
|
612
|
+
'-r', str(fps), # frames per second
|
|
613
|
+
'-i', '-', # The input comes from a pipe
|
|
614
|
+
'-an', # Tells ffmpeg not to expect any audio
|
|
615
|
+
'-loglevel', 'error',
|
|
616
|
+
]
|
|
617
|
+
filters = []
|
|
618
|
+
# Asked for neither more saturation nor a different gamma there is nothing to filter,
|
|
619
|
+
# and saying so anyway is not free: eq works in yuv, so even an identity one sends
|
|
620
|
+
# every pixel out of rgb and back, moving most of them by one or two out of 255.
|
|
621
|
+
if (self.saturation, self.gamma) != (1.0, 1.0):
|
|
622
|
+
filters.append(f'eq=saturation={self.saturation}:gamma={self.gamma}')
|
|
623
|
+
if self.is_yuv():
|
|
624
|
+
# Into yuv as BT.709 has it, and said so in the file, see COLOR_TAGS
|
|
625
|
+
filters.append('scale=out_color_matrix=bt709:out_range=tv')
|
|
626
|
+
# Said of every frame too, which the encoder goes by over its own options
|
|
627
|
+
filters.append('setparams=colorspace=bt709:color_primaries=bt709:color_trc=bt709:range=tv')
|
|
628
|
+
if filters:
|
|
629
|
+
command += ['-vf', ','.join(filters)]
|
|
630
|
+
command += self.video_options()
|
|
631
|
+
if self.is_yuv():
|
|
632
|
+
command += COLOR_TAGS
|
|
633
|
+
if self.pixel_format and self.pixel_format.startswith(("yuv422", "yuv444")):
|
|
634
|
+
log.warning(
|
|
635
|
+
f"{self.pixel_format} keeps color sharper, but players decoding on the GPU, as "
|
|
636
|
+
"Windows' own and QuickTime do, cannot open it and call the file broken; "
|
|
637
|
+
"yuv420p plays everywhere"
|
|
638
|
+
)
|
|
639
|
+
command += [self.temp_file_path]
|
|
640
|
+
self.writing_process = sp.Popen(command, stdin=sp.PIPE)
|
|
641
|
+
# Frames reach the pipe a frame after they were drawn, see FrameStream
|
|
642
|
+
self.frames = FrameStream(self.scene.camera, self.writing_process.stdin)
|
|
643
|
+
|
|
644
|
+
if not self.quiet and self.progress_display is None:
|
|
645
|
+
self.progress_display = ProgressDisplay(
|
|
646
|
+
range(self.total_frames),
|
|
647
|
+
leave=False,
|
|
648
|
+
ascii=True if platform.system() == 'Windows' else None,
|
|
649
|
+
dynamic_ncols=True,
|
|
650
|
+
)
|
|
651
|
+
self.set_progress_display_description()
|
|
652
|
+
|
|
653
|
+
def use_fast_encoding(self):
|
|
654
|
+
self.video_codec = "libx264rgb"
|
|
655
|
+
self.pixel_format = "rgb32"
|
|
656
|
+
|
|
657
|
+
def get_insert_file_path(self, index: int) -> Path:
|
|
658
|
+
movie_path = Path(self.get_movie_file_path())
|
|
659
|
+
scene_name = movie_path.stem
|
|
660
|
+
insert_dir = Path(movie_path.parent, "inserts")
|
|
661
|
+
guarantee_existence(insert_dir)
|
|
662
|
+
return Path(insert_dir, f"{scene_name}_{index}").with_suffix(self.movie_file_extension)
|
|
663
|
+
|
|
664
|
+
def begin_insert(self):
|
|
665
|
+
# Begin writing process
|
|
666
|
+
self.write_to_movie = True
|
|
667
|
+
self.init_output_directories()
|
|
668
|
+
index = 0
|
|
669
|
+
while (insert_path := self.get_insert_file_path(index)).exists():
|
|
670
|
+
index += 1
|
|
671
|
+
self.inserted_file_path = insert_path
|
|
672
|
+
self.open_movie_pipe(self.inserted_file_path)
|
|
673
|
+
|
|
674
|
+
def end_insert(self):
|
|
675
|
+
self.close_movie_pipe()
|
|
676
|
+
self.write_to_movie = False
|
|
677
|
+
self.print_file_ready_message(self.inserted_file_path)
|
|
678
|
+
|
|
679
|
+
def has_progress_display(self):
|
|
680
|
+
return self.progress_display is not None
|
|
681
|
+
|
|
682
|
+
def set_progress_display_description(self, file: str = "", sub_desc: str = "") -> None:
|
|
683
|
+
if self.progress_display is None:
|
|
684
|
+
return
|
|
685
|
+
|
|
686
|
+
desc_len = self.progress_description_len
|
|
687
|
+
if not file:
|
|
688
|
+
file = os.path.split(self.get_movie_file_path())[1]
|
|
689
|
+
full_desc = f"{file} {sub_desc}"
|
|
690
|
+
if len(full_desc) > desc_len:
|
|
691
|
+
full_desc = full_desc[:desc_len - 3] + "..."
|
|
692
|
+
else:
|
|
693
|
+
full_desc += " " * (desc_len - len(full_desc))
|
|
694
|
+
self.progress_display.set_description(full_desc)
|
|
695
|
+
|
|
696
|
+
def write_frame(self) -> None:
|
|
697
|
+
if self.write_to_movie and self.writes_in_pieces():
|
|
698
|
+
if not self.pieces:
|
|
699
|
+
# A frame before any chapter, a piece of its own
|
|
700
|
+
self.begin_chapter([])
|
|
701
|
+
self.pieces[-1][1] += 1
|
|
702
|
+
if self.piece_dry:
|
|
703
|
+
# Taken from before: nothing drawn, nothing written, time goes on
|
|
704
|
+
self.output_time += 1 / self.scene.camera.fps
|
|
705
|
+
if self.progress_display is not None:
|
|
706
|
+
self.progress_display.update()
|
|
707
|
+
return
|
|
708
|
+
if self.write_to_movie:
|
|
709
|
+
self.open_pending_movie_pipe()
|
|
710
|
+
self.frames.send()
|
|
711
|
+
self.output_time += 1 / self.scene.camera.fps
|
|
712
|
+
if self.progress_display is not None:
|
|
713
|
+
self.progress_display.update()
|
|
714
|
+
|
|
715
|
+
def close_movie_pipe(self, final: bool = True) -> None:
|
|
716
|
+
# A movie never written to is opened and closed as it always was
|
|
717
|
+
self.open_pending_movie_pipe()
|
|
718
|
+
# Whatever is still on its way off the gpu, before there is nowhere to put it
|
|
719
|
+
self.frames.drain()
|
|
720
|
+
self.writing_process.stdin.close()
|
|
721
|
+
self.writing_process.wait()
|
|
722
|
+
self.writing_process.terminate()
|
|
723
|
+
self.writing_process = None
|
|
724
|
+
if self.progress_display is not None and final:
|
|
725
|
+
self.progress_display.close()
|
|
726
|
+
self.progress_display = None
|
|
727
|
+
|
|
728
|
+
if not self.ended_with_interrupt:
|
|
729
|
+
shutil.move(self.temp_file_path, self.final_file_path)
|
|
730
|
+
else:
|
|
731
|
+
self.movie_file_path = self.temp_file_path
|
|
732
|
+
|
|
733
|
+
def get_subtitle_cues(self) -> list[tuple[float, float, str]]:
|
|
734
|
+
"""
|
|
735
|
+
Subtitles for what every voice says, see SoundClip.transcript and Transcript.cues,
|
|
736
|
+
timed on the movie, and none past its end.
|
|
737
|
+
"""
|
|
738
|
+
options = self.subtitle_options or {}
|
|
739
|
+
cues = []
|
|
740
|
+
for clip in self.sound_clips:
|
|
741
|
+
if not clip.voice or clip.is_null or clip.source is None:
|
|
742
|
+
continue
|
|
743
|
+
transcript = clip.transcript()
|
|
744
|
+
transcript = transcript.until(clip.duration).shifted(clip.scene_start - self.audio_time_offset)
|
|
745
|
+
cues.extend(transcript.cues(**options))
|
|
746
|
+
end = self.output_time
|
|
747
|
+
return sorted((a, min(b, end), text) for a, b, text in cues if a < end)
|
|
748
|
+
|
|
749
|
+
def write_subtitles(self) -> None:
|
|
750
|
+
"""Writes the subtitles beside the movie, as an .srt of the same name"""
|
|
751
|
+
if self.subtitle_options is None:
|
|
752
|
+
return
|
|
753
|
+
from datacut.scene.transcript import cues_to_srt
|
|
754
|
+
cues = self.get_subtitle_cues()
|
|
755
|
+
if not cues:
|
|
756
|
+
log.warning("Subtitles were asked for, but nothing marked voice=True says anything")
|
|
757
|
+
return
|
|
758
|
+
path = os.path.splitext(self.get_movie_file_path())[0] + ".srt"
|
|
759
|
+
with open(path, "w", encoding="utf-8") as file:
|
|
760
|
+
file.write(cues_to_srt(cues))
|
|
761
|
+
self.print_file_ready_message(path)
|
|
762
|
+
|
|
763
|
+
def apply_master_audio(self) -> None:
|
|
764
|
+
"""
|
|
765
|
+
Puts the whole of the audio through master_audio, see Scene.set_master_audio, keeping
|
|
766
|
+
its length, rate and sample width. Nothing is done to it where there is none.
|
|
767
|
+
"""
|
|
768
|
+
if self.master_audio is None:
|
|
769
|
+
return
|
|
770
|
+
seg = self.audio_segment
|
|
771
|
+
mixed = self.master_audio(Sound.from_segment(seg))
|
|
772
|
+
if mixed.sample_rate != seg.frame_rate:
|
|
773
|
+
mixed = mixed.resample(seg.frame_rate)
|
|
774
|
+
self.audio_segment = mixed.to_segment(sample_width=seg.sample_width)
|
|
775
|
+
|
|
776
|
+
def add_sound_to_video(self) -> None:
|
|
777
|
+
self.apply_sound_clip_changes()
|
|
778
|
+
movie_file_path = self.get_movie_file_path()
|
|
779
|
+
stem, ext = os.path.splitext(movie_file_path)
|
|
780
|
+
sound_file_path = stem + ".wav"
|
|
781
|
+
|
|
782
|
+
# The audio timeline may extend beyond the rendered video after a
|
|
783
|
+
# headless seek. The video duration is authoritative: trailing audio
|
|
784
|
+
# must never extend the output movie.
|
|
785
|
+
video_duration_ms = int(round(
|
|
786
|
+
self.output_time * 1000
|
|
787
|
+
))
|
|
788
|
+
if len(self.audio_segment) > video_duration_ms:
|
|
789
|
+
self.audio_segment = self.audio_segment[:video_duration_ms]
|
|
790
|
+
|
|
791
|
+
# Makes sure sound file length will match video file.
|
|
792
|
+
self.add_audio_segment(AudioSegment.silent(0))
|
|
793
|
+
self.apply_master_audio()
|
|
794
|
+
self.audio_segment.export(
|
|
795
|
+
sound_file_path,
|
|
796
|
+
format="wav",
|
|
797
|
+
)
|
|
798
|
+
temp_file_path = stem + "_temp" + ext
|
|
799
|
+
commands = [
|
|
800
|
+
self.ffmpeg_bin,
|
|
801
|
+
"-i", movie_file_path,
|
|
802
|
+
"-i", sound_file_path,
|
|
803
|
+
'-y', # overwrite output file if it exists
|
|
804
|
+
"-c:v", "copy",
|
|
805
|
+
"-c:a", "aac",
|
|
806
|
+
"-b:a", "320k",
|
|
807
|
+
# select video stream from first file
|
|
808
|
+
"-map", "0:v:0",
|
|
809
|
+
# select audio stream from second file
|
|
810
|
+
"-map", "1:a:0",
|
|
811
|
+
'-loglevel', 'error',
|
|
812
|
+
# "-shortest",
|
|
813
|
+
*self.container_flags,
|
|
814
|
+
temp_file_path,
|
|
815
|
+
]
|
|
816
|
+
sp.call(commands)
|
|
817
|
+
shutil.move(temp_file_path, movie_file_path)
|
|
818
|
+
os.remove(sound_file_path)
|
|
819
|
+
|
|
820
|
+
# Stretches and chapters
|
|
821
|
+
|
|
822
|
+
def is_yuv(self) -> bool:
|
|
823
|
+
return (self.pixel_format or "").startswith("yuv")
|
|
824
|
+
|
|
825
|
+
def apply_quality(self, name: str) -> None:
|
|
826
|
+
"""Encodes as the named profile says, see QUALITY_PROFILES"""
|
|
827
|
+
profile = QUALITY_PROFILES.get(name)
|
|
828
|
+
if profile is None:
|
|
829
|
+
raise ValueError(f"No quality named {name!r}; there are {', '.join(QUALITY_PROFILES)}")
|
|
830
|
+
for key, value in profile.items():
|
|
831
|
+
if key == "note":
|
|
832
|
+
log.info(f"Quality {name}: {value}")
|
|
833
|
+
else:
|
|
834
|
+
setattr(self, key, value)
|
|
835
|
+
|
|
836
|
+
def video_options(self) -> list[str]:
|
|
837
|
+
"""
|
|
838
|
+
What ffmpeg is told of the video: its encoder, how hard it tries and how much it keeps,
|
|
839
|
+
and its pixel format. H.264 is handed to the graphics card's encoder where there is one,
|
|
840
|
+
see hardware_h264_encoder, crf and preset being turned into its own terms.
|
|
841
|
+
"""
|
|
842
|
+
codec = self.video_codec
|
|
843
|
+
options: list[str] = []
|
|
844
|
+
hardware = None
|
|
845
|
+
if codec == "libx264" and self.encoder in ("auto", "gpu"):
|
|
846
|
+
if (self.pixel_format or "yuv420p") in HARDWARE_PIXEL_FORMATS:
|
|
847
|
+
hardware = hardware_h264_encoder(self.ffmpeg_bin)
|
|
848
|
+
if hardware is None and self.encoder == "gpu":
|
|
849
|
+
log.warning("No graphics card encoder for H.264 here, so it is the processor's")
|
|
850
|
+
if hardware is not None:
|
|
851
|
+
codec = hardware
|
|
852
|
+
options += ["-vcodec", codec] + hardware_quality_options(codec, self.crf, self.preset)
|
|
853
|
+
elif codec:
|
|
854
|
+
options += ["-vcodec", codec]
|
|
855
|
+
if self.preset and codec in ("libx264", "libx264rgb", "libx265"):
|
|
856
|
+
options += ["-preset", self.preset]
|
|
857
|
+
if self.crf is not None:
|
|
858
|
+
options += ["-crf", str(self.crf)]
|
|
859
|
+
if self.pixel_format:
|
|
860
|
+
options += ["-pix_fmt", self.pixel_format]
|
|
861
|
+
self.encoder_used = codec
|
|
862
|
+
return options + list(self.movie_flags) + list(self.container_flags)
|
|
863
|
+
|
|
864
|
+
def _encode_options(self) -> list[str]:
|
|
865
|
+
options = self.video_options()
|
|
866
|
+
if self.is_yuv():
|
|
867
|
+
options += COLOR_TAGS
|
|
868
|
+
return options + ["-c:a", "aac", "-b:a", "320k"]
|
|
869
|
+
|
|
870
|
+
def _cut(self, source: str, start: float, end: float, target: str) -> None:
|
|
871
|
+
"""From start to end of source, in seconds, encoded again so as to begin just there"""
|
|
872
|
+
sp.call([
|
|
873
|
+
self.ffmpeg_bin, "-y", "-loglevel", "error",
|
|
874
|
+
"-ss", f"{start:.6f}", "-i", source, "-t", f"{max(end - start, 0.0):.6f}",
|
|
875
|
+
# Picture and sound only, not the chapters the whole has
|
|
876
|
+
"-map", "0:v", "-map", "0:a?", "-map_chapters", "-1",
|
|
877
|
+
*self._encode_options(), target,
|
|
878
|
+
])
|
|
879
|
+
|
|
880
|
+
def cut_to_time_range(self) -> None:
|
|
881
|
+
"""The movie cut down to time_range, see the --time_range flag"""
|
|
882
|
+
start, end = self.time_range
|
|
883
|
+
duration = self.output_time
|
|
884
|
+
end = duration if end < 0 else min(end, duration)
|
|
885
|
+
if start >= end:
|
|
886
|
+
log.warning(f"Nothing of the scene is between {start:g}s and {end:g}s, so all of it is kept")
|
|
887
|
+
return
|
|
888
|
+
path = self.get_movie_file_path()
|
|
889
|
+
stem, ext = os.path.splitext(path)
|
|
890
|
+
temp = stem + "_cut" + ext
|
|
891
|
+
self._cut(path, start, end, temp)
|
|
892
|
+
shutil.move(temp, path)
|
|
893
|
+
|
|
894
|
+
def chapter_list(self) -> list[tuple[float, float, str]]:
|
|
895
|
+
"""(start, end, name) of every chapter, as the movie has them, a cut accounted for"""
|
|
896
|
+
duration = self.output_time
|
|
897
|
+
offset, limit = 0.0, duration
|
|
898
|
+
if self.time_range is not None:
|
|
899
|
+
offset = self.time_range[0]
|
|
900
|
+
end = self.time_range[1]
|
|
901
|
+
limit = min(duration, end if end >= 0 else duration) - offset
|
|
902
|
+
starts = []
|
|
903
|
+
for time, name in getattr(self.scene, "chapters", []):
|
|
904
|
+
t = time - offset
|
|
905
|
+
if t < limit - 1e-6:
|
|
906
|
+
if starts and t <= 1e-6:
|
|
907
|
+
starts = [(0.0, name)]
|
|
908
|
+
else:
|
|
909
|
+
starts.append((max(t, 0.0), name))
|
|
910
|
+
if not starts:
|
|
911
|
+
return []
|
|
912
|
+
if starts[0][0] > 1e-6:
|
|
913
|
+
starts.insert(0, (0.0, ""))
|
|
914
|
+
# Chapters which start together are one, named after the last
|
|
915
|
+
merged = []
|
|
916
|
+
for t, name in starts:
|
|
917
|
+
if merged and abs(merged[-1][0] - t) < 1e-6:
|
|
918
|
+
merged[-1] = (t, name)
|
|
919
|
+
else:
|
|
920
|
+
merged.append((t, name))
|
|
921
|
+
ends = [t for t, _ in merged[1:]] + [limit]
|
|
922
|
+
return [(t, e, name) for (t, name), e in zip(merged, ends) if e - t > 1e-6]
|
|
923
|
+
|
|
924
|
+
def write_chapters(self) -> None:
|
|
925
|
+
"""
|
|
926
|
+
Chapters marked in the movie, which players show and step through, and each written
|
|
927
|
+
as a movie of its own, in a folder beside it, see the --chapters flag
|
|
928
|
+
"""
|
|
929
|
+
chapters = self.chapter_list()
|
|
930
|
+
if not chapters:
|
|
931
|
+
return
|
|
932
|
+
path = self.get_movie_file_path()
|
|
933
|
+
stem, ext = os.path.splitext(path)
|
|
934
|
+
lines = [";FFMETADATA1"]
|
|
935
|
+
for start, end, name in chapters:
|
|
936
|
+
lines += [
|
|
937
|
+
"[CHAPTER]", "TIMEBASE=1/1000",
|
|
938
|
+
f"START={int(round(start * 1000))}", f"END={int(round(end * 1000))}",
|
|
939
|
+
"title=" + (name or "Start").replace("\\", "\\\\").replace("=", "\\=")
|
|
940
|
+
.replace(";", "\\;").replace("#", "\\#").replace("\n", " "),
|
|
941
|
+
]
|
|
942
|
+
meta_path = stem + "_chapters.txt"
|
|
943
|
+
with open(meta_path, "w", encoding="utf-8") as file:
|
|
944
|
+
file.write("\n".join(lines) + "\n")
|
|
945
|
+
temp = stem + "_marked" + ext
|
|
946
|
+
sp.call([
|
|
947
|
+
self.ffmpeg_bin, "-y", "-loglevel", "error", "-i", path, "-i", meta_path,
|
|
948
|
+
"-map", "0", "-map_metadata", "1", "-map_chapters", "1", "-c", "copy",
|
|
949
|
+
*self.container_flags, temp,
|
|
950
|
+
])
|
|
951
|
+
os.remove(meta_path)
|
|
952
|
+
if os.path.exists(temp):
|
|
953
|
+
shutil.move(temp, path)
|
|
954
|
+
|
|
955
|
+
folder = stem + "_chapters"
|
|
956
|
+
os.makedirs(folder, exist_ok=True)
|
|
957
|
+
width = max(2, len(str(len(chapters))))
|
|
958
|
+
for n, (start, end, name) in enumerate(chapters, start=1):
|
|
959
|
+
target = os.path.join(folder, f"{n:0{width}d} {chapter_file_name(name or 'Start')}{ext}")
|
|
960
|
+
self._cut(path, start, end, target)
|
|
961
|
+
self.print_file_ready_message(folder)
|
|
962
|
+
|
|
963
|
+
def save_final_image(self, image: Image) -> None:
|
|
964
|
+
file_path = self.get_image_file_path()
|
|
965
|
+
image.save(file_path)
|
|
966
|
+
self.print_file_ready_message(file_path)
|
|
967
|
+
|
|
968
|
+
def print_file_ready_message(self, file_path: str) -> None:
|
|
969
|
+
if not self.quiet:
|
|
970
|
+
log.info(f"File ready at {file_path}")
|
|
971
|
+
|
|
972
|
+
def should_open_file(self) -> bool:
|
|
973
|
+
return any([
|
|
974
|
+
self.show_file_location_upon_completion,
|
|
975
|
+
self.open_file_upon_completion,
|
|
976
|
+
])
|
|
977
|
+
|
|
978
|
+
def open_file(self) -> None:
|
|
979
|
+
if self.quiet:
|
|
980
|
+
curr_stdout = sys.stdout
|
|
981
|
+
sys.stdout = open(os.devnull, "w")
|
|
982
|
+
|
|
983
|
+
current_os = platform.system()
|
|
984
|
+
file_paths = []
|
|
985
|
+
|
|
986
|
+
if self.save_last_frame:
|
|
987
|
+
file_paths.append(self.get_image_file_path())
|
|
988
|
+
if self.write_to_movie:
|
|
989
|
+
file_paths.append(self.get_movie_file_path())
|
|
990
|
+
|
|
991
|
+
for file_path in file_paths:
|
|
992
|
+
if current_os == "Windows":
|
|
993
|
+
os.startfile(file_path)
|
|
994
|
+
else:
|
|
995
|
+
commands = []
|
|
996
|
+
if current_os == "Linux":
|
|
997
|
+
commands.append("xdg-open")
|
|
998
|
+
elif current_os.startswith("CYGWIN"):
|
|
999
|
+
commands.append("cygstart")
|
|
1000
|
+
else: # Assume macOS
|
|
1001
|
+
commands.append("open")
|
|
1002
|
+
|
|
1003
|
+
if self.show_file_location_upon_completion:
|
|
1004
|
+
commands.append("-R")
|
|
1005
|
+
|
|
1006
|
+
commands.append(file_path)
|
|
1007
|
+
|
|
1008
|
+
FNULL = open(os.devnull, 'w')
|
|
1009
|
+
sp.call(commands, stdout=FNULL, stderr=sp.STDOUT)
|
|
1010
|
+
FNULL.close()
|
|
1011
|
+
|
|
1012
|
+
if self.quiet:
|
|
1013
|
+
sys.stdout.close()
|
|
1014
|
+
sys.stdout = curr_stdout
|