I'm doing multiple operations with FFMPEG. I have 5 files.
- intro_image.jpg: This is an image of any resolution but will be jpeg.
- intro_audio.mp3: This audio is static input of duration 7 seconds.
- outro_image.jpg: This is an image of any resolution but will be jpeg.
- outro_audio.mp3: This audio is static input of duration 7 seconds.
- user_video.mp4: User video can be of any resolution but a minimum 480P and of any format like mp4, avi, mkv. the maximum duration of the video will be 1 minute only.
What I'm doing is merging all the videos in 480P with a black background.
Step 1: Merging intro_image.jpg and intro_audio.mp3 to create intro_video.mp4
ffmpeg -loop 1 -i #{params[:intro_image].path} -i #{params[:intro_audio].path} -vf 'scale=640:480:force_original_aspect_ratio=decrease,pad=640:480:-1:-1:color=black' -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest #{dir}/#{intro_video_name}
Step 2: Merging outro_image.jpg and outro_audio.mp3 to create outro_video.mp4
ffmpeg -loop 1 -i #{params[:outro_image].path} -i #{params[:outro_audio].path} -vf 'scale=640:480:force_original_aspect_ratio=decrease,pad=640:480:-1:-1:color=black' -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest #{dir}/#{outro_video_name}
Step 3: I check if audio is avaiable in the user_video.mp4. if not then:
ffmpeg -i #{params[:video].path} -f lavfi -i anullsrc -c:v copy -c:a aac -shortest #{video_path}
Step 4: Trim users video according to the provided start_time & end_time.
ffmpeg -i movie.mp4 -ss 00:00:03 -t 00:00:08 -async 1 cut.mp4
Step 5: Merge all three videos.
ffmpeg -y -i #{dir}/#{intro_video_name} -i #{video_path} -i #{dir}/#{outro_video_name} -filter_complex '[0:v]scale=640x480,setsar=1[v0];[1:v]scale=640:480:force_original_aspect_ratio=decrease,pad=640:480:-1:-1:color=black,setsar=1[v1];[2:v]scale=640x480,setsar=1[v2];[v0][0:a][v1][1:a][v2][2:a]concat=n=3:v=1:a=1' -ab 48000 -ac 2 -ar 22050 -s 640x480 -vcodec libx264 -crf 27 -preset ultrafast -vsync vfr #{dir}/#{final_video_name}
all these steps take around 40 seconds if the total file size is 10 MB. I'm looking for a way to optimize these commands without losing video quality.