Learn · Developers

How to reverse a video with Python (and FFmpeg)

Contents

A reversed video plays backwards: the last frame comes first, a skater rolls back to where he started, and a splash jumps back into the glass. It’s a quick effect for social clips, and the base of boomerangs and rewind moments.

This guide shows how to reverse a video with Python and Shotstack’s video editing API. The script reverses a whole video or one part of it, and swaps the backwards sound for music. After that comes FFmpeg, with what to watch for on long files.

TL;DR

  • A video clip plays backwards when its speed is a tween with a value of -1. trim sets the point in the source where the reverse starts.
  • The script below reversed a 27.38 second skateboarding clip in one render.
  • Reversing one part, 4 to 12 seconds, gave 192 frames: source frames 287 down to 96, each one once.
  • FFmpeg’s reverse filter holds the whole clip in memory. It used 1.3 GB for this 27 second clip at 1280 x 720.

How reversing works with the API

The Edit API renders a timeline that you describe in JSON. A video clip has a speed setting, and when it’s an array of tweens it can run below zero. The animations guide puts it simply: “A speed of 0 freezes the current frame and a negative speed plays the video backwards.”

Three settings on one clip do the job:

  • trim is where the reverse starts in the source. For a whole video, that’s its full length.
  • speed is one tween from -1 to -1, so the clip plays backwards at normal speed from start to finish.
  • length is how long the clip runs. Speed tweens don’t change a clip’s length, so it’s set to the length of the part you reverse.

This clip reverses the first 8 seconds of a video:

JSON
{
  "asset": {
    "type": "video",
    "src": "https://example.com/video.mp4",
    "trim": 8,
    "speed": [{ "from": -1, "to": -1, "start": 0, "length": 8 }]
  },
  "start": 0,
  "length": 8
}

The sound follows the speed, so it plays backwards too. Speech played backwards can’t be understood, so the script below mutes the clip and puts music on a second track.

Reverse a video with Python

The script reverses a 27 second clip of a skateboarder, hosted by Shotstack. It reads the video’s length and frame rate, reverses it from the end back to the start, and adds a music track that fades out.

The script uses only the Python standard library. Set SHOTSTACK_API_KEY to the API key from your Shotstack dashboard, then run it with Python 3. Each render uses credits from your plan, as listed on the pricing page.

Python
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

API = "https://api.shotstack.io/edit/v1"
ASSETS = "https://shotstack-assets.s3.amazonaws.com"
SOURCE = f"{ASSETS}/footage/skater.hd.mp4"
MUSIC = f"{ASSETS}/music/unminus/lit.mp3"
START = 0  # where the part to reverse begins, in seconds
LENGTH = None  # seconds to reverse; None reverses to the end of the video
KEEP_SOUND = False  # True plays the video's own sound backwards instead of music
FRAME_RATES = (12, 15, 23.976, 24, 25, 29.97, 30, 48, 50, 59.94, 60)


def call(url, body=None):
    data = json.dumps(body).encode() if body is not None else None
    headers = {
        "x-api-key": os.environ["SHOTSTACK_API_KEY"],
        "Content-Type": "application/json",
    }
    try:
        request = urllib.request.Request(url, data, headers)
        with urllib.request.urlopen(request) as response:
            return json.load(response)
    except urllib.error.HTTPError as error:
        sys.exit(f"HTTP {error.code}: {' '.join(error.read().decode().split())[:300]}")


def probe(url):
    """Return the duration in seconds and the frame rate of a video at a URL."""
    encoded = urllib.parse.quote(url, safe="")
    metadata = call(f"{API}/probe/{encoded}")["response"]["metadata"]
    video = next(s for s in metadata["streams"] if s["codec_type"] == "video")
    top, bottom = video["avg_frame_rate"].split("/")
    return float(video["duration"]), int(top) / int(bottom)


def build_edit(start, length, fps):
    video = {
        "type": "video",
        "src": SOURCE,
        "trim": round(start + length, 3),
        "speed": [{"from": -1, "to": -1, "start": 0, "length": length}],
        "volume": 1 if KEEP_SOUND else 0,
    }
    tracks = [{"clips": [{"asset": video, "start": 0, "length": length}]}]
    if not KEEP_SOUND:
        music = {"type": "audio", "src": MUSIC, "effect": "fadeOut"}
        tracks.append({"clips": [{"asset": music, "start": 0, "length": length}]})
    return {
        "timeline": {"tracks": tracks},
        "output": {"format": "mp4", "resolution": "hd", "fps": fps},
    }


if __name__ == "__main__":
    if not os.environ.get("SHOTSTACK_API_KEY"):
        sys.exit("Set SHOTSTACK_API_KEY first.")
    duration, source_fps = probe(SOURCE)
    fps = min(FRAME_RATES, key=lambda rate: abs(rate - source_fps))
    length = round(LENGTH or duration - START, 3)
    print(f"Source: {duration:.2f} s at {source_fps:g} fps")
    end = START + length
    print(f"Reversing {START:.2f} s to {end:.2f} s, {length:.2f} s in all")
    render_id = call(f"{API}/render", build_edit(START, length, fps))["response"]["id"]
    print("Render queued:", render_id)
    while True:
        time.sleep(5)
        status = call(f"{API}/render/{render_id}")["response"]
        if status["status"] == "done":
            break
        if status["status"] == "failed":
            sys.exit(f"Render failed: {status.get('error')}")
    seconds, _ = probe(status["url"])
    print(f"Video: {seconds:.2f} s")
    print(status["url"])

Run python reverse_video.py. It prints the source’s length and frame rate, the part it reverses, the render ID, the length of the result and the URL of the video:

Text
Source: 27.38 s at 24 fps
Reversing 0.00 s to 27.38 s, 27.38 s in all
Render queued: 0656c67c-a046-4634-9383-652b3a666d4a
Video: 27.38 s
https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/35tqpmb0ya/0656c67c-a046-4634-9383-652b3a666d4a.mp4

This video plays the source and the reversed result side by side:

How the script works

  • probe() sends the video’s URL to the Probe endpoint and returns its length and frame rate.
  • The main block works out the length to reverse: from START to the end of the video, unless you set LENGTH.
  • build_edit() sets trim to the end of that part and adds one speed tween of -1 that runs for the whole clip.
  • When KEEP_SOUND is False, the clip’s volume is 0 and a second track plays the music with a fadeOut effect.
  • The output uses the frame rate closest to the source’s own, so a 24 fps video is rendered at 24 fps.

Reverse part of a video

Set START and LENGTH to reverse a section. With START = 4 and LENGTH = 8, the clip starts at second 12 of the source and plays back to second 4.

That section of the 24 fps skateboarding clip comes out as 192 frames, exactly 8 seconds:

Output framesSource frames shown
First287 (the last frame before 12 seconds)
Then286, 285, 284 and so on, one at a time
Last96 (the frame at 4 seconds)

Every source frame between 4 and 12 seconds plays once, in reverse order.

Keep the original sound

Set KEEP_SOUND = True to play the video’s own sound backwards. The script then sets the clip’s volume to 1 and leaves out the music.

Backwards sound works for effects like a rewind, or wind and water. For speech, keep the music, or put a voiceover on its own track. Our guide on how to mute a video and replace the audio covers the second track.

Reverse a video with FFmpeg

FFmpeg can reverse a file on your own machine with its reverse filter for video and areverse for sound:

Bash
ffmpeg -i input.mp4 -vf reverse -af areverse output.mp4

Both filters come with the same note in the FFmpeg filters documentation: “Warning: This filter requires memory to buffer the entire clip, so trimming is suggested.”

The first frame of the output is the last frame of the input, so FFmpeg has to read, and keep, every frame before it can write anything. This is the peak memory FFmpeg used for the skateboarding clip at 1280 x 720:

CommandLength reversedPeak memory
Whole clip27.4 s1,284 MB
-ss 4 -t 8 before -i8 s658 MB

Memory grows with the length and size of the video. A raw 1080p frame takes about 3 MB, so a 10 minute video at 30 fps would need roughly 56 GB for its frames alone. To reverse a long video with FFmpeg, cut it into parts with -ss and -t, reverse each part, and join them in reverse order:

Bash
ffmpeg -ss 4 -t 8 -i input.mp4 -vf reverse -af areverse part.mp4

Our guide on how to trim a video with FFmpeg explains -ss and -t. With the API, the render runs on Shotstack’s servers, so the length of the video doesn’t depend on your machine’s memory.

Reverse your videos with Shotstack

You now have a script that reverses a whole video or one part of it, with music or its own sound. Put your own video URL in SOURCE and run it again.

Create a free Shotstack account to get your API key and reverse your first video.

Frequently asked questions (FAQs)

Can I play a clip forward and then backwards?

Yes. Give the clip two tweens, one at 1 and one at -1, and make the clip long enough for both. Our guide on how to create a boomerang video with Python builds a loop this way.

Can I reverse a video faster or slower?

Yes. A tween of -2 plays backwards at twice the speed, and -0.5 at half speed. The clip’s length doesn’t change with the speed, so set length to the part’s length divided by how fast it plays: 4 seconds for an 8 second part at -2.

Can I reverse a video that’s on my computer?

Yes. SOURCE has to be a URL that Shotstack can fetch, so upload the file first. The Ingest API gives you an upload link and returns the file’s URL when it’s ready. Put that URL in SOURCE.

Can I speed a video up or slow it down instead?

Yes, with the same speed setting and a positive value. Our guide on how to speed up or slow down a video covers a fixed speed, and the speed ramp guide eases from one speed to another.

Keep reading

Start free

  • Unlimited developer sandbox
  • No credit card required