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

yipeiwu_com6年前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调用cmd命令三种方法

目前我使用到的python中执行cmd的方式有三种 使用os.system("cmd")     该方法在调用完shell脚本后,返回一个16位的二进制数...

Python正则表达式匹配数字和小数的方法

Python正则表达式匹配数字和小数的方法

1.正则匹配数字,\为转义字符,d+为匹配一次或多次 如下所示:返回的结果为列表 2.正则匹配小数 如下所示,返回的结果125.6为字符串 总结  以上所述是小编给大家介绍...

Python 3.x 安装opencv+opencv_contrib的操作方法

Note:这篇文章不会包含任何的技术解答,仅是安装教程。同样不保证对所有可能的安装中遇到的问题都能适用。不过如果不幸又幸运地遇到了跟我一样的问题,我希望你能从我这里找到解决方案。 前言...

Python函数式编程指南(二):从函数开始

2. 从函数开始 2.1. 定义一个函数 如下定义了一个求和函数: 复制代码 代码如下: def add(x, y):     return x + y...

python利用MethodType绑定方法到类示例代码

前言 本文主要给大家介绍了关于python用MethodType绑定方法到类的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍: 对python中MethodTyp...