import json
import time
import subprocess as sp
from concurrent.futures import ThreadPoolExecutor
from traceback import format_exc

import ffmpeg
import sys

import numpy as np

"""
获取视频基本信息
"""


def get_video_info(in_file):
    try:
        probe = ffmpeg.probe(
            'https://vod.play.t-aaron.com/customerTrans/edc96ea2115a0723a003730956208134/55547af9-184f0827dae-0004-f90c-f2c-7ec68.mp4')
        # format = probe['format']
        # size = int(format['size'])/1024/1024
        video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
        if video_stream is None:
            print('No video stream found', file=sys.stderr)
            return
        width = int(video_stream['width'])
        height = int(video_stream['height'])
        num_frames = int(video_stream['nb_frames'])
        up, down = str(video_stream['r_frame_rate']).split('/')
        fps = eval(up) / eval(down)
        print("fbs:", fps)
        # duration = float(video_stream['duration'])
        bit_rate = int(video_stream['bit_rate']) / 1000
        print('width: {}'.format(width))
        print('height: {}'.format(height))
        # print('num_frames: {}'.format(num_frames))
        print('bit_rate: {}k'.format(bit_rate))
        # print('fps: {}'.format(fps))
        # print('size: {}MB'.format(size))
        # print('duration: {}'.format(duration))
        return video_stream



    except Exception as err:
        if isinstance(err, ffmpeg._run.Error):
            print(err.stderr.decode(encoding='utf-8'))
        raise err

def aa(p1, in_bytes):
    try:
        p1.stdin.write(in_bytes)
    except Exception:
        print(format_exc())

if __name__ == '__main__':
    file_path = 'rtsp://localhost:8554/live'
    command = ['ffmpeg',
               '-c:v', 'h264_cuvid',
               '-i', file_path,
               '-f', 'rawvideo',
               '-pix_fmt', 'bgr24',
               '-an',
               '-']
    p = sp.Popen(command, stdout=sp.PIPE)
    command1 = ['ffmpeg',
                '-y',
                "-an",
                '-f', 'rawvideo',
                '-vcodec', 'rawvideo',
                '-pix_fmt', 'bgr24',
                '-thread_queue_size', '1024',
                '-s', "{}x{}".format(1280, 720),
                '-i', '-',  # 指定输入文件
                '-r', str(25),
                '-g', str(25),
                '-maxrate', '6000k',
                '-b:v', '4000k',
                '-c:v', 'h264_nvenc',  #
                '-bufsize', '4000k',
                '-pix_fmt', 'yuv420p',
                '-preset', 'p6',
                '-tune', 'll',
                '-f', 'flv',
                "rtmp://192.168.10.101:19350/rlive/stream_124?sign=YJ8aBPFp"]
    # # 管道配置
    p1 = sp.Popen(command1, stdin=sp.PIPE, shell=False)
    command2 = ['ffmpeg',
                '-y',
                "-an",
                '-f', 'rawvideo',
                '-vcodec', 'rawvideo',
                '-pix_fmt', 'bgr24',
                '-thread_queue_size', '1024',
                '-s', "{}x{}".format(1280, 720),
                '-i', '-',  # 指定输入文件
                '-r', str(25),
                '-g', str(25),
                '-maxrate', '6000k',
                '-b:v', '4000k',
                '-c:v', 'h264_nvenc',  #
                '-bufsize', '4000k',
                '-pix_fmt', 'yuv420p',
                '-preset', 'p6',
                '-tune', 'll',
                '-f', 'flv',
                "rtmp://192.168.10.101:19350/rlive/stream_125?sign=uMdRHj9R"]
    # # 管道配置
    p2 = sp.Popen(command1, stdin=sp.PIPE, shell=False)
    start1 = time.time()
    num = 0
    with ThreadPoolExecutor(max_workers=100) as t:
        while True:
            in_bytes = p.stdout.read(1280 * 720 * 3)
            if in_bytes:
                img = (np.frombuffer(in_bytes, np.uint8)).reshape((720, 1280, 3))
                for i in range(1):
                    t.submit(aa, p1, in_bytes)
                    t.submit(aa, p2, in_bytes)
            else:
                break
