Search code examples
pythonffmpegffmpeg-python

Timeline editing with ffmpeg-python


I'm trying to draw a box on one part of the screen at a specific instance in time. I've tried looking through the documentation for ffmpeg-python, but am unable to locate any instance of support for the enable option.

I tried using

(
ffmpeg
  .input(video)
  .drawbox(x, y, w, h, enable=f"between(t,{timestamp},{total_time})")
  .output("out.mp4")
  .run()
)

hoping that it would be passed to ffmpeg as a kwarg, but this has no effect on the video and the box never gets drawn.


Solution

  • According to the ffmpeg-python drawbox documentation the syntax is:

    ffmpeg.drawbox(stream, x, y, width, height, color, thickness=None, **kwargs)

    The first argument is a stream - it should be a video stream.
    We may use drawbox filter as follows:

    filtered_input_video = ffmpeg.drawbox(ffmpeg.input("in.mp4").video, x, y, w, h, color="black", enable=f"between(t, {start_time}, {end_time})")
    

    Note that the arguments of between are start time and end time.

    filtered_input_video comes as first argument of ffmpeg.output:

    ffmpeg.output(filtered_input_video, "out.mp4").run()
    

    Updated code sample (using test pattern as input):

    import ffmpeg
    
    x, y, w, h = 50, 5, 100, 100
    start_time = 3
    end_time = 7
    
    input_video = ffmpeg.input("testsrc=size=192x108:rate=1:duration=10", f="lavfi").video  # Replace this with: ffmpeg.input(video).video
    
    #filtered_input_video = ffmpeg.filter(input_video, "drawbox", x, y, w, h, enable=f"between(t, {start_time}, {end_time})") # Alternative syntax
    filtered_input_video = ffmpeg.drawbox(input_video, x, y, w, h, color="black", enable=f"between(t, {start_time}, {end_time})")
    
    (
    ffmpeg
      .output(filtered_input_video, "out.mp4", vcodec="libx264", pix_fmt="yuv420p")
      .overwrite_output()  # Overwrite output if already exist (optional)
      .run()
    )
    

    Sample output (box is shown from the 3'rd second to the 7'th):

    After 1 second:
    enter image description here

    After 5 seconds:
    enter image description here