import os import subprocess import sys from utils import verify_file_not_empty def run_ffmpeg(args): """ Runs ffmpeg, automatically escaping Flatpak sandbox if necessary. """ in_flatpak = os.path.exists("/.flatpak-info") cmd = ["flatpak-spawn", "--host", "ffmpeg"] + args if in_flatpak else ["ffmpeg"] + args try: subprocess.run(cmd, check=True) return True except subprocess.CalledProcessError as e: print(f"FFmpeg Error: {e}") return False except FileNotFoundError: print("Error: 'ffmpeg' command not found. Please ensure it is installed on your host system.") return False def extract_audio(video_path, output_path=None): """ Extracts audio from a video file using ffmpeg. """ if not os.path.exists(video_path): raise FileNotFoundError(f"Video file not found: {video_path}") if output_path is None: base_name = os.path.splitext(video_path)[0] output_path = f"{base_name}.wav" if verify_file_not_empty(output_path): print(f"Audio file already exists: {output_path}") return output_path print(f"Extracting audio from {video_path}...") args = [ "-i", video_path, "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", "-y", "-v", "error", output_path ] if run_ffmpeg(args): if not verify_file_not_empty(output_path): raise Exception("FFmpeg succeeded but output is empty.") print(f"Audio extracted to: {output_path}") return output_path else: sys.exit(1) def embed_subtitles(video_path, srt_path, output_path=None): """ Embeds subtitles into the video file (Soft Subs) and sets them as primary. """ if not os.path.exists(video_path) or not os.path.exists(srt_path): print("Error: Video or SRT file not found for embedding.") return if output_path is None: base, ext = os.path.splitext(video_path) output_path = f"{base}.subbed{ext}" print(f"Embedding subtitles into: {output_path}...") sub_codec = "mov_text" if video_path.lower().endswith(".mp4") else "srt" args = [ "-ignore_editlist", "1", "-i", video_path, "-i", srt_path, "-map", "0:v", "-map", "0:a", "-map", "1:0", "-c", "copy", "-c:s", sub_codec, "-disposition:s:0", "default", "-metadata:s:s:0", "language=eng", "-metadata:s:s:0", "title=English (AI Translated)", "-max_interleave_delta", "0", "-avoid_negative_ts", "make_zero", "-y", "-v", "error", output_path ] if run_ffmpeg(args): if not verify_file_not_empty(output_path): raise Exception("FFmpeg succeeded but output video is empty.") print(f"Subtitles embedded successfully: {output_path}") else: print("Error: Embedding failed.")