首页 > 解决方案 > ffmpeg 作为子进程需要太长时间

问题描述

我的程序的一部分需要 FFMPEG 使用 GPU 对文件进行转码。

当我在终端中单独执行 FFMPEG 命令时,没有 Python,大约需要 0.7 秒。同时运行 50 个命令不会影响结果。时间总是在 0.7 秒左右(感谢强大的 GPU 可以处理这么多的请求)。

将此命令放入子进程会将时间增加到 1.7 秒,并在我运行多个实例时最多增加 20 秒,即使此命令应该异步工作。

def run_ffmpeg(filename, gop, representation, output_filename=None):
    process_result = subprocess.run(
        args=[
            'sudo', FFMPEG_PATH,
            '-vsync', '0',
            '-hwaccel', 'cuvid', # transport decoded file through GPU without touching CPU
            '-hwaccel_device', '0',
            '-c:v', 'h264_cuvid', # Decoding using GPU
            '-i', filename,
            # ...
            '-c:v', 'hevc_nvenc', # Encoding using GPU
            # ...more filters...
            output_filename
        ]
    )
    log_process_result(process_result)
    return output_filename

序列要复杂得多:

def transcode_file(media_id, target_repr, target_nr):
    # ... variables definitions
    run_ffmpeg(target_segment_path, gop='120', representation=target_repr, output_filename=result)

def prepare_file(media_id, representation_id, file_name):
    # ... variables definitions
        path = transcode_file(media_id, target_repr, target_nr)

async def download_media_handler(request):
    # ... variables definitions
    file_info = await loop.run_in_executor(
        executor, prepare_file, media_dir_name, representation_id, file_name)

GPU 或 CPU 都没有完全使用,所以情况并非如此。

你知道为什么吗?subprocess真的要花那么多时间跑吗?

我怎样才能重写它以最小化时间?有更快的替代方案吗?

标签: pythonasynchronousffmpegsubprocesspython-3.6

解决方案


推荐阅读