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

 # 還可以通過cv2實現。但是彈出框是自帶的,可能出現問題;還可以轉成websocket格式返回給前端··


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM