FFmpeg学习笔记(二):多线程rtsp推流和ffplay拉流操作,并储存为多路avi格式的视频

多线程

import threading
import time
# acquire the face iou
def get_frame():
    print("当前线程的信息:", threading.current_thread())
    time.sleep(1)

# acquire the face feature pkl
def get_feature():
    print("当前线程的信息:", threading.current_thread())
    time.sleep(10)

def main():
    # start the multiprocess
    t1=threading.Thread(target=get_frame,name='face_iou_save')
    t2=threading.Thread(target=get_feature,name='face_feature_pkl')
    t1.daemon = True
    t2.daemon = True # assist the process
    t1.start()
    t2.start() # start the process
    print('threading.active')
    t1.join()
    t2.join()
    print('threading.end')
if __name__ == '__main__':
    main()

如果不了解什么是rtsp推流和ffplay拉流可以看我这篇博客
https://blog.csdn.net/m0_51004308/article/details/117430611?spm=1001.2014.3001.5501
由于项目需要,不得不使用多线程的方式来进行视频流的推送,从边缘端储存到服务器端。多线程的方式很明显有个非常大的特点,线程之间不相互影响,也就是你有你的工作,我有我的工作,你不工作了没关系,也不会影响我。
下面请看推流和拉流的代码

多进程rtsp推流


import cv2
import time
import multiprocessing as mp

def recovery_stream(cap,rtsp_url,retry_delay=10):
    while True:
        try:
            print(f"正在重新连接RTSP流:{rtsp_url}...")
            cap.release()
            cap = cv2.VideoCapture(rtsp_url)
            if cap.isOpened():
                print(f"RTSP流恢复成功:{rtsp_url}")
                return cap
        except Exception as e:
            print(f"尝试恢复RTSP流时遇到错误:{e}")
        time.sleep(retry_delay) # 等待10秒

def image_put(q, rtsp_url, rtsp_name):
    # 创建VideoCapture对象,指定RTSP流地址
    cap = cv2.VideoCapture(rtsp_url)
    fps = cap.get(cv2.CAP_PROP_FPS)
    print("FPS:", fps)
    if not cap.isOpened():
        print(f"无法打开RTSP流:{rtsp_url}")
        cap = recovery_stream(cap,rtsp_url,retry_delay=10)

    while True:
        ret, frame = cap.read()
        if not ret:
            cap = recovery_stream(cap,rtsp_url,retry_delay=10)
            ret,frame = cap.read()

        while q.qsize() > 1:
            try:
                _ = q.get_nowait()
            except Exception as e:
                pass

        q.put(frame)
        time.sleep(1/fps)
        # time.sleep(0.01)

def image_get(q, rtsp_url, rtsp_name):
    windowname = rtsp_url
    cv2.namedWindow(windowname)
    i = 0
    while True:
        frame = q.get(block=True)
        resized_frame = cv2.resize(frame, (640, 480))
        cv2.imshow(windowname, resized_frame)
        i += 1
        if cv2.waitKey(25) == 27: 
            break
        print("{}:{}".format(rtsp_name,i))

def run_multi_camera(rtsp_urls, rtsp_names):
    mp.set_start_method('spawn')
    queues = [mp.Queue(maxsize=2) for _ in rtsp_urls]
    queues1 = [mp.Queue(maxsize=2) for _ in rtsp_urls] # 备用
    stop_event = mp.Event()  # 创建一个停止事件
    processes = []

    for queue,rtsp_url,rtsp_name in zip(queues,rtsp_urls,rtsp_names):
        processes.append(mp.Process(target=image_put, args=(queue, rtsp_url, rtsp_name)))
        processes.append(mp.Process(target=image_get, args=(queue, rtsp_url, rtsp_name)))

    for process in processes:
        process.daemon = True
        process.start()
    for process in processes:
        process.join()
    stop_event.set()  # 设置停止事件,通知所有子进程退出

if __name__ == '__main__':
    # RTSP视频流地址
    rtsp_urls = ['rtsp://21*******e442aae',
            'rtsp://21**********d14275']
    rtsp_names = ["video1", "video2"]
    run_multi_camera(rtsp_urls, rtsp_names)

# 代码描述:利用多进程方法,利用两个海康威视摄像头,同时录取视频并保存本地

import cv2
import time
import multiprocessing as mp
import subprocess as sp
import  traceback

num = 0

# 抓取图片,确认视频流的读入
def image_put(q, name, pwd, ip, channel,ids):
    # if type(channel)== int:
    #cv2.namedWindow(ip, cv2.WINDOW_NORMAL)
    global url
    url="rtsp://%s:%s@%s:%s//Streaming/Channels/%s" \
                           % (name, pwd, ip, channel,ids)
    cap = cv2.VideoCapture(url)
    # 获取视频帧率
    fps = cap.get(cv2.CAP_PROP_FPS)
    print('fps: ', fps)
    if cap.isOpened():
        print('HIKVISION1')
        print('camera ' + ip + " connected.")
    #else:
    #    cap = cv2.VideoCapture("rtsp://%s:%s@%s/cam/realmonitor?channel=%d&subtype=0" % (name, pwd, ip, channel))
    #   print('DaHua')
    while cap.isOpened():
        # print('cap.read()[0]:', cap.read()[0])
        ret, frame = cap.read()
        # print('ret:', ret)
        #frame = cv2.resize(frame, (800, 600))
        # 抓取图片不成功再重新抓取
        if not ret:
            cap = cv2.VideoCapture("rtsp://%s:%s@%s:%s//Streaming/Channels/1" \
                                   % (name, pwd, ip, channel))
            print('HIKVISION2')
            ret, frame = cap.read()
            #frame = cv2.resize(frame, (800,600))
        # Press esc on keyboard to  exit
        # if cv2.waitKey(1) & 0xFF == 27:
        #     break
        q.put(frame) # 线程A不仅将图片放入队列
        # print('q.qsize():',(q.qsize() > 1))
        q.get() if q.qsize() > 1 else time.sleep(0.01) # 线程A还负责移除队列中的旧图
    cap.release()



# 获得视频流帧数图片,保存读入的视频
def image_get(q, name, pwd, ip, channel,ids,command):
    while True:
        if len(command) > 0:
            # 管道配置
            pipe = sp.Popen(command,shell=True, stdin=sp.PIPE)# ,shell=False
            break
    if pipe.poll() is not None:
        print(pipe.poll())
        #pipe = sp.Popen(command,shell=True, stdin=sp.PIPE)# ,shell=False
        time.sleep(3)
    while True:
        num += 1
        frame = q.get()
        if num == 100:
            print("start sleep 50")
            time.sleep(50)
            print("end sleep 50")
        if num >= 100:
            print("超时后的,第%d次写入" % (num - 99))
            time.sleep(5)
        try:
            pipe.stdin.write(frame.tostring())  # 存入管道用于直播
        except:
            traceback.print_exc()

# 解决进程问题
def run_multi_camera():
    # user_name, user_pwd = "admin", "password"
    user_name, user_pwd = "admin", "a12345678"
    # 摄像头的账户密码改成自己摄像头注册的信息
    camera_ip_l = [
         # ipv4
        "10.16.55.149",
        "10.16.55.150",
        "10.16.55.151",
        "10.16.55.152",
        # 把你的摄像头的地址放到这里,如果是ipv6,那么需要加一个中括号
    ]
    ports = ['554', '555', '556','557']#'554',
    idss=['1','2','3','4']
    commands=[]
    for camera_ip,port,ids in zip(camera_ip_l,ports,idss):
        command="""ffmpeg -re -rtsp_transport tcp -i \"rtsp://admin:a12345678@{}:{}//Streaming/Channels/1\" -f flv -vcodec libx264 -vprofile baseline -acodec aac -ar 44100 -strict -2 -ac 1 -f flv -flvflags no_duration_filesize -r 29.97 -s 1280x720 -q 10 \"rtmp://127.0.0.1:1935/live/{}""".format(camera_ip,port,ids)
        command=command+'"'
        commands.append(command)
    mp.set_start_method(method='spawn')  # init
    queues = [mp.Queue(maxsize=2) for _ in camera_ip_l]

    processes = []
    for queue, camera_ip,port,ids,command in zip(queues, camera_ip_l,ports,idss,commands):

        processes.append(mp.Process(target=image_put, args=(queue, user_name, user_pwd, camera_ip,port,ids)))
        processes.append(mp.Process(target=image_get, args=(queue, user_name, user_pwd, camera_ip,port,ids,command)))

    for process in processes:
        process.daemon = True
        process.start()
    for process in processes:
        process.join()


if __name__ == '__main__':
    run_multi_camera()           # 调用主函数


多进程ffplay拉流(并保存视频)

import cv2
import multiprocessing as mp
# 这里需要依赖的还有 ffmpeg 
def image_save(q,url,camera_id):
    print(url)
    cap = cv2.VideoCapture(url)
    ret, frame = cap.read()
    print(ret) # 这里会返回是否正常返回流,正常返回True
    fourcc = cv2.VideoWriter_fourcc(*'XVID') # 创建本地文件
    fps = cap.get(cv2.CAP_PROP_FPS)
    size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
    save_path='{}.avi'.format(camera_id)
    print(save_path)
    out = cv2.VideoWriter(save_path, fourcc, fps, size)
    # while ret:
    while ret:
        ret,frame=cap.read()
        if not ret:
            cap = cv2.VideoCapture(url)
            print('the url {} connect again'.format(url))
            ret, frame = cap.read()
        # print('{}'.format(camera_id),ret)
        try:
            cv2.imshow('{}'.format(url),frame)
        except (cv2.error) as e:
            print('except:', e)
            continue
        if cv2.waitKey(1)&0xFF==ord('q'):
            break

        out.write(frame)
    cv2.destroyAllWindows()
    cap.release()
def main(urls,camera_ids):
    print(urls)
    mp.set_start_method(method='spawn')  # init
    queues = [mp.Queue(maxsize=2) for _ in urls]
    processes = []
    for queue, url,camera_id in zip(queues, urls,camera_ids):
        processes.append(mp.Process(target=image_save, args=(queue, url,camera_id)))
        # processes.append(mp.Process(target=image_get, args=(queue, camera_ip)))
    for process in processes:
        process.daemon = True
        process.start()
    for process in processes:
        process.join()


if __name__ == '__main__':
    """begin detection cemara"""
    urls,camera_ids = [],[]
    for i in range(1, 5):# 1 2
        camera_ids.append(int(i))
        urls.append('rtmp://127.0.0.1:1935/live/{}'.format(i))
    # print(camera_ids)
    main(urls,camera_ids)  # 调用主函数

多进程和多线程的配合使用

import multiprocessing
import threading

def foo():
	print 'threading.current_thread(): ', threading.current_thread()

def bar():
	threads = []
	for _ in range(4): # each Process creates a number of new Threads
    		thread = threading.Thread(target=foo)
    		threads.append(thread)
	for thread in threads:
    		thread.start()
    		thread.join()

if __name__ == "__main__":
	processes = []
	for _ in range(3):
    		p = multiprocessing.Process(target=bar) # create a new Process
    		processes.append(p)
	for process in processes:
    		process.start()
    		process.join()

  • 2
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
ffmpeg 是一个强大的音视频处理工具,它可以用来进行各种音视频格式的编解码、转码、剪辑等操作。下面是基于 C++ 使用 ffmpeg 进行 RTSP 拉流推流的流程: 1. 引入 ffmpeg 库:首先需要在项目中引入 ffmpeg 库,可以使用静态库或者动态库,具体方法不再赘述。 2. 初始化 ffmpeg:在使用 ffmpeg 前,需要初始化 ffmpeg,这可以通过调用 av_register_all() 函数实现。 3. 创建 AVFormatContext:创建一个 AVFormatContext 对象,用于存储音视频流的相关信息,包括音视频编码格式、流的时间基等信息。可以通过调用 avformat_alloc_context() 函数来创建。 4. 打开 RTSP 流:调用 avformat_open_input() 函数打开 RTSP 流,传入 RTSP 地址、AVFormatContext 对象等参数,函数会自动解析出音视频流的信息并存储到 AVFormatContext 对象中。 5. 查找音视频流:通过调用 avformat_find_stream_info() 函数,可以查找音视频流的索引,该函数会自动解析音视频流的信息,并将音视频流的索引存储到 AVFormatContext 对象中。 6. 获取音视频流的信息:可以通过遍历 AVFormatContext 对象的 streams 属性,获取每个音视频流的详细信息,包括编码格式、分辨率、码率等等。 7. 打开音视频解码器:对于每个音视频流,需要打开相应的解码器,可以通过调用 avcodec_find_decoder() 函数查找对应的解码器,然后调用 avcodec_open2() 函数打开解码器。 8. 创建 AVFrame 和 AVPacket:解码音视频帧需要使用 AVFrame 和 AVPacket 对象,可以通过调用 av_frame_alloc() 和 av_packet_alloc() 函数创建。 9. 读取音视频帧:通过调用 av_read_frame() 函数读取音视频帧,该函数会返回一个 AVPacket 对象,包含了音视频帧的数据和相关信息。 10. 解码音视频帧:根据 AVPacket 对象中的信息,可以调用对应的解码器进行解码,解码后的结果存储在 AVFrame 对象中。 11. 处理音视频帧:可以对解码后的音视频帧进行各种处理,比如转换格式、合并音视频等。 12. 推流:可以使用 avformat_new_stream() 函数创建一个新的音视频流,并设置相应的参数,然后使用 avio_open() 函数打开一个输出流,最后调用 avformat_write_header() 函数开始推流。 13. 写入音视频帧:对于每一帧音视频数据,可以调用 av_interleaved_write_frame() 函数写入输出流中,该函数会自动进行封装和编码。 14. 关闭流和解码器:最后记得关闭输入流、输出流和解码器,释放相应的资。 以上是基于 C++ 使用 ffmpeg 进行 RTSP 拉流推流的大致流程,具体实现还需要根据具体的需求和情况进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZZY_dl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值