Skip to content

Instantly share code, notes, and snippets.

@domportera
Last active November 4, 2022 17:41
Show Gist options
  • Save domportera/d23b02695874c207dede0e7c5d8ecfe3 to your computer and use it in GitHub Desktop.
Save domportera/d23b02695874c207dede0e7c5d8ecfe3 to your computer and use it in GitHub Desktop.
ffmpeg-optimize-with-creation-date
#!/bin/bash
#
# this is very much a work in progress, user beware and please test before use.
# I have only tested on the Ubuntu shells on Windows so far
# I have only tested h264->h265(hevc) so far
# some resources I've used to compose this:
# https://unix.stackexchange.com/questions/118577/changing-a-files-date-created-and-last-modified-attributes-to-another-file
# https://superuser.com/questions/901912/copy-creation-date-metadata-when-converting-video-with-ffmpeg
# https://stackoverflow.com/questions/9464617/retrieving-and-saving-media-metadata-using-ffmpeg
inputfile="test.mp4"
outputfile="${inputfile}-ffmpegged.mp4"
metadir="./generated-metadata"
mkdir -p $metadir
metadatafile="${metadir}/${inputfile}-metadata.txt"
crfquality=20
loglevel=info
# save the metadata to a file
ffmpeg -i "$inputfile" -c copy -map_metadata 0 \
-map_metadata:s:v 0:s:v \
-map_metadata:s:a 0:s:a \
-f ffmetadata "$metadatafile" -y
# grab the creation time of the input file
timefound=$(grep "creation_time" "$metadatafile")
# grab the dimensions of the input file
dimensions=$(ffprobe -v error -select_streams v:0 \
-show_entries stream=width,height \
-of json "$inputfile" | \
jq '.streams[0]')
# parse the dimensions of the input file
width=$(echo "$dimensions" | jq '.width')
height=$(echo "$dimensions" | jq '.height')
# transcode - -metadata "$timefound" is what injects the time into the transcoded video
ffmpeg -i "$inputfile" \
-c:v hevc_nvenc \
-movflags use_metadata_tags \
-metadata "$timefound" \
-crf $crfquality \
-preset slow \
-r 30 \
-vf "scale=$width:-1, removegrain=22" \
-c:a copy \
-report \
-loglevel $loglevel \
"$outputfile"
# inject the time into the file system
touch -r "$inputfile" "$outputfile"
# print results for debug and development
printf "\nFound dimensions of first stream:\n"
echo "$dimensions"
printf "\nFound individual width and height:\n"
echo "$width"
echo "$height"
echo "$timefound"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment