CoolFace
Apppublic

skkalwar/video_encode

sourceHugging Faceupdated 10mo agoView on Hugging Face
0likes
transcode_short_video.py66 linesDownload Raw Back to root
1import os2import subprocess3import ffmpeg4 5 6 7def transcode_short_video(input_path: str, output_dir: str, orig_width: int, orig_height: int):8    os.makedirs(output_dir, exist_ok=True)9 10    def has_audio():11        try:12            probe = ffmpeg.probe(input_path)13            return any(s["codec_type"] == "audio" for s in probe.get("streams", []))14        except:15            return False16 17    def get_fps():18        try:19            probe = ffmpeg.probe(input_path)20            v_stream = next(s for s in probe["streams"] if s["codec_type"] == "video")21            return eval(v_stream["r_frame_rate"])22        except:23            return 3024 25    audio_exists = has_audio()26    fps = get_fps()27    gop_size = int(fps * 2)28 29    width = min(orig_width, 720)30    height = min(orig_height, 1280)31    rendition_name = f"{width}x{height}"32 33    ffmpeg_cmd = [34        "ffmpeg", "-y", "-i", input_path,35       "-vf", f"scale='min({width},iw)':'min({height},ih)':force_original_aspect_ratio=decrease,pad={width}:{height}:(ow-iw)/2:(oh-ih)/2",36 37        "-c:v", "libx264",38        "-crf", "24",39        "-preset", "fast",40        "-g", str(gop_size),41        "-keyint_min", str(gop_size),42        "-sc_threshold", "0",43    ]44 45    if audio_exists:46        ffmpeg_cmd += [47            "-c:a", "aac",48            "-b:a", "96000",49            "-ac", "2",50            "-ar", "44100",51        ]52 53    ffmpeg_cmd += [54        "-f", "hls",55        "-hls_time", "4",56        "-hls_playlist_type", "vod",57        "-hls_flags", "independent_segments+single_file",58        "-hls_segment_type", "mpegts",59        "-avoid_negative_ts", "make_zero",60        "-movflags", "+faststart",61        os.path.join(output_dir, "master.m3u8")62    ]63 64    print("[FFMPEG SHORT CMD]", " ".join(ffmpeg_cmd))65    subprocess.run(ffmpeg_cmd, check=True)66