import os import subprocess import ffmpeg def transcode_short_video(input_path: str, output_dir: str, orig_width: int, orig_height: int): os.makedirs(output_dir, exist_ok=True) def has_audio(): try: probe = ffmpeg.probe(input_path) return any(s["codec_type"] == "audio" for s in probe.get("streams", [])) except: return False def get_fps(): try: probe = ffmpeg.probe(input_path) v_stream = next(s for s in probe["streams"] if s["codec_type"] == "video") return eval(v_stream["r_frame_rate"]) except: return 30 audio_exists = has_audio() fps = get_fps() gop_size = int(fps * 2) width = min(orig_width, 720) height = min(orig_height, 1280) rendition_name = f"{width}x{height}" ffmpeg_cmd = [ "ffmpeg", "-y", "-i", input_path, "-vf", f"scale='min({width},iw)':'min({height},ih)':force_original_aspect_ratio=decrease,pad={width}:{height}:(ow-iw)/2:(oh-ih)/2", "-c:v", "libx264", "-crf", "24", "-preset", "fast", "-g", str(gop_size), "-keyint_min", str(gop_size), "-sc_threshold", "0", ] if audio_exists: ffmpeg_cmd += [ "-c:a", "aac", "-b:a", "96000", "-ac", "2", "-ar", "44100", ] ffmpeg_cmd += [ "-f", "hls", "-hls_time", "4", "-hls_playlist_type", "vod", "-hls_flags", "independent_segments+single_file", "-hls_segment_type", "mpegts", "-avoid_negative_ts", "make_zero", "-movflags", "+faststart", os.path.join(output_dir, "master.m3u8") ] print("[FFMPEG SHORT CMD]", " ".join(ffmpeg_cmd)) subprocess.run(ffmpeg_cmd, check=True)