"""Bounded CPU media operations. No shell, CUDA, external URLs or user filters.""" from __future__ import annotations import asyncio import json import math import os from pathlib import Path import uuid from PIL import Image, ImageOps, UnidentifiedImageError class MediaError(RuntimeError): def __init__(self, code: str, message: str, retriable: bool = False): super().__init__(message) self.code, self.message, self.retriable = code, message, retriable def confined(path: Path, settings, *, exists: bool = True, root: Path | None = None) -> Path: try: candidate = Path(path) boundary = Path(root or settings.workspace_root).resolve() if not candidate.is_absolute(): raise ValueError resolved = candidate.resolve() if not resolved.is_relative_to(boundary) or (exists and not resolved.is_file()): raise ValueError return resolved except (OSError, ValueError, TypeError): raise MediaError('invalid_asset', '素材文件不存在或不可访问。') from None async def _stop(process): if process.returncode is None: try: process.terminate() except ProcessLookupError: pass try: await asyncio.wait_for(process.wait(), 2) except asyncio.TimeoutError: try: process.kill() except ProcessLookupError: pass await asyncio.wait_for(process.wait(), 5) async def _cleanup(process, readers): for task in readers: if not task.done(): task.cancel() await asyncio.gather(*readers, return_exceptions=True) async def discard(stream): while await stream.read(65536): pass # Drain after a size rejection/cancel too. Otherwise a full paused pipe # can keep asyncio's process transport alive even after the child exited. drains = [asyncio.create_task(discard(process.stdout)), asyncio.create_task(discard(process.stderr))] try: await _stop(process) await asyncio.wait_for(asyncio.gather(*drains), 5) finally: for task in drains: if not task.done(): task.cancel() await asyncio.gather(*drains, return_exceptions=True) async def run_process(argv: list[str], *, timeout: float = 120, max_output: int = 1024 * 1024, cwd: Path | None = None, return_stderr: bool = False) -> bytes | tuple[bytes, bytes]: """Own one executable; cancellation does TERM/KILL/wait only on that child. FFmpeg/ffprobe do not launch child programs. Pipe readers enforce their bounds while the child runs, rather than buffering arbitrary diagnostics. """ process = None readers = [] async def read_bounded(stream): chunks, count = [], 0 while chunk := await stream.read(65536): count += len(chunk) if count > max_output: raise MediaError('media_output_limit', '媒体处理诊断超出限制。') chunks.append(chunk) return b''.join(chunks) try: process = await asyncio.create_subprocess_exec(*[str(value) for value in argv], stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, cwd=str(cwd) if cwd else None, start_new_session=(os.name == 'posix')) readers = [asyncio.create_task(read_bounded(process.stdout)), asyncio.create_task(read_bounded(process.stderr))] async with asyncio.timeout(timeout): stdout, stderr = await asyncio.gather(*readers) await process.wait() if process.returncode != 0: raise MediaError('media_processing_failed', '媒体解码或处理失败,请检查素材格式。') return (stdout, stderr) if return_stderr else stdout except asyncio.CancelledError: raise except asyncio.TimeoutError: raise MediaError('media_timeout', '媒体处理超时,请缩短素材后重试。', True) from None except (OSError, ValueError): raise MediaError('media_unavailable', '媒体处理程序不可用。', True) from None finally: if process is not None: cleanup = asyncio.create_task(_cleanup(process, readers)) recancelled = False while not cleanup.done(): try: await asyncio.shield(cleanup) except asyncio.CancelledError: recancelled = True await cleanup if recancelled: raise asyncio.CancelledError def input_options() -> list[str]: # Exclude playlists, concat input, network protocols and nested file lists. return ['-protocol_whitelist', 'file,pipe', '-format_whitelist', 'mov,matroska,webm,avi,wav,mp3,flac,ogg,aac,mpeg,mpegts'] def _image_info(path): try: with Image.open(path) as image: mime = {'PNG': 'image/png', 'JPEG': 'image/jpeg', 'WEBP': 'image/webp'}.get(image.format) if mime is None or image.width * image.height > 40_000_000: raise MediaError('invalid_image', '仅支持像素数受限的 PNG、JPEG、WebP 图片。') image.load() return {'kind': 'image', 'mime_type': mime, 'width': image.width, 'height': image.height, 'duration_seconds': None} except UnidentifiedImageError: return None except (OSError, ValueError, Image.DecompressionBombError): raise MediaError('invalid_image', '图片文件无法解码。') from None def _text_info(path): if path.suffix.lower() not in {'.json', '.txt', '.md', '.srt', '.vtt'}: return None try: if path.stat().st_size > 4 * 1024 * 1024: raise ValueError text = path.read_text(encoding='utf-8-sig') if '\x00' in text or not text.strip(): raise ValueError is_json = path.suffix.lower() == '.json' if is_json: json.loads(text, parse_constant=lambda _: (_ for _ in ()).throw(ValueError())) return {'kind': 'json' if is_json else 'text', 'mime_type': 'application/json' if is_json else 'text/plain', 'width': None, 'height': None, 'duration_seconds': None} except (OSError, UnicodeError, ValueError, RecursionError): raise MediaError('invalid_text', '文本或 JSON 文件格式无效。') from None async def inspect_media(path: Path, settings) -> dict: source = confined(path, settings) if source.stat().st_size <= 0: raise MediaError('invalid_asset', '素材文件为空。') text = await asyncio.to_thread(_text_info, source) if text is not None: return text image = await asyncio.to_thread(_image_info, source) if image is not None: return image if source.suffix.lower() in {'.png', '.jpg', '.jpeg', '.webp'}: raise MediaError('invalid_image', '图片文件无法解码。') raw = await run_process([settings.ffprobe_bin, '-v', 'error', *input_options(), '-show_entries', 'format=format_name,duration,start_time:stream=codec_type,codec_name,width,height,duration:stream_disposition=attached_pic', '-of', 'json', str(source)], timeout=30, max_output=256 * 1024) try: data = json.loads(raw) streams = data['streams'] videos = [item for item in streams if item.get('codec_type') == 'video' and not item.get('disposition', {}).get('attached_pic')] audios = [item for item in streams if item.get('codec_type') == 'audio'] if not videos and not audios: raise ValueError stream = videos[0] if videos else audios[0] duration = float(data.get('format', {}).get('duration', stream.get('duration', 0))) start_time = float(data.get('format', {}).get('start_time', 0)) if not math.isfinite(start_time): raise ValueError if not math.isfinite(duration) or not 0 < duration <= 86400: raise ValueError width, height = stream.get('width'), stream.get('height') if videos and (type(width) is not int or type(height) is not int or width <= 0 or height <= 0 or width * height > 40_000_000): raise ValueError formats = str(data.get('format', {}).get('format_name', '')).split(',') if videos: mime = 'video/webm' if 'webm' in formats and source.suffix.lower() == '.webm' else 'video/mp4' if 'mov' in formats else 'video/x-matroska' if 'matroska' in formats else 'video/mp2t' if 'mpegts' in formats else 'video/mpeg' if 'mpeg' in formats else 'video/x-msvideo' else: mime = 'audio/wav' if 'wav' in formats else 'audio/mpeg' if 'mp3' in formats else 'audio/flac' if 'flac' in formats else 'audio/ogg' if 'ogg' in formats else 'audio/aac' if 'aac' in formats else 'audio/mp4' return {'kind': 'video' if videos else 'audio', 'mime_type': mime, 'has_audio': bool(audios), 'width': width if videos else None, 'height': height if videos else None, 'duration_seconds': duration, 'start_seconds': start_time} except (ValueError, TypeError, KeyError, AttributeError): raise MediaError('invalid_media', '媒体文件信息无效。') from None async def make_thumbnail(path: Path, destination: Path, settings) -> Path | None: source, target = confined(path, settings), confined(destination, settings, exists=False) info = await inspect_media(source, settings) if info['kind'] not in {'image', 'video'}: return None target.parent.mkdir(parents=True, exist_ok=True) temporary = target.with_name(target.name + '.part-' + uuid.uuid4().hex + '.jpg') try: if info['kind'] == 'image': def convert(): with Image.open(source) as image: image = ImageOps.exif_transpose(image).convert('RGB') image.thumbnail((512, 512)) image.save(temporary, format='JPEG', quality=85) await asyncio.to_thread(convert) else: await run_process([settings.ffmpeg_bin, '-v', 'error', '-nostdin', *input_options(), '-i', str(source), '-frames:v', '1', '-vf', 'scale=512:512:force_original_aspect_ratio=decrease', '-threads', '2', '-f', 'image2', '-update', '1', str(temporary)], timeout=60) if not temporary.is_file() or temporary.stat().st_size == 0: raise MediaError('thumbnail_failed', '预览图生成失败。') os.replace(temporary, target) return target finally: temporary.unlink(missing_ok=True)