Learn · Developers

Batch edit videos of different sizes and lengths with Python

Contents

A batch of your own footage is easy to edit. Every clip has the same size and roughly the same length, so one template fits them all.

Footage from other people is different. Customers, contributors and field staff send whatever their phones recorded: one clip is vertical, the next is wide, one runs six seconds and another runs ninety. Put those through a single template and you get cropped heads, black bars and videos of every length.

The shape isn’t a detail, either. On YouTube, videos uploaded “with a square or vertical aspect ratio up to three minutes in length will be categorized as Shorts”. The shape and length of the file decide where it’s shown.

So the fix is to look before you edit. The Python script below reads each clip with Shotstack’s video editing API, decides how to trim and frame it, and renders one consistent, branded video for each clip.

TL;DR

  • Shotstack’s Probe endpoint returns a clip’s length, width, height and rotation from its URL. Nothing is downloaded.
  • A clip longer than the limit is cut to its middle part. A shorter one is used whole.
  • A clip close to the shape of the frame fills it. A clip that is too wide or too tall is shown whole, over a blurred copy of itself.
  • A list of styles gives each video its own title color, title position and music, in rotation.
  • Four clips in three shapes, from 5.68 to 14.12 seconds, came out as four 720 x 1280 videos. All four were ready 47 seconds after the script started.

What changes from clip to clip

Three things vary in real footage, and each one needs a decision:

What variesThe decisionHow the script decides
LengthHow much of the clip to useUp to MAX_LENGTH seconds, taken from the middle
ShapeFill the frame, or show the whole clipBy comparing the clip’s shape with the frame’s
SamenessHow to keep 50 videos from looking identicalBy rotating through a list of styles

The brand parts don’t vary: the logo, the title box and the size of the result stay the same in every video.

Read each clip first

The Probe endpoint takes the URL of a media file and returns what FFprobe would report about it: one entry for each stream, with the codec, the size and the frame rate, plus the length of the file. The guide to inspecting media covers the response in full. The script needs three values from it: duration, width and height.

Phone footage adds one catch. A phone held upright often stores a wide picture and a note that says “rotate this 90 degrees”.

I tested that case with a clip stored as 1920 x 1080 with a rotation of 90. The Probe endpoint reported the stored size and the rotation, and the render showed the clip turned, as a player would.

That’s why the script’s probe() swaps the width and the height when it finds a rotation of 90 or 270. Without the swap, it would treat an upright clip as a wide one.

Fill the frame or show the whole clip

Every clip has a fit setting that says what to do when the clip and the frame have different shapes. The guide to the fit property explains all four values. Two matter here:

  • crop fills the frame and cuts off whatever doesn’t fit.
  • contain shows the whole clip and leaves the rest of the frame empty.

Neither is right for every clip. Cropping a wide shot to a vertical frame keeps about a third of the picture. Containing it leaves two empty bands.

The script picks by shape. If the clip’s shape is within 20% of the frame’s, it fills the frame. If not, it uses both: the whole clip on top, and the same clip below it, cropped to fill the frame and blurred.

JSON
{
  "tracks": [
    {
      "clips": [
        { "asset": { "type": "video", "src": "https://example.com/wide.mp4" }, "start": 0, "length": 8, "fit": "contain" }
      ]
    },
    {
      "clips": [
        {
          "asset": { "type": "video", "src": "https://example.com/wide.mp4" },
          "start": 0,
          "length": 8,
          "fit": "crop",
          "filters": [{ "type": "blur", "value": 40 }]
        }
      ]
    }
  ]
}

The first track in the list is the top layer. The blur comes from the clip’s filters list, so there’s no second file to make.

Batch edit clips of any shape with Python

The script works on four clips hosted by Shotstack: a vertical drone shot, a skier, a night sky and a BMX rider. They come in three shapes and four lengths. It probes each one, builds its edit, sends all four renders and prints the URLs of the results.

It runs on plain Python 3, with no packages to add. It reads your API key from SHOTSTACK_API_KEY, and the key is in your Shotstack dashboard. Each render uses credits from your plan.

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"
OUTPUT = {"width": 720, "height": 1280}  # every result has this size
MAX_LENGTH = 8  # seconds; a longer clip is cut to its middle part
STEP = 0.04  # trim points and lengths are placed on this grid, in seconds
LOGO = f"{ASSETS}/logos/shotstack/small/logo-mono-white.png"
CLIPS = [
    {"src": f"{ASSETS}/footage/car-overead-vertical.mp4", "title": "Coast road"},
    {"src": f"{ASSETS}/footage/skier.mp4", "title": "First run"},
    {"src": f"{ASSETS}/footage/night-sky.mp4", "title": "After dark"},
    {"src": f"{ASSETS}/footage/bmx.mp4", "title": "Dirt jump"},
]
STYLES = [
    {"music": "lit.mp3", "color": "#25d0cd", "position": "bottom", "move": "slideUp"},
    {"music": "palmtrees.mp3", "color": "#f2c14e", "position": "top", "move": "slideDown"},
    {"music": "ambition.mp3", "color": "#ecccc6", "position": "bottom", "move": "fade"},
]


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 length, width and height of a video as it is shown on screen."""
    encoded = urllib.parse.quote(url, safe="")
    metadata = call(f"{API}/probe/{encoded}")["response"]["metadata"]
    for stream in metadata["streams"]:
        if stream["codec_type"] == "video":
            width, height = stream["width"], stream["height"]
            turns = [side.get("rotation", 0) for side in stream.get("side_data_list", [])]
            turns.append(int(stream.get("tags", {}).get("rotate", 0)))
            if any(abs(turn) in (90, 270) for turn in turns):
                width, height = height, width  # a phone clip stored on its side
            return float(metadata["format"]["duration"]), width, height
    sys.exit(f"No video in {url}")


def build_edit(clip, style, duration, width, height):
    length = round(int(min(duration, MAX_LENGTH) / STEP) * STEP, 2)
    trim = round(int((duration - length) / 2 / STEP) * STEP, 2)
    video = {"type": "video", "src": clip["src"], "trim": trim, "volume": 0}
    fill = {"asset": video, "start": 0, "length": length, "fit": "crop"}
    footage = [{"clips": [fill]}]
    shape = (width / height) / (OUTPUT["width"] / OUTPUT["height"])
    if not 1 / 1.2 < shape < 1.2:
        # too wide or too tall for the frame: show the whole clip over a blurred copy of itself
        fill["filters"] = [{"type": "blur", "value": 40}]
        whole = {"asset": video, "start": 0, "length": length, "fit": "contain"}
        footage.insert(0, {"clips": [whole]})
    title = {
        "type": "rich-text",
        "text": clip["title"],
        "font": {"family": "Montserrat", "size": 54, "color": "#111111"},
        "background": {"color": style["color"]},
    }
    title_clip = {"asset": title, "start": 0.4, "length": round(length - 0.8, 2)}
    title_clip.update({"width": 520, "height": 110, "position": style["position"]})
    title_clip["offset"] = {"y": 0.16 if style["position"] == "bottom" else -0.16}
    title_clip["transition"] = {"in": style["move"], "out": "fade"}
    logo = {"asset": {"type": "image", "src": LOGO}, "start": 0, "length": length}
    logo.update({"width": 180, "height": 46, "fit": "contain", "position": "topRight"})
    logo["offset"] = {"x": -0.05, "y": -0.03}
    music = {"type": "audio", "src": f"{ASSETS}/music/unminus/{style['music']}"}
    music.update({"volume": 0.7, "effect": "fadeOut"})
    tracks = [{"clips": [logo]}, {"clips": [title_clip]}, *footage]
    tracks.append({"clips": [{"asset": music, "start": 0, "length": length}]})
    output = {"format": "mp4", "size": OUTPUT, "fps": 30}
    return {"timeline": {"background": "#000000", "tracks": tracks}, "output": output}


if __name__ == "__main__":
    if not os.environ.get("SHOTSTACK_API_KEY"):
        sys.exit("Set SHOTSTACK_API_KEY first.")
    started = time.time()
    renders = []
    for number, clip in enumerate(CLIPS):
        duration, width, height = probe(clip["src"])
        style = STYLES[number % len(STYLES)]
        edit = build_edit(clip, style, duration, width, height)
        tracks = edit["timeline"]["tracks"]
        layout = "over a blurred copy" if len(tracks) == 5 else "fills the frame"
        name = clip["src"].rsplit("/", 1)[-1]
        used = tracks[-1]["clips"][0]["length"]
        print(f"{name}: {width} x {height}, {duration:.2f} s -> {used:.2f} s, {layout}")
        renders.append(call(f"{API}/render", edit)["response"]["id"])
    for render_id in renders:
        while True:
            time.sleep(5)
            status = call(f"{API}/render/{render_id}")["response"]
            if status["status"] == "done":
                print(status["url"])
                break
            if status["status"] == "failed":
                sys.exit(f"Render failed: {status.get('error')}")
    print(f"All done in {time.time() - started:.0f} s")

Save it as fit_clips.py and run it:

Text
car-overead-vertical.mp4: 1080 x 1920, 9.68 s -> 8.00 s, fills the frame
skier.mp4: 1920 x 1080, 14.12 s -> 8.00 s, over a blurred copy
night-sky.mp4: 1080 x 720, 13.88 s -> 8.00 s, over a blurred copy
bmx.mp4: 1920 x 1080, 5.68 s -> 5.68 s, over a blurred copy
https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/39afd28f-ff7a-4518-aec0-cfbce51597db.mp4
https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/68dcb78e-a00b-41b4-a4b5-7662843a14ed.mp4
https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/91c2f599-6879-4ba4-a469-0f6f8c1851e3.mp4
https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/m4x7q2k9tz/785ab328-5c5f-4584-aecf-29d1ec20da5b.mp4
All done in 47 s

The four source clips are on the top row, with the results below them:

How the script works

  • probe() reads the length and the size of each clip, and swaps the width and the height for a clip that is stored on its side.
  • build_edit() works out the length first: the clip’s own length, or MAX_LENGTH if the clip is longer. A longer clip is trimmed to its middle, with the same amount cut from each end.
  • The shape test divides the clip’s width-to-height ratio by the frame’s. Between 0.83 and 1.2, the clip fills the frame. Outside that range, it sits whole over a blurred copy.
  • The title is a rich-text clip. It appears 0.4 seconds in and leaves 0.4 seconds before the end, so every video opens and closes on clean footage.
  • STYLES holds three looks. Clip number four takes the first style again.
  • The script sends every render before it waits for any of them.

Every result is 720 x 1280 at 30 frames a second. The three longer clips came out at exactly 8.00 seconds, 240 frames each. The BMX clip kept its full length: 170 frames.

Change the frame, the limit and the styles

The settings sit at the top of the script.

OUTPUT is the size of every result. The shape rule works in both directions, so it holds for any frame. I ran the same four clips into two other frames:

FrameVertical clipThe three wide clips
720 x 1280 (vertical)Fills the frameOver a blurred copy
1280 x 720 (wide)Over a blurred copyFill the frame
1080 x 1080 (square)Over a blurred copyOver a blurred copy

MAX_LENGTH is the longest a result can be. The script takes the middle of a long clip. To keep the start instead, set trim to 0.

STYLES is where the variety comes from. Each style has a music track, a title color, a title position and the way the title comes in. Add a style and the rotation gets longer. For a different order on every run, shuffle the list before the loop.

Run it on your own clips

CLIPS is a plain list, so it can come from anywhere your clips are tracked: an uploads table, a spreadsheet, a folder listing from your storage. Each entry needs a src that Shotstack can reach and a title.

A file that isn’t online yet goes through the Ingest API first. It stores the file and gives you a URL to use as src.

The script builds each edit in code, because the layout changes from clip to clip. When every clip gets exactly the same layout, a saved template with merge fields is less work, and the guide to automating video editing shows that route in Python.

For a large set, the guide to bulk video creation covers how to track each render and re-run only the ones that failed.

If the edits are for more than one brand, keep the logo, the colors and the music in one settings block per brand and pass it to build_edit(). The guide to video production for multiple clients builds on that idea.

One edit, every kind of clip

Mixed footage only breaks a batch when the edit assumes a shape. Read the clip first, and the same few lines of code can trim, frame and brand whatever arrives.

The script needs one thing from you: an API key. Create a free Shotstack account to get one, then point CLIPS at your own footage.

Frequently asked questions (FAQs)

Can I keep the clip’s own sound?

Yes. The script sets volume to 0 on the video and plays music. To keep the original sound, remove "volume": 0 from the video asset, and lower the music’s volume or drop the music track.

Why blur the background instead of using black bars?

Bars work, and fit: "contain" on its own gives you them. A blurred copy fills the frame with the clip’s own colors, so a wide clip in a vertical frame still looks made for that frame. The guide to blurring the sides of a vertical video covers the opposite case in detail.

How do I choose which part of a long clip to keep?

The script keeps the middle. If you know where the action is, add a trim value to that clip’s entry in CLIPS and use it in build_edit() in place of the calculated one. Everything else stays the same.

Does the frame rate of the source matter?

Not for the result. The four sources here run at 25 and 29.97 frames a second, and every result is 30. The Edit API converts each clip to the output’s frame rate.

Keep reading

Start free

  • Unlimited developer sandbox
  • No credit card required