Python多进程调用ffmpeg合并MP4报Output file #0 does not contain any stream错误
问题排查与修复
核心错误点
- 帧读取后未写入输出文件:循环内仅调用
clip.read()读取帧,没有执行out.write(frame)操作,所有输出分片都是空文件,ffmpeg合并空文件自然提示无流。 - 计数器未累加:循环判断条件为
proc_frames < frame_jump_unit,但循环体内没有对proc_frames做自增操作,循环永远无法正常终止,无有效帧输出。 - VideoWriter重复打开冲突:连续两次调用
out.open(),第一次打开的公共文件直接被第二次分片文件覆盖,且多进程同时写入同一个公共文件会导致文件损坏,第一次open操作属于冗余错误代码。 - 语法缩进错误:
if not ret:下的break未缩进,触发语法错误,读帧失败逻辑无法正常执行。 - 空异常捕获吞错:裸
except块会捕获所有异常且无任何提示,无法感知运行过程中出现的错误。 - ffmpeg命令构造错误:代码中ffmpeg命令字符串被强制换行,实际运行会出现命令截断问题。
修复后代码
process_video 函数
def process_video(group_number): num_processes = mp.cpu_count() width, height, frame_count = get_video_frame_details(file_name) frame_jump_unit = frame_count // num_processes # 最后一个进程处理剩余的所有帧,避免丢帧 if group_number == num_processes - 1: process_frames_total = frame_count - frame_jump_unit * group_number else: process_frames_total = frame_jump_unit clip = cv.VideoCapture(file_name) clip.set(cv.CAP_PROP_POS_FRAMES, frame_jump_unit * group_number) width = int(clip.get(cv.CAP_PROP_FRAME_WIDTH)) height = int(clip.get(cv.CAP_PROP_FRAME_HEIGHT)) fps = int(clip.get(cv.CAP_PROP_FPS)) proc_frames = 0 fourcc = cv.VideoWriter_fourcc('m', 'p', '4', 'v') out = cv.VideoWriter() # 删掉冗余的open调用,只打开当前进程对应的分片文件 out.open(f"output_{group_number}.mp4", fourcc, fps, (width, height), True) try: while proc_frames < process_frames_total: ret, frame = clip.read() if not ret: break # 新增写入帧操作 out.write(frame) # 新增计数器累加 proc_frames += 1 except Exception as e: # 打印异常信息方便排查 print(f"进程{group_number}处理出错:{str(e)}") finally: clip.release() out.release()
combine_output_files 函数调整
def combine_output_files(num_processes): output_file_name = "Aktorik_sliced.mp4" list_of_output_files = [f"output_{i}.mp4" for i in range(num_processes)] with open("list_of_output_files.txt", "w") as f: for t in list_of_output_files: f.write(f"file {t}\n") # 命令写在同一行,避免换行截断 ffmpeg_cmd = f"ffmpeg -y -loglevel error -f concat -safe 0 -i list_of_output_files.txt -vcodec copy {output_file_name}" sp.Popen(ffmpeg_cmd, shell=True).wait()
额外验证点
运行前可以先检查单个output_x.mp4文件大小,如果大小为0说明进程处理逻辑还有问题,优先排查视频读取路径、权限问题。
内容的提问来源于stack exchange,提问作者tegarsosi
相关产品推荐
相关产品推荐

