Learn · Developers

How to change the frame rate of a video (Python and FFmpeg)

Contents

Footage shot at 24 frames a second often has to go out at 30. A 60 fps screen recording has to match a 25 fps edit. In both cases you need to change the frame rate of a video without changing how long it runs or how fast it plays.

This guide shows two ways to do it. The first is a Python script that sets the frame rate with one field in Shotstack’s video editing API. The second is FFmpeg on your own machine.

We also measured what happens to the frames. We rendered a test clip with a number on every frame, so the tables below show exactly which frames are dropped or repeated.

TL;DR

  • Changing the frame rate keeps the length and the speed. The video gets fewer frames or more frames in each second.
  • With the Shotstack API, set fps in the output of your edit. It accepts 12, 15, 23.976, 24, 25, 29.97, 30, 48, 50, 59.94 and 60.
  • With FFmpeg, use -filter:v fps=30. Put it after the input file.
  • Going down drops frames at even intervals. Going up repeats frames. In our test, 30 fps to 25 fps dropped every sixth frame, and 30 fps to 60 fps kept every frame and showed almost all of them twice.
  • The audio is not touched. In our renders the audio track kept the same length as the picture.

What changing the frame rate does

Frame rate is the number of pictures a video shows each second, written as frames per second (fps). A 10 second clip at 30 fps has 300 frames. The same clip at 25 fps has 250.

To change the rate, a converter has to decide which pictures to show at the new moments in time:

  • A lower rate drops frames. There are fewer moments to fill, so some of the source frames are left out.
  • A higher rate repeats frames. There are more moments than source frames, so some frames are shown more than once.

In both cases the clip lasts as long as before, and things in it move at the same speed. That is the difference from a speed change, where every frame is kept and the clip gets shorter or longer. Our guide to speeding up and slowing down a video covers speed changes.

Change the frame rate with Python

The script below reads the frame rate of a source video, renders it at a new frame rate, and reads the result. The source is a 24 fps drone clip that Shotstack hosts. The target is 30 fps.

The frame rate is one field. In the edit you send to the API, output.fps sets the frame rate of the finished video:

JSON
"output": { "format": "mp4", "resolution": "hd", "fps": 30 }

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"
SOURCE = "https://shotstack-assets.s3.ap-southeast-2.amazonaws.com/footage/beach-overhead.mp4"
TARGET_FPS = 30  # 12, 15, 23.976, 24, 25, 29.97, 30, 48, 50, 59.94 or 60
LENGTH = 8  # seconds of the source to render


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 frame rate, frame count and duration of the first video stream."""
    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 {
        "fps": int(top) / int(bottom),
        "frames": int(video["nb_frames"]),
        "seconds": float(video["duration"]),
    }


def describe(name, info):
    return (
        f"{name}: {info['fps']:g} fps, {info['frames']} frames, {info['seconds']:.2f} s"
    )


def build_edit(fps):
    clip = {
        "asset": {"type": "video", "src": SOURCE},
        "start": 0,
        "length": LENGTH,
    }
    return {
        "timeline": {"tracks": [{"clips": [clip]}]},
        "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.")
    print(describe("Source", probe(SOURCE)))
    render_id = call(f"{API}/render", build_edit(TARGET_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')}")
    print(describe("Output", probe(status["url"])))
    print(status["url"])

Run python change_frame_rate.py. It prints the source, the render ID, the output, and the URL of the video:

Text
Source: 24 fps, 758 frames, 31.58 s
Render queued: c23ae9ed-3058-414d-b12b-3d3e49b29b63
Output: 30 fps, 240 frames, 8.00 s
https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/35tqpmb0ya/c23ae9ed-3058-414d-b12b-3d3e49b29b63.mp4

Eight seconds at 24 fps is 192 frames. The output has 240 frames in the same eight seconds, which is 30 a second.

A lower rate is easier to see. We ran the script again with TARGET_FPS = 12, and the output had 96 frames in eight seconds. This video plays the 24 fps source next to that 12 fps output:

How the script works

  • probe() sends the video’s URL to the Probe endpoint. It returns the frame rate, the number of frames and the duration of the first video stream.
  • The frame rate arrives as a fraction in a string, such as "24/1" or "30000/1001". The script divides the two numbers to get a decimal value.
  • build_edit() puts the source on the timeline for LENGTH seconds and sets fps in the output.
  • After the render, the script probes the finished MP4 the same way, so you see the new frame rate next to the old one.

To convert a whole video, set LENGTH to the duration that probe() returns for the source.

Frame rates you can set

fps accepts these values, as listed in the API reference: 12, 15, 23.976, 24, 25, 29.97, 30, 48, 50, 59.94 and 60. The default is 25.

Which frames are dropped or repeated

To see what the render does with the frames, we made a 12 second test clip at 30 fps. Each of its 360 frames carries its own number. We rendered it with the API at four frame rates and read the numbers back from every output frame.

Output fpsFrames in the outputLengthWhat happened to the source frames
1518012.0 sEvery second frame was kept
2428812.0 sEvery fifth frame was dropped
2530012.0 sEvery sixth frame was dropped
6072012.0 sAll 360 frames were kept, and 358 of them were shown exactly twice

The drops are spread evenly. At 25 fps the output showed frames 0, 1, 2, 3, 4, then 6, 7, 8, 9, 10, then 12, and so on to the end.

The audio track was 12.0 seconds long in every output, the same as the source.

Change the frame rate with FFmpeg

FFmpeg does the same job on your own machine with the fps filter. The FFmpeg filters documentation describes it this way: “Convert the video to specified constant frame rate by duplicating or dropping frames as necessary.”

Bash
ffmpeg -i input.mp4 -filter:v fps=30 -c:a copy output.mp4

-c:a copy keeps the audio as it is. The video is encoded again, because its frames change.

The -r option gives the same result when it comes after the input file:

Bash
ffmpeg -i input.mp4 -r 30 -c:a copy output.mp4

We ran both commands, and one common mistake, on the 24 fps clip from the script. It has 758 frames and runs for 31.58 seconds.

CommandFramesVideo length
-filter:v fps=3094831.60 s
-r 30 after -i94831.60 s
-r 30 before -i75825.27 s

The last row is the mistake. Before the input, -r tells FFmpeg to read the file as if it were 30 fps. Every frame is kept, the video plays faster, and it ends about six seconds before the 31.59 second audio track does.

If a file has an uneven frame rate, as many phone recordings do, read our guide to variable frame rate video first.

Tips for choosing a frame rate

  • Keep the source rate when you can. YouTube’s recommended upload settings say: “Content should be encoded and uploaded in the same frame rate it was recorded.”
  • Pick one rate for a mixed timeline. When clips at 24, 25 and 30 fps go into one video, the output has a single frame rate. Choose the rate of your main footage.
  • Go to half the rate for the cleanest drop. At 30 to 15 fps the render kept every second frame, so the gap between frames was always the same.
  • Use a lower rate for smaller files. In our test, the eight second clip was 5.7 MB at 30 fps and 4.2 MB at 12 fps.

Our guide to video editing frame rates explains what each common rate is used for.

Change your video’s frame rate with Shotstack

You now have two ways to change the frame rate of a video. The script sets fps in one API request and checks the result with the Probe endpoint. The FFmpeg command does the same on your own machine. Put your own video URL in SOURCE, set TARGET_FPS, and run the script again.

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

Frequently asked questions (FAQs)

Does a higher frame rate make a video smoother?

Not by repeating frames. In our 30 fps to 60 fps test, the output had 720 frames, and they showed the same 360 pictures as the source. Motion looks smoother only when there are new pictures between the old ones. FFmpeg’s minterpolate filter builds them. Its documentation says it converts “the video to specified frame rate using motion interpolation”.

Does changing the frame rate change the audio?

No. Frame rate belongs to the video stream. In our renders the audio came out at the same length as the picture: 8.00 seconds for the script’s output and 12.0 seconds for each test clip.

How do I check a video’s frame rate?

With ffprobe, run ffprobe -v error -select_streams v:0 -show_entries stream=avg_frame_rate -of csv=p=0 input.mp4. It prints a fraction such as 24/1. For a file at a URL, the script’s probe() function reads the same value from the Probe endpoint. Our guide on how to use ffprobe covers the other fields.

Can I change the frame rate without encoding the video again?

No. A new frame rate at the same speed means a different set of frames, so the video stream has to be encoded again. The audio stream doesn’t change, which is why the FFmpeg command above can copy it.

What is 23.976 fps, and when should I use it?

It is 24,000 frames every 1,001 seconds, which is a little under 24 fps. Use it when your source already has that rate. The Probe endpoint reports such a file as 24000/1001, and the script prints it as 23.976.

Keep reading

Start free

  • Unlimited developer sandbox
  • No credit card required