senty
senty

Reputation: 12847

Generating Gif from Mp4 directly - ffmpeg

I am trying to generate a gif from an mp4 video file. I want to scale it and crop it while generating.

I achieved that (cropping & scaling) from mp4 to mp4 with the below line , (so I can extract pngs with ffmpeg and use Imagick to make animated gif), but I believe there is a better way of achieving purely with ffmpeg.

ffmpeg -i in.mp4 -filter:v "scale=300:ih*300/iw, crop=200:500:50:80" -c:a copy out.mp4

My question is how to achieve the same this code is doing, but for directly generating gif from mp4.


Then I started tweaking with mp4 to gif conversion, but when palette comes in, I couldn't fully understand what's going on.

I found this answer and I made it work, however I couldn't understand how to adapt scaling & cropping.

$ ffmpeg -y -ss 30 -t 3 -i in.mp4 \ -vf fps=10,scale=320:-1:flags=lanczos,palettegen palette.png

$ ffmpeg -ss 30 -t 3 -i in.flv -i palette.png -filter_complex \ "fps=10,scale=320:-1:flags=lanczos[x];[x][1:v]paletteuse" out.gif

I partially understand what this bit does -y -ss 30 -t 3 -i in.mp4 (getting the first 30 seconds and generating a 3 second gif out of it). But for the next lines, I am completely lost what it is actually doing.

It'd be amazing if someone can explain what each command does, or refer a link explaining this topic.

Upvotes: 1

Views: 2216

Answers (1)

Gyan
Gyan

Reputation: 93008

In your first command,

ffmpeg -y -ss 30 -t 3 -i in.mp4 \
-vf fps=10,scale=320:-1:flags=lanczos,palettegen palette.png

-y causes ffmpeg to overwrite if output file already exists, so no prompt for confirmation.

-vf, alias for -filter:v, is a video filterchain, which takes one video input and processes each specified filter successively. So input -> filter 1 -> filter 2 ... -> filter n -> filter output

fps=10 converts the source to this framerate by dropping or duplicating frames as needed, no interpolation performed. If your source is 20 fps, this will drop every other frame. If it's 5 fps, it will duplicate every frame once.

scale=320:-1:flags=lanczos resizes the video to a width of 320 pixels and the height to a length so that the original aspect ratio is maintained. If you wanted to resize to 320x300, you would replace the -1 with 300. Lanczos is the scaling algorithm used. See list here. Lanczos is good.

palettegen generates a 256 color palette of the entire input stream. Usually used in conjunction with paletteuse.

The -filter_complex in your second command is when you have to apply filters to multiple inputs and/or need to generate multiple outputs. A bit long to summarize here, see here.

Upvotes: 2

Related Questions