import os import subprocess import sys from pathlib import Path try: import requests from tqdm import tqdm except ImportError: print("Install required packages: pip install requests tqdm") sys.exit(1) def check_ffmpeg(): """Check if ffmpeg is installed.""" try: result = subprocess.run(["ffmpeg", "-version"], capture_output=True, text=True) if result.returncode == 0: print(f"ffmpeg available: {result.stdout.splitlines()[0]}") return True except FileNotFoundError: return False return False def install_ffmpeg(): """Try auto-install ffmpeg (Windows only example with choco).""" if os.name == "nt": print("⚙ Installing ffmpeg via Chocolatey (Windows)...") subprocess.run("choco install ffmpeg -y", shell=True) else: print("⚠ Please install ffmpeg manually for your OS.") def download_file(url, output_path): """Download a file with tqdm progress bar.""" output_path = Path(output_path) if output_path.exists(): print(f"✅ File already exists: {output_path}") return output_path response = requests.get(url, stream=True) total_size = int(response.headers.get("content-length", 0)) block_size = 1024 t = tqdm(total=total_size, unit="iB", unit_scale=True, desc="Downloading") with open(output_path, "wb") as f: for data in response.iter_content(block_size): t.update(len(data)) f.write(data) t.close() if total_size != 0 and output_path.stat().st_size != total_size: print("❌ ERROR: Download incomplete.") else: print("✅ Download complete.") return output_path def convert_to_mp4(input_file: Path, delete_original=True): """Convert MKV to MP4 using ffmpeg.""" # ✅ If already MP4, skip if input_file.suffix.lower() == ".mp4": print(f"✅ Already MP4, skipping conversion: {input_file}") return input_file if input_file.suffix.lower() != ".mkv": print(f"❌ Unsupported format ({input_file.suffix}), skipping conversion.") return input_file output_file = input_file.with_suffix(".mp4") print(f"Converting {input_file} → {output_file}") subprocess.run([ "ffmpeg", "-y", "-i", str(input_file), "-c:v", "copy", "-c:a", "aac", str(output_file) ]) print(f"✅ Conversion complete: {output_file}") if delete_original: input_file.unlink(missing_ok=True) print(f"🗑️ Deleted original file: {input_file}") return output_file def convert_to_hls(input_file, segment_time: int = 10): """Convert MP4 to HLS (.m3u8 + .ts segments).""" input_file = Path(input_file) # Output directory output_dir = input_file.with_suffix("") output_dir.mkdir(exist_ok=True) m3u8_file = output_dir / "output.m3u8" print(f"Converting {input_file} → HLS ({segment_time}s segments) in {output_dir}") subprocess.run([ "ffmpeg", "-y", "-i", str(input_file), "-c:v", "libx264", "-crf", "23", "-preset", "fast", "-c:a", "aac", "-b:a", "128k", "-ac", "2", "-hls_time", str(segment_time), "-hls_playlist_type", "vod", str(m3u8_file) ], check=True) print(f"✅ HLS conversion complete: {m3u8_file}") def main(output, url, delete_original=False): print("LEGAL: Use this only for authorized/public-domain content.") if not check_ffmpeg(): install_ffmpeg() filename = output if output else os.path.basename(url.split("?")[0]) file_path = download_file(url, filename) # Convert MKV → MP4 (skip if already mp4) mp4_file = convert_to_mp4(file_path, delete_original=delete_original) # Convert MP4 → HLS convert_to_hls(mp4_file, segment_time=10) os.system(f'rm -rf {mp4_file}') print("✅ All tasks completed.")