Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

refactor(media): 抽帧与拼图收进 peach.frame_capture

longmeidao74dea6caf597
diff --git a/scripts/sheets.py b/scripts/sheets.py
index d4d119d5e..bf9468725 100644
--- a/scripts/sheets.py
+++ b/scripts/sheets.py
@@ -5,10 +5,8 @@ from __future__ import annotations
import argparse
import hashlib
import queue
-import re
import shutil
import sqlite3
-import subprocess
import tempfile
import threading
import time
@@ -21,6 +19,7 @@ SRC_DIR = PROJECT_ROOT / "src"
if str(SRC_DIR) not in sys.path:
sys.path.insert(0, str(SRC_DIR))
+from peach import frame_capture
from peach.config import DATABASE_PATH, FFMPEG_DIR, GENERATED_DIR, LOG_DIR, STATE_DIR
from peach.ffmpeg import FFmpegResolver
from peach.jobs import (
@@ -71,35 +70,20 @@ def output_path(output_root: Path, location: str, path: str) -> Path:
return directory / f"{digest}.jpg"
-COLOR_OVERRIDE = ["-color_primaries", "bt709", "-color_trc", "bt709", "-colorspace", "bt709"]
-
-# 只有坏色彩元数据才值得用 bt709 覆盖重试。无条件重试会让网盘超时这类必然失败的文件
-# 每帧都白跑第二次:单帧最坏耗时从 45 秒翻到 90 秒,9 帧就是 13.5 分钟。
-COLOR_METADATA_ERROR = re.compile(
- r"(reserved|unsupported|invalid)[^\n]{0,60}(color|primaries|trc|space)"
- r"|(color|primaries|trc|space)[^\n]{0,60}(reserved|unsupported|invalid)",
- re.IGNORECASE,
-)
+COLOR_OVERRIDE = frame_capture.COLOR_OVERRIDE
+COLOR_METADATA_ERROR = frame_capture.COLOR_METADATA_ERROR
def _capture_frame(ffmpeg: str, path: str, timestamp: float, destination: Path,
color_override: bool) -> tuple[bool, str]:
- """抽一帧,返回(是否成功, stderr)。stderr 用于判断值不值得重试。"""
- command = [ffmpeg, "-y", "-v", "error", "-rw_timeout", "8000000"]
- if color_override:
- # 部分网盘视频把色彩原色写成 reserved(非法值),swscale 会拒绝缩放;
- # 声明为 bt709 只是覆盖坏的元数据,不改动像素。
- command += COLOR_OVERRIDE
- command += [
- "-ss", f"{timestamp:.2f}", "-i", path, "-frames:v", "1",
- "-vf", "scale=480:-1", "-q:v", "4", str(destination),
- ]
- try:
- completed = subprocess.run(command, capture_output=True, timeout=45)
- except subprocess.TimeoutExpired:
- return False, "ffmpeg timeout"
- ok = destination.is_file() and destination.stat().st_size > 1024
- return ok, (completed.stderr or b"").decode("utf-8", "replace")
+ """抽一帧,返回(是否成功, stderr)。stderr 用于判断值不值得重试。
+
+ 命令本身在 `peach.frame_capture`,时间轴预览走的是同一条。色彩元数据那条重试判据
+ 只写一处:分成两份之后,坏元数据的那批片子会只在其中一份里被认出来,而失败形态是
+ 「这些片子没有图」,看不出是哪一份少了一条。
+ """
+ return frame_capture.capture_frame(ffmpeg, path, timestamp, destination,
+ width=480, color_override=color_override)
def make_sheet(ffmpeg: str, path: str, duration: float, destination: Path,
@@ -131,16 +115,8 @@ def make_sheet(ffmpeg: str, path: str, duration: float, destination: Path,
if frame != target:
frame.replace(target)
rows = (len(captured) + 2) // 3
- destination.parent.mkdir(parents=True, exist_ok=True)
- subprocess.run(
- [
- ffmpeg, "-y", "-v", "error", "-i", str(temporary / "s%02d.jpg"),
- "-filter_complex", f"tile=3x{rows}", "-q:v", "4", str(destination),
- ],
- capture_output=True,
- timeout=60,
- )
- if destination.is_file() and destination.stat().st_size > 4096:
+ if frame_capture.tile_frames(ffmpeg, str(temporary / "s%02d.jpg"), 3, rows,
+ destination):
return True, ""
return False, "tile_failed"
finally:
diff --git a/src/peach/frame_capture.py b/src/peach/frame_capture.py
new file mode 100644
index 000000000..419e4f176
--- /dev/null
+++ b/src/peach/frame_capture.py
@@ -0,0 +1,74 @@
+"""按时间点抽单帧、把若干帧拼成一张接触印相。
+
+九宫格(`scripts/sheets.py`)和时间轴预览(`timeline_sheets`)要的是同一件事:在给定
+时间点取一帧、缩到固定宽度、若干帧拼成一张图。两处各写一份的代价不是重复,而是分叉
+——网盘上那批坏色彩元数据的片子只在其中一份里被认出来并重试,另一份就永远少一批图,
+而失败形态是「这些片子没有预览」,看不出是哪一份的判据少了一条。
+"""
+from __future__ import annotations
+
+import re
+import subprocess
+from pathlib import Path
+
+#: 部分网盘视频把色彩原色写成 reserved(非法值),swscale 会拒绝缩放;声明为 bt709
+#: 只是覆盖坏的元数据,不改动像素。
+COLOR_OVERRIDE = ["-color_primaries", "bt709", "-color_trc", "bt709", "-colorspace", "bt709"]
+
+#: 只有坏色彩元数据才值得用 bt709 覆盖重试。无条件重试会让网盘超时这类必然失败的文件
+#: 每帧都白跑第二次:单帧最坏耗时从 45 秒翻到 90 秒,9 帧就是 13.5 分钟。
+COLOR_METADATA_ERROR = re.compile(
+ r"(reserved|unsupported|invalid)[^\n]{0,60}(color|primaries|trc|space)"
+ r"|(color|primaries|trc|space)[^\n]{0,60}(reserved|unsupported|invalid)",
+ re.IGNORECASE,
+)
+
+
+def capture_frame(ffmpeg: str, path: str, timestamp: float, destination: Path, *,
+ width: int = 480, color_override: bool = False,
+ timeout: float = 45) -> tuple[bool, str]:
+ """抽一帧,返回(是否成功, stderr)。stderr 用于判断值不值得重试。
+
+ `-ss` 在 `-i` 之前:那是输入端 seek,只解目标附近的帧。放到后面就是从头解码到
+ 那个时间点,两小时的片子抽最后一帧要几分钟。
+ """
+ command = [ffmpeg, "-y", "-v", "error", "-rw_timeout", "8000000"]
+ if color_override:
+ command += COLOR_OVERRIDE
+ command += [
+ "-ss", f"{timestamp:.2f}", "-i", path, "-frames:v", "1",
+ "-vf", f"scale={int(width)}:-1", "-q:v", "4", str(destination),
+ ]
+ try:
+ completed = subprocess.run(command, capture_output=True, timeout=timeout)
+ except subprocess.TimeoutExpired:
+ return False, "ffmpeg timeout"
+ ok = destination.is_file() and destination.stat().st_size > 1024
+ return ok, (completed.stderr or b"").decode("utf-8", "replace")
+
+
+def capture_with_retry(ffmpeg: str, path: str, timestamp: float, destination: Path,
+ *, width: int = 480, timeout: float = 45) -> bool:
+ """抽一帧;只在错误明说色彩元数据不合法时,带 bt709 声明重试一次。"""
+ ok, stderr = capture_frame(ffmpeg, path, timestamp, destination,
+ width=width, timeout=timeout)
+ if not ok and COLOR_METADATA_ERROR.search(stderr):
+ ok, _ = capture_frame(ffmpeg, path, timestamp, destination,
+ width=width, color_override=True, timeout=timeout)
+ return ok
+
+
+def tile_frames(ffmpeg: str, pattern: str, columns: int, rows: int, destination: Path,
+ *, timeout: float = 60) -> bool:
+ """把 `pattern`(形如 `dir/s%02d.jpg`)指的那串帧拼成 columns×rows 一张。
+
+ 帧要先按连续序号改好名再进来:`image2` 读的是序号序列,中间缺一个号它就在那里停下,
+ 于是拼出来的图少了后半段,而命令本身照样退出 0。
+ """
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ subprocess.run(
+ [ffmpeg, "-y", "-v", "error", "-i", pattern,
+ "-filter_complex", f"tile={int(columns)}x{int(rows)}", "-q:v", "4", str(destination)],
+ capture_output=True, timeout=timeout,
+ )
+ return destination.is_file() and destination.stat().st_size > 4096
diff --git a/tests/test_frame_capture.py b/tests/test_frame_capture.py
new file mode 100644
index 000000000..853f33c95
--- /dev/null
+++ b/tests/test_frame_capture.py
@@ -0,0 +1,111 @@
+"""按时间点抽单帧、把若干帧拼成一张接触印相。九宫格与时间轴预览共用这一份。"""
+from __future__ import annotations
+
+import shutil
+import subprocess
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+from peach import frame_capture
+
+
+class _Completed:
+ def __init__(self, stderr: bytes = b""):
+ self.stderr = stderr
+ self.returncode = 0
+
+
+class CaptureFrameTests(unittest.TestCase):
+ def setUp(self):
+ self.root = Path(tempfile.mkdtemp(prefix="frame-capture-"))
+ self.addCleanup(lambda: shutil.rmtree(self.root, ignore_errors=True))
+ self.commands: list[list[str]] = []
+
+ def _run(self, produce: bool = True, stderr: bytes = b""):
+ def fake(command, **_kwargs):
+ self.commands.append(list(command))
+ if produce:
+ Path(command[-1]).write_bytes(b"x" * 2048)
+ return _Completed(stderr)
+ return patch.object(frame_capture.subprocess, "run", fake)
+
+ def test_the_seek_happens_before_the_input_so_only_that_part_is_decoded(self):
+ """`-ss` 放到 `-i` 后面就是从头解码到那个时间点,两小时的片子抽最后一帧要几分钟。"""
+ with self._run():
+ ok, _ = frame_capture.capture_frame("ffmpeg", "movie.mp4", 61.5,
+ self.root / "one.jpg", width=320)
+ self.assertTrue(ok)
+ command = self.commands[0]
+ self.assertLess(command.index("-ss"), command.index("-i"))
+ self.assertIn("scale=320:-1", command)
+ self.assertNotIn("bt709", command)
+
+ def test_a_frame_too_small_to_be_a_picture_does_not_count_as_taken(self):
+ """命令退出 0 不等于出了图。写了个几百字节的壳,页面上就是一块灰。"""
+ def fake(command, **_kwargs):
+ Path(command[-1]).write_bytes(b"x" * 64)
+ return _Completed()
+ with patch.object(frame_capture.subprocess, "run", fake):
+ ok, _ = frame_capture.capture_frame("ffmpeg", "movie.mp4", 1.0,
+ self.root / "small.jpg")
+ self.assertFalse(ok)
+
+ def test_a_timeout_is_reported_as_a_failure_not_an_exception(self):
+ def fake(_command, **_kwargs):
+ raise subprocess.TimeoutExpired("ffmpeg", 45)
+ with patch.object(frame_capture.subprocess, "run", fake):
+ ok, stderr = frame_capture.capture_frame("ffmpeg", "movie.mp4", 1.0,
+ self.root / "late.jpg")
+ self.assertFalse(ok)
+ self.assertEqual(stderr, "ffmpeg timeout")
+
+ def test_only_bad_color_metadata_is_worth_a_second_try(self):
+ """无条件重试会让网盘超时这类必然失败的文件每帧白跑第二次:单帧最坏耗时从
+ 45 秒翻到 90 秒,9 帧就是 13.5 分钟。"""
+ for stderr, attempts in (
+ (b"[swscale] Unsupported color primaries: reserved", 2),
+ (b"color_trc reserved is invalid", 2),
+ (b"Error opening input: Input/output error", 1),
+ (b"", 1),
+ ):
+ self.commands = []
+ with self._run(produce=False, stderr=stderr):
+ ok = frame_capture.capture_with_retry("ffmpeg", "movie.mp4", 1.0,
+ self.root / "retry.jpg")
+ self.assertFalse(ok)
+ self.assertEqual(len(self.commands), attempts, stderr)
+ if attempts == 2:
+ self.assertIn("bt709", self.commands[1])
+
+
+class TileFramesTests(unittest.TestCase):
+ def setUp(self):
+ self.root = Path(tempfile.mkdtemp(prefix="frame-tile-"))
+ self.addCleanup(lambda: shutil.rmtree(self.root, ignore_errors=True))
+
+ def test_the_grid_size_reaches_the_filter(self):
+ seen: list[list[str]] = []
+
+ def fake(command, **_kwargs):
+ seen.append(list(command))
+ Path(command[-1]).write_bytes(b"x" * 8192)
+ return _Completed()
+
+ with patch.object(frame_capture.subprocess, "run", fake):
+ made = frame_capture.tile_frames("ffmpeg", str(self.root / "s%03d.jpg"), 10, 7,
+ self.root / "out" / "000.jpg")
+ self.assertTrue(made)
+ self.assertIn("tile=10x7", seen[0])
+
+ def test_a_tile_that_did_not_land_is_not_reported_as_made(self):
+ with patch.object(frame_capture.subprocess, "run",
+ lambda command, **_kwargs: _Completed()):
+ made = frame_capture.tile_frames("ffmpeg", str(self.root / "s%03d.jpg"), 3, 3,
+ self.root / "out" / "000.jpg")
+ self.assertFalse(made)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_scripts.py b/tests/test_scripts.py
index ccf6f70d2..422e9e08f 100644
--- a/tests/test_scripts.py
+++ b/tests/test_scripts.py
@@ -1718,12 +1718,13 @@ class OperationalScriptTests(unittest.TestCase):
"stderr": b"[swscale] Unsupported color primaries: reserved",
})()
- original = sheets.subprocess.run
- sheets.subprocess.run = fake_run
+ capture = sheets.frame_capture
+ original = capture.subprocess.run
+ capture.subprocess.run = fake_run
try:
ok, reason = sheets.make_sheet("ffmpeg", "reserved.mp4", 600.0, dest, 9)
finally:
- sheets.subprocess.run = original
+ capture.subprocess.run = original
self.assertTrue(ok, reason)
self.assertEqual(
sum(1 for c in calls if "bt709" in c), 9,