python实现实时视频流播放代码实例


Posted in Python onJanuary 11, 2020

这篇文章主要介绍了python实现实时视频流播放代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

@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',
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python每天必学之bytes字节
Jan 28 Python
python基础_文件操作实现全文或单行替换的方法
Sep 04 Python
Python类中方法getitem和getattr详解
Aug 30 Python
Django中提示消息messages的设置方式
Nov 15 Python
完美解决keras保存好的model不能成功加载问题
Jun 11 Python
使用npy转image图像并保存的实例
Jul 01 Python
numpy中生成随机数的几种常用函数(小结)
Aug 18 Python
Django创建一个后台的基本步骤记录
Oct 02 Python
使用pycharm运行flask应用程序的详细教程
Jun 07 Python
python 网络编程要点总结
Jun 18 Python
Python Pandas解析读写 CSV 文件
Apr 11 Python
Python线程池与GIL全局锁实现抽奖小案例
Apr 13 Python
python3下pygame如何实现显示中文
Jan 11 #Python
Pytorch 实现sobel算子的卷积操作详解
Jan 10 #Python
Pytorch保存模型用于测试和用于继续训练的区别详解
Jan 10 #Python
使用pytorch完成kaggle猫狗图像识别方式
Jan 10 #Python
解决Pytorch 加载训练好的模型 遇到的error问题
Jan 10 #Python
Ubuntu16.04安装python3.6.5步骤详解
Jan 10 #Python
Pytorch 保存模型生成图片方式
Jan 10 #Python
You might like
PHP静态新闻列表自动生成代码
2007/06/14 PHP
php新建文件自动编号的思路与实现
2011/06/27 PHP
php指定函数参数默认值示例代码
2013/12/04 PHP
PHP随机生成随机个数的字母组合示例
2014/01/14 PHP
PHP的preg_match匹配字符串长度问题解决方法
2014/05/03 PHP
PHP实现手机号码中间四位用星号(*)隐藏的自定义函数分享
2014/09/27 PHP
遍历echsop的region表形成缓存的程序实例代码
2016/11/01 PHP
JS 实现完美include载入实现代码
2010/08/05 Javascript
js改变img标签的src属性在IE下没反应的解决方法
2013/07/23 Javascript
ajax请求get与post的区别总结
2013/11/04 Javascript
IE下Ajax缓存问题的快速解决方法(get方式)
2014/01/09 Javascript
jQuery中fadein与fadeout方法用法示例
2016/09/16 Javascript
js 文字超出长度用省略号代替,鼠标悬停并以悬浮框显示实例
2016/12/06 Javascript
vue-resouce设置请求头的三种方法
2017/09/12 Javascript
jQuery实现监听下拉框选中内容发生改变操作示例
2018/07/13 jQuery
在vue项目中集成graphql(vue-ApolloClient)
2018/09/08 Javascript
vue 内置过滤器的使用总结(附加自定义过滤器)
2018/12/11 Javascript
layui中select,radio设置不生效的解决方法
2019/09/05 Javascript
Python实现求解一元二次方程的方法示例
2018/06/20 Python
Flask框架URL管理操作示例【基于@app.route】
2018/07/23 Python
对DJango视图(views)和模版(templates)的使用详解
2019/07/17 Python
Django框架中序列化和反序列化的例子
2019/08/06 Python
python openCV实现摄像头获取人脸图片
2020/08/20 Python
Python基于staticmethod装饰器标示静态方法
2020/10/17 Python
python处理写入数据代码讲解
2020/10/22 Python
Django怎么在admin后台注册数据库表
2020/11/14 Python
Spy++的使用方法及下载教程
2021/01/29 Python
世界上最好的儿童品牌:AlexandAlexa
2018/01/27 全球购物
Kipling澳洲官网:购买凯浦林包包
2020/12/17 全球购物
优秀辅导员事迹材料
2014/02/16 职场文书
新春文艺演出主持词
2014/03/27 职场文书
商场客服专员岗位职责
2014/06/13 职场文书
学雷锋宣传标语
2014/06/25 职场文书
大学生村官个人对照检查材料(群众路线)
2014/09/26 职场文书
云冈石窟导游词
2015/02/04 职场文书
redis 查看所有的key方式
2021/05/07 Redis