Advertisement
Guest User

Untitled

a guest
Apr 1st, 2020
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. import ffmpeg
  2. import numpy as np
  3.  
  4.  
  5. class FfmpegReader:
  6. def __init__(self, path):
  7. self.process1 = (
  8. ffmpeg
  9. .input(path, **{'hwaccel': "cuda"})
  10. .output('pipe:', format='rawvideo', pix_fmt='rgb24')
  11. .run_async(pipe_stdout=True)
  12. )
  13. self.width=1280
  14. self.height=720
  15. # probe = ffmpeg.probe(path)
  16. # video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
  17. # self.width = int(video_stream['width'])
  18. # self.height = int(video_stream['height'])
  19. # print("")
  20.  
  21. def read(self):
  22. in_bytes = self.process1.stdout.read(self.width * self.height * 3)
  23. if not in_bytes:
  24. return False, None
  25. in_frame = (
  26. np
  27. .frombuffer(in_bytes, np.uint8)
  28. .reshape([self.width, self.height, 3])
  29. )
  30. return True, in_frame
  31.  
  32.  
  33. class FfmpegWriter:
  34. def __init__(self, output_path, width, height, fps, gpu_on=False):
  35.  
  36. self.width = width
  37. self.height = height
  38. self.fps = fps
  39. if gpu_on:
  40. self.process2 = (
  41. ffmpeg
  42. .input('pipe:', format='rawvideo', pix_fmt='rgb24', s='{}x{}'.format(self.height, self.width),
  43. **{"hwaccel_output_format": "cuda"})
  44. .output(output_path, pix_fmt='yuv420p', **{"c:v": "h264_nvenc"})
  45. .overwrite_output()
  46. .run_async(pipe_stdin=True)
  47. )
  48. else:
  49. self.process2 = (
  50. ffmpeg
  51. .input('pipe:', format='rawvideo', pix_fmt='rgb24', s='{}x{}'.format(self.height, self.width))
  52. .output(output_path, pix_fmt='yuv420p', **{"r":self.fps, "c:v": "h264"})
  53. .overwrite_output()
  54. .run_async(pipe_stdin=True)
  55. )
  56.  
  57. def write(self, image):
  58. self.process2.stdin.write(
  59. image
  60. .astype(np.uint8)
  61. .tobytes()
  62. )
  63.  
  64.  
  65. if __name__ == "__main__":
  66. input = FfmpegReader("/home/sergej/Downloads/borya.mp4")
  67. output = None
  68. while True:
  69. ret, frame = input.read()
  70.  
  71. # print("test")
  72. if not ret:
  73. break
  74.  
  75. if output is None:
  76. output = FfmpegWriter("ffmpeg_write_dec9.mp4", frame.shape[1], frame.shape[0], 30, gpu_on=False)
  77. output.write(frame)
  78. print("a")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement