python實(shí)現(xiàn)實(shí)時(shí)視頻流播放代碼實(shí)例
這篇文章主要介紹了python實(shí)現(xiàn)實(shí)時(shí)視頻流播放代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
@action(methods=['GET'], detail=True)
def video(self, request, pk=None):
"""
獲取設(shè)備實(shí)時(shí)視頻流
:param request:
:param pk:
:return:
"""
device_obj = self.get_object()
# if device_obj.status == 0:
# return Response({'error': '設(shè)備離線'})
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: # 任務(wù)初始化,設(shè)置初始時(shí)間
cache.set(cache_id, time.time(), timeout=60)
elif isinstance(cache_status, float) and time.time() - cache_status > 30: # 任務(wù)已超時(shí), 返回錯(cuò)誤信息, 一段時(shí)間內(nèi)不再入隊(duì)
return Response({'error': '連接數(shù)目超過限制, 請(qǐng)稍后再試'})
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': # 視頻流正常推送中, 刷新播放時(shí)間, 返回視頻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': # 視頻任務(wù)等待中
return Response({'status': '等待建立視頻連接'})
else: # 建立視頻任務(wù)失敗
return Response({'error': '打開視頻失敗'})
class JobQueue:
"""實(shí)時(shí)視頻播放"""
def __init__(self):
self.video_queue = django_rq.get_queue('video') # 視頻推流消息隊(duì)列
def enqueue_video(self, rtsp_address, device_hash):
"""視頻流隊(duì)列"""
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))
# 實(shí)時(shí)視頻流播放
RQ_QUEUES = {
'video': {
'USE_REDIS_CACHE': 'video',
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Pytorch實(shí)現(xiàn)神經(jīng)網(wǎng)絡(luò)的分類方式
今天小編就為大家分享一篇Pytorch實(shí)現(xiàn)神經(jīng)網(wǎng)絡(luò)的分類方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-01-01
循環(huán)神經(jīng)網(wǎng)絡(luò)TextRNN實(shí)現(xiàn)情感短文本分類任務(wù)
這篇文章主要為大家介紹了循環(huán)神經(jīng)網(wǎng)絡(luò)TextRNN實(shí)現(xiàn)情感短文本分類任務(wù)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
Python+ChatGPT制作一個(gè)AI實(shí)用百寶箱
ChatGPT最近在互聯(lián)網(wǎng)掀起了一陣熱潮,其高度智能化的功能能夠給我們現(xiàn)實(shí)生活帶來諸多的便利。本文就來用Python和ChatGPT制作一個(gè)AI實(shí)用百寶箱吧2023-02-02
Python Counting Bloom Filter原理與實(shí)現(xiàn)詳細(xì)介紹
這篇文章主要介紹了Python Counting Bloom Filter原理與實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-10-10
利用Python批量提取Win10鎖屏壁紙實(shí)戰(zhàn)教程
這篇文章主要給大家介紹了關(guān)于利用Python批量提取Win10鎖屏壁紙的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-03-03
Python利用Matplotlib庫實(shí)現(xiàn)繪制餅形圖
這篇文章主要為大家分享了基于python+matplotlib庫的餅形圖繪制,具體內(nèi)容涉及一般的餅圖、分裂餅圖、以及環(huán)形圖,感興趣的小伙伴可以了解一下2022-04-04
python PrettyTable模塊的安裝與簡(jiǎn)單應(yīng)用
prettyTable 是一款很簡(jiǎn)潔但是功能強(qiáng)大的第三方模塊,主要是將輸入的數(shù)據(jù)轉(zhuǎn)化為格式化的形式來輸出,這篇文章主要介紹了python PrettyTable模塊的安裝與簡(jiǎn)單應(yīng)用,感興趣的小伙伴們可以參考一下2019-01-01

