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

 更新时间:2020年01月11日 11:03:34   作者:前方、有光  
这篇文章主要介绍了python实现实时视频流播放代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

这篇文章主要介绍了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黑魔法库安装及操作字典示例详解

    这篇文章主要为大家介绍了Python中黑魔法库的安装及操作字典的示例详解,有需要的 朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步
    2021-10-10
  • python实现斗地主分牌洗牌

    python实现斗地主分牌洗牌

    这篇文章主要为大家详细介绍了python实现斗地主分牌洗牌,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-06-06
  • 利用Python实现一个可定制风格的绘图系统

    利用Python实现一个可定制风格的绘图系统

    这篇文章主要为大家详细介绍了如何基于Python实现一个可定制风格的绘图系统,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起了解下
    2023-09-09
  • python设置环境变量的几种方法总结

    python设置环境变量的几种方法总结

    这篇文章主要介绍了在Python中设置环境变量可以通过多种方式实现,包括使用os.environ、os.putenv、setuptools以及在操作系统级别设置,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2025-01-01
  • Ubuntu 下 vim 搭建python 环境 配置

    Ubuntu 下 vim 搭建python 环境 配置

    这篇文章主要介绍了Ubuntu 下 vim 搭建python环境配置,需要的朋友可以参考下
    2017-06-06
  • Python写的Discuz7.2版faq.php注入漏洞工具

    Python写的Discuz7.2版faq.php注入漏洞工具

    这篇文章主要介绍了Python写的Discuz7.2版faq.php注入漏洞工具,全自动的一款注入工具,针对Discuz7.2版,需要的朋友可以参考下
    2014-08-08
  • 为什么python比较流行

    为什么python比较流行

    在本篇文章里小编给大家分析了关于python比较流行的原因以及优势等,需要的朋友们可以参考下。
    2020-06-06
  • 什么是Python中的匿名函数

    什么是Python中的匿名函数

    在本篇文章里小编给大家整理的是关于Python匿名函数知识点总结,需要的朋友们可以学习参考下。
    2020-06-06
  • Python 画出来六维图

    Python 画出来六维图

    这篇文章主要介绍了Python 画出来六维图,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-07-07
  • pip安装提示Twisted错误问题(Python3.6.4安装Twisted错误)

    pip安装提示Twisted错误问题(Python3.6.4安装Twisted错误)

    这篇文章主要介绍了pip安装提示Twisted错误问题(Python3.6.4安装Twisted错误),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-05-05

最新评论