import json
import time
import subprocess as sp
import ffmpeg
import cv2
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


if __name__ == '__main__':
    file_path = r'D:\shipin\777.mp4'
    video_info = get_video_info(file_path)
    print(json.dumps(video_info))
    # total_frames = int(video_info['nb_frames'])
    # print('总帧数：' + str(total_frames))
    # random_frame = random.randint(1, total_frames)
    # print('随机帧：' + str(random_frame))
    #     out = read_frame_as_jpeg(file_path, i)
    # image_array = numpy.asarray(bytearray(out), dtype="uint8")
    # image = cv2.imdecode(image_array, cv2.IMREAD_COLOR)
    #     kwargs={'fflags': 'nobuffer', 'flags': 'low_delay'}
    width = int(video_info['width'])
    height = int(video_info['height'])
    width_2_1 = int(width/2)
    height_2_1 = int(height/2)
    print("长:", width, "宽:", height)
    text = ''
    command = ['ffmpeg',
               #               '-hwaccel', 'cuvid',
               '-c:v', 'h264_cuvid',
               #               '-hwaccel_output_format', 'cuda',
               # '-resize', '%sx%s' % (width_2_1, height_2_1),
               '-i', file_path,
               #               '-c:v', 'hevc_nvenc',
               #               '-pix_fmt', 'yuv420p',
               '-f', 'rawvideo',
               '-pix_fmt', 'bgr24',
               '-an',
               '-']
    p = sp.Popen(command, stdout=sp.PIPE)
    # for line in p.stderr:
    # #     print(line.strip())
    # for line in p.stdout:
    #     print(text)

    command1 = ['ffmpeg',
                '-report',
                # '-loglevel', 'debug',
                '-y',  # 不经过确认，输出时直接覆盖同名文件。
                '-f', 'rawvideo',
                '-vcodec', 'rawvideo',
                '-pix_fmt', 'bgr24',
                #                       '-hwaccel', 'cuvid',
                #                       '-c:v', 'h264_cuvid',
                #                       '-hwaccel_output_format', 'cuda',
                # '-s', "{}x{}".format(self.width * 2, self.height),
                '-s', "{}x{}".format(width, height),
                '-r', str(25),
                '-i', '-',  # 指定输入文件
                '-g', str(5),
                # '-maxrate', '15000k',
                # '-profile:v', 'high',
                #                       '-b:v', '4000k',
                # '-crf', '18',
                '-rc:v', 'vbr',
                '-cq:v', '30',
                '-qmin', '30',
                '-qmax', '30',
                '-bufsize', '1',
                '-c:v', 'h264_nvenc', #

                #                       '-c:v', 'libx264',  # 指定视频编码器
                #                       '-tune', 'zerolatency',  # 加速编码速度
                #                       '-sc_threshold', '0',
                '-pix_fmt', 'yuv420p',
                "-an",
                # '-flvflags', 'no_duration_filesize',
                '-preset', 'fast',
                #                       '-f', 'flv',ags', 'no_duration_filesize',
                #                       '-preset', 'fast',  # 指定输出的视频质量，会影响文件的生成速度，有以下几个可用的值 ultrafast,
                # superfast, veryfast, faster, fast, medium, slow, slower, veryslow。
                '-f', 'flv',
                'rtmp://live.push.t-aaron.com/live/THSAr']

    # # 管道配置
    p1 = sp.Popen(command1, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE, )
    start1 = time.time()
    num = 0
    while True:

        # num += 1
        # #        if num ==100:
        # #        	print(time.time()-start1)
        # #        	break
        # start = time.time()
        in_bytes = p.stdout.read(int(width * height*3))
        # # print(type(in_bytes))
        img = (np.frombuffer(in_bytes, np.uint8)).reshape((height, width, 3))
        # # result = cv2.cvtColor(img, cv2.COLOR_YUV2BGR_NV12)
        # # result = cv2.resize(result, (int(width / 2), int(height / 2)), interpolation=cv2.INTER_LINEAR)
        # # result = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)

        for line in iter(p1.stdout.readline, b''):
            print(line)
        # if in_bytes:
        #     p1.stdin.write(img.tostring())
        #     print(p1.stderr.read().decode('utf-8'))
            # for line in iter(p1.std
            #
            #
            # out.readline, ''):
            #     line = line.decode('utf-8')
            #     print(line)
        # print(num)
        # time.sleep(0.001)

    #        p1.stdin.write(in_frame.tostring())
    #	      frame
    #        .astype(np.uint8)
    #        .tobytes()
    # frame = cv2.resize(in_frame, (1280, 720))   # 改变图片尺寸
    # frame = cv2.cvtColor(in_frame, cv2.COLOR_RGB2BGR)  # 转成BGR
    # i += 1
    # print(round(time.time()-start, 5))
    #
    # ai_video_file.write(in_frame)
    # if time.time() - start1 > 60:
    #     ai_video_file.release()
    #     p.stdout.close()
    #     p.wait()
    #     break
    # cv2.imshow('frame', frame)
    # time.sleep(1111)
    # p.kill()