import json
import time
import subprocess as sp
import ffmpeg
import cv2
import sys
import random

import numpy as np


def read_frame_as_jpeg(in_file, frame_num):
    """
    指定帧数读取任意帧
    """
    out, err = (
        ffmpeg.input(in_file)
            .filter('select', 'gte(n,{})'.format(frame_num))
            .output('pipe:', vframes=1, format='image2', vcodec='mjpeg')
            .run(capture_stdout=True)
    )
    return out


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


def get_video_info(in_file):
    try:
        probe = ffmpeg.probe(in_file)
        # 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)
        # 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:
        print("aaaaaaaaaaaaaaaaaaaa", err)


if __name__ == '__main__':
    #file_path = 'https://vod.play.t-aaron.com/0bc905ef5651439da2bfba8427fe467e/a76a7ebb6e3b44ef9c0c7820c7e9c574-f2d7ee90cba11aa91971d58e06d295d2-4k.mp4'
    file_path = 'https://vod.play.t-aaron.com/customerTrans/edc96ea2115a0723a003730956208134/55547af9-184f0827dae-0004-f90c-f2c-7ec68.mp4'
    #file_path = 'https://vod.play.t-aaron.com/customerTrans/edc96ea2115a0723a003730956208134/40b416f7-183b57f6be0-0004-f90c-f2c-7ec68.mp4'
    #file_path = 'https://vod.play.t-aaron.com/3301fc8e166f45be88f2214e7a8f4a9d/e29535365b54434d9ed2e8c3b0a175da-fba35541b31a1049ca05b145a283c33a-hd.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'}
    kwargs={
        # "hwaccel": "nvdec",
        # "vcodec": "h264_cuvid",
        # "c:v": "h264_cuvid"
    }
    output_args = {
        # "vcodec": "hevc_nvenc",
        # "c:v": "hevc_nvenc",
        # "preset": "fast",
    }
    # i = 1
    # process1 = (
    #     ffmpeg
    #         .input(file_path, **kwargs)
    #         .output('pipe:', format='rawvideo', pix_fmt='rgb24', **output_args)
    #         # .global_args("-an")
    #         .overwrite_output()
    #         .run_async(pipe_stdout=True, pipe_stderr=True)
    # )
    width = int(video_info['width'])
    height = int(video_info['height'])
    command = ['ffmpeg',
               '-hwaccel cuda',
               '-c:v', 'h264_cuvid',
               '-resize', '1920x1080',
               # '-hwaccel_output_format', 'bgr24',
               '-i', file_path,
               # '-vf', "hwdownload,format=bgr24",
               # "-vcodec", "h264_nvenc",  # hevc_nvenc h264_nvenc
               '-f', 'rawvideo',
               # '-g', '5',
               # '-pix_fmt', 'bgr24',
               # '-hwaccel_output_format', 'bgr24',
               # '-an',
               '-']
    p = sp.Popen(command, stdout=sp.PIPE)
    # ai_video_file = cv2.VideoWriter(r"C:\Users\chenyukun\Desktop\shipin\aa.mp4", cv2.VideoWriter_fourcc(*'mp4v'), 30,
    #                                 (width, height))
    start1 = time.time()
    while True:
        start = time.time()
        # in_bytes = p.stdout.read()
        in_bytes = p.stdout.read(int(width * height * 3 // 8))
        # in_bytes = p.stdout.read(int(width * height * 3/4))
        if not in_bytes:
            print(in_bytes)
            # ai_video_file.release()
            p.stdout.close()
            p.wait()
            break
        # 转成ndarray
        img = (np.frombuffer(in_bytes, np.uint8)).reshape((int(height/2 * 3 // 2), int(width/2)))
        bgr_img = cv2.cvtColor(img, cv2.COLOR_YUV2BGR_NV12)
        # in_frame = (np.frombuffer(in_bytes, np.uint8).reshape([int(height/2), int(width/2), 3]))
        # print("拉流时间：", time.time() - start)
        # frame = cv2.resize(in_frame, (1280, 720))   # 改变图片尺寸
        # 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', bgr_img)
        # cv2.waitKey(1)
        # time.sleep(1111)
    p.kill()
