From 01b87a1632a9024eb8be807cfc41a592b6a3c8ce Mon Sep 17 00:00:00 2001 From: Eugen Rochko Date: Mon, 28 Aug 2023 19:40:08 +0200 Subject: [PATCH] Change video compression parameters (#26631) --- app/models/media_attachment.rb | 16 ++++++---------- lib/paperclip/transcoder.rb | 10 ++++++++-- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/app/models/media_attachment.rb b/app/models/media_attachment.rb index 7474b5653..88abd9339 100644 --- a/app/models/media_attachment.rb +++ b/app/models/media_attachment.rb @@ -44,6 +44,7 @@ class MediaAttachment < ApplicationRecord MAX_VIDEO_MATRIX_LIMIT = 8_294_400 # 3840x2160px MAX_VIDEO_FRAME_RATE = 120 + MAX_VIDEO_FRAMES = 36_000 # Approx. 5 minutes at 120 fps IMAGE_FILE_EXTENSIONS = %w(.jpg .jpeg .png .gif .webp .heic .heif .avif).freeze VIDEO_FILE_EXTENSIONS = %w(.webm .mp4 .m4v .mov).freeze @@ -98,17 +99,12 @@ class MediaAttachment < ApplicationRecord convert_options: { output: { 'loglevel' => 'fatal', - 'movflags' => 'faststart', - 'pix_fmt' => 'yuv420p', - 'vf' => 'scale=\'trunc(iw/2)*2:trunc(ih/2)*2\'', - 'vsync' => 'cfr', + 'preset' => 'veryfast', 'c:v' => 'h264', - 'maxrate' => '1300K', - 'bufsize' => '1300K', - 'b:v' => '1300K', - 'frames:v' => 60 * 60 * 3, - 'crf' => 18, + 'c:a' => 'aac', + 'b:a' => '192k', 'map_metadata' => '-1', + 'frames:v' => MAX_VIDEO_FRAMES, }.freeze, }.freeze, }.freeze @@ -135,7 +131,7 @@ class MediaAttachment < ApplicationRecord convert_options: { output: { 'loglevel' => 'fatal', - :vf => 'scale=\'min(400\, iw):min(400\, ih)\':force_original_aspect_ratio=decrease', + :vf => 'scale=\'min(640\, iw):min(640\, ih)\':force_original_aspect_ratio=decrease', }.freeze, }.freeze, format: 'png', diff --git a/lib/paperclip/transcoder.rb b/lib/paperclip/transcoder.rb index 0f2e30f7d..b88cf662c 100644 --- a/lib/paperclip/transcoder.rb +++ b/lib/paperclip/transcoder.rb @@ -4,6 +4,9 @@ module Paperclip # This transcoder is only to be used for the MediaAttachment model # to check when uploaded videos are actually gifv's class Transcoder < Paperclip::Processor + # This is the H.264 "High" value taken from https://www.dr-lex.be/info-stuff/videocalc.html + BITS_PER_PIXEL = 0.11 + def initialize(file, options = {}, attachment = nil) super @@ -38,8 +41,11 @@ module Paperclip @output_options['vframes'] = 1 when 'mp4' unless eligible_to_passthrough?(metadata) - @output_options['acodec'] = 'aac' - @output_options['strict'] = 'experimental' + bitrate = (metadata.width * metadata.height * 30 * BITS_PER_PIXEL) / 1_000 + + @output_options['b:v'] = "#{bitrate}k" + @output_options['maxrate'] = "#{bitrate + 192}k" + @output_options['bufsize'] = "#{bitrate * 5}k" if high_vfr?(metadata) @output_options['vsync'] = 'vfr'