You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

143 lines
5.0KB

  1. import json
  2. import time
  3. import subprocess as sp
  4. import ffmpeg
  5. import cv2
  6. import sys
  7. import random
  8. import numpy as np
  9. def read_frame_as_jpeg(in_file, frame_num):
  10. """
  11. 指定帧数读取任意帧
  12. """
  13. out, err = (
  14. ffmpeg.input(in_file)
  15. .filter('select', 'gte(n,{})'.format(frame_num))
  16. .output('pipe:', vframes=1, format='image2', vcodec='mjpeg')
  17. .run(capture_stdout=True)
  18. )
  19. return out
  20. """
  21. 获取视频基本信息
  22. """
  23. def get_video_info(in_file):
  24. try:
  25. probe = ffmpeg.probe(in_file)
  26. # format = probe['format']
  27. # size = int(format['size'])/1024/1024
  28. video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
  29. if video_stream is None:
  30. print('No video stream found', file=sys.stderr)
  31. return
  32. width = int(video_stream['width'])
  33. height = int(video_stream['height'])
  34. # num_frames = int(video_stream['nb_frames'])
  35. # up, down = str(video_stream['r_frame_rate']).split('/')
  36. # fps = eval(up) / eval(down)
  37. # duration = float(video_stream['duration'])
  38. bit_rate = int(video_stream['bit_rate'])/1000
  39. print('width: {}'.format(width))
  40. print('height: {}'.format(height))
  41. # print('num_frames: {}'.format(num_frames))
  42. print('bit_rate: {}k'.format(bit_rate))
  43. # print('fps: {}'.format(fps))
  44. # print('size: {}MB'.format(size))
  45. # print('duration: {}'.format(duration))
  46. return video_stream
  47. except Exception as err:
  48. print("aaaaaaaaaaaaaaaaaaaa", err)
  49. if __name__ == '__main__':
  50. file_path = 'https://vod.play.t-aaron.com/0bc905ef5651439da2bfba8427fe467e/a76a7ebb6e3b44ef9c0c7820c7e9c574-f2d7ee90cba11aa91971d58e06d295d2-4k.mp4'
  51. #file_path = 'https://vod.play.t-aaron.com/customerTrans/edc96ea2115a0723a003730956208134/40b416f7-183b57f6be0-0004-f90c-f2c-7ec68.mp4'
  52. #file_path = 'https://vod.play.t-aaron.com/3301fc8e166f45be88f2214e7a8f4a9d/e29535365b54434d9ed2e8c3b0a175da-fba35541b31a1049ca05b145a283c33a-hd.mp4'
  53. video_info = get_video_info(file_path)
  54. print(json.dumps(video_info))
  55. # total_frames = int(video_info['nb_frames'])
  56. # print('总帧数:' + str(total_frames))
  57. # random_frame = random.randint(1, total_frames)
  58. # print('随机帧:' + str(random_frame))
  59. # out = read_frame_as_jpeg(file_path, i)
  60. # image_array = numpy.asarray(bytearray(out), dtype="uint8")
  61. # image = cv2.imdecode(image_array, cv2.IMREAD_COLOR)
  62. # kwargs={'fflags': 'nobuffer', 'flags': 'low_delay'}
  63. kwargs={
  64. # "hwaccel": "nvdec",
  65. # "vcodec": "h264_cuvid",
  66. # "c:v": "h264_cuvid"
  67. }
  68. output_args = {
  69. # "vcodec": "hevc_nvenc",
  70. # "c:v": "hevc_nvenc",
  71. # "preset": "fast",
  72. }
  73. # i = 1
  74. # process1 = (
  75. # ffmpeg
  76. # .input(file_path, **kwargs)
  77. # .output('pipe:', format='rawvideo', pix_fmt='rgb24', **output_args)
  78. # # .global_args("-an")
  79. # .overwrite_output()
  80. # .run_async(pipe_stdout=True, pipe_stderr=True)
  81. # )
  82. width = int(video_info['width'])
  83. height = int(video_info['height'])
  84. command = ['ffmpeg',
  85. '-hwaccel cuda',
  86. '-c:v', 'h264_cuvid',
  87. '-resize', '1920x1080',
  88. # '-hwaccel_output_format', 'bgr24',
  89. '-i', file_path,
  90. # '-vf', "hwdownload,format=bgr24",
  91. # "-vcodec", "h264_nvenc", # hevc_nvenc h264_nvenc
  92. '-f', 'rawvideo',
  93. # '-g', '5',
  94. # '-pix_fmt', 'bgr24',
  95. # '-hwaccel_output_format', 'bgr24',
  96. # '-an',
  97. '-']
  98. p = sp.Popen(command, stdout=sp.PIPE)
  99. # ai_video_file = cv2.VideoWriter(r"C:\Users\chenyukun\Desktop\shipin\aa.mp4", cv2.VideoWriter_fourcc(*'mp4v'), 30,
  100. # (width, height))
  101. start1 = time.time()
  102. while True:
  103. start = time.time()
  104. # in_bytes = p.stdout.read()
  105. in_bytes = p.stdout.read(int(width * height * 3 // 8))
  106. # in_bytes = p.stdout.read(int(width * height * 3/4))
  107. if not in_bytes:
  108. print(in_bytes)
  109. # ai_video_file.release()
  110. p.stdout.close()
  111. p.wait()
  112. break
  113. # 转成ndarray
  114. img = (np.frombuffer(in_bytes, np.uint8)).reshape((int(height/2 * 3 // 2), int(width/2)))
  115. bgr_img = cv2.cvtColor(img, cv2.COLOR_YUV2BGR_NV12)
  116. # in_frame = (np.frombuffer(in_bytes, np.uint8).reshape([int(height/2), int(width/2), 3]))
  117. # print("拉流时间:", time.time() - start)
  118. # frame = cv2.resize(in_frame, (1280, 720)) # 改变图片尺寸
  119. # i += 1
  120. # print(round(time.time()-start, 5))
  121. #
  122. # ai_video_file.write(in_frame)
  123. # if time.time() - start1 > 60:
  124. # ai_video_file.release()
  125. # p.stdout.close()
  126. # p.wait()
  127. # break
  128. # cv2.imshow('frame', bgr_img)
  129. # cv2.waitKey(1)
  130. # time.sleep(1111)
  131. p.kill()