Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(playback): 按解码活动判定长片探测停滞并报告进度

longmeidao1c49ff464103
diff --git a/src/peach/mp4repair.py b/src/peach/mp4repair.py
index a9137b503..01209e84a 100644
--- a/src/peach/mp4repair.py
+++ b/src/peach/mp4repair.py
@@ -30,7 +30,8 @@ LOGGER = logging.getLogger(__name__)
CONTAINERS = frozenset({b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts"})
#: 头部盒子加起来的上限;超过这个数就不是我们认识的片源,宁可不修。
HEADER_LIMIT = 64 << 20
-PROBE_TIMEOUT_SECONDS = 900
+#: 连续没有任何解码输出的等待时间;整片解码不按片长限制总耗时。
+PROBE_IDLE_SECONDS = 900
SIDECAR_MAGIC = b"PEACHMP4\x02"
LEGACY_SIDECAR_MAGIC = b"PEACHMP4\x01"
SIDECAR_SUFFIX = ".mp4hdr"
@@ -137,7 +138,7 @@ def _decode_times(stts: bytes) -> list[int]:
return times
-def _display_order(ffprobe: Path, source: Path, decode_times: list[int]) -> list[int]:
+def _display_order(ffprobe: Path, source: Path, decode_times: list[int], *, progress=None) -> list[int]:
"""每个样本(解码序)的显示名次。
解码器吐出来的帧就是显示顺序,每帧的 `pts` 原样来自它那个样本;这里 pts 就等于 dts,
@@ -157,10 +158,21 @@ def _display_order(ffprobe: Path, source: Path, decode_times: list[int]) -> list
"-ignore_editlist", "1", "-select_streams", "v:0",
"-show_entries", "frame=pts", "-of", "csv=p=0", input_url(source),
)
+ frames = 0
+
+ def report(chunk):
+ nonlocal frames
+ frames += chunk.count(b'\n')
+ if progress is not None:
+ progress(min(frames, len(decode_times)), len(decode_times))
+
try:
- completed = run_task_process(command, capture_output=True, timeout=PROBE_TIMEOUT_SECONDS,
+ completed = run_task_process(command, capture_output=True, idle_timeout=PROBE_IDLE_SECONDS,
+ on_stdout=report,
creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0)
- except (OSError, subprocess.TimeoutExpired) as exc:
+ except subprocess.TimeoutExpired as exc:
+ raise RepairUnavailable(f"ffprobe 连续 {PROBE_IDLE_SECONDS} 秒没有解码输出") from exc
+ except OSError as exc:
raise RepairUnavailable(f"ffprobe 没跑完:{exc}") from exc
if completed.returncode:
raise RepairUnavailable(f"ffprobe 退出码 {completed.returncode}")
@@ -356,7 +368,7 @@ def _layout(source: Path) -> _Layout:
after[start:stop], moov[2] - moov[1], None)
-def repaired_header(source: Path, ffprobe: Path) -> RepairedHeader:
+def repaired_header(source: Path, ffprobe: Path, *, progress=None) -> RepairedHeader:
"""算出修好的头。修不了就抛 `RepairUnavailable`。"""
layout = _layout(source)
mdat = layout.mdat
@@ -375,7 +387,7 @@ def repaired_header(source: Path, ffprobe: Path) -> RepairedHeader:
decode_times = _decode_times(stts.payload)
offsets, shift = _composition_offsets(
- decode_times, _display_order(ffprobe, source, decode_times))
+ decode_times, _display_order(ffprobe, source, decode_times, progress=progress))
if not shift and all(value == 0 for value in offsets):
raise RepairUnavailable("显示顺序本来就等于解码顺序,没有要修的")
@@ -540,7 +552,7 @@ class HeaderRepairStore:
self.resolver = resolver
self._slots = threading.Semaphore(max(1, max_concurrent))
self._running: set[str] = set()
- self._failed: set[str] = set()
+ self._failed: dict[str, str] = {}
# 一份头有几 MB(整个 moov 加 ctts),而播放时每个 Range 请求都要问一次。
# 同时在播的片子就那么一两部,留最近几份在手边,别反复读同一个文件。
self._cached: dict[str, RepairedHeader] = {}
@@ -600,9 +612,10 @@ class HeaderRepairStore:
self._jobs[name] = job
def work(job_id):
- made = self.repair_now(asset_id, source)
+ made = self.repair_now(asset_id, source, progress=lambda current, total: job.update(
+ job_id, checked=current, total=total))
job.update(job_id, status='complete' if made else 'failed',
- repaired=int(made), error='' if made else '播放文件头未能修复')
+ repaired=int(made), error='' if made else self._failed.get(name, '播放文件头未能修复'))
job.start(work, initial={'stage': '读取帧时间戳', 'name': source.name, 'asset_id': asset_id})
@@ -612,7 +625,7 @@ class HeaderRepairStore:
for job in jobs:
job.stop()
- def repair_now(self, asset_id: int, source: Path) -> bool:
+ def repair_now(self, asset_id: int, source: Path, *, progress=None) -> bool:
"""当场算一份头并存下来。已经有、正在算或上次算不出来都返回 False。"""
name = self._name(asset_id, source)
ffprobe = self.resolver.ffprobe()
@@ -628,7 +641,9 @@ class HeaderRepairStore:
checkpoint()
try:
checkpoint()
- write_sidecar(self.root / name, repaired_header(source, ffprobe.path))
+ header = (repaired_header(source, ffprobe.path) if progress is None else
+ repaired_header(source, ffprobe.path, progress=progress))
+ write_sidecar(self.root / name, header)
finally:
self._slots.release()
for stale in self.root.glob(f"{asset_id}-*{SIDECAR_SUFFIX}"):
@@ -638,7 +653,7 @@ class HeaderRepairStore:
except (RepairUnavailable, OSError, struct.error) as exc:
LOGGER.info("mp4 header repair unavailable for asset %s: %s", asset_id, exc)
with self._guard:
- self._failed.add(name)
+ self._failed[name] = str(exc)
return False
finally:
with self._guard:
diff --git a/src/peach/task_control.py b/src/peach/task_control.py
index 35e71d3c6..7bcf89e9d 100644
--- a/src/peach/task_control.py
+++ b/src/peach/task_control.py
@@ -8,11 +8,13 @@ import signal
import subprocess
import sys
import threading
+import tempfile
import time
import uuid
from functools import wraps
-from contextlib import contextmanager
+from contextlib import ExitStack, contextmanager
from contextvars import ContextVar
+from pathlib import Path
import psutil
@@ -391,16 +393,113 @@ def committing():
CURRENT.reset(token)
+class _OutputCapture:
+ """独立读写句柄观察输出;Windows communicate 只在 EOF 后交出管道内容。"""
+
+ def __init__(self):
+ self.stack = ExitStack()
+ root = Path(self.stack.enter_context(tempfile.TemporaryDirectory(prefix='peach-process-')))
+ self.writers = [self.stack.enter_context((root / name).open('wb')) for name in ('stdout', 'stderr')]
+ self.readers = [self.stack.enter_context((root / name).open('rb')) for name in ('stdout', 'stderr')]
+ self.parts = [[], []]
+
+ def drain(self, on_stdout):
+ chunks = [reader.read() for reader in self.readers]
+ for parts, chunk in zip(self.parts, chunks):
+ if chunk:
+ parts.append(chunk)
+ if chunks[0] and on_stdout is not None:
+ # 短进度投影不重入无进程的检查点,暂停由等待循环携子进程响应。
+ token = CURRENT.set(None)
+ try:
+ on_stdout(chunks[0])
+ finally:
+ CURRENT.reset(token)
+ return bool(chunks[0])
+
+ def result(self, process=None):
+ output = tuple(b''.join(parts) for parts in self.parts)
+ if process is not None and process.text_mode:
+ return tuple(value.decode(process.encoding, process.errors or 'strict').replace('\r\n', '\n').replace('\r', '\n')
+ for value in output)
+ return output
+
+ def close(self):
+ self.stack.close()
+
+
+def _wait_process(process, control, capture, *, input, timeout, idle_timeout, on_stdout):
+ """轮询进程并观察 stdout 活动;用户暂停的时间不计入两种超时。"""
+ started = time.monotonic()
+ paused = 0.0
+ last_output_at = 0.0
+ while True:
+ if control is not None:
+ paused += control.checkpoint(process) or 0.0
+ try:
+ output = process.communicate(input=input, timeout=.1)
+ if capture is not None:
+ capture.drain(on_stdout)
+ output = capture.result(process)
+ return output
+ except subprocess.TimeoutExpired as error:
+ input = None
+ elapsed = time.monotonic() - started - paused
+ if capture is not None and capture.drain(on_stdout):
+ last_output_at = elapsed
+ if idle_timeout is not None and elapsed - last_output_at >= idle_timeout:
+ raise subprocess.TimeoutExpired(process.args, idle_timeout, output=error.output, stderr=error.stderr) from None
+ if timeout is not None and elapsed >= timeout:
+ raise subprocess.TimeoutExpired(process.args, timeout, output=error.output, stderr=error.stderr) from None
+
+
+def _reap_process(process, job):
+ """终止本次进程树并回收输出,完成后才允许任务结算。"""
+ from .process_job import close_job
+ try:
+ if process.poll() is None:
+ try:
+ children = psutil.Process(process.pid).children(recursive=True)
+ except psutil.NoSuchProcess:
+ children = []
+ for child in reversed(children):
+ try:
+ child.kill()
+ except psutil.NoSuchProcess:
+ pass
+ try:
+ process.kill()
+ except ProcessLookupError:
+ pass
+ finally:
+ if os.name != 'nt':
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ except PermissionError:
+ # macOS 上进程组只剩已退出但未回收的进程时会报 EPERM。
+ if sys.platform != 'darwin':
+ raise
+ close_job(job)
+ return process.communicate()
+
+
@controlled
-def run(command, *, capture_output=False, timeout=None, check=False, input=None, **kwargs):
- """执行当前任务拥有的子进程;暂停保留进程,取消回收后才向外结算。"""
+def run(command, *, capture_output=False, timeout=None, check=False, input=None,
+ idle_timeout=None, on_stdout=None, **kwargs):
+ """执行当前任务拥有的子进程;idle_timeout 监测 stdout,回调接收增量 bytes。"""
control = CURRENT.get()
- if control is None:
+ if control is None and idle_timeout is None and on_stdout is None:
return subprocess.run(command, capture_output=capture_output, timeout=timeout,
check=check, input=input, **kwargs)
checkpoint()
+ if (idle_timeout is not None or on_stdout is not None) and not capture_output:
+ raise ValueError('输出活动监测需要 capture_output=True')
+ capture = _OutputCapture() if idle_timeout is not None or on_stdout is not None else None
if capture_output:
- kwargs.update(stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ kwargs.update(stdout=capture.writers[0] if capture else subprocess.PIPE,
+ stderr=capture.writers[1] if capture else subprocess.PIPE)
if input is not None:
kwargs['stdin'] = subprocess.PIPE
if os.name != 'nt':
@@ -411,66 +510,44 @@ def run(command, *, capture_output=False, timeout=None, check=False, input=None,
process = subprocess.Popen(command, **kwargs)
except BaseException:
close_job(job)
+ if capture is not None:
+ capture.close()
raise
assign_to_job(job, process)
- with control.lock:
- control.operations[id(process)] = False
- control.owners[id(process)] = threading.get_ident()
- started = time.monotonic()
- paused = 0.0
+ if control is not None:
+ with control.lock:
+ control.operations[id(process)] = False
+ control.owners[id(process)] = threading.get_ident()
timeout_error = None
try:
- control.usage.enter_process(process)
- while True:
- paused += control.checkpoint(process) or 0.0
- try:
- stdout, stderr = process.communicate(input=input, timeout=.1)
- break
- except subprocess.TimeoutExpired as error:
- input = None
- elapsed = time.monotonic() - started - paused
- if timeout is not None and elapsed >= timeout:
- timeout_error = subprocess.TimeoutExpired(command, timeout, output=error.output, stderr=error.stderr)
- raise timeout_error from None
+ if control is not None:
+ control.usage.enter_process(process)
+ stdout, stderr = _wait_process(process, control, capture, input=input, timeout=timeout,
+ idle_timeout=idle_timeout, on_stdout=on_stdout)
checkpoint()
result = subprocess.CompletedProcess(command, process.returncode, stdout, stderr)
if check:
result.check_returncode()
return result
+ except subprocess.TimeoutExpired as error:
+ timeout_error = error
+ raise
finally:
try:
- if process.poll() is None:
- try:
- children = psutil.Process(process.pid).children(recursive=True)
- except psutil.NoSuchProcess:
- children = []
- for child in reversed(children):
- try:
- child.kill()
- except psutil.NoSuchProcess:
- pass
- try:
- process.kill()
- except ProcessLookupError:
- pass
+ stdout, stderr = _reap_process(process, job)
+ if timeout_error is not None:
+ if capture is not None:
+ capture.drain(None)
+ stdout, stderr = capture.result()
+ timeout_error.output = stdout
+ timeout_error.stderr = stderr
finally:
- if os.name != 'nt':
- try:
- os.killpg(process.pid, signal.SIGKILL)
- except ProcessLookupError:
- pass
- except PermissionError:
- # 进程组由 start_new_session 自建;macOS 上组内只剩未回收的僵尸时 killpg 报 EPERM。
- if sys.platform != 'darwin':
- raise
- close_job(job)
try:
- stdout, stderr = process.communicate()
- if timeout_error is not None:
- timeout_error.output = stdout
- timeout_error.stderr = stderr
+ if control is not None:
+ with control.lock:
+ control.operations.pop(id(process), None)
+ control.owners.pop(id(process), None)
+ control.usage.leave_process(process)
finally:
- with control.lock:
- control.operations.pop(id(process), None)
- control.owners.pop(id(process), None)
- control.usage.leave_process(process)
+ if capture is not None:
+ capture.close()
diff --git a/tests/test_mp4repair.py b/tests/test_mp4repair.py
index 5800cbef5..c6f5b66a1 100644
--- a/tests/test_mp4repair.py
+++ b/tests/test_mp4repair.py
@@ -5,6 +5,7 @@
from __future__ import annotations
import struct
+import subprocess
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
@@ -110,7 +111,7 @@ class Mp4HeaderRepairTests(unittest.TestCase):
def repair(self, path: Path, order=DECODE_TO_DISPLAY) -> RepairedHeader:
"""把「解一遍片子问显示顺序」换成已知答案,只验头里的算术。"""
with patch.object(mp4repair, "_display_order",
- lambda ffprobe, source, times: list(order)):
+ lambda ffprobe, source, times, **_kwargs: list(order)):
return repaired_header(path, Path("ffprobe"))
def test_a_rebuilt_header_puts_every_frame_back_in_display_order(self):
@@ -286,7 +287,7 @@ class Mp4HeaderRepairTests(unittest.TestCase):
def test_the_display_order_is_the_order_the_decoder_hands_frames_back(self):
"""解码器按显示顺序出帧,每帧的时间戳原样来自它那个样本,所以置换是读出来的。"""
- with patch.object(mp4repair.subprocess, "run",
+ with patch.object(mp4repair, "run_task_process",
lambda *args, **options: _Probe(b"0\n800\n1200\n400\n")):
order = mp4repair._display_order(Path("ffprobe"), Path("movie.mp4"),
[0, 400, 800, 1200])
@@ -295,11 +296,32 @@ class Mp4HeaderRepairTests(unittest.TestCase):
def test_a_decode_that_loses_frames_is_refused_instead_of_guessed(self):
"""少一帧就说明这份表和码流对不上,宁可不修,也不能写一张错的 ctts。"""
- with patch.object(mp4repair.subprocess, "run",
+ with patch.object(mp4repair, "run_task_process",
lambda *args, **options: _Probe(b"0\n800\n")):
with self.assertRaises(RepairUnavailable):
mp4repair._display_order(Path("ffprobe"), Path("movie.mp4"), [0, 400, 800])
+ def test_probe_timeout_means_missing_output_and_reports_decoded_frames(self):
+ progress = []
+
+ def probe(command, **options):
+ self.assertIsNone(options.get('timeout'))
+ self.assertEqual(options['idle_timeout'], mp4repair.PROBE_IDLE_SECONDS)
+ options['on_stdout'](b'0\n800\n')
+ options['on_stdout'](b'1200\n400\n')
+ return _Probe(b'0\n800\n1200\n400\n')
+
+ with patch.object(mp4repair, 'run_task_process', side_effect=probe):
+ result = mp4repair._display_order(Path('ffprobe'), Path('movie.mp4'),
+ [0, 400, 800, 1200], progress=lambda *v: progress.append(v))
+ self.assertEqual(result, [0, 3, 1, 2])
+ self.assertEqual(progress, [(2, 4), (4, 4)])
+
+ def test_a_stalled_probe_has_a_distinct_failure_reason(self):
+ with patch.object(mp4repair, 'run_task_process', side_effect=subprocess.TimeoutExpired('ffprobe', 900)):
+ with self.assertRaisesRegex(RepairUnavailable, '没有解码输出'):
+ mp4repair._display_order(Path('ffprobe'), Path('movie.mp4'), [0, 400])
+
class SidecarTests(unittest.TestCase):
def setUp(self) -> None:
@@ -437,7 +459,7 @@ class HeaderRepairStoreTests(unittest.TestCase):
store = TaskRunStore(fresh_ledger(ledger))
repairs = HeaderRepairStore(self.root / 'managed-cache', _Resolver(), runs=store)
entered, release = threading.Event(), threading.Event()
- def build(source, ffprobe):
+ def build(source, ffprobe, **_options):
entered.set()
release.wait(5)
task_control.checkpoint()
@@ -476,6 +498,26 @@ class HeaderRepairStoreTests(unittest.TestCase):
self.assertEqual(len(attempts), 1)
self.assertIsNone(self.store.lookup(6297, self.source))
+ def test_background_repair_keeps_frame_progress_and_the_probe_failure_reason(self):
+ from support.ledger import fresh_ledger
+ from peach.task_runs import TaskRunStore
+ ledger = self.root / 'ledger'
+ ledger.mkdir()
+ runs = TaskRunStore(fresh_ledger(ledger))
+ repairs = HeaderRepairStore(self.root / 'managed-cache', _Resolver(), runs=runs)
+ def build(_source, _ffprobe, *, progress):
+ progress(20, 100)
+ raise RepairUnavailable('ffprobe 连续 900 秒没有解码输出')
+ with patch.object(mp4repair, 'repaired_header', build):
+ repairs.request(6297, self.source)
+ job = next(iter(repairs._jobs.values()))
+ job.thread.join(5)
+ self.assertFalse(job.thread.is_alive())
+ run = runs.query(task_key='mp4-header-repair')[0]
+ self.assertEqual(run.status, 'failed')
+ self.assertEqual((run.result_summary['checked'], run.result_summary['total']), (20, 100))
+ self.assertIn('900 秒没有解码输出', run.error)
+
def test_a_stored_header_is_not_computed_a_second_time(self):
write_sidecar(self.sidecar(), self.header)
diff --git a/tests/test_task_control.py b/tests/test_task_control.py
index fa514953e..e5afd744c 100644
--- a/tests/test_task_control.py
+++ b/tests/test_task_control.py
@@ -32,6 +32,95 @@ for _ in range(int(sys.argv[2])):
class TaskControlTests(unittest.TestCase):
+ def test_output_activity_allows_a_process_to_outlive_the_idle_timeout(self):
+ command = [sys.executable, '-u', '-c',
+ "import time; [(print(i, flush=True), time.sleep(.15)) for i in range(8)]"]
+ chunks = []
+ result = task_control.run(command, capture_output=True, idle_timeout=.8, on_stdout=chunks.append)
+ self.assertEqual(result.returncode, 0)
+ self.assertEqual(b''.join(chunks), result.stdout)
+ self.assertEqual(len(result.stdout.splitlines()), 8)
+
+ def test_a_stalled_process_is_reaped_and_retains_its_output(self):
+ command = [sys.executable, '-u', '-c', "import time; print('started', flush=True); time.sleep(30)"]
+ with self.record_child():
+ with self.assertRaises(subprocess.TimeoutExpired) as caught:
+ task_control.run(command, capture_output=True, idle_timeout=.8)
+ self.assertIn(b'started', caught.exception.output)
+ self.assertIsNotNone(self.children[-1].poll())
+
+ def test_stderr_activity_does_not_extend_the_stdout_idle_timeout(self):
+ command = [sys.executable, '-u', '-c',
+ "import sys,time; [(print('decode error', file=sys.stderr, flush=True), time.sleep(.1)) "
+ "for _ in range(300)]"]
+ with self.record_child(), self.assertRaises(subprocess.TimeoutExpired) as caught:
+ task_control.run(command, capture_output=True, idle_timeout=.8)
+ self.assertIn(b'decode error', caught.exception.stderr)
+ self.assertIsNotNone(self.children[-1].poll())
+
+ def test_output_monitor_keeps_the_text_result_and_binary_callback_contracts(self):
+ chunks = []
+ command = [sys.executable, '-u', '-c', "print('sample')"]
+ result = task_control.run(command, capture_output=True, text=True, encoding='utf-8',
+ idle_timeout=1, on_stdout=chunks.append)
+ self.assertEqual(result.stdout, 'sample\n')
+ self.assertEqual(b''.join(chunks).replace(b'\r\n', b'\n'), b'sample\n')
+ with self.assertRaisesRegex(ValueError, 'capture_output'):
+ task_control.run(command, idle_timeout=1)
+
+ def test_a_pause_requested_inside_progress_projection_suspends_the_owned_child(self):
+ path = self.root / 'heartbeat-progress'
+ chunks = []
+ def work(job, identity):
+ def progress(chunk):
+ chunks.append(chunk)
+ if len(chunks) == 1:
+ task_control.request(self.store, job.snapshot()['run_id'], 'pause')
+ job.update(identity, checked=len(chunks))
+ command = [sys.executable, '-u', '-c',
+ "import sys,time; from pathlib import Path; p=Path(sys.argv[1]); "
+ "[(p.write_bytes(str(i).encode()), print(i, flush=True), time.sleep(.15)) for i in range(200)]",
+ str(path)]
+ task_control.run(command, capture_output=True, idle_timeout=.8, on_stdout=progress)
+ with self.record_child():
+ job, original = self.start(work)
+ run_id = original['run_id']
+ self.wait_until(lambda: self.state(run_id)['state'] == 'paused')
+ before = path.read_bytes()
+ time.sleep(1)
+ self.assertEqual(path.read_bytes(), before)
+ count = len(chunks)
+ task_control.request(self.store, run_id, 'resume')
+ self.wait_until(lambda: len(chunks) > count)
+ self.assertEqual(self.store.get(run_id).status, 'running')
+ task_control.request(self.store, run_id, 'cancel')
+ job.thread.join(5)
+ self.assertFalse(job.thread.is_alive())
+ self.assertEqual(self.store.get(run_id).status, 'cancelled')
+
+ def test_idle_timeout_excludes_a_user_pause_and_cancel_reaps_the_process(self):
+ chunks = []
+ command = [sys.executable, '-u', '-c',
+ "import time; [(print(i, flush=True), time.sleep(.15)) for i in range(200)]"]
+ def work(_job, _identity):
+ task_control.run(command, capture_output=True, idle_timeout=.8, on_stdout=chunks.append)
+ with self.record_child():
+ job, original = self.start(work)
+ self.wait_until(lambda: len(chunks) >= 2)
+ run_id = original['run_id']
+ task_control.request(self.store, run_id, 'pause')
+ self.wait_until(lambda: self.state(run_id)['state'] == 'paused')
+ time.sleep(1)
+ count = len(chunks)
+ task_control.request(self.store, run_id, 'resume')
+ self.wait_until(lambda: len(chunks) > count)
+ self.assertEqual(self.store.get(run_id).status, 'running')
+ task_control.request(self.store, run_id, 'cancel')
+ job.thread.join(5)
+ self.assertFalse(job.thread.is_alive())
+ self.assertEqual(self.store.get(run_id).status, 'cancelled')
+ self.assertIsNotNone(self.children[-1].poll())
+
def setUp(self):
temporary = tempfile.TemporaryDirectory()
self.addCleanup(temporary.cleanup)