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

所属分类: 脚本专栏 / python 阅读数: 1057
收藏 0 赞 0 分享

这篇文章主要介绍了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基于Image模块实现图像翻转、旋转、改变大小等操作的相关技巧,非常简单实用,需要的朋友可以参考下
收藏 0 赞 0 分享

Python中的urllib模块使用详解

这篇文章主要介绍了Python中的urllib模块使用详解,是Python入门学习中的基础知识,需要的朋友可以参考下
收藏 0 赞 0 分享

Python的多态性实例分析

这篇文章主要介绍了Python的多态性,以实例形式深入浅出的分析了Python在面向对象编程中多态性的原理与实现方法,需要的朋友可以参考下
收藏 0 赞 0 分享

python生成IP段的方法

这篇文章主要介绍了python生成IP段的方法,涉及Python文件读写及随机数操作的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

python操作redis的方法

这篇文章主要介绍了python操作redis的方法,包括Python针对redis的连接、设置、获取、删除等常用技巧,具有一定参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

python妹子图简单爬虫实例

这篇文章主要介绍了python妹子图简单爬虫,实例分析了Python爬虫程序所涉及的页面源码获取、进度显示、正则匹配等技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

分析用Python脚本关闭文件操作的机制

这篇文章主要介绍了分析用Python脚本关闭文件操作的机制,作者分Python2.x版本和3.x版本两种情况进行了阐述,需要的朋友可以参考下
收藏 0 赞 0 分享

python实现搜索指定目录下文件及文件内搜索指定关键词的方法

这篇文章主要介绍了python实现搜索指定目录下文件及文件内搜索指定关键词的方法,可实现针对文件夹及文件内关键词的搜索功能,需要的朋友可以参考下
收藏 0 赞 0 分享

python中getaddrinfo()基本用法实例分析

这篇文章主要介绍了python中getaddrinfo()基本用法,实例分析了Python中使用getaddrinfo方法进行IP地址解析的基本技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

python查找指定具有相同内容文件的方法

这篇文章主要介绍了python查找指定具有相同内容文件的方法,涉及Python针对文件操作的相关技巧,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多