树莓派使用python-librtmp实现rtmp推流h264的方法
作者:西红柿炖番茄 发布时间:2021-10-24 13:50:15
标签:python,librtmp,rtmp,h264
目的是能使用Python进行rtmp推流,方便在h264帧里加入弹幕等操作。
librtmp使用的是0.3.0,使用树莓派noir官方摄像头适配的。
通过wireshark抓ffmpeg的包一点点改动,最终可以在red5和斗鱼上推流了。
没怎么写过python,有不恰当的地方请包涵。
上代码:
# -- coding: utf-8 --
# http://blog.csdn.net/luhanglei
import picamera
import time
import traceback
import ctypes
from librtmp import *
global meta_packet
global start_time
class Writer(): # camera可以通过一个类文件的对象来输出,实现write方法即可
conn = None # rtmp连接
sps = None # 记录sps帧,发过以后就不需要再发了(抓包看到ffmpeg是这样的)
pps = None # 同上
sps_len = 0 # 同上
pps_len = 0 # 同上
time_stamp = 0
def __init__(self, conn):
self.conn = conn
def write(self, data):
try:
# 寻找h264帧间隔符
indexs = []
index = 0
data_len = len(data)
while index < data_len - 3:
if ord(data[index]) == 0x00 and ord(data[index + 1]) == 0x00 and ord(
data[index + 2]) == 0x00 and ord(data[index + 3]) == 0x01:
indexs.append(index)
index = index + 3
index = index + 1
# 寻找h264帧间隔符 完成
# 通过间隔符个数确定类型,树莓派摄像头的第一帧是sps+pps同时发的
if len(indexs) == 1: # 非sps pps帧
buf = data[4: len(data)] # 裁掉原来的头(00 00 00 01),把帧内容拿出来
buf_len = len(buf)
type = ord(buf[0]) & 0x1f
if type == 0x05: # 关键帧,根据wire shark抓包结果,需要拼装sps pps 帧内容 三部分,长度都用4个字节表示
body0 = 0x17
data_body_array = [bytes(bytearray(
[body0, 0x01, 0x00, 0x00, 0x00, (self.sps_len >> 24) & 0xff, (self.sps_len >> 16) & 0xff,
(self.sps_len >> 8) & 0xff,
self.sps_len & 0xff])), self.sps,
bytes(bytearray(
[(self.pps_len >> 24) & 0xff, (self.pps_len >> 16) & 0xff, (self.pps_len >> 8) & 0xff,
self.pps_len & 0xff])),
self.pps,
bytes(bytearray(
[(buf_len >> 24) & 0xff, (buf_len >> 16) & 0xff, (buf_len >> 8) & 0xff, (buf_len) & 0xff])),
buf
]
mbody = ''.join(data_body_array)
time_stamp = 0 # 第一次发出的时候,发时间戳0,此后发真时间戳
if self.time_stamp != 0:
time_stamp = int((time.time() - start_time) * 1000)
packet_body = RTMPPacket(type=PACKET_TYPE_VIDEO, format=PACKET_SIZE_LARGE, channel=0x06,
timestamp=time_stamp, body=mbody)
packet_body.packet.m_nInfoField2 = 1
else: # 非关键帧
body0 = 0x27
data_body_array = [bytes(bytearray(
[body0, 0x01, 0x00, 0x00, 0x00, (buf_len >> 24) & 0xff, (buf_len >> 16) & 0xff,
(buf_len >> 8) & 0xff,
(buf_len) & 0xff])), buf]
mbody = ''.join(data_body_array)
# if (self.time_stamp == 0):
self.time_stamp = int((time.time() - start_time) * 1000)
packet_body = RTMPPacket(type=PACKET_TYPE_VIDEO, format=PACKET_SIZE_MEDIUM, channel=0x06,
timestamp=self.time_stamp, body=mbody)
self.conn.send_packet(packet_body)
elif len(indexs) == 2: # sps pps帧
if self.sps is not None:
return
data_body_array = [bytes(bytearray([0x17, 0x00, 0x00, 0x00, 0x00, 0x01]))]
sps = data[indexs[0] + 4: indexs[1]]
sps_len = len(sps)
pps = data[indexs[1] + 4: len(data)]
pps_len = len(pps)
self.sps = sps
self.sps_len = sps_len
self.pps = pps
self.pps_len = pps_len
data_body_array.append(sps[1:4])
data_body_array.append(bytes(bytearray([0xff, 0xe1, (sps_len >> 8) & 0xff, sps_len & 0xff])))
data_body_array.append(sps)
data_body_array.append(bytes(bytearray([0x01, (pps_len >> 8) & 0xff, pps_len & 0xff])))
data_body_array.append(pps)
data_body = ''.join(data_body_array)
body_packet = RTMPPacket(type=PACKET_TYPE_VIDEO, format=PACKET_SIZE_LARGE, channel=0x06,
timestamp=0, body=data_body)
body_packet.packet.m_nInfoField2 = 1
self.conn.send_packet(meta_packet, queue=True)
self.conn.send_packet(body_packet, queue=True)
except Exception, e:
traceback.print_exc()
def flush(self):
pass
def get_property_string(string): # 返回两字节string长度及string
length = len(string)
return ''.join([chr((length >> 8) & 0xff), chr(length & 0xff), string])
def get_meta_string(string): # 按照meta packet要求格式返回bytes,带02前缀
return ''.join([chr(0x02), get_property_string(string)])
def get_meta_double(db):
nums = [0x00]
fp = ctypes.pointer(ctypes.c_double(db))
cp = ctypes.cast(fp, ctypes.POINTER(ctypes.c_longlong))
for i in range(7, -1, -1):
nums.append((cp.contents.value >> (i * 8)) & 0xff)
return ''.join(bytes(bytearray(nums)))
def get_meta_boolean(isTrue):
nums = [0x01]
if (isTrue):
nums.append(0x01)
else:
nums.append(0x00)
return ''.join(bytes(bytearray(nums)))
conn = RTMP(
'rtmp://192.168.199.154/oflaDemo/test', # 推流地址
live=True)
librtmp.RTMP_EnableWrite(conn.rtmp)
conn.connect()
start_time = time.time()
# 拼装视频格式的数据包
meta_body_array = [get_meta_string('@setDataFrame'), get_meta_string('onMetaData'),
bytes(bytearray([0x08, 0x00, 0x00, 0x00, 0x06])), # 两个字符串和ECMA array头,共计6个元素,注释掉了音频相关数据
get_property_string('width'), get_meta_double(640.0),
get_property_string('height'), get_meta_double(480.0),
get_property_string('videodatarate'), get_meta_double(0.0),
get_property_string('framerate'), get_meta_double(25.0),
get_property_string('videocodecid'), get_meta_double(7.0),
# get_property_string('audiodatarate'), get_meta_double(125.0),
# get_property_string('audiosamplerate'), get_meta_double(44100.0),
# get_property_string('audiosamplesize'), get_meta_double(16.0),
# get_property_string('stereo'), get_meta_boolean(True),
# get_property_string('audiocodecid'), get_meta_double(10.0),
get_property_string('encoder'), get_meta_string('Lavf57.56.101'),
bytes(bytearray([0x00, 0x00, 0x09]))
]
meta_body = ''.join(meta_body_array)
print meta_body.encode('hex')
meta_packet = RTMPPacket(type=PACKET_TYPE_INFO, format=PACKET_SIZE_LARGE, channel=0x04,
timestamp=0, body=meta_body)
meta_packet.packet.m_nInfoField2 = 1 # 修改stream id
stream = conn.create_stream(writeable=True)
with picamera.PiCamera() as camera:
camera.start_preview()
time.sleep(2)
camera.start_recording(Writer(conn), format='h264', resize=(640, 480), intra_period=25,
quality=25) # 开始录制,数据输出到Writer的对象里
while True:#永远不停止
time.sleep(60)
camera.stop_recording()
camera.stop_preview()
来源:https://blog.csdn.net/luhanglei/article/details/78403900
0
投稿
猜你喜欢
- 如下所示:lists = ['tom','Jack','luCy','lily
- 由于可将 Microsoft? SQL Server? 2000 设置为包含一个或多个命名实例和一个默认实例(也可无),所以要用新命名规则来
- <?php/*定义和用法strstr() 函数搜索一个字符串在另一个字符串中的第一次出现。该函数返回字符串的其余部分(从匹配点)。如果
- 本文大纲os模块是Python标准库中一个重要的模块,里面提供了对目录和文件的一般常用操作。而Python另外一个标准库——shutil库,
- 为大家提供了两种有效PyCharm激活方法,第一种PyCharm激活方法是直接输入激活码,一般PyCharm激活使用的人多了会被官方封,所以
- 惭愧啊,今天写了个查找子串的Python程序被BS了…如果让你写一个程序检查字符串s2中是不是包含有s1。也许你会很直观的写下下面的代码:#
- varint今天本来在研究 OpenTelemetry 的基准性能测试 github.com/zdyj3170101…
- pandas可以对不同索引的对象进行算术运算,如果存在不同的索引对,结果的索引就是该索引对的并集。一、算术运算a、series的加法运算 &
- function sAlert(msg,boxtype,func,msgtitle) sAlert('信息内容',1,
- 思路复原魔方困难问题的分解:1、用合适的数据结构表示出三阶魔方的六个面以及每一面的颜色2、每一次不同旋转操作的实现3、复原时如何判断当前魔方
- 编写函数装饰器本节主要介绍编写函数装饰器的相关内容。跟踪调用如下代码定义并应用一个函数装饰器,来统计对装饰的函数的调用次数,并且针对每一次调
- 前言在安装MySQL的时候会默认初始化几个MySQL运行所需的数据库:mysql, sys, information_schema, per
- 使用Keras训练好的模型用来直接进行预测,这个时候我们该怎么做呢?【我这里使用的就是一个图片分类网络】现在让我来说说怎么样使用已经训练好的
- 我要说的内容都是非常基础的内容,高手就免看了,如果看了欢迎给点意见啊。新手或者对低层还不是很了解的人可以看看,帮助理解与记忆。XMLHttp
- Python中国象棋单机版鼠标点击操作;两天制作,较为粗糙,很多效果还未实现。# -*- coding: utf-8 -*-"&q
- 1、自定义 图表 组件Echarts.vue<!-- 自定义 echart 组件 --><template> <
- 1、权限赋予 说明:mysql部署在服务器A上,内网上主机B通过客户端工具连接服务器A以进行数据库操作,需要服务器A赋予主机B操作mysql
- .游标方式 1 DECLARE @Data NVARCHAR(max) SET @Data='1,tanw;2,keen
- 这篇文章主要介绍了如何获取Python简单for循环索引,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的
- 最近使用到一个文件上传功能,发现恶意上传一个2G文件时,后台处理响应较慢,遂想到能否使用js来进行客户端的验证。但查阅网上多处资料,均使用