From gif to mp4 and return with ffmpeg and other features

A fast recap of other posts about ffmpeg

As you can be aware of reading the other post from this blog, I have used ffmpeg for many different tasks like:

Now I want also to trasform gif into mp4, as in one of the most recent post I showed a way to create gif with animation on the fly:

I want to show you the command to transfom the gif that we can make with the above example (go to the link above) into a convenient mp4 format… for any reason… for example you want to add a soundtrack (I will make another post about this and I’ll give you some tips at the end of this one).

From Gif to Mp4 with ffmpeg

The command is this

ffmpeg -r 30 -i input.gif -movflags faststart -pix_fmt yuv420p -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" output.mp4

If you want to make the movie go slower, you will have to change the frame rate, that in this case is -r 30. So if you put it to 15, it will be slower and viceversa.

I have showed this into this post about making animated gif with PIL to show how to convert the gif obtained into a convenient mp4 format.

From Mp4 to Gif.

And now let’s go from an mp4 to a gif

ffmpeg -i romeo18_15.mp4 -vf "fps=15,scale=600:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse" -loop 0 romeo18_from_mp4.gif

Other interesting features of ffmpeg

Get sound from an mp4

ffmpeg -i output5.mp4 -q:a 0 -map a output6.mp3

Substitute (or add) sound to an mp4

I’ve made a little script in python for this

import os

os.system("ffmpeg -i output5.mp4 -i output6.mp3 -map 0:v -map 1:a -c copy -shortest output8.mp4")

It needs some adjustment to make it usable whitout having to change the code.

My configuration to record the screen

You will need to configure this script for your needs. Take also a look at this post about this topic.

import os
import glob

x = 0
def record():
	global x
	if not "output" + str(x) + ".mp4" in glob.glob("*.mp4"):
		filename = "output" + str(x) + ".mp4"
	else:
		x += 1
		record()


	os.system(f"""ffmpeg -y -rtbufsize 200M -f gdigrab -thread_queue_size 1024 -probesize 10M -r 10 -draw_mouse 1 -video_size 1366x768 -i desktop -f dshow -channel_layout stereo -thread_queue_size 1024 -i audio="Microfono (8- Logitech USB Headset)" -c:v libx264 -r 10 -preset ultrafast -tune zerolatency -crf 25 -pix_fmt yuv420p -c:a aac -strict -2 -ac 2 -b:a 128k -vf "pad=ceil(iw/2)*2:ceil(ih/2)*2" "{filename}" """)

record()

 

 

 

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.