Search code examples
pythonffmpegmoviepy

100% of gif does not convert to mp4 with moviepy


when I execute the following code:

import requests
import moviepy.editor as mp

url = "https://i.imgur.com/VaTidQA.gif"
with open('temp.gif', 'wb') as f:
    f.write(requests.get(url).content)
clip = mp.VideoFileClip("temp.gif")
print(clip.duration)
clip.write_videofile("temp.mp4")

I experience loss of frames on the mp4 file. the mp4 will always start from the beginning but will seemingly arbitrarily cut off at some point.

Here is an example:

GIF: https://i.imgur.com/VaTidQA.gif

MP4: https://giphy.com/gifs/pesky-wabbit-5UqQOjkYLuWrvHzvsA

The gif is indeed downloaded in its entirety.

Upon testing, I found that if I change the last line to:

clip.set_duration(clip.duration + X).write_videofile("temp.mp4")

then it will indeed extend the MP4 and cut off less, but this needs to be a variable script as it will be used for many, many gifs. It is almost certainly due to the fact that moviepy is getting the wrong duration from the gif. Any suggestions on how I can remedy this?

update: I have determined that moviepy is obtaining the incorrect duration from the gif. when that duration is passed to the write_videofile() call, it only writes that shorter interval. I am looking into how it determines the gif duration.


Solution

  • I changed my .gif conversion to

    os.system('echo "y"| ffmpeg -i temp.gif -movflags faststart -pix_fmt yuv420p -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" temp.mp4')

    and then clip the duration to a max of 15s by using

           if (dur > 15):
                print("changing duration")
                clip.set_duration(15).write_videofile("buffertemp.mp4")
                clip = mp.VideoFileClip("buffertemp.mp4")
                clip.write_videofile("temp.mp4")