"""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) async def inspect_video_track(path: Path, settings) -> dict: """Count decoded video frames; container or audio duration cannot mask a short source.""" from fractions import Fraction source=confined(path,settings) raw=await run_process([settings.ffprobe_bin,'-v','error',*input_options(),'-select_streams','v:0','-count_frames','-show_entries','stream=width,height,avg_frame_rate,nb_read_frames,duration,time_base:format=duration','-of','json',str(source)],timeout=120,max_output=256*1024) try: data=json.loads(raw);stream=data['streams'][0] frames=int(stream['nb_read_frames']);fps=Fraction(stream['avg_frame_rate']) width,height=int(stream['width']),int(stream['height']) if frames<=0 or fps<=0 or width<=0 or height<=0 or width*height>40000000:raise ValueError return {'frames':frames,'fps':float(fps),'width':width,'height':height,'duration':float(data['format']['duration']),'time_base':stream.get('time_base')} except (KeyError,IndexError,TypeError,ValueError,ZeroDivisionError): raise MediaError('invalid_media','Video frame decoding failed.') from None async def compose_workflow(plan,work_dir,control=None,*,settings,sources,audio=None): """Render a frozen multi-shot timeline from internal resolved asset paths.""" from .providers import CpuResult if len(sources)!=len(plan.spec['shots']):raise MediaError('invalid_timeline','Source videos differ from the frozen shot count.') shot_frames=plan.shot_frames or (plan.clip_frames,)*len(sources) duration=plan.frames/plan.fps duration_text=f'{duration:.9f}'.rstrip('0').rstrip('.') sources=[confined(p,settings) for p in sources] work=Path(work_dir).resolve() if not work.is_relative_to(Path(settings.workspace_root).resolve()):raise MediaError('invalid_asset','Invalid work directory.') width,height=plan.canvas expected=(plan.generation_parameters['upscale_width'],plan.generation_parameters['upscale_height']) for source,frames in zip(sources,shot_frames): info=await inspect_video_track(source,settings) if info['frames']round(info['duration_seconds']*1000):raise MediaError('invalid_timeline','Audio cut exceeds decoded source.') work.mkdir(parents=True,exist_ok=True) async def checkpoint(): if control is not None: result=control() if callable(control) else control.checkpoint() if hasattr(result,'__await__'):await result parts=[] for index,(source,frames) in enumerate(zip(sources,shot_frames)): await checkpoint();target=work/f'shot-{index}.mp4' fit=plan.spec['render']['fit'] canvas=f'scale={width}:{height}:force_original_aspect_ratio=' + ('decrease' if fit=='contain' else 'increase') canvas+=f',pad={width}:{height}:(ow-iw)/2:(oh-ih)/2' if fit=='contain' else f',crop={width}:{height}' vf=f'trim=start_frame=0:end_frame={frames},setpts=PTS-STARTPTS,'+canvas+',setsar=1' await run_process([settings.ffmpeg_bin,'-v','error','-nostdin',*input_options(),'-i',str(source),'-map','0:v:0','-an','-vf',vf,'-r','24','-frames:v',str(frames),'-c:v','libx264','-preset','veryfast','-crf','20','-pix_fmt','yuv420p','-threads','2','-fs',str(settings.max_output_bytes),str(target)],timeout=600) parts.append(target) if sum(p.stat().st_size for p in parts)>=settings.max_output_bytes:raise MediaError('output_too_large','Intermediate media exceeds size budget.') listing=work/'concat.txt';listing.write_text(''.join(f"file '{p.name}'\n" for p in parts),encoding='utf-8') target=work/'workflow.mp4' command=[settings.ffmpeg_bin,'-v','error','-nostdin','-f','concat','-safe','1','-i',listing.name] if audio:command += [*input_options(),'-i',str(audio)] else:command += ['-f','lavfi','-i','anullsrc=channel_layout=stereo:sample_rate=48000'] filters=[] for index,cue in enumerate(plan.spec['render']['subtitles']): name=f'cue-{index:04d}.txt';(work/name).write_text(cue['text'],encoding='utf-8') filters.append(f"drawtext=font='Noto Sans CJK SC':textfile={name}:expansion=none:fontcolor=white:fontsize=48:borderw=3:x=(w-tw)/2:y=h-th-60:enable='gte(n,{cue['start_frame']})*lt(n,{cue['end_frame']})'") if audio: start,end=audio_spec['source_start_ms']/1000,audio_spec['source_end_ms']/1000 delay=audio_spec['offset_frame']*1000/24 af=f'atrim=start={start:.3f}:end={end:.3f},asetpts=PTS-STARTPTS,adelay={delay:.9f}:all=1,apad,atrim=duration={duration_text}' else:af=f'atrim=duration={duration_text}' command+=['-map','0:v:0','-map','1:a:0'] if filters:command+=['-vf',','.join(filters)] command+=['-af',af,'-frames:v',str(plan.frames),'-r','24','-c:v','libx264','-preset','veryfast','-crf','20','-pix_fmt','yuv420p','-c:a','aac','-ar','48000','-ac','2','-threads','2','-movflags','+faststart','-fs',str(settings.max_output_bytes),str(target)] await checkpoint();await run_process(command,timeout=min(3600,max(600,duration*5)),cwd=work) info=await inspect_video_track(target,settings) if info['frames']!=plan.frames or info['fps']!=24 or (info['width'],info['height'])!=plan.canvas or abs(info['duration']-duration)>.10 or target.stat().st_size>=settings.max_output_bytes: raise MediaError('composition_incomplete','Final video differs from the frozen frame count, profile or duration.') result={'frames':plan.frames,'fps':24,'duration_seconds':duration,'width':width,'height':height,'clip_count':len(sources),'subtitle_count':len(filters)} return CpuResult([target],result,{'provider':'ffmpeg-cpu','profile':plan.spec['profile'],'template_version':'plain-v1'})