media file: get duration of animated GIFs, PNGs, and ugoiras.

Add methods to MediaFile to calculate the duration, frame count, and
frame rate of animated GIFs, PNGs, Ugoiras, and videos.

Some considerations:

* It's possible to have a GIF or PNG that's technically animated but
  just has one frame. These are treated as non-animated images.

* It's possible to have an animated GIF that has an unspecified
  frame rate. In this case we assume the frame rate is 10 FPS; this is
  browser dependent and may not be correct.

* Animated GIFs, PNGs, and Ugoiras all support variable frame rates.
  Technically, each frame has a separate delay, and the delays can be
  different frame-to-frame. We report only the average frame rate.

* Getting the duration of an APNG is surprisingly hard. Most tools don't
  have good support for APNGs since it's a rare and non-standardized
  format. The best we can do is get the frame count using ExifTool and the
  frame rate using ffprobe, then calculate the duration from that.
This commit is contained in:
evazion
2021-09-27 04:41:40 -05:00
parent 79fdfa86ae
commit 0e901b2f84
6 changed files with 156 additions and 18 deletions

View File

@@ -135,7 +135,26 @@ class MediaFile
# @return [Boolean] true if the file is animated. Note that GIFs and PNGs may be animated.
def is_animated?
is_video?
is_video? || frame_count.to_i > 1
end
# @return [Float, nil] the duration of the video or animation in seconds, or
# nil if not a video or animation, or the duration is unknown.
def duration
nil
end
# @return [Float, nil] the number of frames in the video or animation, or nil
# if not a video or animation.
def frame_count
nil
end
# @return [Float, nil] the average frame rate of the video or animation, or
# nil if not a video or animation. Note that GIFs and PNGs can have a
# variable frame rate.
def frame_rate
nil
end
# @return [Boolean] true if the file has an audio track. The track may not be audible.
@@ -143,11 +162,6 @@ class MediaFile
false
end
# @return [Float] the duration of the video or animation, in seconds.
def duration
0.0
end
# Return a preview of the file, sized to fit within the given width and
# height (preserving the aspect ratio).
#
@@ -179,6 +193,9 @@ class MediaFile
file_size: file_size,
md5: md5,
is_corrupt?: is_corrupt?,
duration: duration,
frame_count: frame_count,
frame_rate: frame_rate,
metadata: metadata
}.stringify_keys
end