"""Bounded, CPU-only reverse loops for generated Horizon videos.""" import json import math import os from pathlib import Path import re import shutil import subprocess import uuid def reverse_loop(storage, video_name, turnaround=0.0, passes=1, append_original=False): """Export end→turnaround, turnaround→end, ... with forward audio per pass.""" if not isinstance(video_name, str) or not re.fullmatch(r'h3-[A-Za-z0-9_-]+\.mp4', video_name): raise ValueError('Select a generated video to edit.') if not isinstance(append_original, bool): raise ValueError('Include original must be a checkbox value.') root = Path(storage).resolve() source = (root / video_name).resolve() if source.parent != root or not source.is_file(): raise ValueError('This video is no longer available.') probe = shutil.which('ffprobe') ffmpeg = shutil.which('ffmpeg') if not probe or not ffmpeg: raise RuntimeError('FFmpeg and FFprobe are required for video editing.') try: result = subprocess.run([probe, '-v', 'error', '-show_streams', '-show_format', '-of', 'json', str(source)], check=True, timeout=15, capture_output=True) data = json.loads(result.stdout) video = next(s for s in data['streams'] if s.get('codec_type') == 'video') duration = float(video.get('duration') or data['format']['duration']) from fractions import Fraction fps = float(Fraction(video.get('avg_frame_rate') or '24/1')) width, height = int(video['width']), int(video['height']) has_audio = any(s.get('codec_type') == 'audio' for s in data['streams']) except (OSError, ValueError, KeyError, IndexError, StopIteration, ZeroDivisionError, OverflowError, subprocess.SubprocessError) as exc: raise ValueError('Unable to read this video. Select a completed clip.') from exc if not math.isfinite(duration) or not 0 < duration <= 20.5 or not 0 < fps <= 30 or max(width, height) > 1920 or width * height > 2073600: raise ValueError('Reverse supports clips up to 20 seconds, 30 fps and 1080p.') try: point = float(turnaround) count = int(passes) except (TypeError, ValueError, OverflowError) as exc: raise ValueError('Enter a valid turnaround time and pass count.') from exc if (not math.isfinite(point) or not 0 <= point <= duration - max(0.1, 1/fps) or isinstance(passes, bool) or count != passes or not 1 <= count <= 10): raise ValueError('Choose a turnaround before the clip ends and 1–10 passes.') segment = duration - point if segment * count + (duration if append_original else 0) > 120: raise ValueError('Combined output must be at most 120 seconds.') backward, forward = (count + 1)//2, count//2 trim = f'trim=start={point:.6f}:end={duration:.6f},setpts=PTS-STARTPTS' if forward: graph = f'[0:v:0]{trim},split=2[backward][forward];' graph += f'[backward]reverse,setpts=PTS-STARTPTS,split={backward}' + ''.join(f'[v{i}]' for i in range(0,count,2)) + ';' graph += f'[forward]split={forward}' + ''.join(f'[v{i}]' for i in range(1,count,2)) + ';' else: graph = f'[0:v:0]{trim},reverse,setpts=PTS-STARTPTS[v0];' if has_audio: graph += f'[0:a:0]atrim=start={point:.6f}:end={duration:.6f},asetpts=PTS-STARTPTS,apad=whole_dur={segment:.6f},atrim=duration={segment:.6f},asplit={count}' + ''.join(f'[a{i}]' for i in range(count)) + ';' graph += ''.join(f'[v{i}]' + (f'[a{i}]' if has_audio else '') for i in range(count)) graph += f'concat=n={count}:v=1:a={int(has_audio)}[vout]' + ('[aout]' if has_audio else '') video_out, audio_out = 'vout', 'aout' if append_original: graph += f';[0:v:0]trim=duration={duration:.6f},setpts=PTS-STARTPTS[originalv]' if has_audio: graph += f';[0:a:0]asetpts=PTS-STARTPTS,apad=whole_dur={duration:.6f},atrim=duration={duration:.6f}[originala]' graph += ';[originalv]' + ('[originala]' if has_audio else '') + '[vout]' + ('[aout]' if has_audio else '') graph += f'concat=n=2:v=1:a={int(has_audio)}[mergedv]' + ('[mergeda]' if has_audio else '') video_out, audio_out = 'mergedv', 'mergeda' target = root / f'h3-edit-{uuid.uuid4().hex}.mp4' temporary = root / f'.reverse-{uuid.uuid4().hex}.mp4' args = [ffmpeg, '-nostdin', '-hide_banner', '-loglevel', 'error', '-y', '-hwaccel', 'none', '-threads', '2', '-i', str(source), '-filter_complex_threads', '1', '-filter_threads', '1', '-filter_complex', graph, '-map', f'[{video_out}]'] if has_audio: args += ['-map', f'[{audio_out}]'] args += ['-c:v', 'libx264', '-preset', 'fast', '-crf', '18', '-pix_fmt', 'yuv420p', '-threads', '2', '-c:a', 'aac', '-movflags', '+faststart', str(temporary)] try: subprocess.run(args, check=True, timeout=300, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) if not temporary.is_file() or not temporary.stat().st_size: raise RuntimeError('The encoder returned an empty video.') os.replace(temporary, target) return target except (OSError, subprocess.SubprocessError) as exc: raise RuntimeError('Reverse export failed. Try a shorter clip.') from exc finally: temporary.unlink(missing_ok=True)