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 代码示例

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)可用一个账号管理全部磁盘


高维文件管理器

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值