media_attachment.rb 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: media_attachments
  5. #
  6. # id :bigint(8) not null, primary key
  7. # status_id :bigint(8)
  8. # file_file_name :string
  9. # file_content_type :string
  10. # file_file_size :integer
  11. # file_updated_at :datetime
  12. # remote_url :string default(""), not null
  13. # created_at :datetime not null
  14. # updated_at :datetime not null
  15. # shortcode :string
  16. # type :integer default("image"), not null
  17. # file_meta :json
  18. # account_id :bigint(8)
  19. # description :text
  20. # scheduled_status_id :bigint(8)
  21. # blurhash :string
  22. # processing :integer
  23. # file_storage_schema_version :integer
  24. # thumbnail_file_name :string
  25. # thumbnail_content_type :string
  26. # thumbnail_file_size :integer
  27. # thumbnail_updated_at :datetime
  28. # thumbnail_remote_url :string
  29. #
  30. class MediaAttachment < ApplicationRecord
  31. self.inheritance_column = nil
  32. include Attachmentable
  33. enum type: [:image, :gifv, :video, :unknown, :audio]
  34. enum processing: [:queued, :in_progress, :complete, :failed], _prefix: true
  35. MAX_DESCRIPTION_LENGTH = 1_500
  36. IMAGE_LIMIT = 10.megabytes
  37. VIDEO_LIMIT = 40.megabytes
  38. MAX_VIDEO_MATRIX_LIMIT = 2_304_000 # 1920x1200px
  39. MAX_VIDEO_FRAME_RATE = 60
  40. IMAGE_FILE_EXTENSIONS = %w(.jpg .jpeg .png .gif .webp .heic .heif .avif).freeze
  41. VIDEO_FILE_EXTENSIONS = %w(.webm .mp4 .m4v .mov).freeze
  42. AUDIO_FILE_EXTENSIONS = %w(.ogg .oga .mp3 .wav .flac .opus .aac .m4a .3gp .wma).freeze
  43. META_KEYS = %i(
  44. focus
  45. colors
  46. original
  47. small
  48. ).freeze
  49. IMAGE_MIME_TYPES = %w(image/jpeg image/png image/gif image/heic image/heif image/webp image/avif).freeze
  50. IMAGE_CONVERTIBLE_MIME_TYPES = %w(image/heic image/heif).freeze
  51. VIDEO_MIME_TYPES = %w(video/webm video/mp4 video/quicktime video/ogg).freeze
  52. VIDEO_CONVERTIBLE_MIME_TYPES = %w(video/webm video/quicktime).freeze
  53. AUDIO_MIME_TYPES = %w(audio/wave audio/wav audio/x-wav audio/x-pn-wave audio/vnd.wave audio/ogg audio/vorbis audio/mpeg audio/mp3 audio/webm audio/flac audio/aac audio/m4a audio/x-m4a audio/mp4 audio/3gpp video/x-ms-asf).freeze
  54. BLURHASH_OPTIONS = {
  55. x_comp: 4,
  56. y_comp: 4,
  57. }.freeze
  58. IMAGE_STYLES = {
  59. original: {
  60. pixels: 2_073_600, # 1920x1080px
  61. file_geometry_parser: FastGeometryParser,
  62. }.freeze,
  63. small: {
  64. pixels: 230_400, # 640x360px
  65. file_geometry_parser: FastGeometryParser,
  66. blurhash: BLURHASH_OPTIONS,
  67. }.freeze,
  68. }.freeze
  69. IMAGE_CONVERTED_STYLES = {
  70. original: {
  71. format: 'jpeg',
  72. content_type: 'image/jpeg',
  73. }.merge(IMAGE_STYLES[:original]).freeze,
  74. small: {
  75. format: 'jpeg',
  76. }.merge(IMAGE_STYLES[:small]).freeze,
  77. }.freeze
  78. VIDEO_FORMAT = {
  79. format: 'mp4',
  80. content_type: 'video/mp4',
  81. vfr_frame_rate_threshold: MAX_VIDEO_FRAME_RATE,
  82. convert_options: {
  83. output: {
  84. 'loglevel' => 'fatal',
  85. 'movflags' => 'faststart',
  86. 'pix_fmt' => 'yuv420p',
  87. 'vf' => 'scale=\'trunc(iw/2)*2:trunc(ih/2)*2\'',
  88. 'vsync' => 'cfr',
  89. 'c:v' => 'h264',
  90. 'maxrate' => '1300K',
  91. 'bufsize' => '1300K',
  92. 'b:v' => '1300K',
  93. 'frames:v' => 60 * 60 * 3,
  94. 'crf' => 18,
  95. 'map_metadata' => '-1',
  96. }.freeze,
  97. }.freeze,
  98. }.freeze
  99. VIDEO_PASSTHROUGH_OPTIONS = {
  100. video_codecs: ['h264'].freeze,
  101. audio_codecs: ['aac', nil].freeze,
  102. colorspaces: ['yuv420p'].freeze,
  103. options: {
  104. format: 'mp4',
  105. convert_options: {
  106. output: {
  107. 'loglevel' => 'fatal',
  108. 'map_metadata' => '-1',
  109. 'c:v' => 'copy',
  110. 'c:a' => 'copy',
  111. }.freeze,
  112. }.freeze,
  113. }.freeze,
  114. }.freeze
  115. VIDEO_STYLES = {
  116. small: {
  117. convert_options: {
  118. output: {
  119. 'loglevel' => 'fatal',
  120. vf: 'scale=\'min(400\, iw):min(400\, ih)\':force_original_aspect_ratio=decrease',
  121. }.freeze,
  122. }.freeze,
  123. format: 'png',
  124. time: 0,
  125. file_geometry_parser: FastGeometryParser,
  126. blurhash: BLURHASH_OPTIONS,
  127. }.freeze,
  128. original: VIDEO_FORMAT.merge(passthrough_options: VIDEO_PASSTHROUGH_OPTIONS).freeze,
  129. }.freeze
  130. AUDIO_STYLES = {
  131. original: {
  132. format: 'mp3',
  133. content_type: 'audio/mpeg',
  134. convert_options: {
  135. output: {
  136. 'loglevel' => 'fatal',
  137. 'q:a' => 2,
  138. }.freeze,
  139. }.freeze,
  140. }.freeze,
  141. }.freeze
  142. VIDEO_CONVERTED_STYLES = {
  143. small: VIDEO_STYLES[:small].freeze,
  144. original: VIDEO_FORMAT.freeze,
  145. }.freeze
  146. THUMBNAIL_STYLES = {
  147. original: IMAGE_STYLES[:small].freeze,
  148. }.freeze
  149. GLOBAL_CONVERT_OPTIONS = {
  150. all: '-quality 90 +profile "!icc,*" +set modify-date +set create-date',
  151. }.freeze
  152. belongs_to :account, inverse_of: :media_attachments, optional: true
  153. belongs_to :status, inverse_of: :media_attachments, optional: true
  154. belongs_to :scheduled_status, inverse_of: :media_attachments, optional: true
  155. has_attached_file :file,
  156. styles: ->(f) { file_styles f },
  157. processors: ->(f) { file_processors f },
  158. convert_options: GLOBAL_CONVERT_OPTIONS
  159. before_file_validate :set_type_and_extension
  160. before_file_validate :check_video_dimensions
  161. validates_attachment_content_type :file, content_type: IMAGE_MIME_TYPES + VIDEO_MIME_TYPES + AUDIO_MIME_TYPES
  162. validates_attachment_size :file, less_than: ->(m) { m.larger_media_format? ? VIDEO_LIMIT : IMAGE_LIMIT }
  163. remotable_attachment :file, VIDEO_LIMIT, suppress_errors: false, download_on_assign: false, attribute_name: :remote_url
  164. has_attached_file :thumbnail,
  165. styles: THUMBNAIL_STYLES,
  166. processors: [:lazy_thumbnail, :blurhash_transcoder, :color_extractor],
  167. convert_options: GLOBAL_CONVERT_OPTIONS
  168. validates_attachment_content_type :thumbnail, content_type: IMAGE_MIME_TYPES
  169. validates_attachment_size :thumbnail, less_than: IMAGE_LIMIT
  170. remotable_attachment :thumbnail, IMAGE_LIMIT, suppress_errors: true, download_on_assign: false
  171. validates :account, presence: true
  172. validates :description, length: { maximum: MAX_DESCRIPTION_LENGTH }
  173. validates :file, presence: true, if: :local?
  174. validates :thumbnail, absence: true, if: -> { local? && !audio_or_video? }
  175. scope :attached, -> { where.not(status_id: nil).or(where.not(scheduled_status_id: nil)) }
  176. scope :unattached, -> { where(status_id: nil, scheduled_status_id: nil) }
  177. scope :local, -> { where(remote_url: '') }
  178. scope :remote, -> { where.not(remote_url: '') }
  179. scope :cached, -> { remote.where.not(file_file_name: nil) }
  180. default_scope { order(id: :asc) }
  181. attr_accessor :skip_download
  182. def local?
  183. remote_url.blank?
  184. end
  185. def not_processed?
  186. processing.present? && !processing_complete?
  187. end
  188. def needs_redownload?
  189. file.blank? && remote_url.present?
  190. end
  191. def significantly_changed?
  192. description_previously_changed? || thumbnail_updated_at_previously_changed? || file_meta_previously_changed?
  193. end
  194. def larger_media_format?
  195. video? || gifv? || audio?
  196. end
  197. def audio_or_video?
  198. audio? || video?
  199. end
  200. def to_param
  201. shortcode.presence || id&.to_s
  202. end
  203. def focus=(point)
  204. return if point.blank?
  205. x, y = (point.is_a?(Enumerable) ? point : point.split(',')).map(&:to_f)
  206. meta = (file.instance_read(:meta) || {}).with_indifferent_access.slice(*META_KEYS)
  207. meta['focus'] = { 'x' => x, 'y' => y }
  208. file.instance_write(:meta, meta)
  209. end
  210. def focus
  211. x = file.meta&.dig('focus', 'x')
  212. y = file.meta&.dig('focus', 'y')
  213. return if x.nil? || y.nil?
  214. "#{x},#{y}"
  215. end
  216. attr_writer :delay_processing
  217. def delay_processing?
  218. @delay_processing && larger_media_format?
  219. end
  220. def delay_processing_for_attachment?(attachment_name)
  221. delay_processing? && attachment_name == :file
  222. end
  223. after_commit :enqueue_processing, on: :create
  224. after_commit :reset_parent_cache, on: :update
  225. before_create :set_unknown_type
  226. before_create :set_processing
  227. after_post_process :set_meta
  228. class << self
  229. def supported_mime_types
  230. IMAGE_MIME_TYPES + VIDEO_MIME_TYPES + AUDIO_MIME_TYPES
  231. end
  232. def supported_file_extensions
  233. IMAGE_FILE_EXTENSIONS + VIDEO_FILE_EXTENSIONS + AUDIO_FILE_EXTENSIONS
  234. end
  235. private
  236. def file_styles(attachment)
  237. if attachment.instance.file_content_type == 'image/gif' || VIDEO_CONVERTIBLE_MIME_TYPES.include?(attachment.instance.file_content_type)
  238. VIDEO_CONVERTED_STYLES
  239. elsif IMAGE_CONVERTIBLE_MIME_TYPES.include?(attachment.instance.file_content_type)
  240. IMAGE_CONVERTED_STYLES
  241. elsif IMAGE_MIME_TYPES.include?(attachment.instance.file_content_type)
  242. IMAGE_STYLES
  243. elsif VIDEO_MIME_TYPES.include?(attachment.instance.file_content_type)
  244. VIDEO_STYLES
  245. else
  246. AUDIO_STYLES
  247. end
  248. end
  249. def file_processors(instance)
  250. if instance.file_content_type == 'image/gif'
  251. [:gif_transcoder, :blurhash_transcoder]
  252. elsif VIDEO_MIME_TYPES.include?(instance.file_content_type)
  253. [:transcoder, :blurhash_transcoder, :type_corrector]
  254. elsif AUDIO_MIME_TYPES.include?(instance.file_content_type)
  255. [:image_extractor, :transcoder, :type_corrector]
  256. else
  257. [:lazy_thumbnail, :blurhash_transcoder, :type_corrector]
  258. end
  259. end
  260. end
  261. private
  262. def set_unknown_type
  263. self.type = :unknown if file.blank? && !type_changed?
  264. end
  265. def set_type_and_extension
  266. self.type = begin
  267. if VIDEO_MIME_TYPES.include?(file_content_type)
  268. :video
  269. elsif AUDIO_MIME_TYPES.include?(file_content_type)
  270. :audio
  271. else
  272. :image
  273. end
  274. end
  275. end
  276. def set_processing
  277. self.processing = delay_processing? ? :queued : :complete
  278. end
  279. def check_video_dimensions
  280. return unless (video? || gifv?) && file.queued_for_write[:original].present?
  281. movie = ffmpeg_data(file.queued_for_write[:original].path)
  282. return unless movie.valid?
  283. raise Mastodon::StreamValidationError, 'Video has no video stream' if movie.width.nil? || movie.frame_rate.nil?
  284. raise Mastodon::DimensionsValidationError, "#{movie.width}x#{movie.height} videos are not supported" if movie.width * movie.height > MAX_VIDEO_MATRIX_LIMIT
  285. raise Mastodon::DimensionsValidationError, "#{movie.frame_rate.floor}fps videos are not supported" if movie.frame_rate.floor > MAX_VIDEO_FRAME_RATE
  286. end
  287. def set_meta
  288. file.instance_write :meta, populate_meta
  289. end
  290. def populate_meta
  291. meta = (file.instance_read(:meta) || {}).with_indifferent_access.slice(*META_KEYS)
  292. file.queued_for_write.each do |style, file|
  293. meta[style] = style == :small || image? ? image_geometry(file) : video_metadata(file)
  294. end
  295. meta[:small] = image_geometry(thumbnail.queued_for_write[:original]) if thumbnail.queued_for_write.key?(:original)
  296. meta
  297. end
  298. def image_geometry(file)
  299. width, height = FastImage.size(file.path)
  300. return {} if width.nil?
  301. {
  302. width: width,
  303. height: height,
  304. size: "#{width}x#{height}",
  305. aspect: width.to_f / height,
  306. }
  307. end
  308. def video_metadata(file)
  309. movie = ffmpeg_data(file.path)
  310. return {} unless movie.valid?
  311. {
  312. width: movie.width,
  313. height: movie.height,
  314. frame_rate: movie.frame_rate,
  315. duration: movie.duration,
  316. bitrate: movie.bitrate,
  317. }.compact
  318. end
  319. # We call this method about 3 different times on potentially different
  320. # paths but ultimately the same file, so it makes sense to memoize the
  321. # result while disregarding the path
  322. def ffmpeg_data(path = nil)
  323. @ffmpeg_data ||= VideoMetadataExtractor.new(path)
  324. end
  325. def enqueue_processing
  326. PostProcessMediaWorker.perform_async(id) if delay_processing?
  327. end
  328. def reset_parent_cache
  329. Rails.cache.delete("statuses/#{status_id}") if status_id.present?
  330. end
  331. end