python实时视频流播放
2023-09-14 08:57:24 时间
@action(methods=['GET'], detail=True) def video(self, request, pk=None): """ 获取设备实时视频流 :param request: :param pk: :return: """ device_obj = self.get_object() # if device_obj.status == 0: # return Response({'error': '设备离线'}) if not device_obj.rtsp_address: return Response({'error': '缺少rtsp地址'}) cache_id = '_video_stream_{}'.format(device_obj.hash) cache_status = cache.get(cache_id, None) if cache_status is None: # 任务初始化,设置初始时间 cache.set(cache_id, time.time(), timeout=60) elif isinstance(cache_status, float) and time.time() - cache_status > 30: # 任务已超时, 返回错误信息, 一段时间内不再入队 return Response({'error': '连接数目超过限制, 请稍后再试'}) ret = job_queue.enqueue_video(rtsp_address=device_obj.rtsp_address, device_hash=device_obj.hash) logger.info('fetch device %s video job status: %s', pk, ret._status) if ret._status == b'started' or 'started': # 视频流正常推送中, 刷新播放时间, 返回视频ID cache.set(cache_id, 'continue', timeout=30) return Response({'video': ''.join([settings.FFMPEG_VIDEO, device_obj.hash])}) elif ret._status == b'queued' or 'queued': # 视频任务等待中 return Response({'status': '等待建立视频连接'}) else: # 建立视频任务失败 return Response({'error': '打开视频失败'})
class JobQueue: """实时视频播放""" def __init__(self): self.video_queue = django_rq.get_queue('video') # 视频推流消息队列 def enqueue_video(self, rtsp_address, device_hash): """视频流队列""" job_id = 'video_{}'.format(device_hash) job = self.video_queue.fetch_job(job_id) if not job: job = self.video_queue.enqueue_call( func='utils.ffmpeg.ffmpeg_play', args=(rtsp_address, device_hash), timeout=-1, ttl=30, # 最多等待30秒 result_ttl=0, job_id=job_id ) return job
# -*- coding: utf-8 -*- import subprocess import threading import time import logging from django.core.cache import cache logger = logging.getLogger('server.default') def ffmpeg_play(stream, name): play = True cache_id = '_video_stream_{}'.format(name) cache.set(cache_id, 'continue', timeout=30) process = None def upstream(): cmd = "ffmpeg -i '{}' -c:v h264 -f flv -r 25 -an 'rtmp://127.0.0.1:1935/live/{}'".format(stream, name) process = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stderr=subprocess.DEVNULL) try: logger.info('device: {} stream thread start: {}'.format(name, stream)) while play: time.sleep(1) except Exception as e: logger.info('device: {} stream thread error {}'.format(name, e)) finally: logger.info('device: {} stream thread stop'.format(name)) process.communicate(b'q') thr = threading.Thread(target=upstream) thr.start() try: while True: play = cache.get(cache_id, '') if play != 'continue': logger.info('stop device {} video stream'.format(name)) play = False break time.sleep(1) except Exception as e: logger.info('device: {} play stream error {}'.format(name, e)) process.communicate(b'q') logger.info('wait device {} video thread stop'.format(name)) thr.join() logger.info('device {} video job stop'.format(name))
# 实时视频流播放 RQ_QUEUES = { 'video': { 'USE_REDIS_CACHE': 'video', } }
# 还可以通过cv2实现。但是弹出框是自带的,可能出现问题;还可以转成websocket格式返回给前端··
相关文章
- 【Python成长之路】python 基础篇 -- 装饰器【华为云分享】
- 【Python】python 日期操作
- 【Oracle】Python 连接Oracle 数据库
- 归纳整理Python中的控制流语句的知识点
- Python 进阶(五)定制类
- python:pip升级pip本身和setuptools(Python 3.7.15)
- [LINK]Python服务器开发一:python基础
- Atitit python3.0 3.3 3.5 3.6 新特性 Python2.7新特性1Python 3_x 新特性1python3.4新特性1python3.5新特性1值得关注的新特性1Python3.6新特性2 Python2.7新特性Python 2.7的新特性 - 牛皮糖NewPtone - 博客园.html Python 3_x 新特性及10大变化_python_脚本之家.htm
- Python编程语言学习:包导入和模块搜索路径(包路径)简介、使用方法(python系统环境路径的查询与添加)之详细攻略
- Python:利用python语言实现18位身份证号码和15位身份证号码相互转换
- Python编程语言学习:包导入和模块搜索路径(包路径)简介、使用方法(python系统环境路径的查询与添加)之详细攻略
- Python之ffmpeg:利用python编程基于ffmpeg将m4a格式音频文件转为mp3格式文件
- Python之tkinter:动态演示调用python库的tkinter带你进入GUI世界(计算器简单功能)
- Python之tkinter:动态演示调用python库的tkinter带你进入GUI世界(Find/undo事件)
- Python:利用python语言绘制多个子图经典案例、代码实现之详细攻略
- Python IDE之Pydev: 基于Eclipse搭建python的编译环境(Eclipse+pydev)简介、安装、使用技巧方法集合之详细攻略
- Python语言学习之字符串那些事:python和字符串的使用方法之详细攻略
- Python语言学习之文件夹那些事:python和文件夹的使用方法之详细攻略
- Python之ffmpeg-python:ffmpeg-python库的简介、安装、使用方法之详细攻略
- 【python代码】:能在手机上敲 Python 代码几款App
- 〖Python WEB 自动化测试实战篇③〗- python-selenium环境配置搭建
- 电力系统短期负荷预测(Python代码+数据+详细文章讲解)
- 用Python快速实现实时人脸活体检测
- Python编程:通过百度地图接口抓取机构的地址和电话信息
- Python:使用nltk统计词频并绘制统计图
- Python: yield, python 实现tail -f
- python 读取.mat文件
- python utc时间转换为strftime
- python基础===jieba模块,Python 中文分词组件
- Python 搜寻指定范围内的RAR压缩文件并批量解压缩(通用版本,Windows和Linux都可用)