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

@@ -32,6 +32,22 @@ class MediaFile::Ugoira < MediaFile
preview_frame.crop(width, height)
end
def duration
(frame_delays.sum / 1000.0)
end
def frame_count
frame_data.count
end
def frame_rate
frame_count / duration
end
def frame_delays
frame_data.map { |frame| frame["delay"] }
end
# Convert a ugoira to a webm.
# XXX should take width and height and resize image
def convert