Skip to content

Instantly share code, notes, and snippets.

@marcusstenbeck
Created October 14, 2015 00:09
Show Gist options
  • Save marcusstenbeck/107e654e62776b26ede3 to your computer and use it in GitHub Desktop.
Save marcusstenbeck/107e654e62776b26ede3 to your computer and use it in GitHub Desktop.
Take a bunch of input video clips and turn them into a video mosaic
#######################
# clips_to_mosaic.sh #
# Requires ffmpeg #
#######################
# This file contains video paths, one per line
FILE="infile.txt"
# Square tile size (pixels)
TILE_SIDE=108
# Video tiles are populated top-to-bottom and left-to-right
TILE_COLS=16
# "Initialize" vars
INPUTS=""
SOURCES=""
LAYERS=""
COUNTER=0
while read line
do
# Prevent appending `[tmpX];` to first and last layer
if [ $(($COUNTER)) -ne 0 ]
then
LAYERS+=" [tmp$(($COUNTER))]; "
fi
INPUTS+="-i $line "
# ~> [3:v] setpts=PTS-STARTPTS, scale=128x128 [stream3];
SOURCES+="[$COUNTER:v] setpts=PTS-STARTPTS, scale=$(($TILE_SIDE))x$(($TILE_SIDE)) [stream$COUNTER]; "
# ~> [tmp3][stream3] overlay=shortest=1:x=324:y=0"
# Note: for COUNTER == 0, the `tmpX` is replaced with `base`
LAYERS+="[tmp$COUNTER][stream$COUNTER] overlay=shortest=1:x=$(($COUNTER%$TILE_COLS*$TILE_SIDE)):y=$(($COUNTER/$TILE_COLS*$TILE_SIDE))"
let COUNTER+=1
done < $FILE
# Undo the last increment
let COUNTER-=1
# Now that we have the total count of videos, calculate video size
TILE_ROWS=$(($COUNTER/$TILE_COLS+1))
OUT_WIDTH=$(($TILE_COLS*$TILE_SIDE))
OUT_HEIGHT=$(($TILE_ROWS*$TILE_SIDE))
# Create base (null source) and black color sources
SOURCES="nullsrc=size=$(($OUT_WIDTH))x$OUT_HEIGHT [base]; color=c=black, scale=$(($OUT_WIDTH))x$OUT_HEIGHT [black]; $SOURCES"
# Apply black color source on top of the base null source
LAYERS="[base][black] overlay=shortest=1 [tmp0]; $LAYERS"
# Combine intro a filter graph
FILTER_GRAPH="\"$SOURCES $LAYERS\""
# Run ffmpeg command to generate mosaic
eval ffmpeg $INPUTS -filter_complex $FILTER_GRAPH -c:v libx264 -preset fast -crf 18 output.mp4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment