Adding chapters to mp4 using bash script and ffmpeg
I’m trying to add chapters to an mp4 file using bash and ffmpeg. The chapters are located in a file called chapters.txt. When the bash script is run which is called add_chapters.sh it reads the chapters.txt file and creates a file called chapters.ffmetadata. The issue is the START and END times in the file chapters.ffmetadata aren’t being created correctly. How can I fix this?
I have a file called chapters.txt
1- That has the chapters in it.
00:00:00=Intro
00:02:12=What are selections
00:03:19=Booleans
2- The bash file I run is add_chapters.sh
The code in it is:
#!/bin/bash
input_file="chapters.txt"
output_file="chapters.ffmetadata"
# Create the FFmetadata chapter file
echo ";FFMETADATA1" > "$output_file"
previous_seconds=0
while IFS="=" read -r timestamp chapter_name; do
# Convert start time to seconds
seconds=$(date -u -d "1970-01-01 $timestamp" +"%s")
# Calculate the end time (previous chapter's start time)
end_seconds=$previous_seconds
# Update previous_seconds for the next iteration
previous_seconds=$seconds
echo "[CHAPTER]" >> "$output_file"
echo "TIMEBASE=1/1000" >> "$output_file"
echo "START=${end_seconds}000" >> "$output_file"
echo "END=${seconds}000" >> "$output_file"
echo "title=$chapter_name" >> "$output_file"
done < "$input_file"
echo "Chapter file '$output_file' created successfully."
# Run FFmpeg to add chapters to the video
ffmpeg -i input_video.mp4 -i chapters.ffmetadata -map_metadata 1 -c:v copy -c:a copy -y output_video.mp4
3- It creates a file called chapters.ffmetadata
;FFMETADATA1
[CHAPTER]
TIMEBASE=1/1000
START=0000
END=0000
title=Intro
[CHAPTER]
TIMEBASE=1/1000
START=0000
END=132000
title=What are selections
[CHAPTER]
TIMEBASE=1/1000
START=132000
END=199000
title=Booleans
[CHAPTER]
TIMEBASE=1/1000
START=199000
END=0000
title=
The START and END times aren’t being “calculated” correctly how can I fix this?
Read more here: Source link