From 772973eb3f5adf3656d2446d68babe94f7cbd82f Mon Sep 17 00:00:00 2001 From: SystemZion Date: Fri, 31 Jul 2026 17:23:04 +0800 Subject: [PATCH 1/2] Add audio mixing and subtitle rendering --- CHANGELOG.md | 37 + README.md | 35 +- examples/demo.srt | 7 + pyproject.toml | 2 +- src/facut/__init__.py | 2 +- src/facut/cli/audio_commands.py | 87 + src/facut/cli/main.py | 5 + src/facut/cli/subtitle_commands.py | 383 +++++ src/facut/core/command_engine.py | 5 + src/facut/core/models.py | 127 +- src/facut/core/timeline_engine.py | 117 +- src/facut/render/ffmpeg_backend.py | 108 +- src/facut/render/graph_builder.py | 111 ++ src/facut/schemas/project.schema.json | 2150 ++++++++++++++----------- src/facut/subtitles/__init__.py | 23 + src/facut/subtitles/compiler.py | 165 ++ src/facut/subtitles/editor.py | 131 ++ src/facut/subtitles/formats.py | 256 +++ tests/test_audio_tracks.py | 203 +++ tests/test_phase1_cli.py | 7 +- tests/test_render_core.py | 77 + tests/test_subtitle_cli.py | 154 ++ tests/test_subtitle_editor.py | 76 + tests/test_subtitle_formats.py | 62 + 24 files changed, 3357 insertions(+), 973 deletions(-) create mode 100644 CHANGELOG.md create mode 100644 examples/demo.srt create mode 100644 src/facut/cli/audio_commands.py create mode 100644 src/facut/cli/subtitle_commands.py create mode 100644 src/facut/subtitles/__init__.py create mode 100644 src/facut/subtitles/compiler.py create mode 100644 src/facut/subtitles/editor.py create mode 100644 src/facut/subtitles/formats.py create mode 100644 tests/test_audio_tracks.py create mode 100644 tests/test_subtitle_cli.py create mode 100644 tests/test_subtitle_editor.py create mode 100644 tests/test_subtitle_formats.py diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..8733419 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,37 @@ +# Changelog + +All notable changes to `facut` are documented here. + +## 0.2.0 — 2026-07-31 + +### Added + +- Independent audio tracks for background music and sound effects. +- Audio gain, fade-in, fade-out, delayed placement, and source looping. +- Mixing of independent audio tracks with the original camera audio. +- SRT and VTT import, export, timing shift, listing, and removal. +- Styled text overlays with position, color, outline, and background controls. +- Automatic ASS compilation and subtitle/text burn-in during preview and render. +- Encoding fallback for UTF-8, UTF-16, and GB18030 subtitle files. + +### Changed + +- Narrow-terminal CLI help tests now use a deterministic terminal width. +- The render graph accepts an optional generated subtitle file. +- Project Schema includes audio-loop, subtitle, and text-overlay data. + +### Verified + +- Real FFmpeg rendering with transitions, native audio, looped music, text, and + subtitle burn-in. +- Windows, Linux, Python 3.11, and Python 3.13 remain covered by CI. + +## 0.1.0 — 2026-07-28 + +- Initial installable CLI and Windows single-file executable. +- Project creation, media import and inspection, stable media IDs, and schema + validation. +- Non-destructive timeline editing with split, trim, move, delete, ripple + delete, undo, redo, and atomic JSON batches. +- Dissolve, fade-black, fade-white, slide, wipe, zoom, and blur transitions. +- Range preview and H.264/AAC final rendering through FFmpeg. diff --git a/README.md b/README.md index e0c9589..0b32f76 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ **facut**(Fast AI Cut)是一款面向 AI Agent、自动化脚本与高级用户的非破坏性命令行视频编辑器。它使用稳定素材 ID、结构化工程、可组合子命令及统一 JSON 返回值,让复杂剪辑既能由人操作,也能可靠地被程序调用。 -当前版本 `0.1.0` 是首个可用版本:工程、素材探测、单视频轨时间线、帧级时间表示、原子批处理、基础转场、快速预览、H.264/AAC 渲染和撤销/重做均可实际执行。Windows 单文件发行版内置 FFmpeg/FFprobe,不依赖系统 Python。 +当前开发版本 `0.2.0` 已形成完整的基础制作链路:工程、素材探测、单视频轨时间线、帧级时间表示、原子批处理、基础转场、快速预览、H.264/AAC 渲染、撤销/重做、独立背景音乐、原声混合、字幕和文字烧录均可实际执行。Windows 单文件发行版内置 FFmpeg/FFprobe,不依赖系统 Python。 ## 安装 @@ -41,7 +41,8 @@ facut doctor ```text facut init/import/inspect -facut timeline/clip/transition +facut timeline/clip/transition/audio +facut subtitle/text facut preview/render facut project/history facut undo/redo/run/doctor @@ -154,11 +155,38 @@ facut --project demo run ai-edit-plan.json --json facut --project demo render --preset youtube-1080p --output result.mp4 ``` +字幕与文字: + +```bash +facut --project demo timeline track add --type subtitle --name S1 +facut --project demo subtitle import captions.srt --track S1 +facut --project demo subtitle shift S1 --offset +500ms +facut --project demo subtitle export S1 --format vtt --output captions.vtt +facut --project demo text add --text "临港两日" --at 1s --duration 3s --y 20% +facut --project demo subtitle compile-ass --output render-text.ass +facut --project demo render --output subtitled.mp4 +``` + +渲染和预览会自动将工程中的字幕与文字编译为临时 ASS 并烧录。`compile-ass` 仍可生成独立、可检查的 ASS 侧车文件。 + +背景音乐与原声混合: + +```bash +facut --project demo import music.mp3 +facut --project demo timeline track add --type audio --name A1 +facut --project demo audio add --track A1 --at 0 --loop --volume-db -12 --fade-in 1s --fade-out 2s +facut --project demo render --output mixed.mp4 +``` + +独立音频轨会与视频素材自带的相机原声混合;`--loop` 默认循环到视频时间线末尾,也可配合 `--duration` 指定长度。 + ### 当前明确限制 - 渲染器当前支持一个启用的视频/图片轨;多视频轨叠加不会伪造成功,而会明确返回 `NOT_IMPLEMENTED`。 - 首版最终编码为 H.264/AAC;H.265、AV1、ProRes 等已保留后端扩展边界,但尚未开放。 -- 背景音乐专用音轨、字幕烧录、文字、关键帧 CLI、高级分析和自动剪辑属于后续版本。 +- 音频首版支持独立轨混音、增益、淡入淡出和循环;自动闪避、降噪与响度标准化尚未开放。 +- 字幕/文字支持工程编辑、SRT/VTT 往返、ASS 编译,并会自动烧录到预览和最终视频。 +- 关键帧 CLI、高级分析和自动剪辑属于后续版本。 - `fade-in`/`fade-out` 已注册,首版成对片段间的稳定转场重点为 `dissolve`、`fade-black`、`fade-white`、`slide`、`wipe`、`zoom`、`blur`。 ## 开发与测试 @@ -180,6 +208,7 @@ src/facut/ ├── render/ 滤镜图、缓存、硬件和 FFmpeg 后端 ├── transitions/ 插件式转场 ├── effects/ 插件式视频/音频效果 +├── subtitles/ SRT/VTT 解析、编辑与 ASS 编译 ├── config.py 跨平台配置 ├── exceptions.py 领域错误和稳定退出码 ├── logging_config.py 轮转日志 diff --git a/examples/demo.srt b/examples/demo.srt new file mode 100644 index 0000000..49229b8 --- /dev/null +++ b/examples/demo.srt @@ -0,0 +1,7 @@ +1 +00:00:01,200 --> 00:00:02,400 +Hello from facut + +2 +00:00:02,600 --> 00:00:03,500 +Background music + subtitles diff --git a/pyproject.toml b/pyproject.toml index 31ccbe5..951f7cb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "facut" -version = "0.1.0" +version = "0.2.0" description = "Fast AI Cut — a deterministic, agent-friendly command-line video editor" readme = "README.md" requires-python = ">=3.11" diff --git a/src/facut/__init__.py b/src/facut/__init__.py index 98e1988..bd8436d 100644 --- a/src/facut/__init__.py +++ b/src/facut/__init__.py @@ -4,4 +4,4 @@ __all__ = ["__version__"] -__version__ = "0.1.0" +__version__ = "0.2.0" diff --git a/src/facut/cli/audio_commands.py b/src/facut/cli/audio_commands.py new file mode 100644 index 0000000..431e421 --- /dev/null +++ b/src/facut/cli/audio_commands.py @@ -0,0 +1,87 @@ +"""Independent audio-track editing commands.""" + +from __future__ import annotations + +from typing import Annotated + +import typer + +from facut.cli.timeline_commands import _execute + + +audio_app = typer.Typer( + help="Add and shape independent music or sound-effect tracks." +) + + +@audio_app.command("add") +def audio_add( + ctx: typer.Context, + media_id: Annotated[str, typer.Argument()], + track: Annotated[str, typer.Option("--track")], + at: Annotated[str, typer.Option("--at")] = "0", + source_in: Annotated[str, typer.Option("--in")] = "0", + source_out: Annotated[str | None, typer.Option("--out")] = None, + volume_db: Annotated[float, typer.Option("--volume-db")] = 0.0, + fade_in: Annotated[str, typer.Option("--fade-in")] = "0", + fade_out: Annotated[str, typer.Option("--fade-out")] = "0", + loop: Annotated[ + bool, + typer.Option( + "--loop", + help="Repeat the selected source range; defaults to covering the video timeline.", + ), + ] = False, + duration: Annotated[ + str | None, + typer.Option("--duration", help="Explicit looped timeline duration."), + ] = None, + dry_run: Annotated[bool, typer.Option("--dry-run")] = False, +) -> None: + """Place music or a sound effect on an audio track.""" + + params = { + "media_id": media_id, + "track": track, + "at": at, + "in": source_in, + "volume_db": volume_db, + "fade_in": fade_in, + "fade_out": fade_out, + "loop": loop, + } + if source_out is not None: + params["out"] = source_out + if duration is not None: + params["duration"] = duration + _execute(ctx, "audio.add", params, dry_run) + + +@audio_app.command("volume") +def audio_volume( + ctx: typer.Context, + clip_id: Annotated[str, typer.Argument()], + db: Annotated[float, typer.Option("--db")], + dry_run: Annotated[bool, typer.Option("--dry-run")] = False, +) -> None: + """Set gain for an independent audio clip in decibels.""" + + _execute(ctx, "audio.volume", {"clip_id": clip_id, "db": db}, dry_run) + + +@audio_app.command("fade") +def audio_fade( + ctx: typer.Context, + clip_id: Annotated[str, typer.Argument()], + fade_in: Annotated[str | None, typer.Option("--in")] = None, + fade_out: Annotated[str | None, typer.Option("--out")] = None, + dry_run: Annotated[bool, typer.Option("--dry-run")] = False, +) -> None: + """Apply a fade-in, fade-out, or both.""" + + params = {"clip_id": clip_id} + if fade_in is not None: + params["fade_in"] = fade_in + if fade_out is not None: + params["fade_out"] = fade_out + _execute(ctx, "audio.fade", params, dry_run) diff --git a/src/facut/cli/main.py b/src/facut/cli/main.py index a6174ef..87ecf62 100644 --- a/src/facut/cli/main.py +++ b/src/facut/cli/main.py @@ -187,6 +187,8 @@ def main() -> None: transition_app, ) from facut.cli.render_commands import preview_app, render_command # noqa: E402 +from facut.cli.audio_commands import audio_app # noqa: E402 +from facut.cli.subtitle_commands import subtitle_app, text_app # noqa: E402 app.command("init")(init_command) app.command("import")(import_command) @@ -200,6 +202,9 @@ def main() -> None: app.add_typer(clip_app, name="clip") app.add_typer(transition_app, name="transition") app.add_typer(preview_app, name="preview") +app.add_typer(audio_app, name="audio") +app.add_typer(subtitle_app, name="subtitle") +app.add_typer(text_app, name="text") app.command("render")(render_command) diff --git a/src/facut/cli/subtitle_commands.py b/src/facut/cli/subtitle_commands.py new file mode 100644 index 0000000..6607ad3 --- /dev/null +++ b/src/facut/cli/subtitle_commands.py @@ -0,0 +1,383 @@ +"""Subtitle and free-text command groups.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Annotated, Any + +import typer + +from facut.cli.common import manager_for, public_error +from facut.core.models import TextStyle +from facut.core.timeline_engine import parse_time +from facut.responses import success_response +from facut.subtitles.compiler import SubtitleCompiler +from facut.subtitles.editor import ( + add_text_overlay, + import_cues, + remove_cue, + remove_text_overlay, + require_subtitle_track, + shift_track, +) +from facut.subtitles.formats import export_srt, export_vtt, parse_subtitle_file + + +subtitle_app = typer.Typer(help="Import, shift, inspect, export, and compile subtitles.") +text_app = typer.Typer(help="Add and manage timed free-text overlays.") + + +def _state(ctx: typer.Context): + from facut.cli.main import CliState + + return ctx.ensure_object(CliState) + + +def _abort(ctx: typer.Context, command: str, error: Exception) -> None: + from facut.cli.main import fail + + fail(_state(ctx), command, public_error(error)) + + +def _serialized(value: Any) -> Any: + if hasattr(value, "model_dump"): + return value.model_dump(mode="json") + if isinstance(value, list): + return [_serialized(item) for item in value] + return value + + +def _emit_mutation( + ctx: typer.Context, + command: str, + result: Any, + revision: int, + *, + dry_run: bool, +) -> None: + from facut.cli.main import emit + + data = {"result": _serialized(result), "dry_run": dry_run} + emit( + _state(ctx), + success_response(command, data, project_revision=revision), + human=f"[green]{command} completed.[/green]\n" + f"{json.dumps(data['result'], ensure_ascii=False, indent=2)}", + ) + + +@subtitle_app.command("import") +def subtitle_import( + ctx: typer.Context, + source: Annotated[Path, typer.Argument(help="SRT or WebVTT file.")], + track: Annotated[str, typer.Option("--track", help="Destination subtitle track.")], + subtitle_format: Annotated[ + str | None, typer.Option("--format", help="Override srt/vtt format detection.") + ] = None, + offset: Annotated[ + str, typer.Option("--offset", help="Signed timeline offset, for example +500ms.") + ] = "0", + dry_run: Annotated[bool, typer.Option("--dry-run")] = False, +) -> None: + """Import all cues from an SRT or VTT file in one project revision.""" + + command = "subtitle.import" + try: + manager = manager_for(_state(ctx)) + document = manager.require_document() + offset_seconds = float(parse_time(offset, document.project.fps).seconds) + parsed = parse_subtitle_file(source, subtitle_format) + + def operation(candidate): + return import_cues( + candidate, + track, + parsed, + offset=offset_seconds, + source=source.name, + ) + + result, state = manager.mutate( + command, + f"Imported {len(parsed)} subtitle cues into {track}", + operation, + command={ + "source": source.name, + "track": track, + "format": subtitle_format, + "offset": offset, + }, + dry_run=dry_run, + ) + _emit_mutation(ctx, command, result, state.revision, dry_run=dry_run) + except Exception as error: + _abort(ctx, command, error) + + +@subtitle_app.command("shift") +def subtitle_shift( + ctx: typer.Context, + track: Annotated[str, typer.Argument(help="Subtitle track ID.")], + offset: Annotated[str, typer.Option("--offset", help="Signed offset.")], + dry_run: Annotated[bool, typer.Option("--dry-run")] = False, +) -> None: + """Shift every cue on a subtitle track.""" + + command = "subtitle.shift" + try: + manager = manager_for(_state(ctx)) + document = manager.require_document() + offset_seconds = float(parse_time(offset, document.project.fps).seconds) + result, state = manager.mutate( + command, + f"Shifted subtitle track {track} by {offset}", + lambda candidate: shift_track(candidate, track, offset_seconds), + command={"track": track, "offset": offset}, + dry_run=dry_run, + ) + _emit_mutation(ctx, command, result, state.revision, dry_run=dry_run) + except Exception as error: + _abort(ctx, command, error) + + +@subtitle_app.command("list") +def subtitle_list( + ctx: typer.Context, + track: Annotated[str | None, typer.Option("--track")] = None, +) -> None: + """List subtitle cues in timeline order.""" + + from facut.cli.main import emit + + command = "subtitle.list" + try: + document = manager_for(_state(ctx)).require_document() + if track is not None: + require_subtitle_track(document, track) + cues = [ + cue + for cue in document.subtitle_cues + if track is None or cue.track_id == track + ] + data = [cue.model_dump(mode="json") for cue in cues] + human = "\n".join( + f"{cue.id} {cue.start:8.3f} → {cue.end:8.3f} {cue.text}" + for cue in cues + ) + emit( + _state(ctx), + success_response(command, data, project_revision=document.revision), + human=human or "No subtitle cues.", + ) + except Exception as error: + _abort(ctx, command, error) + + +@subtitle_app.command("remove") +def subtitle_remove( + ctx: typer.Context, + cue_id: Annotated[str, typer.Argument()], + dry_run: Annotated[bool, typer.Option("--dry-run")] = False, +) -> None: + """Remove one subtitle cue.""" + + command = "subtitle.remove" + try: + manager = manager_for(_state(ctx)) + result, state = manager.mutate( + command, + f"Removed subtitle cue {cue_id}", + lambda candidate: remove_cue(candidate, cue_id), + command={"cue_id": cue_id}, + dry_run=dry_run, + ) + _emit_mutation(ctx, command, result, state.revision, dry_run=dry_run) + except Exception as error: + _abort(ctx, command, error) + + +@subtitle_app.command("export") +def subtitle_export( + ctx: typer.Context, + track: Annotated[str, typer.Argument(help="Subtitle track ID.")], + output: Annotated[Path, typer.Option("--output", "-o")], + subtitle_format: Annotated[ + str | None, typer.Option("--format", help="srt or vtt; defaults to extension.") + ] = None, + overwrite: Annotated[bool, typer.Option("--overwrite")] = False, +) -> None: + """Export one subtitle track without modifying the project.""" + + from facut.cli.main import emit + + command = "subtitle.export" + try: + document = manager_for(_state(ctx)).require_document() + require_subtitle_track(document, track) + selected = (subtitle_format or output.suffix.lstrip(".")).lower() + cues = [cue for cue in document.subtitle_cues if cue.track_id == track] + if selected == "srt": + content = export_srt(cues) + elif selected in {"vtt", "webvtt"}: + content = export_vtt(cues) + selected = "vtt" + else: + raise ValueError("Subtitle export format must be srt or vtt.") + if output.exists() and not overwrite: + raise FileExistsError( + f'Output "{output}" exists; use --overwrite to replace it.' + ) + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text(content, encoding="utf-8", newline="\n") + data = {"output": str(output.resolve()), "format": selected, "cue_count": len(cues)} + emit( + _state(ctx), + success_response(command, data, project_revision=document.revision), + human=f"[green]Exported {len(cues)} cues to {output}.[/green]", + ) + except Exception as error: + _abort(ctx, command, error) + + +@subtitle_app.command("compile-ass") +def subtitle_compile_ass( + ctx: typer.Context, + output: Annotated[Path, typer.Option("--output", "-o")], + overwrite: Annotated[bool, typer.Option("--overwrite")] = False, +) -> None: + """Compile all project subtitles and text overlays to an ASS render sidecar.""" + + from facut.cli.main import emit + + command = "subtitle.compile-ass" + try: + document = manager_for(_state(ctx)).require_document() + plan = SubtitleCompiler().compile(document) + written = plan.write(output, overwrite=overwrite) + data = { + "output": str(written.resolve()), + "format": plan.format, + "cue_count": plan.cue_count, + "text_overlay_count": plan.text_overlay_count, + } + emit( + _state(ctx), + success_response(command, data, project_revision=document.revision), + human=f"[green]Compiled ASS sidecar to {written}.[/green]", + ) + except Exception as error: + _abort(ctx, command, error) + + +@text_app.command("add") +def text_add( + ctx: typer.Context, + text: Annotated[str, typer.Option("--text")], + at: Annotated[str, typer.Option("--at")], + duration: Annotated[str, typer.Option("--duration")], + x: Annotated[str, typer.Option("--x")] = "center", + y: Annotated[str, typer.Option("--y")] = "80%", + track: Annotated[str | None, typer.Option("--track")] = None, + font: Annotated[str | None, typer.Option("--font")] = None, + font_size: Annotated[float, typer.Option("--font-size")] = 64.0, + color: Annotated[str, typer.Option("--color")] = "#FFFFFF", + stroke_color: Annotated[str, typer.Option("--stroke-color")] = "#000000", + stroke_width: Annotated[float, typer.Option("--stroke-width")] = 2.0, + entrance: Annotated[str | None, typer.Option("--in-animation")] = None, + exit_animation: Annotated[str | None, typer.Option("--out-animation")] = None, + dry_run: Annotated[bool, typer.Option("--dry-run")] = False, +) -> None: + """Add a timed, styled text overlay.""" + + command = "text.add" + try: + manager = manager_for(_state(ctx)) + document = manager.require_document() + at_seconds = float(parse_time(at, document.project.fps).seconds) + duration_seconds = float(parse_time(duration, document.project.fps).seconds) + style = TextStyle( + font_family=font, + font_size=font_size, + color=color, + stroke_color=stroke_color, + stroke_width=stroke_width, + ) + + def operation(candidate): + return add_text_overlay( + candidate, + text=text, + at=at_seconds, + duration=duration_seconds, + x=x, + y=y, + track_id=track, + style=style, + entrance=entrance, + exit=exit_animation, + ) + + result, state = manager.mutate( + command, + f"Added text overlay at {at}", + operation, + command={ + "text": text, + "at": at, + "duration": duration, + "x": x, + "y": y, + "track": track, + }, + dry_run=dry_run, + ) + _emit_mutation(ctx, command, result, state.revision, dry_run=dry_run) + except Exception as error: + _abort(ctx, command, error) + + +@text_app.command("list") +def text_list(ctx: typer.Context) -> None: + """List free-text overlays.""" + + from facut.cli.main import emit + + command = "text.list" + try: + document = manager_for(_state(ctx)).require_document() + data = [item.model_dump(mode="json") for item in document.text_overlays] + human = "\n".join( + f"{item.id} {item.at:8.3f} → {item.end:8.3f} {item.text}" + for item in document.text_overlays + ) + emit( + _state(ctx), + success_response(command, data, project_revision=document.revision), + human=human or "No text overlays.", + ) + except Exception as error: + _abort(ctx, command, error) + + +@text_app.command("remove") +def text_remove( + ctx: typer.Context, + overlay_id: Annotated[str, typer.Argument()], + dry_run: Annotated[bool, typer.Option("--dry-run")] = False, +) -> None: + """Remove one free-text overlay.""" + + command = "text.remove" + try: + manager = manager_for(_state(ctx)) + result, state = manager.mutate( + command, + f"Removed text overlay {overlay_id}", + lambda candidate: remove_text_overlay(candidate, overlay_id), + command={"overlay_id": overlay_id}, + dry_run=dry_run, + ) + _emit_mutation(ctx, command, result, state.revision, dry_run=dry_run) + except Exception as error: + _abort(ctx, command, error) diff --git a/src/facut/core/command_engine.py b/src/facut/core/command_engine.py index 532053a..f6e0afb 100644 --- a/src/facut/core/command_engine.py +++ b/src/facut/core/command_engine.py @@ -120,6 +120,8 @@ def apply(document: ProjectDocument, command: dict[str, Any]) -> Any: aliases = {"track": "track_id"} if action == "timeline.add": aliases.update({"in": "source_in", "out": "source_out"}) + elif action == "audio.add": + aliases.update({"track": "track_id", "in": "source_in", "out": "source_out"}) elif action == "timeline.track.add": aliases.update({"type": "track_type"}) elif action == "transition.add": @@ -137,6 +139,9 @@ def apply(document: ProjectDocument, command: dict[str, Any]) -> Any: handlers = { "timeline.track.add": timeline.add_track, "timeline.add": timeline.add_clip, + "audio.add": timeline.add_audio_clip, + "audio.volume": timeline.set_audio_volume, + "audio.fade": timeline.set_audio_fades, "clip.move": timeline.move_clip, "clip.duplicate": timeline.duplicate_clip, "clip.split": timeline.split_clip, diff --git a/src/facut/core/models.py b/src/facut/core/models.py index 1ab1d81..da2c833 100644 --- a/src/facut/core/models.py +++ b/src/facut/core/models.py @@ -135,6 +135,10 @@ class Clip(StrictModel): enabled: bool = True muted: bool = False volume_db: float = 0.0 + timeline_duration: float | None = Field(default=None, gt=0.0) + loop: bool = False + audio_fade_in: float = Field(default=0.0, ge=0.0) + audio_fade_out: float = Field(default=0.0, ge=0.0) transform: Transform = Field(default_factory=Transform) effects: list[Effect] = Field(default_factory=list) keyframes: list[Keyframe] = Field(default_factory=list) @@ -146,11 +150,19 @@ def validate_source_range(self) -> "Clip": raise ValueError("source_out must be greater than source_in") if self.speed == 0: raise ValueError("speed cannot be zero") + natural_duration = (self.source_out - self.source_in) / abs(self.speed) + if self.timeline_duration is not None and not self.loop: + raise ValueError("timeline_duration requires loop to be enabled") + duration = self.timeline_duration or natural_duration + if self.audio_fade_in > duration or self.audio_fade_out > duration: + raise ValueError("audio fade duration cannot exceed clip duration") return self @property def duration(self) -> float: - return (self.source_out - self.source_in) / abs(self.speed) + return self.timeline_duration or ( + (self.source_out - self.source_in) / abs(self.speed) + ) @property def end(self) -> float: @@ -212,6 +224,90 @@ class Marker(StrictModel): metadata: dict[str, Any] = Field(default_factory=dict) +class TextStyle(StrictModel): + """Portable styling shared by subtitle cues and free text overlays.""" + + font_family: str | None = None + font_size: float = Field(default=64.0, gt=0.0) + font_weight: str = "normal" + color: str = Field(default="#FFFFFF", pattern=r"^#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$") + stroke_color: str = Field( + default="#000000", pattern=r"^#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$" + ) + stroke_width: float = Field(default=2.0, ge=0.0) + shadow: float = Field(default=1.0, ge=0.0) + background: str | None = Field( + default=None, pattern=r"^#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$" + ) + alignment: Literal["left", "center", "right"] = "center" + line_spacing: float = 1.0 + letter_spacing: float = 0.0 + + +class SubtitleCue(StrictModel): + """One timed subtitle cue attached to a subtitle track.""" + + id: str = Field(default_factory=lambda: new_id("subtitle")) + track_id: str + start: float = Field(ge=0.0) + end: float = Field(gt=0.0) + text: str = Field(min_length=1) + style: TextStyle | None = None + source_identifier: str | None = None + settings: dict[str, str] = Field(default_factory=dict) + metadata: dict[str, Any] = Field(default_factory=dict) + + @model_validator(mode="after") + def validate_range(self) -> "SubtitleCue": + if self.end <= self.start: + raise ValueError("subtitle cue end must be greater than start") + return self + + +class TextOverlay(StrictModel): + """Timed free text rendered independently of spoken-word subtitles.""" + + id: str = Field(default_factory=lambda: new_id("text")) + track_id: str | None = None + text: str = Field(min_length=1) + at: float = Field(ge=0.0) + duration: float = Field(gt=0.0) + x: float | str = "center" + y: float | str = "80%" + style: TextStyle = Field(default_factory=TextStyle) + entrance: str | None = None + exit: str | None = None + enabled: bool = True + metadata: dict[str, Any] = Field(default_factory=dict) + + @field_validator("x", "y") + @classmethod + def validate_position(cls, value: float | str) -> float | str: + if isinstance(value, float): + return value + normalized = value.strip().lower() + if normalized in {"left", "center", "right", "top", "bottom"}: + return normalized + if normalized.endswith("%"): + try: + percent = float(normalized[:-1]) + except ValueError as exc: + raise ValueError("position percentage must be numeric") from exc + if not 0.0 <= percent <= 100.0: + raise ValueError("position percentage must be between 0% and 100%") + return normalized + try: + return float(normalized) + except ValueError as exc: + raise ValueError( + "position must be a number, percentage, or named alignment" + ) from exc + + @property + def end(self) -> float: + return self.at + self.duration + + class HistoryEntry(StrictModel): revision: int = Field(ge=1) action: str @@ -240,6 +336,8 @@ class ProjectDocument(StrictModel): media: list[MediaAsset] = Field(default_factory=list) tracks: list[Track] = Field(default_factory=list) transitions: list[Transition] = Field(default_factory=list) + subtitle_cues: list[SubtitleCue] = Field(default_factory=list) + text_overlays: list[TextOverlay] = Field(default_factory=list) markers: list[Marker] = Field(default_factory=list) settings: dict[str, Any] = Field(default_factory=dict) history: list[HistoryEntry] = Field(default_factory=list) @@ -272,15 +370,34 @@ def validate_global_ids_and_references(self) -> "ProjectDocument": raise ValueError( f"transition {transition.id} references unknown track {transition.track_id}" ) + cue_ids: set[str] = set() + for cue in self.subtitle_cues: + if cue.id in cue_ids: + raise ValueError(f"duplicate subtitle cue id {cue.id}") + cue_ids.add(cue.id) + track = self.find_track(cue.track_id) + if track is None: + raise ValueError(f"subtitle cue {cue.id} references unknown track {cue.track_id}") + if track.type != TrackType.SUBTITLE: + raise ValueError(f"subtitle cue {cue.id} requires a subtitle track") + overlay_ids: set[str] = set() + for overlay in self.text_overlays: + if overlay.id in overlay_ids: + raise ValueError(f"duplicate text overlay id {overlay.id}") + overlay_ids.add(overlay.id) + if overlay.track_id is not None and overlay.track_id not in known_tracks: + raise ValueError( + f"text overlay {overlay.id} references unknown track {overlay.track_id}" + ) return self def recompute_duration(self) -> float: """Update and return the maximum enabled clip end.""" - duration = max( - (clip.end for track in self.tracks for clip in track.clips if clip.enabled), - default=0.0, - ) + ends = [clip.end for track in self.tracks for clip in track.clips if clip.enabled] + ends.extend(cue.end for cue in self.subtitle_cues) + ends.extend(overlay.end for overlay in self.text_overlays if overlay.enabled) + duration = max(ends, default=0.0) self.project.duration = duration return duration diff --git a/src/facut/core/timeline_engine.py b/src/facut/core/timeline_engine.py index 2920299..2c42658 100644 --- a/src/facut/core/timeline_engine.py +++ b/src/facut/core/timeline_engine.py @@ -8,7 +8,15 @@ import re from typing import Any -from facut.core.models import Clip, ProjectDocument, Track, TrackType, Transition, new_id +from facut.core.models import ( + Clip, + MediaKind, + ProjectDocument, + Track, + TrackType, + Transition, + new_id, +) from facut.transitions import registry as transition_registry @@ -204,6 +212,110 @@ def add_clip( self.project.recompute_duration() return clip + def add_audio_clip( + self, + media_id: str, + track_id: str, + at: str | float = 0, + source_in: str | float = 0, + source_out: str | float | None = None, + *, + volume_db: float = 0.0, + fade_in: str | float = 0, + fade_out: str | float = 0, + loop: bool = False, + duration: str | float | None = None, + clip_id: str | None = None, + ) -> Clip: + """Place an audio source on an audio track. + + When ``loop`` is enabled and no duration is supplied, the source is + repeated until the end of the current video timeline. + """ + + track = self._track(track_id) + if track.type != TrackType.AUDIO: + raise TimelineError(f'Track "{track_id}" is not an audio track.') + asset = self.project.find_media(media_id) + if asset is None: + raise TimelineItemNotFound(f'Media "{media_id}" was not found.') + if asset.kind not in {MediaKind.AUDIO, MediaKind.VIDEO}: + raise TimelineError(f'Media "{media_id}" does not contain usable audio.') + if not asset.technical.audio_codec: + raise TimelineError(f'Media "{media_id}" does not contain an audio stream.') + if not -96.0 <= float(volume_db) <= 24.0: + raise TimelineError("Audio volume must be between -96 dB and +24 dB.") + + clip = self.add_clip( + media_id, + track_id, + at=at, + source_in=source_in, + source_out=source_out, + clip_id=clip_id, + ) + fade_in_seconds = seconds(fade_in, self.fps) + fade_out_seconds = seconds(fade_out, self.fps) + if fade_in_seconds < 0 or fade_out_seconds < 0: + raise TimelineError("Audio fade durations cannot be negative.") + clip.volume_db = float(volume_db) + clip.loop = loop + if duration is not None: + if not loop: + raise TimelineError("An explicit loop duration requires loop=true.") + clip.timeline_duration = seconds(duration, self.fps) + elif loop: + video_end = max( + ( + item.end + for candidate in self.project.tracks + if candidate.type in {TrackType.VIDEO, TrackType.IMAGE} + for item in candidate.clips + if item.enabled + ), + default=clip.timeline_start + clip.duration, + ) + clip.timeline_duration = max( + 1 / self.fps, video_end - clip.timeline_start + ) + clip.audio_fade_in = fade_in_seconds + clip.audio_fade_out = fade_out_seconds + Clip.model_validate(clip.model_dump()) + self.project.recompute_duration() + return clip + + def set_audio_volume(self, clip_id: str, db: float) -> Clip: + """Set clip gain in decibels for an audio-track clip.""" + + clip, track = self._clip_and_track(clip_id) + if track.type != TrackType.AUDIO: + raise TimelineError(f'Clip "{clip_id}" is not on an audio track.') + if not -96.0 <= float(db) <= 24.0: + raise TimelineError("Audio volume must be between -96 dB and +24 dB.") + clip.volume_db = float(db) + return clip + + def set_audio_fades( + self, + clip_id: str, + *, + fade_in: str | float | None = None, + fade_out: str | float | None = None, + ) -> Clip: + """Set non-destructive fade-in and fade-out durations.""" + + clip, track = self._clip_and_track(clip_id) + if track.type != TrackType.AUDIO: + raise TimelineError(f'Clip "{clip_id}" is not on an audio track.') + if fade_in is None and fade_out is None: + raise TimelineError("Specify fade_in, fade_out, or both.") + if fade_in is not None: + clip.audio_fade_in = seconds(fade_in, self.fps) + if fade_out is not None: + clip.audio_fade_out = seconds(fade_out, self.fps) + Clip.model_validate(clip.model_dump()) + return clip + def move_clip( self, clip_id: str, @@ -419,6 +531,9 @@ def conflicts(self, track_id: str | None = None) -> list[dict[str, Any]]: else [track for track in self.project.tracks if track.enabled] ) for track in tracks: + if track.type == TrackType.AUDIO: + # Independent sound layers are mixed, so overlaps are valid. + continue clips = sorted( (clip for clip in track.clips if clip.enabled), key=lambda item: item.timeline_start, diff --git a/src/facut/render/ffmpeg_backend.py b/src/facut/render/ffmpeg_backend.py index c3d8506..ffed883 100644 --- a/src/facut/render/ffmpeg_backend.py +++ b/src/facut/render/ffmpeg_backend.py @@ -13,6 +13,7 @@ from facut.core.models import ProjectDocument from facut.render.graph_builder import FilterGraph, GraphBuilder from facut.render.hardware import EncoderChoice, choose_h264_encoder +from facut.subtitles.compiler import SubtitleCompiler class RenderError(RuntimeError): @@ -118,53 +119,64 @@ def render( raise FileExistsError( f'Output "{destination}" already exists; use overwrite to replace it.' ) - destination.parent.mkdir(parents=True, exist_ok=True) - graph = GraphBuilder(project, project_dir).build( - width=width, - height=height, - fps=fps, - range_from=range_from, - range_to=range_to, - preview=preview, - ) if codec not in {"h264", "libx264"}: raise NotImplementedError( f"NOT_IMPLEMENTED: the v1 backend currently renders H.264, not {codec}." ) - choice = choose_h264_encoder(self.ffmpeg, hardware) - warnings = list(choice.warnings) + destination.parent.mkdir(parents=True, exist_ok=True) + subtitle_file = self._compile_subtitles(project) try: - self._run( - graph, - destination, - choice, - audio_codec=audio_codec, - audio_bitrate=audio_bitrate, - bitrate=bitrate, - preview=preview, - overwrite=overwrite, - progress=progress, - ) - except RenderError: - if choice.hardware == "none": - raise - warnings.append( - f"{choice.encoder} was detected but failed to initialize; " - "rendered with libx264 instead." - ) - software = EncoderChoice("libx264", "none") - self._run( - graph, - destination, - software, - audio_codec=audio_codec, - audio_bitrate=audio_bitrate, - bitrate=bitrate, + graph = GraphBuilder(project, project_dir).build( + width=width, + height=height, + fps=fps, + range_from=range_from, + range_to=range_to, preview=preview, - overwrite=True, - progress=progress, + subtitle_file=subtitle_file, ) - choice = software + except Exception: + if subtitle_file is not None: + subtitle_file.unlink(missing_ok=True) + raise + choice = choose_h264_encoder(self.ffmpeg, hardware) + warnings = list(choice.warnings) + try: + try: + self._run( + graph, + destination, + choice, + audio_codec=audio_codec, + audio_bitrate=audio_bitrate, + bitrate=bitrate, + preview=preview, + overwrite=overwrite, + progress=progress, + ) + except RenderError: + if choice.hardware == "none": + raise + warnings.append( + f"{choice.encoder} was detected but failed to initialize; " + "rendered with libx264 instead." + ) + software = EncoderChoice("libx264", "none") + self._run( + graph, + destination, + software, + audio_codec=audio_codec, + audio_bitrate=audio_bitrate, + bitrate=bitrate, + preview=preview, + overwrite=True, + progress=progress, + ) + choice = software + finally: + if subtitle_file is not None: + subtitle_file.unlink(missing_ok=True) return RenderResult( output=destination.resolve(), duration=graph.duration, @@ -173,6 +185,22 @@ def render( warnings=warnings, ) + @staticmethod + def _compile_subtitles(project: ProjectDocument) -> Path | None: + """Create a temporary ASS document only when visible text is present.""" + + if not project.subtitle_cues and not any( + overlay.enabled for overlay in project.text_overlays + ): + return None + plan = SubtitleCompiler().compile(project) + with tempfile.NamedTemporaryFile( + prefix="facut-subtitles-", suffix=".ass", delete=False + ) as temporary: + path = Path(temporary.name) + plan.write(path, overwrite=True) + return path + def preview_range( self, project: ProjectDocument, diff --git a/src/facut/render/graph_builder.py b/src/facut/render/graph_builder.py index e997036..059522b 100644 --- a/src/facut/render/graph_builder.py +++ b/src/facut/render/graph_builder.py @@ -26,6 +26,21 @@ def _fmt(value: float) -> str: return f"{value:.9f}".rstrip("0").rstrip(".") +def _filter_path(path: str | Path) -> str: + """Escape an absolute path for an FFmpeg filter option on every platform.""" + + normalized = Path(path).resolve().as_posix() + return ( + normalized.replace("\\", r"\\") + .replace(":", r"\:") + .replace("'", r"\'") + .replace("[", r"\[") + .replace("]", r"\]") + .replace(",", r"\,") + .replace(";", r"\;") + ) + + def _atempo(rate: float) -> str: filters: list[str] = [] remaining = rate @@ -86,6 +101,7 @@ def build( range_from: float | None = None, range_to: float | None = None, preview: bool = False, + subtitle_file: str | Path | None = None, ) -> FilterGraph: TimelineEngine(self.project).validate() width = width or self.project.project.width @@ -267,6 +283,101 @@ def build( current_duration += max(0.0, gap) + clip.duration current_v, current_a = out_v, out_a + # Independent audio tracks are layered after the video track's native + # sound has been assembled. This keeps camera/dialogue audio intact + # while allowing music and effects to overlap freely. + mix_labels = [current_a] + audio_clips = [ + clip + for audio_track in self.project.tracks + if audio_track.enabled + and not audio_track.muted + and audio_track.type == TrackType.AUDIO + for clip in sorted( + (item for item in audio_track.clips if item.enabled and not item.muted), + key=lambda item: (item.timeline_start, item.id), + ) + ] + for audio_index, clip in enumerate(audio_clips): + asset = self.project.find_media(clip.media_id) + if asset is None: + raise ValueError( + f"Audio clip {clip.id} references missing media {clip.media_id}." + ) + if not asset.technical.audio_codec: + raise ValueError(f"Media {asset.original_name} has no audio stream.") + source = self._source(asset.path) + if not source.is_file(): + raise FileNotFoundError(f"Media file is offline: {asset.original_name}") + input_index = len(paths) + paths.append(source) + inputs.extend(["-i", str(source)]) + speed = abs(clip.speed) + audio_chain = [ + f"[{input_index}:a:0]atrim=start={_fmt(clip.source_in)}:" + f"end={_fmt(clip.source_out)}", + "asetpts=PTS-STARTPTS", + ] + if clip.speed < 0: + audio_chain.append("areverse") + if abs(speed - 1) > 1e-9: + audio_chain.append(_atempo(speed)) + audio_chain.extend( + [ + f"aresample={self.project.project.sample_rate}", + "aformat=sample_fmts=fltp:channel_layouts=stereo", + ] + ) + natural_duration = (clip.source_out - clip.source_in) / speed + if clip.loop: + loop_samples = max( + 1, round(natural_duration * self.project.project.sample_rate) + ) + audio_chain.append(f"aloop=loop=-1:size={loop_samples}") + audio_chain.extend( + [ + f"atrim=duration={_fmt(clip.duration)}", + "asetpts=PTS-STARTPTS", + ] + ) + if clip.volume_db: + audio_chain.append(f"volume={_fmt(clip.volume_db)}dB") + if clip.audio_fade_in: + audio_chain.append( + f"afade=t=in:st=0:d={_fmt(clip.audio_fade_in)}" + ) + if clip.audio_fade_out: + fade_start = max(0.0, clip.duration - clip.audio_fade_out) + audio_chain.append( + f"afade=t=out:st={_fmt(fade_start)}:" + f"d={_fmt(clip.audio_fade_out)}" + ) + if clip.timeline_start: + delay_ms = max(0, round(clip.timeline_start * 1000)) + audio_chain.append(f"adelay={delay_ms}:all=1") + audio_chain.extend( + [ + f"apad=whole_dur={_fmt(current_duration)}", + f"atrim=duration={_fmt(current_duration)}", + ] + ) + label = f"bgm{audio_index}" + filters.append(",".join(audio_chain) + f"[{label}]") + mix_labels.append(label) + if len(mix_labels) > 1: + filters.append( + "".join(f"[{label}]" for label in mix_labels) + + f"amix=inputs={len(mix_labels)}:duration=first:" + "dropout_transition=0:normalize=0[amixed]" + ) + current_a = "amixed" + + if subtitle_file is not None: + filters.append( + f"[{current_v}]subtitles=filename='{_filter_path(subtitle_file)}'[vtext]" + ) + current_v = "vtext" + output_duration = current_duration if range_from is not None or range_to is not None: start = max(0.0, range_from or 0.0) diff --git a/src/facut/schemas/project.schema.json b/src/facut/schemas/project.schema.json index 2649e5e..9554e55 100644 --- a/src/facut/schemas/project.schema.json +++ b/src/facut/schemas/project.schema.json @@ -1,921 +1,1229 @@ -{ - "$defs": { - "Clip": { - "additionalProperties": false, - "properties": { - "id": { - "title": "Id", - "type": "string" - }, - "media_id": { - "title": "Media Id", - "type": "string" - }, - "track_id": { - "title": "Track Id", - "type": "string" - }, - "timeline_start": { - "default": 0.0, - "minimum": 0.0, - "title": "Timeline Start", - "type": "number" - }, - "source_in": { - "default": 0.0, - "minimum": 0.0, - "title": "Source In", - "type": "number" - }, - "source_out": { - "exclusiveMinimum": 0.0, - "title": "Source Out", - "type": "number" - }, - "speed": { - "default": 1.0, - "ne": 0.0, - "title": "Speed", - "type": "number" - }, - "enabled": { - "default": true, - "title": "Enabled", - "type": "boolean" - }, - "muted": { - "default": false, - "title": "Muted", - "type": "boolean" - }, - "volume_db": { - "default": 0.0, - "title": "Volume Db", - "type": "number" - }, - "transform": { - "$ref": "#/$defs/Transform" - }, - "effects": { - "items": { - "$ref": "#/$defs/Effect" - }, - "title": "Effects", - "type": "array" - }, - "keyframes": { - "items": { - "$ref": "#/$defs/Keyframe" - }, - "title": "Keyframes", - "type": "array" - }, - "metadata": { - "additionalProperties": true, - "title": "Metadata", - "type": "object" - } - }, - "required": [ - "media_id", - "track_id", - "source_out" - ], - "title": "Clip", - "type": "object" - }, - "Effect": { - "additionalProperties": false, - "properties": { - "id": { - "title": "Id", - "type": "string" - }, - "type": { - "title": "Type", - "type": "string" - }, - "enabled": { - "default": true, - "title": "Enabled", - "type": "boolean" - }, - "parameters": { - "additionalProperties": true, - "title": "Parameters", - "type": "object" - }, - "keyframes": { - "items": { - "$ref": "#/$defs/Keyframe" - }, - "title": "Keyframes", - "type": "array" - } - }, - "required": [ - "type" - ], - "title": "Effect", - "type": "object" - }, - "HistoryEntry": { - "additionalProperties": false, - "properties": { - "revision": { - "minimum": 1, - "title": "Revision", - "type": "integer" - }, - "action": { - "title": "Action", - "type": "string" - }, - "timestamp": { - "format": "date-time", - "title": "Timestamp", - "type": "string" - }, - "summary": { - "title": "Summary", - "type": "string" - }, - "command": { - "additionalProperties": true, - "title": "Command", - "type": "object" - } - }, - "required": [ - "revision", - "action", - "summary" - ], - "title": "HistoryEntry", - "type": "object" - }, - "Keyframe": { - "additionalProperties": false, - "properties": { - "id": { - "title": "Id", - "type": "string" - }, - "property": { - "title": "Property", - "type": "string" - }, - "time": { - "minimum": 0.0, - "title": "Time", - "type": "number" - }, - "value": { - "title": "Value" - }, - "easing": { - "default": "linear", - "title": "Easing", - "type": "string" - } - }, - "required": [ - "property", - "time", - "value" - ], - "title": "Keyframe", - "type": "object" - }, - "Marker": { - "additionalProperties": false, - "properties": { - "id": { - "title": "Id", - "type": "string" - }, - "at": { - "minimum": 0.0, - "title": "At", - "type": "number" - }, - "label": { - "default": "", - "title": "Label", - "type": "string" - }, - "color": { - "default": "#FFD54F", - "title": "Color", - "type": "string" - }, - "metadata": { - "additionalProperties": true, - "title": "Metadata", - "type": "object" - } - }, - "required": [ - "at" - ], - "title": "Marker", - "type": "object" - }, - "MediaAsset": { - "additionalProperties": false, - "properties": { - "id": { - "title": "Id", - "type": "string" - }, - "kind": { - "$ref": "#/$defs/MediaKind" - }, - "path": { - "title": "Path", - "type": "string" - }, - "original_name": { - "title": "Original Name", - "type": "string" - }, - "size": { - "minimum": 0, - "title": "Size", - "type": "integer" - }, - "sha256": { - "pattern": "^[0-9a-f]{64}$", - "title": "Sha256", - "type": "string" - }, - "imported_at": { - "format": "date-time", - "title": "Imported At", - "type": "string" - }, - "technical": { - "$ref": "#/$defs/MediaTechnicalInfo" - }, - "proxy_path": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Proxy Path" - }, - "offline": { - "default": false, - "title": "Offline", - "type": "boolean" - }, - "metadata": { - "additionalProperties": true, - "title": "Metadata", - "type": "object" - } - }, - "required": [ - "id", - "kind", - "path", - "original_name", - "size", - "sha256" - ], - "title": "MediaAsset", - "type": "object" - }, - "MediaKind": { - "enum": [ - "video", - "audio", - "image", - "subtitle" - ], - "title": "MediaKind", - "type": "string" - }, - "MediaTechnicalInfo": { - "additionalProperties": false, - "properties": { - "container": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Container" - }, - "duration": { - "anyOf": [ - { - "minimum": 0.0, - "type": "number" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Duration" - }, - "bitrate": { - "anyOf": [ - { - "minimum": 0, - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Bitrate" - }, - "video_codec": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Video Codec" - }, - "audio_codec": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Audio Codec" - }, - "width": { - "anyOf": [ - { - "minimum": 1, - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Width" - }, - "height": { - "anyOf": [ - { - "minimum": 1, - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Height" - }, - "frame_rate": { - "anyOf": [ - { - "exclusiveMinimum": 0.0, - "type": "number" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Frame Rate" - }, - "average_frame_rate": { - "anyOf": [ - { - "exclusiveMinimum": 0.0, - "type": "number" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Average Frame Rate" - }, - "pixel_format": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Pixel Format" - }, - "color_space": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Color Space" - }, - "color_transfer": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Color Transfer" - }, - "color_primaries": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Color Primaries" - }, - "audio_channels": { - "anyOf": [ - { - "minimum": 1, - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Audio Channels" - }, - "sample_rate": { - "anyOf": [ - { - "minimum": 1, - "type": "integer" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Sample Rate" - }, - "rotation": { - "default": 0, - "title": "Rotation", - "type": "integer" - }, - "has_subtitles": { - "default": false, - "title": "Has Subtitles", - "type": "boolean" - }, - "variable_frame_rate": { - "default": false, - "title": "Variable Frame Rate", - "type": "boolean" - }, - "creation_time": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Creation Time" - }, - "keyframes": { - "items": { - "type": "number" - }, - "title": "Keyframes", - "type": "array" - } - }, - "title": "MediaTechnicalInfo", - "type": "object" - }, - "ProjectSettings": { - "additionalProperties": false, - "properties": { - "id": { - "title": "Id", - "type": "string" - }, - "name": { - "title": "Name", - "type": "string" - }, - "width": { - "default": 1920, - "maximum": 16384, - "minimum": 16, - "title": "Width", - "type": "integer" - }, - "height": { - "default": 1080, - "maximum": 16384, - "minimum": 16, - "title": "Height", - "type": "integer" - }, - "fps": { - "default": 30.0, - "exclusiveMinimum": 0.0, - "maximum": 240.0, - "title": "Fps", - "type": "number" - }, - "sample_rate": { - "default": 48000, - "maximum": 384000, - "minimum": 8000, - "title": "Sample Rate", - "type": "integer" - }, - "background": { - "default": "#000000", - "pattern": "^#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$", - "title": "Background", - "type": "string" - }, - "duration": { - "default": 0.0, - "minimum": 0.0, - "title": "Duration", - "type": "number" - }, - "created_at": { - "format": "date-time", - "title": "Created At", - "type": "string" - }, - "updated_at": { - "format": "date-time", - "title": "Updated At", - "type": "string" - } - }, - "required": [ - "name" - ], - "title": "ProjectSettings", - "type": "object" - }, - "Track": { - "additionalProperties": false, - "properties": { - "id": { - "title": "Id", - "type": "string" - }, - "type": { - "$ref": "#/$defs/TrackType" - }, - "name": { - "title": "Name", - "type": "string" - }, - "order": { - "default": 0, - "minimum": 0, - "title": "Order", - "type": "integer" - }, - "enabled": { - "default": true, - "title": "Enabled", - "type": "boolean" - }, - "locked": { - "default": false, - "title": "Locked", - "type": "boolean" - }, - "muted": { - "default": false, - "title": "Muted", - "type": "boolean" - }, - "clips": { - "items": { - "$ref": "#/$defs/Clip" - }, - "title": "Clips", - "type": "array" - }, - "metadata": { - "additionalProperties": true, - "title": "Metadata", - "type": "object" - } - }, - "required": [ - "id", - "type", - "name" - ], - "title": "Track", - "type": "object" - }, - "TrackType": { - "enum": [ - "video", - "audio", - "image", - "subtitle", - "adjustment", - "mask" - ], - "title": "TrackType", - "type": "string" - }, - "Transform": { - "additionalProperties": false, - "properties": { - "x": { - "default": 0.0, - "title": "X", - "type": "number" - }, - "y": { - "default": 0.0, - "title": "Y", - "type": "number" - }, - "scale_x": { - "default": 1.0, - "title": "Scale X", - "type": "number" - }, - "scale_y": { - "default": 1.0, - "title": "Scale Y", - "type": "number" - }, - "rotation": { - "default": 0.0, - "title": "Rotation", - "type": "number" - }, - "anchor_x": { - "default": 0.5, - "title": "Anchor X", - "type": "number" - }, - "anchor_y": { - "default": 0.5, - "title": "Anchor Y", - "type": "number" - }, - "opacity": { - "default": 1.0, - "maximum": 1.0, - "minimum": 0.0, - "title": "Opacity", - "type": "number" - }, - "crop_left": { - "default": 0.0, - "minimum": 0.0, - "title": "Crop Left", - "type": "number" - }, - "crop_top": { - "default": 0.0, - "minimum": 0.0, - "title": "Crop Top", - "type": "number" - }, - "crop_right": { - "default": 0.0, - "minimum": 0.0, - "title": "Crop Right", - "type": "number" - }, - "crop_bottom": { - "default": 0.0, - "minimum": 0.0, - "title": "Crop Bottom", - "type": "number" - }, - "fit": { - "default": "contain", - "enum": [ - "contain", - "cover", - "stretch", - "none" - ], - "title": "Fit", - "type": "string" - }, - "flip_x": { - "default": false, - "title": "Flip X", - "type": "boolean" - }, - "flip_y": { - "default": false, - "title": "Flip Y", - "type": "boolean" - } - }, - "title": "Transform", - "type": "object" - }, - "Transition": { - "additionalProperties": false, - "properties": { - "id": { - "title": "Id", - "type": "string" - }, - "type": { - "title": "Type", - "type": "string" - }, - "duration": { - "exclusiveMinimum": 0.0, - "title": "Duration", - "type": "number" - }, - "from_clip_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "From Clip Id" - }, - "to_clip_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "To Clip Id" - }, - "track_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Track Id" - }, - "at": { - "anyOf": [ - { - "minimum": 0.0, - "type": "number" - }, - { - "type": "null" - } - ], - "default": null, - "title": "At" - }, - "parameters": { - "additionalProperties": true, - "title": "Parameters", - "type": "object" - }, - "sound_media_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "title": "Sound Media Id" - }, - "sound_offset": { - "default": 0.0, - "title": "Sound Offset", - "type": "number" - } - }, - "required": [ - "type", - "duration" - ], - "title": "Transition", - "type": "object" - } - }, - "additionalProperties": false, - "properties": { - "version": { - "default": "1.0", - "title": "Version", - "type": "string" - }, - "revision": { - "default": 0, - "minimum": 0, - "title": "Revision", - "type": "integer" - }, - "project": { - "$ref": "#/$defs/ProjectSettings" - }, - "media": { - "items": { - "$ref": "#/$defs/MediaAsset" - }, - "title": "Media", - "type": "array" - }, - "tracks": { - "items": { - "$ref": "#/$defs/Track" - }, - "title": "Tracks", - "type": "array" - }, - "transitions": { - "items": { - "$ref": "#/$defs/Transition" - }, - "title": "Transitions", - "type": "array" - }, - "markers": { - "items": { - "$ref": "#/$defs/Marker" - }, - "title": "Markers", - "type": "array" - }, - "settings": { - "additionalProperties": true, - "title": "Settings", - "type": "object" - }, - "history": { - "items": { - "$ref": "#/$defs/HistoryEntry" - }, - "title": "History", - "type": "array" - } - }, - "required": [ - "project" - ], - "title": "ProjectDocument", - "type": "object" -} +{ + "$defs": { + "Clip": { + "additionalProperties": false, + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "media_id": { + "title": "Media Id", + "type": "string" + }, + "track_id": { + "title": "Track Id", + "type": "string" + }, + "timeline_start": { + "default": 0.0, + "minimum": 0.0, + "title": "Timeline Start", + "type": "number" + }, + "source_in": { + "default": 0.0, + "minimum": 0.0, + "title": "Source In", + "type": "number" + }, + "source_out": { + "exclusiveMinimum": 0.0, + "title": "Source Out", + "type": "number" + }, + "speed": { + "default": 1.0, + "title": "Speed", + "type": "number" + }, + "enabled": { + "default": true, + "title": "Enabled", + "type": "boolean" + }, + "muted": { + "default": false, + "title": "Muted", + "type": "boolean" + }, + "volume_db": { + "default": 0.0, + "title": "Volume Db", + "type": "number" + }, + "timeline_duration": { + "anyOf": [ + { + "exclusiveMinimum": 0.0, + "type": "number" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Timeline Duration" + }, + "loop": { + "default": false, + "title": "Loop", + "type": "boolean" + }, + "audio_fade_in": { + "default": 0.0, + "minimum": 0.0, + "title": "Audio Fade In", + "type": "number" + }, + "audio_fade_out": { + "default": 0.0, + "minimum": 0.0, + "title": "Audio Fade Out", + "type": "number" + }, + "transform": { + "$ref": "#/$defs/Transform" + }, + "effects": { + "items": { + "$ref": "#/$defs/Effect" + }, + "title": "Effects", + "type": "array" + }, + "keyframes": { + "items": { + "$ref": "#/$defs/Keyframe" + }, + "title": "Keyframes", + "type": "array" + }, + "metadata": { + "additionalProperties": true, + "title": "Metadata", + "type": "object" + } + }, + "required": [ + "media_id", + "track_id", + "source_out" + ], + "title": "Clip", + "type": "object" + }, + "Effect": { + "additionalProperties": false, + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "type": { + "title": "Type", + "type": "string" + }, + "enabled": { + "default": true, + "title": "Enabled", + "type": "boolean" + }, + "parameters": { + "additionalProperties": true, + "title": "Parameters", + "type": "object" + }, + "keyframes": { + "items": { + "$ref": "#/$defs/Keyframe" + }, + "title": "Keyframes", + "type": "array" + } + }, + "required": [ + "type" + ], + "title": "Effect", + "type": "object" + }, + "HistoryEntry": { + "additionalProperties": false, + "properties": { + "revision": { + "minimum": 1, + "title": "Revision", + "type": "integer" + }, + "action": { + "title": "Action", + "type": "string" + }, + "timestamp": { + "format": "date-time", + "title": "Timestamp", + "type": "string" + }, + "summary": { + "title": "Summary", + "type": "string" + }, + "command": { + "additionalProperties": true, + "title": "Command", + "type": "object" + } + }, + "required": [ + "revision", + "action", + "summary" + ], + "title": "HistoryEntry", + "type": "object" + }, + "Keyframe": { + "additionalProperties": false, + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "property": { + "title": "Property", + "type": "string" + }, + "time": { + "minimum": 0.0, + "title": "Time", + "type": "number" + }, + "value": { + "title": "Value" + }, + "easing": { + "default": "linear", + "title": "Easing", + "type": "string" + } + }, + "required": [ + "property", + "time", + "value" + ], + "title": "Keyframe", + "type": "object" + }, + "Marker": { + "additionalProperties": false, + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "at": { + "minimum": 0.0, + "title": "At", + "type": "number" + }, + "label": { + "default": "", + "title": "Label", + "type": "string" + }, + "color": { + "default": "#FFD54F", + "title": "Color", + "type": "string" + }, + "metadata": { + "additionalProperties": true, + "title": "Metadata", + "type": "object" + } + }, + "required": [ + "at" + ], + "title": "Marker", + "type": "object" + }, + "MediaAsset": { + "additionalProperties": false, + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "kind": { + "$ref": "#/$defs/MediaKind" + }, + "path": { + "title": "Path", + "type": "string" + }, + "original_name": { + "title": "Original Name", + "type": "string" + }, + "size": { + "minimum": 0, + "title": "Size", + "type": "integer" + }, + "sha256": { + "pattern": "^[0-9a-f]{64}$", + "title": "Sha256", + "type": "string" + }, + "imported_at": { + "format": "date-time", + "title": "Imported At", + "type": "string" + }, + "technical": { + "$ref": "#/$defs/MediaTechnicalInfo" + }, + "proxy_path": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Proxy Path" + }, + "offline": { + "default": false, + "title": "Offline", + "type": "boolean" + }, + "metadata": { + "additionalProperties": true, + "title": "Metadata", + "type": "object" + } + }, + "required": [ + "id", + "kind", + "path", + "original_name", + "size", + "sha256" + ], + "title": "MediaAsset", + "type": "object" + }, + "MediaKind": { + "enum": [ + "video", + "audio", + "image", + "subtitle" + ], + "title": "MediaKind", + "type": "string" + }, + "MediaTechnicalInfo": { + "additionalProperties": false, + "properties": { + "container": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Container" + }, + "duration": { + "anyOf": [ + { + "minimum": 0.0, + "type": "number" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Duration" + }, + "bitrate": { + "anyOf": [ + { + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Bitrate" + }, + "video_codec": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Video Codec" + }, + "audio_codec": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Audio Codec" + }, + "width": { + "anyOf": [ + { + "minimum": 1, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Width" + }, + "height": { + "anyOf": [ + { + "minimum": 1, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Height" + }, + "frame_rate": { + "anyOf": [ + { + "exclusiveMinimum": 0.0, + "type": "number" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Frame Rate" + }, + "average_frame_rate": { + "anyOf": [ + { + "exclusiveMinimum": 0.0, + "type": "number" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Average Frame Rate" + }, + "pixel_format": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Pixel Format" + }, + "color_space": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Color Space" + }, + "color_transfer": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Color Transfer" + }, + "color_primaries": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Color Primaries" + }, + "audio_channels": { + "anyOf": [ + { + "minimum": 1, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Audio Channels" + }, + "sample_rate": { + "anyOf": [ + { + "minimum": 1, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Sample Rate" + }, + "rotation": { + "default": 0, + "title": "Rotation", + "type": "integer" + }, + "has_subtitles": { + "default": false, + "title": "Has Subtitles", + "type": "boolean" + }, + "variable_frame_rate": { + "default": false, + "title": "Variable Frame Rate", + "type": "boolean" + }, + "creation_time": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Creation Time" + }, + "keyframes": { + "items": { + "type": "number" + }, + "title": "Keyframes", + "type": "array" + } + }, + "title": "MediaTechnicalInfo", + "type": "object" + }, + "ProjectSettings": { + "additionalProperties": false, + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "name": { + "title": "Name", + "type": "string" + }, + "width": { + "default": 1920, + "maximum": 16384, + "minimum": 16, + "title": "Width", + "type": "integer" + }, + "height": { + "default": 1080, + "maximum": 16384, + "minimum": 16, + "title": "Height", + "type": "integer" + }, + "fps": { + "default": 30.0, + "exclusiveMinimum": 0.0, + "maximum": 240.0, + "title": "Fps", + "type": "number" + }, + "sample_rate": { + "default": 48000, + "maximum": 384000, + "minimum": 8000, + "title": "Sample Rate", + "type": "integer" + }, + "background": { + "default": "#000000", + "pattern": "^#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$", + "title": "Background", + "type": "string" + }, + "duration": { + "default": 0.0, + "minimum": 0.0, + "title": "Duration", + "type": "number" + }, + "created_at": { + "format": "date-time", + "title": "Created At", + "type": "string" + }, + "updated_at": { + "format": "date-time", + "title": "Updated At", + "type": "string" + } + }, + "required": [ + "name" + ], + "title": "ProjectSettings", + "type": "object" + }, + "SubtitleCue": { + "additionalProperties": false, + "description": "One timed subtitle cue attached to a subtitle track.", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "track_id": { + "title": "Track Id", + "type": "string" + }, + "start": { + "minimum": 0.0, + "title": "Start", + "type": "number" + }, + "end": { + "exclusiveMinimum": 0.0, + "title": "End", + "type": "number" + }, + "text": { + "minLength": 1, + "title": "Text", + "type": "string" + }, + "style": { + "anyOf": [ + { + "$ref": "#/$defs/TextStyle" + }, + { + "type": "null" + } + ], + "default": null + }, + "source_identifier": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Source Identifier" + }, + "settings": { + "additionalProperties": { + "type": "string" + }, + "title": "Settings", + "type": "object" + }, + "metadata": { + "additionalProperties": true, + "title": "Metadata", + "type": "object" + } + }, + "required": [ + "track_id", + "start", + "end", + "text" + ], + "title": "SubtitleCue", + "type": "object" + }, + "TextOverlay": { + "additionalProperties": false, + "description": "Timed free text rendered independently of spoken-word subtitles.", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "track_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Track Id" + }, + "text": { + "minLength": 1, + "title": "Text", + "type": "string" + }, + "at": { + "minimum": 0.0, + "title": "At", + "type": "number" + }, + "duration": { + "exclusiveMinimum": 0.0, + "title": "Duration", + "type": "number" + }, + "x": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "default": "center", + "title": "X" + }, + "y": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "default": "80%", + "title": "Y" + }, + "style": { + "$ref": "#/$defs/TextStyle" + }, + "entrance": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Entrance" + }, + "exit": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Exit" + }, + "enabled": { + "default": true, + "title": "Enabled", + "type": "boolean" + }, + "metadata": { + "additionalProperties": true, + "title": "Metadata", + "type": "object" + } + }, + "required": [ + "text", + "at", + "duration" + ], + "title": "TextOverlay", + "type": "object" + }, + "TextStyle": { + "additionalProperties": false, + "description": "Portable styling shared by subtitle cues and free text overlays.", + "properties": { + "font_family": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Font Family" + }, + "font_size": { + "default": 64.0, + "exclusiveMinimum": 0.0, + "title": "Font Size", + "type": "number" + }, + "font_weight": { + "default": "normal", + "title": "Font Weight", + "type": "string" + }, + "color": { + "default": "#FFFFFF", + "pattern": "^#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$", + "title": "Color", + "type": "string" + }, + "stroke_color": { + "default": "#000000", + "pattern": "^#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$", + "title": "Stroke Color", + "type": "string" + }, + "stroke_width": { + "default": 2.0, + "minimum": 0.0, + "title": "Stroke Width", + "type": "number" + }, + "shadow": { + "default": 1.0, + "minimum": 0.0, + "title": "Shadow", + "type": "number" + }, + "background": { + "anyOf": [ + { + "pattern": "^#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Background" + }, + "alignment": { + "default": "center", + "enum": [ + "left", + "center", + "right" + ], + "title": "Alignment", + "type": "string" + }, + "line_spacing": { + "default": 1.0, + "title": "Line Spacing", + "type": "number" + }, + "letter_spacing": { + "default": 0.0, + "title": "Letter Spacing", + "type": "number" + } + }, + "title": "TextStyle", + "type": "object" + }, + "Track": { + "additionalProperties": false, + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "type": { + "$ref": "#/$defs/TrackType" + }, + "name": { + "title": "Name", + "type": "string" + }, + "order": { + "default": 0, + "minimum": 0, + "title": "Order", + "type": "integer" + }, + "enabled": { + "default": true, + "title": "Enabled", + "type": "boolean" + }, + "locked": { + "default": false, + "title": "Locked", + "type": "boolean" + }, + "muted": { + "default": false, + "title": "Muted", + "type": "boolean" + }, + "clips": { + "items": { + "$ref": "#/$defs/Clip" + }, + "title": "Clips", + "type": "array" + }, + "metadata": { + "additionalProperties": true, + "title": "Metadata", + "type": "object" + } + }, + "required": [ + "id", + "type", + "name" + ], + "title": "Track", + "type": "object" + }, + "TrackType": { + "enum": [ + "video", + "audio", + "image", + "subtitle", + "adjustment", + "mask" + ], + "title": "TrackType", + "type": "string" + }, + "Transform": { + "additionalProperties": false, + "properties": { + "x": { + "default": 0.0, + "title": "X", + "type": "number" + }, + "y": { + "default": 0.0, + "title": "Y", + "type": "number" + }, + "scale_x": { + "default": 1.0, + "title": "Scale X", + "type": "number" + }, + "scale_y": { + "default": 1.0, + "title": "Scale Y", + "type": "number" + }, + "rotation": { + "default": 0.0, + "title": "Rotation", + "type": "number" + }, + "anchor_x": { + "default": 0.5, + "title": "Anchor X", + "type": "number" + }, + "anchor_y": { + "default": 0.5, + "title": "Anchor Y", + "type": "number" + }, + "opacity": { + "default": 1.0, + "maximum": 1.0, + "minimum": 0.0, + "title": "Opacity", + "type": "number" + }, + "crop_left": { + "default": 0.0, + "minimum": 0.0, + "title": "Crop Left", + "type": "number" + }, + "crop_top": { + "default": 0.0, + "minimum": 0.0, + "title": "Crop Top", + "type": "number" + }, + "crop_right": { + "default": 0.0, + "minimum": 0.0, + "title": "Crop Right", + "type": "number" + }, + "crop_bottom": { + "default": 0.0, + "minimum": 0.0, + "title": "Crop Bottom", + "type": "number" + }, + "fit": { + "default": "contain", + "enum": [ + "contain", + "cover", + "stretch", + "none" + ], + "title": "Fit", + "type": "string" + }, + "flip_x": { + "default": false, + "title": "Flip X", + "type": "boolean" + }, + "flip_y": { + "default": false, + "title": "Flip Y", + "type": "boolean" + } + }, + "title": "Transform", + "type": "object" + }, + "Transition": { + "additionalProperties": false, + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "type": { + "title": "Type", + "type": "string" + }, + "duration": { + "exclusiveMinimum": 0.0, + "title": "Duration", + "type": "number" + }, + "from_clip_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "From Clip Id" + }, + "to_clip_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "To Clip Id" + }, + "track_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Track Id" + }, + "at": { + "anyOf": [ + { + "minimum": 0.0, + "type": "number" + }, + { + "type": "null" + } + ], + "default": null, + "title": "At" + }, + "parameters": { + "additionalProperties": true, + "title": "Parameters", + "type": "object" + }, + "sound_media_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Sound Media Id" + }, + "sound_offset": { + "default": 0.0, + "title": "Sound Offset", + "type": "number" + } + }, + "required": [ + "type", + "duration" + ], + "title": "Transition", + "type": "object" + } + }, + "additionalProperties": false, + "properties": { + "version": { + "default": "1.0", + "title": "Version", + "type": "string" + }, + "revision": { + "default": 0, + "minimum": 0, + "title": "Revision", + "type": "integer" + }, + "project": { + "$ref": "#/$defs/ProjectSettings" + }, + "media": { + "items": { + "$ref": "#/$defs/MediaAsset" + }, + "title": "Media", + "type": "array" + }, + "tracks": { + "items": { + "$ref": "#/$defs/Track" + }, + "title": "Tracks", + "type": "array" + }, + "transitions": { + "items": { + "$ref": "#/$defs/Transition" + }, + "title": "Transitions", + "type": "array" + }, + "subtitle_cues": { + "items": { + "$ref": "#/$defs/SubtitleCue" + }, + "title": "Subtitle Cues", + "type": "array" + }, + "text_overlays": { + "items": { + "$ref": "#/$defs/TextOverlay" + }, + "title": "Text Overlays", + "type": "array" + }, + "markers": { + "items": { + "$ref": "#/$defs/Marker" + }, + "title": "Markers", + "type": "array" + }, + "settings": { + "additionalProperties": true, + "title": "Settings", + "type": "object" + }, + "history": { + "items": { + "$ref": "#/$defs/HistoryEntry" + }, + "title": "History", + "type": "array" + } + }, + "required": [ + "project" + ], + "title": "ProjectDocument", + "type": "object" +} diff --git a/src/facut/subtitles/__init__.py b/src/facut/subtitles/__init__.py new file mode 100644 index 0000000..b0edae6 --- /dev/null +++ b/src/facut/subtitles/__init__.py @@ -0,0 +1,23 @@ +"""Subtitle parsing, editing, exporting, and render-plan compilation.""" + +from .compiler import SubtitleCompiler +from .formats import ( + ParsedCue, + SubtitleFormatError, + export_srt, + export_vtt, + parse_srt, + parse_subtitle_file, + parse_vtt, +) + +__all__ = [ + "ParsedCue", + "SubtitleCompiler", + "SubtitleFormatError", + "export_srt", + "export_vtt", + "parse_srt", + "parse_subtitle_file", + "parse_vtt", +] diff --git a/src/facut/subtitles/compiler.py b/src/facut/subtitles/compiler.py new file mode 100644 index 0000000..98879ae --- /dev/null +++ b/src/facut/subtitles/compiler.py @@ -0,0 +1,165 @@ +"""Compile project text into an ASS sidecar without coupling to a render backend.""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + +from facut.core.models import ProjectDocument, TextStyle + + +@dataclass(frozen=True, slots=True) +class SubtitleRenderPlan: + """Independent artifact that a render backend may consume later.""" + + format: str + content: str + cue_count: int + text_overlay_count: int + + def write(self, path: str | Path, *, overwrite: bool = False) -> Path: + destination = Path(path) + if destination.exists() and not overwrite: + raise FileExistsError( + f'Output "{destination}" exists; use overwrite to replace it.' + ) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(self.content, encoding="utf-8-sig", newline="\n") + return destination + + +class SubtitleCompiler: + """Compile cues and overlays to a portable Advanced SubStation Alpha file.""" + + def compile(self, document: ProjectDocument) -> SubtitleRenderPlan: + styles: list[TextStyle] = [TextStyle(font_size=52)] + events: list[str] = [] + for cue in sorted(document.subtitle_cues, key=lambda item: (item.start, item.id)): + style = cue.style or styles[0] + style_name = self._style_name(styles, style) + events.append( + self._dialogue(cue.start, cue.end, style_name, self._escape(cue.text)) + ) + for overlay in sorted( + (item for item in document.text_overlays if item.enabled), + key=lambda item: (item.at, item.id), + ): + style_name = self._style_name(styles, overlay.style) + x = self._position(overlay.x, document.project.width, axis="x") + y = self._position(overlay.y, document.project.height, axis="y") + text = f"{{\\an5\\pos({x:.2f},{y:.2f})}}{self._escape(overlay.text)}" + events.append( + self._dialogue( + overlay.at, overlay.end, style_name, text, effect=overlay.entrance or "" + ) + ) + style_lines = [ + self._style_line(f"Style{index}", style) + for index, style in enumerate(styles) + ] + content = "\n".join( + [ + "[Script Info]", + "ScriptType: v4.00+", + f"PlayResX: {document.project.width}", + f"PlayResY: {document.project.height}", + "WrapStyle: 0", + "ScaledBorderAndShadow: yes", + "", + "[V4+ Styles]", + "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, " + "OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, " + "ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, " + "Alignment, MarginL, MarginR, MarginV, Encoding", + *style_lines, + "", + "[Events]", + "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, " + "Effect, Text", + *events, + "", + ] + ) + return SubtitleRenderPlan( + format="ass", + content=content, + cue_count=len(document.subtitle_cues), + text_overlay_count=sum(1 for item in document.text_overlays if item.enabled), + ) + + @staticmethod + def _style_name(styles: list[TextStyle], target: TextStyle) -> str: + for index, style in enumerate(styles): + if style == target: + return f"Style{index}" + styles.append(target) + return f"Style{len(styles) - 1}" + + @staticmethod + def _ass_color(value: str | None, *, default: str = "#00000000") -> str: + value = value or default + raw = value.lstrip("#") + red, green, blue = raw[0:2], raw[2:4], raw[4:6] + alpha = raw[6:8] if len(raw) == 8 else "FF" + ass_alpha = 255 - int(alpha, 16) + return f"&H{ass_alpha:02X}{blue}{green}{red}" + + def _style_line(self, name: str, style: TextStyle) -> str: + bold = -1 if style.font_weight.lower() in {"bold", "600", "700", "800", "900"} else 0 + border_style = 3 if style.background else 1 + alignment = {"left": 1, "center": 2, "right": 3}[style.alignment] + return ( + f"Style: {name},{style.font_family or 'Arial'},{style.font_size:g}," + f"{self._ass_color(style.color)},&H000000FF," + f"{self._ass_color(style.stroke_color)},{self._ass_color(style.background)}," + f"{bold},0,0,0,100,100,{style.letter_spacing:g},0,{border_style}," + f"{style.stroke_width:g},{style.shadow:g},{alignment},40,40,40,1" + ) + + @staticmethod + def _ass_time(seconds: float) -> str: + centiseconds = round(seconds * 100) + hours, remainder = divmod(centiseconds, 360_000) + minutes, remainder = divmod(remainder, 6_000) + whole_seconds, centis = divmod(remainder, 100) + return f"{hours}:{minutes:02d}:{whole_seconds:02d}.{centis:02d}" + + def _dialogue( + self, + start: float, + end: float, + style_name: str, + text: str, + *, + effect: str = "", + ) -> str: + return ( + f"Dialogue: 0,{self._ass_time(start)},{self._ass_time(end)}," + f"{style_name},,0,0,0,{effect},{text}" + ) + + @staticmethod + def _escape(text: str) -> str: + return ( + text.replace("\\", r"\\") + .replace("{", r"\{") + .replace("}", r"\}") + .replace("\r\n", "\n") + .replace("\r", "\n") + .replace("\n", r"\N") + ) + + @staticmethod + def _position(value: float | str, extent: int, *, axis: str) -> float: + if isinstance(value, (int, float)): + return float(value) + normalized = value.lower() + if normalized.endswith("%"): + return float(normalized[:-1]) * extent / 100.0 + named = { + "x": {"left": 0.1, "center": 0.5, "right": 0.9}, + "y": {"top": 0.1, "center": 0.5, "bottom": 0.9}, + } + if normalized in named[axis]: + return named[axis][normalized] * extent + return float(normalized) diff --git a/src/facut/subtitles/editor.py b/src/facut/subtitles/editor.py new file mode 100644 index 0000000..8693983 --- /dev/null +++ b/src/facut/subtitles/editor.py @@ -0,0 +1,131 @@ +"""Non-destructive project operations for subtitles and free text.""" + +from __future__ import annotations + +from collections.abc import Iterable + +from facut.core.models import ( + ProjectDocument, + SubtitleCue, + TextOverlay, + TextStyle, + TrackType, +) +from facut.subtitles.formats import ParsedCue + + +class SubtitleEditError(ValueError): + """A recoverable subtitle timeline validation error.""" + + code = "SUBTITLE_EDIT_ERROR" + + +def require_subtitle_track(document: ProjectDocument, track_id: str): + track = document.find_track(track_id) + if track is None: + raise SubtitleEditError(f'Subtitle track "{track_id}" was not found.') + if track.type != TrackType.SUBTITLE: + raise SubtitleEditError(f'Track "{track_id}" is not a subtitle track.') + if track.locked: + raise SubtitleEditError(f'Subtitle track "{track_id}" is locked.') + return track + + +def import_cues( + document: ProjectDocument, + track_id: str, + parsed_cues: Iterable[ParsedCue], + *, + offset: float = 0.0, + source: str | None = None, +) -> list[SubtitleCue]: + """Append parsed cues to one subtitle track.""" + + require_subtitle_track(document, track_id) + created: list[SubtitleCue] = [] + for parsed in parsed_cues: + start = parsed.start + offset + end = parsed.end + offset + if start < 0: + raise SubtitleEditError("Subtitle offset would move a cue before time zero.") + created.append( + SubtitleCue( + track_id=track_id, + start=start, + end=end, + text=parsed.text, + source_identifier=parsed.identifier, + settings=parsed.settings, + metadata={"source": source} if source else {}, + ) + ) + document.subtitle_cues.extend(created) + document.subtitle_cues.sort(key=lambda cue: (cue.start, cue.end, cue.id)) + document.recompute_duration() + return created + + +def shift_track(document: ProjectDocument, track_id: str, offset: float) -> list[SubtitleCue]: + """Shift all cues on a subtitle track by a signed offset.""" + + require_subtitle_track(document, track_id) + cues = [cue for cue in document.subtitle_cues if cue.track_id == track_id] + if any(cue.start + offset < 0 for cue in cues): + raise SubtitleEditError("Subtitle shift would move a cue before time zero.") + for cue in cues: + cue.start += offset + cue.end += offset + document.subtitle_cues.sort(key=lambda cue: (cue.start, cue.end, cue.id)) + document.recompute_duration() + return cues + + +def remove_cue(document: ProjectDocument, cue_id: str) -> SubtitleCue: + for cue in document.subtitle_cues: + if cue.id == cue_id: + require_subtitle_track(document, cue.track_id) + document.subtitle_cues.remove(cue) + document.recompute_duration() + return cue + raise SubtitleEditError(f'Subtitle cue "{cue_id}" was not found.') + + +def add_text_overlay( + document: ProjectDocument, + *, + text: str, + at: float, + duration: float, + x: float | str = "center", + y: float | str = "80%", + track_id: str | None = None, + style: TextStyle | None = None, + entrance: str | None = None, + exit: str | None = None, +) -> TextOverlay: + if track_id is not None and document.find_track(track_id) is None: + raise SubtitleEditError(f'Track "{track_id}" was not found.') + overlay = TextOverlay( + text=text, + at=at, + duration=duration, + x=x, + y=y, + track_id=track_id, + style=style or TextStyle(), + entrance=entrance, + exit=exit, + ) + document.text_overlays.append(overlay) + document.text_overlays.sort(key=lambda item: (item.at, item.id)) + document.recompute_duration() + return overlay + + +def remove_text_overlay(document: ProjectDocument, overlay_id: str) -> TextOverlay: + for overlay in document.text_overlays: + if overlay.id == overlay_id: + document.text_overlays.remove(overlay) + document.recompute_duration() + return overlay + raise SubtitleEditError(f'Text overlay "{overlay_id}" was not found.') diff --git a/src/facut/subtitles/formats.py b/src/facut/subtitles/formats.py new file mode 100644 index 0000000..f3699ca --- /dev/null +++ b/src/facut/subtitles/formats.py @@ -0,0 +1,256 @@ +"""Deterministic SRT and WebVTT parsing and serialization.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from pathlib import Path +import re +from typing import Iterable + +from facut.core.models import SubtitleCue + + +_SRT_TIMING = re.compile( + r"^(?P\d{1,3}:\d{2}:\d{2}[,.]\d{3})\s*-->\s*" + r"(?P\d{1,3}:\d{2}:\d{2}[,.]\d{3})(?:\s+(?P.*))?$" +) +_VTT_TIMING = re.compile( + r"^(?P(?:\d{1,3}:)?\d{2}:\d{2}\.\d{3})\s*-->\s*" + r"(?P(?:\d{1,3}:)?\d{2}:\d{2}\.\d{3})(?:\s+(?P.*))?$" +) + + +class SubtitleFormatError(ValueError): + """Raised when a subtitle document cannot be parsed safely.""" + + code = "SUBTITLE_PARSE_ERROR" + + +@dataclass(frozen=True, slots=True) +class ParsedCue: + """Renderer-independent cue returned by subtitle parsers.""" + + start: float + end: float + text: str + identifier: str | None = None + settings: dict[str, str] = field(default_factory=dict) + + +def _timestamp_seconds(value: str) -> float: + normalized = value.replace(",", ".") + parts = normalized.split(":") + if len(parts) == 2: + hours = 0 + minutes, seconds = parts + elif len(parts) == 3: + hours, minutes, seconds = parts + else: + raise SubtitleFormatError(f"Invalid subtitle timestamp: {value}") + try: + total = int(hours) * 3600 + int(minutes) * 60 + float(seconds) + except ValueError as exc: + raise SubtitleFormatError(f"Invalid subtitle timestamp: {value}") from exc + if int(minutes) > 59 or float(seconds) >= 60: + raise SubtitleFormatError(f"Invalid subtitle timestamp: {value}") + return total + + +def _settings(value: str | None) -> dict[str, str]: + if not value: + return {} + result: dict[str, str] = {} + for token in value.split(): + if ":" in token: + key, setting = token.split(":", 1) + result[key] = setting + else: + result[token] = "" + return result + + +def _make_cue( + match: re.Match[str], + text_lines: list[str], + identifier: str | None, + *, + block_number: int, +) -> ParsedCue: + text = "\n".join(text_lines).strip() + if not text: + raise SubtitleFormatError(f"Subtitle cue {block_number} has no text.") + start = _timestamp_seconds(match["start"]) + end = _timestamp_seconds(match["end"]) + if end <= start: + raise SubtitleFormatError( + f"Subtitle cue {block_number} must end after it starts." + ) + return ParsedCue( + start=start, + end=end, + text=text, + identifier=identifier, + settings=_settings(match.groupdict().get("settings")), + ) + + +def parse_srt(content: str) -> list[ParsedCue]: + """Parse UTF-decoded SubRip text into ordered cues.""" + + normalized = content.lstrip("\ufeff").replace("\r\n", "\n").replace("\r", "\n") + blocks = re.split(r"\n[ \t]*\n", normalized.strip()) + cues: list[ParsedCue] = [] + for block_number, block in enumerate(blocks, 1): + lines = block.splitlines() + if not lines: + continue + identifier: str | None = None + timing_index = 0 + if not _SRT_TIMING.fullmatch(lines[0].strip()): + identifier = lines[0].strip() or None + timing_index = 1 + if timing_index >= len(lines): + raise SubtitleFormatError(f"Subtitle block {block_number} has no timing line.") + timing = _SRT_TIMING.fullmatch(lines[timing_index].strip()) + if timing is None: + raise SubtitleFormatError( + f"Invalid timing line in subtitle block {block_number}: " + f"{lines[timing_index]!r}" + ) + cues.append( + _make_cue( + timing, + lines[timing_index + 1 :], + identifier, + block_number=block_number, + ) + ) + return cues + + +def parse_vtt(content: str) -> list[ParsedCue]: + """Parse WebVTT, ignoring NOTE/STYLE/REGION metadata blocks.""" + + normalized = content.lstrip("\ufeff").replace("\r\n", "\n").replace("\r", "\n") + lines = normalized.splitlines() + if not lines or not lines[0].strip().startswith("WEBVTT"): + raise SubtitleFormatError("WebVTT input must begin with WEBVTT.") + body_start = 1 + header_end = body_start + while header_end < len(lines) and lines[header_end].strip(): + header_end += 1 + header_metadata = lines[body_start:header_end] + if header_metadata and not any("-->" in line for line in header_metadata): + body_start = min(header_end + 1, len(lines)) + elif body_start < len(lines) and not lines[body_start].strip(): + body_start += 1 + blocks = re.split(r"\n[ \t]*\n", "\n".join(lines[body_start:]).strip()) + cues: list[ParsedCue] = [] + for block_number, block in enumerate(blocks, 1): + block_lines = block.splitlines() + if not block_lines: + continue + first = block_lines[0].strip() + if first.startswith(("NOTE", "STYLE", "REGION")): + continue + identifier: str | None = None + timing_index = 0 + if not _VTT_TIMING.fullmatch(first): + identifier = first or None + timing_index = 1 + if timing_index >= len(block_lines): + raise SubtitleFormatError(f"WebVTT block {block_number} has no timing line.") + timing = _VTT_TIMING.fullmatch(block_lines[timing_index].strip()) + if timing is None: + raise SubtitleFormatError( + f"Invalid timing line in WebVTT block {block_number}: " + f"{block_lines[timing_index]!r}" + ) + cues.append( + _make_cue( + timing, + block_lines[timing_index + 1 :], + identifier, + block_number=block_number, + ) + ) + return cues + + +def _decode_subtitle(path: Path) -> str: + raw = path.read_bytes() + errors: list[str] = [] + for encoding in ("utf-8-sig", "utf-16", "gb18030"): + try: + return raw.decode(encoding) + except UnicodeDecodeError as exc: + errors.append(f"{encoding}: {exc}") + raise SubtitleFormatError( + f'Could not decode subtitle "{path.name}" as UTF-8, UTF-16, or GB18030.' + ) + + +def parse_subtitle_file( + path: str | Path, subtitle_format: str | None = None +) -> list[ParsedCue]: + """Parse an SRT or VTT file selected by option or extension.""" + + source = Path(path).expanduser() + if not source.is_file(): + raise FileNotFoundError(f'Subtitle file "{source}" was not found.') + selected = (subtitle_format or source.suffix.lstrip(".")).lower() + content = _decode_subtitle(source) + if selected == "srt": + return parse_srt(content) + if selected in {"vtt", "webvtt"}: + return parse_vtt(content) + raise SubtitleFormatError( + f'Unsupported subtitle format "{selected}"; use srt or vtt.' + ) + + +def _timecode(seconds: float, separator: str, *, short_hours: bool = False) -> str: + milliseconds = round(seconds * 1000) + hours, remainder = divmod(milliseconds, 3_600_000) + minutes, remainder = divmod(remainder, 60_000) + whole_seconds, millis = divmod(remainder, 1000) + if short_hours and hours == 0: + return f"{minutes:02d}:{whole_seconds:02d}{separator}{millis:03d}" + return f"{hours:02d}:{minutes:02d}:{whole_seconds:02d}{separator}{millis:03d}" + + +def _cue_values(cue: ParsedCue | SubtitleCue) -> tuple[float, float, str, str | None, dict[str, str]]: + if isinstance(cue, ParsedCue): + return cue.start, cue.end, cue.text, cue.identifier, cue.settings + return cue.start, cue.end, cue.text, cue.source_identifier, cue.settings + + +def export_srt(cues: Iterable[ParsedCue | SubtitleCue]) -> str: + """Serialize cues as normalized UTF-8 SubRip text.""" + + blocks: list[str] = [] + for index, cue in enumerate(sorted(cues, key=lambda item: _cue_values(item)[0]), 1): + start, end, text, _, _ = _cue_values(cue) + blocks.append( + f"{index}\n{_timecode(start, ',')} --> {_timecode(end, ',')}\n{text}" + ) + return "\n\n".join(blocks) + ("\n" if blocks else "") + + +def export_vtt(cues: Iterable[ParsedCue | SubtitleCue]) -> str: + """Serialize cues as normalized WebVTT text.""" + + blocks: list[str] = [] + for cue in sorted(cues, key=lambda item: _cue_values(item)[0]): + start, end, text, identifier, settings = _cue_values(cue) + timing = ( + f"{_timecode(start, '.', short_hours=True)} --> " + f"{_timecode(end, '.', short_hours=True)}" + ) + if settings: + timing += " " + " ".join( + f"{key}:{value}" if value else key for key, value in settings.items() + ) + prefix = f"{identifier}\n" if identifier else "" + blocks.append(f"{prefix}{timing}\n{text}") + return "WEBVTT\n\n" + "\n\n".join(blocks) + ("\n" if blocks else "") diff --git a/tests/test_audio_tracks.py b/tests/test_audio_tracks.py new file mode 100644 index 0000000..59dd1fb --- /dev/null +++ b/tests/test_audio_tracks.py @@ -0,0 +1,203 @@ +from __future__ import annotations + +from array import array +import math +import os +from pathlib import Path +import shutil +import subprocess + +import pytest + +from facut.core.models import ( + MediaAsset, + MediaKind, + MediaTechnicalInfo, + ProjectDocument, + ProjectSettings, +) +from facut.core.timeline_engine import TimelineEngine +from facut.render.ffmpeg_backend import FFmpegBackend +from facut.render.graph_builder import GraphBuilder + + +def _modern_ffmpeg() -> tuple[str, str] | None: + candidates = [ + os.environ.get("FACUT_TEST_FFMPEG"), + r"D:\工具\jianyin\JianyingPro\9.3.0.13547\ffmpeg.exe", + shutil.which("ffmpeg"), + ] + for candidate in candidates: + if not candidate or not Path(candidate).is_file(): + continue + filters = subprocess.run( + [candidate, "-hide_banner", "-filters"], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + ) + encoders = subprocess.run( + [candidate, "-hide_banner", "-encoders"], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + ) + if " amix " not in filters.stdout or " aloop " not in filters.stdout: + continue + if " libx264 " in encoders.stdout: + return str(candidate), "none" + if " h264_qsv " in encoders.stdout: + return str(candidate), "qsv" + return None + + +def _project(root: Path) -> tuple[ProjectDocument, str]: + document = ProjectDocument( + project=ProjectSettings(name="audio-test", width=320, height=180, fps=30), + media=[ + MediaAsset( + id="camera", + kind=MediaKind.VIDEO, + path="camera.mp4", + original_name="camera.mp4", + size=(root / "camera.mp4").stat().st_size, + sha256="1" * 64, + technical=MediaTechnicalInfo(duration=3, audio_codec="aac"), + ), + MediaAsset( + id="music", + kind=MediaKind.AUDIO, + path="music.wav", + original_name="music.wav", + size=(root / "music.wav").stat().st_size, + sha256="2" * 64, + technical=MediaTechnicalInfo( + duration=1, audio_codec="pcm_s16le", sample_rate=48000 + ), + ), + ], + ) + timeline = TimelineEngine(document) + timeline.add_track("video", "V1") + timeline.add_clip("camera", "V1", source_out=3) + timeline.add_track("audio", "A1") + music = timeline.add_audio_clip( + "music", + "A1", + volume_db=-12, + fade_in=0.2, + fade_out=0.2, + loop=True, + ) + return document, music.id + + +def _tone_strength(samples: array, frequency: float, rate: int = 48000) -> float: + real = 0.0 + imaginary = 0.0 + for index, sample in enumerate(samples): + angle = 2 * math.pi * frequency * index / rate + real += sample * math.cos(angle) + imaginary += sample * math.sin(angle) + return math.hypot(real, imaginary) / len(samples) + + +def test_audio_track_builds_loop_fades_gain_and_mix(tmp_path: Path) -> None: + (tmp_path / "camera.mp4").write_bytes(b"video") + (tmp_path / "music.wav").write_bytes(b"audio") + document, music_id = _project(tmp_path) + clip = document.find_clip(music_id) + assert clip is not None + assert clip.duration == pytest.approx(3) + graph = GraphBuilder(document, tmp_path).build() + assert "aloop=loop=-1" in graph.filter_complex + assert "volume=-12dB" in graph.filter_complex + assert "afade=t=in:st=0:d=0.2" in graph.filter_complex + assert "afade=t=out:st=2.8:d=0.2" in graph.filter_complex + assert "amix=inputs=2:duration=first" in graph.filter_complex + + +def test_real_ffmpeg_mix_keeps_original_and_looped_music(tmp_path: Path) -> None: + tool = _modern_ffmpeg() + if tool is None: + pytest.skip("No FFmpeg with aloop/amix and H.264 encoder is available") + ffmpeg, hardware = tool + encoder = "libx264" if hardware == "none" else "h264_qsv" + subprocess.run( + [ + ffmpeg, + "-hide_banner", + "-loglevel", + "error", + "-f", + "lavfi", + "-i", + "color=c=navy:s=320x180:r=30:d=3", + "-f", + "lavfi", + "-i", + "sine=frequency=440:sample_rate=48000:duration=3", + "-shortest", + "-c:v", + encoder, + "-pix_fmt", + "yuv420p", + "-c:a", + "aac", + "-y", + str(tmp_path / "camera.mp4"), + ], + check=True, + ) + subprocess.run( + [ + ffmpeg, + "-hide_banner", + "-loglevel", + "error", + "-f", + "lavfi", + "-i", + "sine=frequency=880:sample_rate=48000:duration=1", + "-c:a", + "pcm_s16le", + "-y", + str(tmp_path / "music.wav"), + ], + check=True, + ) + document, _ = _project(tmp_path) + output = tmp_path / "mixed.mp4" + FFmpegBackend(ffmpeg).render( + document, tmp_path, output, hardware=hardware, overwrite=False + ) + decoded = subprocess.run( + [ + ffmpeg, + "-hide_banner", + "-loglevel", + "error", + "-ss", + "2.2", + "-t", + "0.5", + "-i", + str(output), + "-vn", + "-ac", + "1", + "-ar", + "48000", + "-f", + "f32le", + "pipe:1", + ], + capture_output=True, + check=True, + ).stdout + samples = array("f") + samples.frombytes(decoded) + assert _tone_strength(samples, 440) > 0.01, "camera audio was lost" + assert _tone_strength(samples, 880) > 0.003, "looped music was not mixed" diff --git a/tests/test_phase1_cli.py b/tests/test_phase1_cli.py index 728f1e6..399567b 100644 --- a/tests/test_phase1_cli.py +++ b/tests/test_phase1_cli.py @@ -10,7 +10,12 @@ def test_help_lists_doctor_and_global_options() -> None: - result = runner.invoke(app, ["--help"]) + result = runner.invoke( + app, + ["--help"], + env={"COLUMNS": "140"}, + terminal_width=140, + ) assert result.exit_code == 0 assert "doctor" in result.stdout assert "--project" in result.stdout diff --git a/tests/test_render_core.py b/tests/test_render_core.py index 2c21c7e..01d70c4 100644 --- a/tests/test_render_core.py +++ b/tests/test_render_core.py @@ -14,6 +14,9 @@ MediaTechnicalInfo, ProjectDocument, ProjectSettings, + SubtitleCue, + TextOverlay, + TextStyle, ) from facut.core.timeline_engine import TimelineEngine from facut.render.cache import cache_key @@ -163,6 +166,26 @@ def test_render_and_range_preview_are_playable(tmp_path: Path) -> None: check=True, ) document = _document(tmp_path) + TimelineEngine(document).add_track("subtitle", "S1") + document.subtitle_cues.append( + SubtitleCue( + track_id="S1", + start=1.1, + end=1.4, + text="CAPTION", + style=TextStyle(font_size=32, color="#FFFFFF", stroke_width=2), + ) + ) + document.text_overlays.append( + TextOverlay( + text="FACUT", + at=0.2, + duration=0.8, + x="center", + y="center", + style=TextStyle(font_size=52, color="#FFFFFF", stroke_width=2), + ) + ) backend = FFmpegBackend(ffmpeg) final = backend.render( document, @@ -199,6 +222,60 @@ def test_render_and_range_preview_are_playable(tmp_path: Path) -> None: ) duration = float(json.loads(probe.stdout)["format"]["duration"]) assert duration == pytest.approx(expected, abs=0.12) + title_frame = subprocess.run( + [ + ffmpeg, + "-hide_banner", + "-loglevel", + "error", + "-ss", + "0.5", + "-i", + str(final.output), + "-frames:v", + "1", + "-pix_fmt", + "rgb24", + "-f", + "rawvideo", + "pipe:1", + ], + capture_output=True, + check=True, + ).stdout + bright_pixels = sum( + 1 + for index in range(0, len(title_frame), 3) + if all(channel > 180 for channel in title_frame[index : index + 3]) + ) + assert bright_pixels > 20, "text overlay was not burned into the output" + subtitle_frame = subprocess.run( + [ + ffmpeg, + "-hide_banner", + "-loglevel", + "error", + "-ss", + "1.25", + "-i", + str(final.output), + "-frames:v", + "1", + "-pix_fmt", + "rgb24", + "-f", + "rawvideo", + "pipe:1", + ], + capture_output=True, + check=True, + ).stdout + subtitle_bright_pixels = sum( + 1 + for index in range(0, len(subtitle_frame), 3) + if all(channel > 180 for channel in subtitle_frame[index : index + 3]) + ) + assert subtitle_bright_pixels > 20, "subtitle cue was not burned into the output" midpoint = subprocess.run( [ ffmpeg, diff --git a/tests/test_subtitle_cli.py b/tests/test_subtitle_cli.py new file mode 100644 index 0000000..99a35bf --- /dev/null +++ b/tests/test_subtitle_cli.py @@ -0,0 +1,154 @@ +"""End-to-end subtitle and text CLI tests.""" + +from __future__ import annotations + +import json + +from typer.testing import CliRunner + +from facut.cli.main import app + + +runner = CliRunner() + + +def _json(result): + assert result.exit_code == 0, result.output + return json.loads(result.stdout) + + +def test_import_shift_export_text_and_compile(tmp_path) -> None: + project = tmp_path / "demo" + _json(runner.invoke(app, ["--json", "init", str(project)])) + _json( + runner.invoke( + app, + [ + "--project", + str(project), + "--json", + "timeline", + "track", + "add", + "--type", + "subtitle", + "--name", + "S1", + ], + ) + ) + source = tmp_path / "captions.srt" + source.write_text( + "1\n00:00:00,500 --> 00:00:01,500\n你好\n\n" + "2\n00:00:02,000 --> 00:00:03,000\n世界\n", + encoding="utf-8", + ) + imported = _json( + runner.invoke( + app, + [ + "--project", + str(project), + "--json", + "subtitle", + "import", + str(source), + "--track", + "S1", + "--offset", + "+500ms", + ], + ) + ) + assert len(imported["data"]["result"]) == 2 + assert imported["project_revision"] == 2 + + shifted = _json( + runner.invoke( + app, + [ + "--project", + str(project), + "--json", + "subtitle", + "shift", + "S1", + "--offset", + "+250ms", + "--dry-run", + ], + ) + ) + assert shifted["data"]["dry_run"] is True + + listed = _json( + runner.invoke( + app, + ["--project", str(project), "--json", "subtitle", "list", "--track", "S1"], + ) + ) + assert listed["data"][0]["start"] == 1.0 + + output = tmp_path / "captions.vtt" + exported = _json( + runner.invoke( + app, + [ + "--project", + str(project), + "--json", + "subtitle", + "export", + "S1", + "--output", + str(output), + ], + ) + ) + assert exported["data"]["cue_count"] == 2 + assert output.read_text(encoding="utf-8").startswith("WEBVTT") + + overlay = _json( + runner.invoke( + app, + [ + "--project", + str(project), + "--json", + "text", + "add", + "--text", + "临港两日", + "--at", + "0", + "--duration", + "2s", + "--x", + "center", + "--y", + "20%", + "--font-size", + "72", + ], + ) + ) + assert overlay["data"]["result"]["style"]["font_size"] == 72.0 + + ass = tmp_path / "captions.ass" + compiled = _json( + runner.invoke( + app, + [ + "--project", + str(project), + "--json", + "subtitle", + "compile-ass", + "--output", + str(ass), + ], + ) + ) + assert compiled["data"]["cue_count"] == 2 + assert compiled["data"]["text_overlay_count"] == 1 + assert "[Events]" in ass.read_text(encoding="utf-8-sig") diff --git a/tests/test_subtitle_editor.py b/tests/test_subtitle_editor.py new file mode 100644 index 0000000..0f06dde --- /dev/null +++ b/tests/test_subtitle_editor.py @@ -0,0 +1,76 @@ +"""Project subtitle and text overlay tests.""" + +from __future__ import annotations + +import pytest + +from facut.core.models import ProjectDocument, ProjectSettings, Track, TrackType +from facut.subtitles.compiler import SubtitleCompiler +from facut.subtitles.editor import ( + SubtitleEditError, + add_text_overlay, + import_cues, + shift_track, +) +from facut.subtitles.formats import ParsedCue + + +def _project() -> ProjectDocument: + return ProjectDocument( + project=ProjectSettings(name="captions", width=1920, height=1080), + tracks=[ + Track(id="S1", type=TrackType.SUBTITLE, name="Captions"), + Track(id="V1", type=TrackType.VIDEO, name="Video", order=1), + ], + ) + + +def test_import_shift_and_project_round_trip() -> None: + project = _project() + created = import_cues( + project, + "S1", + [ + ParsedCue(0.5, 1.5, "你好"), + ParsedCue(2.0, 3.0, "再见", settings={"align": "middle"}), + ], + offset=0.25, + source="captions.srt", + ) + assert [cue.start for cue in created] == [0.75, 2.25] + assert project.project.duration == 3.25 + + shifted = shift_track(project, "S1", 0.5) + assert [cue.start for cue in shifted] == [1.25, 2.75] + restored = ProjectDocument.model_validate_json(project.model_dump_json()) + assert restored.subtitle_cues[0].text == "你好" + + +def test_wrong_track_and_negative_shift_are_rejected() -> None: + project = _project() + with pytest.raises(SubtitleEditError, match="not a subtitle"): + import_cues(project, "V1", [ParsedCue(0, 1, "bad")]) + import_cues(project, "S1", [ParsedCue(0.1, 1, "early")]) + with pytest.raises(SubtitleEditError, match="before time zero"): + shift_track(project, "S1", -0.2) + + +def test_ass_compiler_includes_cues_and_positioned_text() -> None: + project = _project() + import_cues(project, "S1", [ParsedCue(1, 2, "Line 1\nLine 2")]) + add_text_overlay( + project, + text="临港 VLOG", + at=0, + duration=2, + x="50%", + y="20%", + ) + plan = SubtitleCompiler().compile(project) + assert plan.format == "ass" + assert plan.cue_count == 1 + assert plan.text_overlay_count == 1 + assert r"Line 1\NLine 2" in plan.content + assert r"\pos(960.00,216.00)" in plan.content + assert "临港 VLOG" in plan.content + diff --git a/tests/test_subtitle_formats.py b/tests/test_subtitle_formats.py new file mode 100644 index 0000000..dbb8d75 --- /dev/null +++ b/tests/test_subtitle_formats.py @@ -0,0 +1,62 @@ +"""Subtitle parser and serializer tests.""" + +from __future__ import annotations + +import pytest + +from facut.subtitles.formats import ( + SubtitleFormatError, + export_srt, + export_vtt, + parse_srt, + parse_vtt, +) + + +def test_srt_multiline_round_trip() -> None: + cues = parse_srt( + "\ufeff1\r\n00:00:01,250 --> 00:00:03,500\r\n第一行\r\n第二行\r\n\r\n" + "2\r\n00:01:04.000 --> 00:01:05.125\r\nDone\r\n" + ) + assert len(cues) == 2 + assert cues[0].start == 1.25 + assert cues[0].end == 3.5 + assert cues[0].text == "第一行\n第二行" + assert cues[0].identifier == "1" + + rendered = export_srt(cues) + assert "00:00:01,250 --> 00:00:03,500" in rendered + assert rendered.endswith("\n") + reparsed = parse_srt(rendered) + assert [(cue.start, cue.end, cue.text) for cue in reparsed] == [ + (cue.start, cue.end, cue.text) for cue in cues + ] + + +def test_webvtt_metadata_settings_and_round_trip() -> None: + cues = parse_vtt( + "WEBVTT - facut\nLanguage: zh-CN\nKind: captions\n\n" + "NOTE generated fixture\nignore this\n\n" + "intro\n00:01.000 --> 00:03.250 align:start position:10%\nHello\nworld\n" + ) + assert len(cues) == 1 + assert cues[0].identifier == "intro" + assert cues[0].settings == {"align": "start", "position": "10%"} + + rendered = export_vtt(cues) + assert rendered.startswith("WEBVTT\n\n") + assert "00:01.000 --> 00:03.250 align:start position:10%" in rendered + assert parse_vtt(rendered)[0] == cues[0] + + +@pytest.mark.parametrize( + "content", + [ + "1\n00:00:02,000 --> 00:00:01,000\nBackwards\n", + "1\nnot a timing line\nBroken\n", + "1\n00:00:01,000 --> 00:00:02,000\n", + ], +) +def test_invalid_srt_is_rejected(content: str) -> None: + with pytest.raises(SubtitleFormatError): + parse_srt(content) From 3ba5b3817e69ec20058bafac4320f344359f5c59 Mon Sep 17 00:00:00 2001 From: SystemZion Date: Fri, 31 Jul 2026 17:27:14 +0800 Subject: [PATCH 2/2] Stabilize CLI help test --- tests/test_phase1_cli.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/test_phase1_cli.py b/tests/test_phase1_cli.py index 399567b..c3fa9e4 100644 --- a/tests/test_phase1_cli.py +++ b/tests/test_phase1_cli.py @@ -3,6 +3,7 @@ import json from typer.testing import CliRunner +from typer.main import get_command from facut.cli.main import app @@ -18,8 +19,13 @@ def test_help_lists_doctor_and_global_options() -> None: ) assert result.exit_code == 0 assert "doctor" in result.stdout - assert "--project" in result.stdout - assert "--json" in result.stdout + registered_options = { + option + for parameter in get_command(app).params + for option in getattr(parameter, "opts", ()) + } + assert "--project" in registered_options + assert "--json" in registered_options def test_version() -> None: