2

below is my code to convert h264 to gif

var ffmpeg = require("fluent-ffmpeg");
var inFilename = "/home/pi/Videos/video.mp4";
var outFilename = "/home/pi/Videos/video.gif";
var fs = require('fs');
ffmpeg(inFilename)
  .outputOptions("-c:v", "copy")
  .output(outFilename)
  .run();

this code works PERFECTLY when it goes from h264 to mp4 just wondering why it doesnt work with h264 to gif or if I could make it work.

cdoern
  • 97
  • 1
  • 12

1 Answers1

6

The main problem is that in this case you cannot use H.264 inside a GIF file so you have to remove the outputOptions line (which tries to copy the H.264 video directly to GIF) in order for FFmpeg to reencode the input video.

However, converting video size and frame rate AS-IS to GIF animation is not always a wise thing to do, so I would recommend adding a new option (see for example this answer for more examples and options) to account for that.

Lets modify the code a bit as a start; lets replace the output options for this case:

var ffmpeg = require("fluent-ffmpeg");
var inFilename = "/home/pi/Videos/video.mp4";
var outFilename = "/home/pi/Videos/video.gif";

ffmpeg(inFilename)
  .outputOption("-vf", "scale=320:-1:flags=lanczos,fps=15")
  .save(outFilename);

The options here are the same as running FFmpeg directly with:

ffmpeg -i inputfile.h264 -vf scale=320:-1:flags=lanczos,fps=15 outputfile.gif

The parameters are:

  • scale=320:-1 will scale to width 320 pixels. -1 will use a height proportional to width. You can flip them around to use height as absolute size.
  • flags=lanczos is the algorithm used to resample the image. lanczos provides good resample quality
  • fps=15 means the GIF will run at about 15 frames per second (FPS).
  • yep, this does the trick i changed my code to have your output options and the gif saved correctly – cdoern Sep 04 '18 at 00:33
  • would you happen to know how to speed up the gif? is there a filter setting I can use for that – cdoern Sep 04 '18 at 01:38
  • You can play around with the FPS value. If you want to retime you can look at the options used by ffmpeg [here](https://trac.ffmpeg.org/wiki/How%20to%20speed%20up%20/%20slow%20down%20a%20video) and add those to the call chain. –  Sep 04 '18 at 02:02
  • Was there any particular reason you unaccepted the answer which was for the main question? –  Sep 04 '18 at 02:18
  • whoops sorry I didn't realize I did that, just re accepted it – cdoern Sep 04 '18 at 03:40
  • No problem, you're in your full right to unaccept if you decide to do so; I just wondered if the answer didn't solve the original problem so I could update it if needed. However, glad it worked out. Cheers. –  Sep 04 '18 at 11:44