Contents
Flipping a video turns it into its own mirror image. A horizontal flip swaps left and right, so a skier carving to the left now carves to the right. A vertical flip turns the picture upside down.
You might mirror a video to undo a front camera that recorded everything backwards, to make a person face into the page instead of out of it, or to fix a clip that was filmed upside down.
This guide shows how to mirror a video with Python and Shotstack’s video editing API, then how to do the same with FFmpeg.
TL;DR
- A clip’s
transformsetting takes"flip": {"horizontal": true}to mirror it, or"vertical": trueto turn it upside down. - The script below renders a 14.12 second clip twice: mirrored, and upside down. The sound plays as it was.
- Each result matches what FFmpeg’s
hflipandvflipfilters make of the same clip. - Both flips together turn the picture by 180 degrees.
How flipping works with the API
The Edit API renders a timeline that you describe in JSON. Flipping is a setting on the clip, not on the video file. The API reference describes it in one line: “Flip a clip vertically or horizontally. Acts as a mirror effect of the clip along the selected plane.”
This clip plays a video mirrored from left to right:
{
"asset": { "type": "video", "src": "https://example.com/video.mp4" },
"start": 0,
"length": 10,
"transform": { "flip": { "horizontal": true } }
}Use "vertical": true to turn it upside down, or set both to true to turn it by 180 degrees.
Mirror a video with Python
The script below takes a 14 second clip of a skier, hosted by Shotstack. It reads the clip’s length, then renders it twice: once mirrored and once upside down.
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.
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.amazonaws.com/footage/skier.mp4"
FLIPS = {
"mirrored": {"horizontal": True},
"upside-down": {"vertical": True},
}
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 of the first video stream 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")
return float(video["duration"])
def build_edit(flip, length):
clip = {
"asset": {"type": "video", "src": SOURCE},
"start": 0,
"length": length,
"transform": {"flip": flip},
}
return {
"timeline": {"tracks": [{"clips": [clip]}]},
"output": {"format": "mp4", "resolution": "hd"},
}
if __name__ == "__main__":
if not os.environ.get("SHOTSTACK_API_KEY"):
sys.exit("Set SHOTSTACK_API_KEY first.")
length = probe(SOURCE)
print(f"Source: {length:.2f} s")
renders = {
name: call(f"{API}/render", build_edit(flip, length))["response"]["id"]
for name, flip in FLIPS.items()
}
for name, render_id in renders.items():
while True:
status = call(f"{API}/render/{render_id}")["response"]
if status["status"] == "done":
break
if status["status"] == "failed":
sys.exit(f"{name} failed: {status.get('error')}")
time.sleep(5)
print(f"{name}: {status['url']}")Run python flip_video.py. It prints the length of the source and the URL of each video:
Source: 14.12 s
mirrored: https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/35tqpmb0ya/9b97111c-b3e1-41cb-bab6-7154bfae5943.mp4
upside-down: https://shotstack-api-v1-output.s3-ap-southeast-2.amazonaws.com/35tqpmb0ya/737b8456-997d-41c5-8c91-59197baa5d07.mp4This video plays the original next to both results:
How the script works
probe()sends the clip’s URL to the Probe endpoint and returns its length, so the render covers the whole clip.FLIPSnames each version and the flip it gets. Add or remove entries to render other versions.build_edit()makes one clip with the flip in itstransform.- The main block posts both renders before it waits for either, then prints each URL when it’s done.
Flip only part of a video
The flip belongs to one clip, so split the video into clips and flip the ones you want. This track plays the first 3 seconds as they are and turns the next 3 seconds by 180 degrees:
[
{ "asset": { "type": "video", "src": "https://example.com/video.mp4", "trim": 0 }, "start": 0, "length": 3 },
{
"asset": { "type": "video", "src": "https://example.com/video.mp4", "trim": 3 },
"start": 3,
"length": 3,
"transform": { "flip": { "horizontal": true, "vertical": true } }
}
]Text, logos and captions on other tracks keep their own settings. A title on the track above a mirrored clip still reads the right way round.
Flip a video with FFmpeg
FFmpeg flips a video on your own machine with its hflip and vflip filters:
ffmpeg -i input.mp4 -vf hflip -c:a copy mirrored.mp4
ffmpeg -i input.mp4 -vf vflip -c:a copy upside-down.mp4-c:a copy keeps the sound as it is. The video is always encoded again, because a filter changes the pixels. To turn a video by 180 degrees, use both filters: -vf hflip,vflip gives the same frames as two 90 degree turns with transpose.
The skier clip flipped with these commands gives the same pictures as the API’s results. For other kinds of rotation, our guide on how to rotate videos using FFmpeg covers transpose and rotation metadata.
Mirror your videos with Shotstack
You now have a script that mirrors a video, or turns it upside down, in one render each. Put your own video URL in SOURCE and run it again.
Create a free Shotstack account to get your API key and flip your first video.
Frequently asked questions (FAQs)
Can I flip an image instead of a video?
Yes. transform belongs to the clip, so it works the same way on an image asset. Use the image’s URL in src and give the clip a length.
Can I mirror a video and play it backwards?
Yes. Keep the flip and add a speed tween with a negative value to the same clip. Our guide on how to reverse a video with Python explains how the speed setting plays a clip backwards.
Can I flip 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.