Ticket #8721: fffmpeg.py

File fffmpeg.py, 2.4 KB (added by grisk, 6 years ago)

Python script

Line 
1from PIL import Image, ImageDraw
2import os
3import shutil
4f = "/content/frames/"
5outFile = "/content/video.mp4"
6outFile_concat = "/content/video_concat.mp4"
7
8if os.path.exists(f):
9 shutil.rmtree(f)
10
11os.makedirs(f)
12
13
14#Final video should always have around 1 sec. duration
15#Setting fps = 25 should not remove any frames from final output.
16#Setting a high fps like 100 will remove 3 in 4 frames and encode it as 100fps
17ffps = 120
18
19
20dur = 1 / ffps
21
22endTime = 0
23strFile = ""
24
25for i in range(1, ffps):
26 img = Image.new('RGB', (100, 30), color = (73, 109, 137))
27 d = ImageDraw.Draw(img)
28 d.text((10,10), str(i).zfill(10), fill=(255,255,0))
29 name = str(i).zfill(10) +'.png'
30 img.save(f + "/"+ name)
31 strFile += "file '"+ name+"'\nduration "+ "{:.5f}".format(dur) + "\n"
32 endTime += dur
33
34
35filename = f + "/my_file.txt"
36myfile = open(filename, 'w')
37myfile.write(strFile)
38myfile.close()
39
40print("Final durations should be: " +str(endTime))
41
42# -r before "-f concat" : Override all durations from file. Its just like using a static fps
43# -vf "fps=X" : Fake final fps, it will keep very few frames.
44# -r after -i "{txtPath}" : It appear to work, but its get glitchy after 60fps.
45# -filter:v "fps={fps},setpts={speed}*PTS" : It encode correctly after the video is encoded at 25fps. So if there is a duration smaller than 25fps, it will delete those frames.
46
47speed = 1
48
49os.system('ffmpeg -y -framerate {fps} -i "{input}%10d.png" {muxer} {fmt} "{out}"'.format(fps=ffps, input=f, muxer="-c:v libx264 -crf 1", fmt="-pix_fmt yuv420p", out=outFile))
50os.system('ffmpeg -y -f concat -i "{txtPath}" {muxer} {fmt} -r {fps} "{out}"'.format(txtPath=filename, speed=speed, fps=ffps, muxer="-c:v libx264 -crf 1", fmt="-pix_fmt yuv420p", out=outFile_concat))
51
52
53t1 = "/content/t1/"
54t2 = "/content/t2/"
55
56if os.path.exists(t1):
57 shutil.rmtree(t1)
58if os.path.exists(t2):
59 shutil.rmtree(t2)
60
61os.makedirs(t1)
62os.makedirs(t2)
63
64os.system('ffmpeg -i "{}" -vsync 0 -vf mpdecimate -qscale:v 1 "{}%10d.png"'.format(outFile, t1))
65os.system('ffmpeg -i "{}" -vsync 0 -vf mpdecimate -qscale:v 1 "{}%10d.png"'.format(outFile_concat, t2))
66
67#Show total frames from each encode.
68print("Frames in regular: " + str(len(os.listdir(t1))))
69print("Frames in concat: " + str(len(os.listdir(t2))))
70
71
72#Output data of each video
73!ffmpeg -i {outFile}
74!ffmpeg -i {outFile_concat}