spacepaste

  1.  
  2. def prependBlack( self, video_input, black_s=1.0 ):
  3. """ Add black_s seconds of black to the start of the video.
  4. use ffmpeg for efficiency.
  5. """
  6. if black_s is None:
  7. black_s = 1.0
  8. # intermediate
  9. video_timescaled = tmp_filename('_video_timescaled.mp4')
  10. video_black = tmp_filename('_black_video.mp4')
  11. video_list = tmp_filename('_video_list.txt')
  12. # output
  13. video_with_black = ('_video_with_black.mp4')
  14. try:
  15. t1 = time.time()
  16. # ffmpeg -i fullvideo.mp4 -vf trim=0:3,geq=0:128:128 -af atrim=0:3,volume=0 -video_track_timescale 600 3sec.mp4
  17. args_create_black = ['ffmpeg', '-y', '-i', video_input,
  18. '-vf', 'trim=0:{},geq=0:128:128'.format(float(black_s)),
  19. '-af', 'atrim=0:1,volume=0',
  20. '-video_track_timescale', '600', '-strict', '-2',
  21. '-threads', '0', video_black]
  22. subprocess.run(args_create_black, check=True)
  23. t2 = time.time()
  24. print('Elapsed time creating black:', t2 - t1)
  25. # ffmpeg -i fullvideo.mp4 -c copy -video_track_timescale 600 full600.mp4
  26. args_ensure_speed = ['ffmpeg', '-y', '-i', video_input, '-c', 'copy',
  27. '-video_track_timescale', '600', '-threads', '0',
  28. video_timescaled]
  29. subprocess.run(args_ensure_speed, check=True)
  30. t3 = time.time()
  31. print('Elapsed time for timescale conversion:', t3 - t2)
  32. # create a list of concatencated videos
  33. with open(video_list, 'w') as f:
  34. f.write('file ' + video_black + '\n' +
  35. 'file ' + video_timescaled + '\n')
  36. # ffmpeg -f concat -i list.txt -c copy merged.mp4
  37. args_concat = ['ffmpeg', '-y', '-f', 'concat', '-safe', '0',
  38. '-i', video_list, '-c', 'copy', '-threads', '0',
  39. video_with_black]
  40. subprocess.run(args_concat, check=True)
  41. t4 = time.time()
  42. print('Elapsed time concatenating videos:', t4 - t3)
  43. # in case ffmpeg does not support the input video feature, use other backend
  44. except subprocess.CalledProcessError as e:
  45. print('Error:', e)
  46. print('Fallback to moviepy library!')
  47. t_fallback_1 = time.time()
  48. # Add 1.0 seconds of black to the start of the video
  49. video = VideoFileClip(video_input)
  50. black_clip = ColorClip(video.size, color=(0, 0, 0),
  51. duration=1.0)
  52. final_clip = concatenate_videoclips([black_clip, video])
  53. final_clip.write_videofile(video_with_black, fps=video.fps)
  54. t_fallback_2 = time.time()
  55. print('Elapsed time for fallback adding black to video with moviepy:',
  56. t_fallback_2 - t_fallback_1)
  57. return video_with_black
  58.