Skip to content

Instantly share code, notes, and snippets.

@apeckham
Created August 10, 2024 23:29
Show Gist options
  • Save apeckham/9c4b7a682726319eb1a1b8a8040f277b to your computer and use it in GitHub Desktop.
Save apeckham/9c4b7a682726319eb1a1b8a8040f277b to your computer and use it in GitHub Desktop.
ffmpeg reverse video in memory-friendly chunks
#!/bin/bash
set -ex
# Input file name
input_file="input.mp4"
# Output file name
output_file="output.mp4"
# Duration of each segment in seconds (5 minutes)
segment_duration=300
# Get the total duration of the video
duration=$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$input_file")
duration=${duration%.*}
# Create temporary directories
mkdir -p temp_segments reversed_segments
# Split the video into segments
for ((i=0; i<duration; i+=segment_duration)); do
ffmpeg -i "$input_file" -ss $i -t $segment_duration -c copy "temp_segments/segment_$(printf "%06d" $i).mp4"
done
# Reverse each segment
for segment in temp_segments/*.mp4; do
base_name=$(basename "$segment")
ffmpeg -i "$segment" -vf reverse -af areverse -threads 4 -filter_threads 4 "reversed_segments/reversed_$base_name"
done
# Create a file list for concatenation in reverse order
ls -1v reversed_segments/*.mp4 | tac | while read segment; do
echo "file '$segment'" >> segment_list.txt
done
# Concatenate reversed segments
ffmpeg -f concat -safe 0 -i segment_list.txt -c copy "$output_file"
# Clean up temporary files and directories
rm -r temp_segments reversed_segments segment_list.txt
echo "Reversal complete. Output file: $output_file"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment