阿朴朴 2025-12-18 10:23
浏览 6
已结题

使用FFmpeg保存视频碰到诡异事件

问题:
当我使用FFmpeg保存视频的时候遇到问题,同样的代码,用Jupyter运行可以成功,在.py文件运行却报错了。机器为8*A800

下面是我的代码


import os

import subprocess
import time

from concurrent.futures import ThreadPoolExecutor, as_completed,ProcessPoolExecutor

from pathlib import Path
import os

import torch
torch.cuda.init()
torch.cuda.synchronize()
def _ffmpeg_batch_split_gpu( video_path: str, scene: list, output_folder: str) -> list:
        """单个片段的切割逻辑(供线程池调用)"""
        start_time, end_time, scene_idx = scene
        current_duration = end_time - start_time
        gpu =scene_idx%8


        # 构建输出路径
        output_folder_path = Path(output_folder) / f"scene_{scene_idx:02d}"
        output_folder_path.mkdir(parents=True, exist_ok=True)
        output_path = str(output_folder_path / f"scene_{scene_idx:02d}.mp4")
                
        # 构建FFmpeg命令
        ffmpeg_cmd = [
            "ffmpeg", 

            "-hwaccel", "cuda",          
            "-hwaccel_device", str(gpu),      # 指定GPU
            "-i", video_path,            # 输入视频(-hwaccel必须在-i前)
            "-ss", str(start_time),      # 精准切片(保留)
            "-to", str(end_time),        
            "-c:v", "h264_nvenc",        
            "-preset", "4",             # 核心:(最快预设,等效superfast)
            "-crf", "26",                
            "-hide_banner",
            "-threads", "2",             
            "-loglevel", "error",
            "-y",
            "-gpu", str(gpu),                 
            "-rc", "vbr",                
            "-c:a", "aac",              
            "-b:a", "128k",              
            output_path                 
        ]

        # 执行切割
        try:
            result = subprocess.run(ffmpeg_cmd,capture_output=True,text=True,encoding="utf-8",errors="ignore",shell=False)#, timeout=30)

            # 验证有效性
            if result.returncode != 0:
                raise RuntimeError(f"FFmpeg错误:{result.stderr.strip()[:100]}")
            if not os.path.exists(output_path) or os.path.getsize(output_path) < 1024:
                raise RuntimeError(f"文件无效(大小:{os.path.getsize(output_path) or 0}字节)")

            # video_Transtion.info(f"片段{scene_idx}成功:{output_path}")
            return (output_path, [round(current_duration, 3), round(start_time,3),round(end_time, 3)])
        except Exception as e:
            print(e)
            if os.path.exists(output_path):
                os.remove(output_path)

def executor():

    save_video_executor = ThreadPoolExecutor(max_workers=2)
    video_path = '/data/server/video_analysis/test/images/d1dd4c494dac1dd8b342afca06e76b0e.mp4'
    futures = {}
    start_time = time.time()
    ouput_path = '/data/server/video_analysis/test/output_data'
    os.makedirs(ouput_path,exist_ok=True)
    count=0
    for i in range(10):

        futures[save_video_executor.submit(_ffmpeg_batch_split_gpu,video_path,[i*5,(i+2)*5,i],ouput_path)]=i
    for future in as_completed(futures):
        idx = futures[future]
        try:
            result = future.result()  
            if result:
                count+=1
        except Exception as e:
            print(e)
    print(time.time()-start_time)

 executor()

报错内容
FFmpeg错误:[h264_nvenc @ 0x5614c128c540] OpenEncodeSessionEx failed: unsupported device (2)
[h264_nvenc @ 0x561

然后我把相同的代码,放在L20机器上运行,Jupyter和.py文件运行都没有出错,问AI也没有解决这个问题,这是为什么?各位大佬有碰到过这个问题吗?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    问题事件

    • 系统已结题 12月26日
    • 创建了问题 12月18日