ffmpeg 子进程从内存读取文件、提取图片到内存

除了网络、文件io,由python或java或go或c等语言开启的ffmpeg子进程还支持pipe,可以从stdin读入数据,输出转化后的图像到stdout。无需编译 ffmpeg,直接调用 ffmpeg.exe不香么!

"从内存读"可用于边下载边转码,节省硬盘寿命。

"提取到内存"可用于服务端生成缩小的预览图,然后发给客户端,传输较快。

从内存读数据流 注意事项

对格式有要求,不能是需要随机读取的文件,比如不能是 MP4,可以是 flv。

参考资料 1:go - ffmpeg via pipe: stream 1, offset 0x30: partial file - Stack Overflow

参考资料 2:command line - FFmpeg "Pipe:0: Invalid data found when processing input" TGA files - Super User

ffmpeg_subprocess.py 代码示例

py 复制代码
import subprocess


print(123)

# Assuming you have the buffer stored in a variable called 'buffer'


ffmpegexe = r'ffmpeg.exe'

# Invoke FFmpeg and pass the buffer as input using the 'pipe' protocol
process = subprocess.Popen([ffmpegexe
            # , "-loglevel", "quiet"
            # , '-f', 'ts'
            , '-f', 'flv'
            , '-i', 'pipe:0'
            , '-c', 'copy'
            , '-y', 'E:\\test_output.flv'], stdin=subprocess.PIPE)


path = 'E:\\test.flv'
length = 0
# Read from the file 'path' in a while loop, 1024 bytes per loop, and write the buffer to process.stdin
with open(path, 'rb') as file:
    while True:
        buffer = file.read(1024)
        if not buffer:
            break
        size = len(buffer)
        print('read::', size)
        length += size
        process.stdin.write(buffer)
        process.stdin.flush()


print('readed all::', length)

# Close the stdin to indicate the end of input
process.stdin.close()

# Wait for the FFmpeg process to finish
process.wait()

结果是,while一边读取flv视频流,ffmpeg一边转换。

输出图像至内存

比如:用于为视频生成缩略图,不用产生临时文件,比较干净:

\生成(视频、图片)缩略图的办法

别老抱着es不放了,视频、图片缩略图可以都用 ffmpeg 生成,有多种办法实现,可移植到windows平台。

方法一、将 lib_ffmpeg 集成到客户端,从网络生成缩略图

这种方法需要编译支持ftp协议的 ffmpeg,然后自行适配各个平台,需要解决各种问题,开发效率低下,而且一旦处理不好,会导致jni崩溃。

结果是传输慢、消耗流量多。

方法二、魔改ftp服务端,调用 ffmpeg.exe 生成缩略图,直接返回图片

无需编译 ffmpeg,直接调用 ffmpeg.exe。

由服务端生成缩小的预览图,然后发给ftp客户端,传输较快。

而且得益于 ffmpeg 丰富的命令配置,可以自定义缩小的尺寸(-vf scale=100:100)、无需生成临时文件(PIPE)等等。

ftp服务端 客户端 我用的都是 appache ftpserver,并加以扩展。

新增 服务端缩略图生成能力

新增 支持目录链接(lnk)可用一个账号管理全部磁盘


高维文件管理器

相关推荐
iummature3 小时前
FFmpeg命令
ffmpeg
渔舟唱晚@4 小时前
FFmpeg+WebSocket+JsMpeg实时视频流实现方案
websocket·网络协议·ffmpeg
xcg34012321 小时前
关于视频抽帧调用虹软人脸识别的BufferedImage读取优化策略
ffmpeg·音视频·视频抽帧
繁依Fanyi1 天前
使用 FFmpeg 剪辑视频指南
java·服务器·开发语言·ffmpeg·音视频
deadknight92 天前
定期自动统计大表执行情况
ffmpeg
cuijiecheng20184 天前
音视频入门基础:RTP专题(9)——FFmpeg接收RTP流的原理和内部实现
ffmpeg·音视频
偶是老李头4 天前
Ubuntu虚拟机NDK编译ffmpeg
linux·ubuntu·ffmpeg·android ndk
lucky-billy4 天前
Qt 中使用 ffmpeg 获取采集卡数据录制视频
qt·ffmpeg·音视频
cuijiecheng20185 天前
FFmpeg源码:url_find_protocol函数分析
ffmpeg
大懒猫软件5 天前
使用 Python 爬虫和 FFmpeg 爬取 B 站高清视频
爬虫·python·ffmpeg