Learn · Developers

How to create a video collage with Python

Contents

A video collage plays several videos at the same time in one frame. Two clips side by side, four customer videos in a 2x2 grid and nine travel shots in a 3x3 grid are all collages.

This article shows how to make them with a short Python script and Shotstack’s video editing API. You describe each collage in a JSON file, and the script renders one MP4 for each one. We rendered three layouts on production and measured every cell edge in the files.

Here is the 3x3 collage from the sample file:

TL;DR

  • Each video in a collage is one clip on its own track. All the clips start at 0 and have the same length.
  • Cell width = (frame width - gap x (columns + 1)) / columns. Cell height uses the frame height and the rows in the same way.
  • Each clip gets its cell’s width and height, fit: "crop" and an offset from the center of the frame.
  • One groups.json file describes many collages. The script renders all of them and saves the video links in results.json.
  • In our renders, every cell was where we planned it, to the pixel. Portrait and landscape clips both filled their cells.

How a collage works in the Edit API

A Shotstack edit is a timeline of tracks, and each track holds clips. Clips on different tracks play at the same time, like layers. A collage puts each video on its own track, with the same start and length.

Three clip properties make the layout. The positioning guide describes all of them:

  • width and height set the size of the clip’s box in pixels. Here, each box is one cell of the grid.
  • fit: "crop" scales the video to fill the box and keeps its shape. The parts that fall outside the box are cut off.
  • offset moves the box away from the center of the frame. An x of 0.5 moves it half the frame width to the right, and a positive y moves it up.

Do not use fit: "cover" for a collage. In Shotstack, cover stretches the video to fill the box and does not keep its shape. If you want to see the whole video instead of a crop, use contain, which fits the whole video inside the box and keeps its shape. The fit property guide compares all four options.

What you need

  • Python 3 and the requests library. We ran the script with Python 3.13. Install the library with pip install requests.
  • A Shotstack API key. Create a free account to get one. The script calls the production API.
  • A public URL for each video and for the music. Shotstack downloads each file when it renders the video, so a path on your computer will not work. Upload local files first, for example with the Ingest API.

Describe your collages in groups.json

Each group in the file becomes one video. The values at the top are the defaults for every group.

JSON
{
  "width": 1920,
  "height": 1080,
  "gap": 12,
  "background": "#14161A",
  "length": 5,
  "groups": [
    {
      "name": "road-trip",
      "grid": [1, 2],
      "soundtrack": "https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/music/unminus/palmtrees.mp3",
      "clips": [
        "https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/footage/car-overead-vertical.mp4",
        "https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/footage/road.mp4"
      ]
    },
    {
      "name": "city-weekend",
      "grid": [2, 2],
      "soundtrack": "https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/music/unminus/berlin.mp3",
      "clips": [
        "https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/footage/drone-city-flyover.mp4",
        "https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/footage/cars-tunnel.mp4",
        "https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/footage/city-timelapse.mp4",
        "https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/footage/night-sky.mp4"
      ]
    },
    {
      "name": "summer-recap",
      "grid": [3, 3],
      "soundtrack": "https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/music/freepd/motions.mp3",
      "clips": [
        "https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/footage/beach-overhead.mp4",
        "https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/footage/skier.mp4",
        "https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/footage/cliffs-sunset.mp4",
        "https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/footage/sunset.mp4",
        "https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/footage/bmx.mp4",
        "https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/footage/skateboarder.mp4",
        "https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/footage/table-mountain.mp4",
        "https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/footage/mountains.mp4",
        "https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/footage/drone-over-fields.mp4"
      ]
    }
  ]
}
FieldWhat it does
width, heightThe size of the video in pixels. Use even numbers: the API requires output sizes that divide by 2.
gapThe space between the cells and around the edge, in pixels.
backgroundThe color of the gaps and of any empty cell.
lengthThe length of the collage in seconds.
nameThe name of the group. The script uses it in its messages and in results.json, so give each group a different name.
grid[rows, columns]. [1, 2] is side by side, [2, 2] is a 2x2 grid.
clipsThe video URLs, in cell order: left to right, then top to bottom.
soundtrackA music URL. This is optional. Every clip is muted, so the music is the only sound.

A group can also set its own width, height, gap, background or length. These values replace the defaults for that group only.

The sample uses Shotstack’s stock footage and music, so you can run it without changes. The clips have different shapes and frame rates on purpose: one is portrait, and the frame rates go from 23.976 to 59.94 fps.

How the grid math works

A row of cells has one gap before each cell and one more at the end. So the script takes all the gaps away from the frame width and shares what is left between the columns. The height works the same way with the rows:

Python
cell_w = (width - gap * (cols + 1)) // cols
cell_h = (height - gap * (rows + 1)) // rows

For a 1920x1080 frame with a 12-pixel gap, that gives these cells:

GridCellsCell size
Side by side, [1, 2]2942x1056
2x2, [2, 2]4942x522
3x3, [3, 3]9624x344

Cell sizes are rounded down to whole pixels. If the frame does not divide evenly, the spare pixels go to the right and bottom edges.

Next, the script finds the center of each cell in pixels, counting from the top-left corner of the frame. Then it turns that point into an offset from the center of the frame:

  • x = cell center x / frame width - 0.5
  • y = 0.5 - cell center y / frame height

The y formula is the other way round because pixel rows count down from the top, but a positive y offset moves the clip up.

For example, the top-left cell of the 2x2 grid has its center at pixel (483, 273). Its offset is x = 483 / 1920 - 0.5 = -0.2484 and y = 0.5 - 273 / 1080 = 0.2472. Here is the clip the script makes for that cell:

JSON
{
  "asset": {
    "type": "video",
    "src": "https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/footage/drone-city-flyover.mp4",
    "volume": 0
  },
  "start": 0,
  "length": 5,
  "width": 942,
  "height": 522,
  "fit": "crop",
  "offset": {
    "x": -0.2484,
    "y": 0.2472
  }
}

The script

Save this as collage.py, in the same folder as groups.json:

Python
"""Render one video collage per group of clips with the Shotstack Edit API.

Usage:
  python collage.py groups.json            render every group
  python collage.py groups.json --dry-run  print the Edit JSON only (no API key needed)

Set SHOTSTACK_API_KEY to your production API key before you render.
"""
import json
import os
import sys
import time

import requests

API = os.environ.get("SHOTSTACK_API", "https://api.shotstack.io/edit/v1")


def grid_clips(urls, rows, cols, width, height, gap, length):
    """One muted clip per cell, left to right, top to bottom. Each clip is cropped to fill its cell."""
    if not urls or len(urls) > rows * cols:
        raise ValueError(f"{len(urls)} clips do not fit a {rows} x {cols} grid")
    cell_w = (width - gap * (cols + 1)) // cols
    cell_h = (height - gap * (rows + 1)) // rows
    clips = []
    for i, url in enumerate(urls):
        row, col = divmod(i, cols)
        center_x = gap + col * (cell_w + gap) + cell_w / 2
        center_y = gap + row * (cell_h + gap) + cell_h / 2
        clips.append({
            "asset": {"type": "video", "src": url, "volume": 0},
            "start": 0,
            "length": length,
            "width": cell_w,
            "height": cell_h,
            "fit": "crop",
            # Offset is a fraction of the frame size, measured from the center. Positive y moves up.
            "offset": {"x": round(center_x / width - 0.5, 4), "y": round(0.5 - center_y / height, 4)},
        })
    return clips


def build_edit(group, defaults):
    g = {**defaults, **group}
    rows, cols = g["grid"]
    clips = grid_clips(g["clips"], rows, cols, g["width"], g["height"], g["gap"], g["length"])
    timeline = {
        "background": g["background"],
        # One track per clip: clips on the same track cannot play at the same time.
        "tracks": [{"clips": [clip]} for clip in clips],
    }
    if g.get("soundtrack"):
        timeline["soundtrack"] = {"src": g["soundtrack"], "effect": "fadeOut"}
    output = {"format": "mp4", "fps": 30, "size": {"width": g["width"], "height": g["height"]}}
    return {"timeline": timeline, "output": output}


def render_all(edits, key):
    headers = {"x-api-key": key}
    jobs = {}
    for name, edit in edits.items():
        r = requests.post(f"{API}/render", json=edit, headers=headers, timeout=30)
        if r.ok:
            jobs[name] = {"id": r.json()["response"]["id"], "status": "queued", "url": ""}
        else:
            jobs[name] = {"id": "", "status": "failed", "url": "", "error": r.text[:300]}
        print(f"{name}: {jobs[name]['status']} {jobs[name]['id']}")
        time.sleep(0.25)  # stays under the Edit API limit of 300 requests a minute

    deadline = time.time() + 15 * 60
    while time.time() < deadline:
        waiting = [n for n, j in jobs.items() if j["status"] not in ("done", "failed")]
        if not waiting:
            break
        time.sleep(max(10, len(waiting) / 4))  # one status check per render, under the same limit
        for name in waiting:
            r = requests.get(f"{API}/render/{jobs[name]['id']}", headers=headers, timeout=30)
            if not r.ok:
                continue  # try again on the next round
            render = r.json()["response"]
            jobs[name].update(status=render["status"], url=render.get("url", ""), error=render.get("error", ""))
            if render["status"] in ("done", "failed"):
                print(f"{name}: {render['status']} {render.get('url') or render.get('error', '')}")
    return jobs


def main():
    with open(sys.argv[1], encoding="utf-8") as f:
        config = json.load(f)
    groups = config.pop("groups")
    edits = {group["name"]: build_edit(group, config) for group in groups}
    if "--dry-run" in sys.argv:
        print(json.dumps(edits, indent=2))
        return
    jobs = render_all(edits, os.environ["SHOTSTACK_API_KEY"])
    with open("results.json", "w", encoding="utf-8") as f:
        json.dump(jobs, f, indent=2)
    print("Saved results.json")


if __name__ == "__main__":
    main()

How the script works

  • grid_clips() makes one clip for each video. Each clip is muted, starts at 0 and gets its cell’s size, fit: "crop" and offset. If a group has more clips than cells, the function stops with an error.
  • build_edit() puts the group’s own values over the defaults. It gives each clip its own track, adds the music with a fade out at the end, and asks for an MP4 at 30 fps in the group’s size.
  • render_all() sends every group first. Then it checks each unfinished render about every 10 seconds until all of them are done or failed.
  • main() saves the result for each group in results.json.

The pauses in render_all() keep the script under Shotstack’s rate limit. The Edit API takes 300 requests a minute on production, and each render and each status check is one request. The script waits 0.25 seconds between renders. Between status checks, it waits 10 seconds, or a quarter of a second for each render still waiting if that is longer. With 200 renders waiting, it waits 50 seconds between rounds.

Run the script

Set your API key in the terminal. On macOS or Linux:

Bash
export SHOTSTACK_API_KEY="your_production_api_key"

On Windows, in PowerShell:

powershell
$env:SHOTSTACK_API_KEY = "your_production_api_key"

First, check the Edit JSON without rendering anything. This prints one edit for each group and does not need an API key:

Bash
python collage.py groups.json --dry-run

Then render all the groups:

Bash
python collage.py groups.json

The script prints a line when it sends each group and another when each video is ready:

Text
road-trip: queued 3f9a1c27-6b2e-4d18-a5c0-7e41b9d2f863
city-weekend: queued 8c25e0b4-91d7-4f3a-b6e2-0d5a7c13f948
summer-recap: queued d41e7a92-3c58-4b0f-8e17-a62c9f05b3d1
road-trip: done https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/7n4qk2xw9e/3f9a1c27-6b2e-4d18-a5c0-7e41b9d2f863.mp4
city-weekend: done https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/7n4qk2xw9e/8c25e0b4-91d7-4f3a-b6e2-0d5a7c13f948.mp4
summer-recap: done https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/7n4qk2xw9e/d41e7a92-3c58-4b0f-8e17-a62c9f05b3d1.mp4
Saved results.json

results.json holds the render ID, status, video URL and any error message for each group. Open a URL to watch the video or download it.

What the renders showed

We ran the script on production with the sample file and measured the three videos.

  • Each video is 1920x1080, 30 fps and 5 seconds long. Each has one audio track, which is the group’s music.
  • We checked every planned cell edge on frames at 0.5, 2.5 and 4.5 seconds. The first and last pixel row and column of each cell were video. The background color showed from 2 pixels outside each cell. Bright edges blurred over 1 or 2 pixels because of video compression.
  • fit: "crop" filled every cell, whatever the shape of the video. In the side by side collage, the portrait clip lost its top and bottom, and the landscape clip lost its sides.
  • Clips at 23.976, 24, 25, 29.97 and 59.94 fps played together in the 30 fps videos.
  • volume: 0 mutes each clip. The skier clip has sound, but a collage with it and no music was silent.

Here is a frame from the side by side collage:

Side by side video collage: a portrait clip of a car on a forest road on the left and a landscape clip of a cliff road by a river on the right, with a dark gap between them

Fewer clips than cells

You do not need a clip for every cell. We rendered 7 clips in a 3x3 grid. The clips filled the first 7 cells, left to right and top to bottom, and the last 2 cells showed the background color:

A 3x3 video grid with seven clips playing and the last two cells empty in the dark background color

We rendered a group that had a URL to a file that does not exist. Its render failed with this error:

Text
This URL is not accessible (access denied): https://shotstack-assets.s3-ap-southeast-2.amazonaws.com/footage/does-not-exist.mp4

The script saved the error in results.json, and the other group in the same run still finished. Some storage services answer “access denied” for a missing file, so check the URL for typing errors as well as for permissions.

Too many clips

If a group has more clips than cells, the script stops before it sends anything:

Text
ValueError: 3 clips do not fit a 1 x 2 grid

The script builds every edit before it renders any of them. So one group with too many clips stops the whole run, and nothing is rendered. Fix the group, then run the script again.

Change the layout

Change groups.json, not the script:

  • Grid: set grid to the rows and columns you want. [2, 3] gives six cells.
  • Order: move the URLs in clips. The first URL goes in the top-left cell.
  • Spacing and color: change gap and background.
  • Length: set length no longer than your shortest clip. See the FAQ below for what happens if a clip is shorter.
  • One group only: add width, height, gap, background or length inside that group.

If you would rather see each whole video than a crop, change "crop" to "contain" in grid_clips(). Batch edit videos of different sizes with Python shows how crop and contain handle clips of mixed sizes. To move clips to other places on the frame, how to position clips explains position and offset.

Make your first collage

Create a free Shotstack account, copy your production API key, and run the script with the sample file. Then replace the URLs with your own videos. Add a group for each event, customer or product, and the script makes all the collages in one run.

Frequently asked questions (FAQs)

How do I make a side by side video with Python?

Use a group with "grid": [1, 2] and two clips. On a 1920x1080 frame with a 12-pixel gap, each video gets a 942x1056 cell. To put one video above the other, use "grid": [2, 1].

How do I make a vertical video collage for TikTok, Reels or Shorts?

Give the group its own size: "width": 1080, "height": 1920. With "grid": [2, 1] and a 12-pixel gap, the two videos are stacked in 1056x942 cells. We rendered this layout on production, and the file was 1080x1920 at 30 fps:

A vertical 1080x1920 video collage with a BMX rider under a bridge at the top and a skier on a sunny slope at the bottom

To build a vertical split screen by hand instead, see how to make split screen videos for TikTok and YouTube Shorts.

What happens if one video is shorter than the collage?

Its cell holds the clip’s last frame until the collage ends. It does not go blank. We tested this with a 5.68-second clip in a 7-second collage: from about 5.7 seconds, the cell showed the same still frame to the end. To avoid the freeze, set length no longer than your shortest clip.

Keep reading

Start free

  • Unlimited developer sandbox
  • No credit card required