media_attachment.rb 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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: 0, gifv: 1, video: 2, unknown: 3, audio: 4 }
  34. enum :processing, { queued: 0, in_progress: 1, complete: 2, failed: 3 }, prefix: true
  35. MAX_DESCRIPTION_LENGTH = 1_500
  36. IMAGE_LIMIT = 16.megabytes
  37. VIDEO_LIMIT = 99.megabytes
  38. MAX_VIDEO_MATRIX_LIMIT = 8_294_400 # 3840x2160px
  39. MAX_VIDEO_FRAME_RATE = 120
  40. MAX_VIDEO_FRAMES = 36_000 # Approx. 5 minutes at 120 fps
  41. IMAGE_FILE_EXTENSIONS = %w(.jpg .jpeg .png .gif .webp .heic .heif .avif).freeze
  42. VIDEO_FILE_EXTENSIONS = %w(.webm .mp4 .m4v .mov).freeze
  43. AUDIO_FILE_EXTENSIONS = %w(.ogg .oga .mp3 .wav .flac .opus .aac .m4a .3gp .wma).freeze
  44. META_KEYS = %i(
  45. focus
  46. colors
  47. original
  48. small
  49. ).freeze
  50. IMAGE_MIME_TYPES = %w(image/jpeg image/png image/gif image/heic image/heif image/webp image/avif).freeze
  51. IMAGE_CONVERTIBLE_MIME_TYPES = %w(image/heic image/heif image/avif).freeze
  52. VIDEO_MIME_TYPES = %w(video/webm video/mp4 video/quicktime video/ogg).freeze
  53. VIDEO_CONVERTIBLE_MIME_TYPES = %w(video/webm video/quicktime).freeze
  54. 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
  55. BLURHASH_OPTIONS = {
  56. x_comp: 4,
  57. y_comp: 4,
  58. }.freeze
  59. IMAGE_STYLES = {
  60. original: {
  61. pixels: 8_294_400, # 3840x2160px
  62. file_geometry_parser: FastGeometryParser,
  63. }.freeze,
  64. small: {
  65. pixels: 230_400, # 640x360px
  66. file_geometry_parser: FastGeometryParser,
  67. blurhash: BLURHASH_OPTIONS,
  68. }.freeze,
  69. }.freeze
  70. IMAGE_CONVERTED_STYLES = {
  71. original: {
  72. format: 'jpeg',
  73. content_type: 'image/jpeg',
  74. }.merge(IMAGE_STYLES[:original]).freeze,
  75. small: {
  76. format: 'jpeg',
  77. }.merge(IMAGE_STYLES[:small]).freeze,
  78. }.freeze
  79. VIDEO_FORMAT = {
  80. format: 'mp4',
  81. content_type: 'video/mp4',
  82. vfr_frame_rate_threshold: MAX_VIDEO_FRAME_RATE,
  83. convert_options: {
  84. output: {
  85. 'loglevel' => 'fatal',
  86. 'preset' => 'veryfast',
  87. 'movflags' => 'faststart', # Move metadata to start of file so playback can begin before download finishes
  88. 'pix_fmt' => 'yuv420p', # Ensure color space for cross-browser compatibility
  89. 'vf' => 'crop=floor(iw/2)*2:floor(ih/2)*2', # h264 requires width and height to be even. Crop instead of scale to avoid blurring
  90. 'c:v' => 'h264',
  91. 'c:a' => 'aac',
  92. 'b:a' => '192k',
  93. 'map_metadata' => '-1',
  94. 'frames:v' => MAX_VIDEO_FRAMES,
  95. }.freeze,
  96. }.freeze,
  97. }.freeze
  98. VIDEO_PASSTHROUGH_OPTIONS = {
  99. video_codecs: ['h264'].freeze,
  100. audio_codecs: ['aac', nil].freeze,
  101. colorspaces: ['yuv420p'].freeze,
  102. options: {
  103. format: 'mp4',
  104. convert_options: {
  105. output: {
  106. 'loglevel' => 'fatal',
  107. 'map_metadata' => '-1',
  108. 'c:v' => 'copy',
  109. 'c:a' => 'copy',
  110. }.freeze,
  111. }.freeze,
  112. }.freeze,
  113. }.freeze
  114. VIDEO_STYLES = {
  115. small: {
  116. convert_options: {
  117. output: {
  118. 'loglevel' => 'fatal',
  119. :vf => 'scale=\'min(640\, iw):min(640\, ih)\':force_original_aspect_ratio=decrease',
  120. }.freeze,
  121. }.freeze,
  122. format: 'png',
  123. time: 0,
  124. file_geometry_parser: FastGeometryParser,
  125. blurhash: BLURHASH_OPTIONS,
  126. }.freeze,
  127. original: VIDEO_FORMAT.merge(passthrough_options: VIDEO_PASSTHROUGH_OPTIONS).freeze,
  128. }.freeze
  129. AUDIO_STYLES = {
  130. original: {
  131. format: 'mp3',
  132. content_type: 'audio/mpeg',
  133. convert_options: {
  134. output: {
  135. 'loglevel' => 'fatal',
  136. 'q:a' => 2,
  137. }.freeze,
  138. }.freeze,
  139. }.freeze,
  140. }.freeze
  141. VIDEO_CONVERTED_STYLES = {
  142. small: VIDEO_STYLES[:small].freeze,
  143. original: VIDEO_FORMAT.freeze,
  144. }.freeze
  145. THUMBNAIL_STYLES = {
  146. original: IMAGE_STYLES[:small].freeze,
  147. }.freeze
  148. DEFAULT_STYLES = [:original].freeze
  149. GLOBAL_CONVERT_OPTIONS = {
  150. all: '-quality 90 +profile "!icc,*" +set date:modify +set date:create +set date:timestamp -define jpeg:dct-method=float',
  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 :cached, -> { remote.where.not(file_file_name: nil) }
  177. scope :created_before, ->(value) { where(arel_table[:created_at].lt(value)) }
  178. scope :local, -> { where(remote_url: '') }
  179. scope :ordered, -> { order(id: :asc) }
  180. scope :remote, -> { where.not(remote_url: '') }
  181. scope :unattached, -> { where(status_id: nil, scheduled_status_id: nil) }
  182. scope :updated_before, ->(value) { where(arel_table[:updated_at].lt(value)) }
  183. attr_accessor :skip_download
  184. def local?
  185. remote_url.blank?
  186. end
  187. def not_processed?
  188. processing.present? && !processing_complete?
  189. end
  190. def needs_redownload?
  191. file.blank? && remote_url.present?
  192. end
  193. def significantly_changed?
  194. description_previously_changed? || thumbnail_updated_at_previously_changed? || file_meta_previously_changed?
  195. end
  196. def larger_media_format?
  197. video? || gifv? || audio?
  198. end
  199. def audio_or_video?
  200. audio? || video?
  201. end
  202. def to_param
  203. shortcode.presence || id&.to_s
  204. end
  205. def focus=(point)
  206. return if point.blank?
  207. x, y = (point.is_a?(Enumerable) ? point : point.split(',')).map(&:to_f)
  208. meta = (file.instance_read(:meta) || {}).with_indifferent_access.slice(*META_KEYS)
  209. meta['focus'] = { 'x' => x, 'y' => y }
  210. file.instance_write(:meta, meta)
  211. end
  212. def focus
  213. x = file.meta&.dig('focus', 'x')
  214. y = file.meta&.dig('focus', 'y')
  215. return if x.nil? || y.nil?
  216. "#{x},#{y}"
  217. end
  218. attr_writer :delay_processing
  219. def delay_processing?
  220. @delay_processing && larger_media_format?
  221. end
  222. def delay_processing_for_attachment?(attachment_name)
  223. delay_processing? && attachment_name == :file
  224. end
  225. before_create :set_unknown_type
  226. before_create :set_processing
  227. after_commit :enqueue_processing, on: :create
  228. after_commit :reset_parent_cache, on: :update
  229. after_post_process :set_meta
  230. class << self
  231. def supported_mime_types
  232. IMAGE_MIME_TYPES + VIDEO_MIME_TYPES + AUDIO_MIME_TYPES
  233. end
  234. def supported_file_extensions
  235. IMAGE_FILE_EXTENSIONS + VIDEO_FILE_EXTENSIONS + AUDIO_FILE_EXTENSIONS
  236. end
  237. private
  238. def file_styles(attachment)
  239. if attachment.instance.file_content_type == 'image/gif' || VIDEO_CONVERTIBLE_MIME_TYPES.include?(attachment.instance.file_content_type)
  240. VIDEO_CONVERTED_STYLES
  241. elsif IMAGE_CONVERTIBLE_MIME_TYPES.include?(attachment.instance.file_content_type)
  242. IMAGE_CONVERTED_STYLES
  243. elsif IMAGE_MIME_TYPES.include?(attachment.instance.file_content_type)
  244. IMAGE_STYLES
  245. elsif VIDEO_MIME_TYPES.include?(attachment.instance.file_content_type)
  246. VIDEO_STYLES
  247. else
  248. AUDIO_STYLES
  249. end
  250. end
  251. def file_processors(instance)
  252. if instance.file_content_type == 'image/gif'
  253. [:gif_transcoder, :blurhash_transcoder]
  254. elsif VIDEO_MIME_TYPES.include?(instance.file_content_type)
  255. [:transcoder, :blurhash_transcoder, :type_corrector]
  256. elsif AUDIO_MIME_TYPES.include?(instance.file_content_type)
  257. [:image_extractor, :transcoder, :type_corrector]
  258. else
  259. [:lazy_thumbnail, :blurhash_transcoder, :type_corrector]
  260. end
  261. end
  262. end
  263. private
  264. def set_unknown_type
  265. self.type = :unknown if file.blank? && !type_changed?
  266. end
  267. def set_type_and_extension
  268. self.type = begin
  269. if VIDEO_MIME_TYPES.include?(file_content_type)
  270. :video
  271. elsif AUDIO_MIME_TYPES.include?(file_content_type)
  272. :audio
  273. else
  274. :image
  275. end
  276. end
  277. end
  278. def set_processing
  279. self.processing = delay_processing? ? :queued : :complete
  280. end
  281. def check_video_dimensions
  282. return unless (video? || gifv?) && file.queued_for_write[:original].present?
  283. movie = ffmpeg_data(file.queued_for_write[:original].path)
  284. return unless movie.valid?
  285. raise Mastodon::StreamValidationError, 'Video has no video stream' if movie.width.nil? || movie.frame_rate.nil?
  286. raise Mastodon::DimensionsValidationError, "#{movie.width}x#{movie.height} videos are not supported" if movie.width * movie.height > MAX_VIDEO_MATRIX_LIMIT
  287. raise Mastodon::DimensionsValidationError, "#{movie.frame_rate.floor}fps videos are not supported" if movie.frame_rate.floor > MAX_VIDEO_FRAME_RATE
  288. end
  289. def set_meta
  290. file.instance_write :meta, populate_meta
  291. end
  292. def populate_meta
  293. meta = (file.instance_read(:meta) || {}).with_indifferent_access.slice(*META_KEYS)
  294. file.queued_for_write.each do |style, file|
  295. meta[style] = style == :small || image? ? image_geometry(file) : video_metadata(file)
  296. end
  297. meta[:small] = image_geometry(thumbnail.queued_for_write[:original]) if thumbnail.queued_for_write.key?(:original)
  298. meta
  299. end
  300. def image_geometry(file)
  301. width, height = FastImage.size(file.path)
  302. return {} if width.nil?
  303. {
  304. width: width,
  305. height: height,
  306. size: "#{width}x#{height}",
  307. aspect: width.to_f / height,
  308. }
  309. end
  310. def video_metadata(file)
  311. movie = ffmpeg_data(file.path)
  312. return {} unless movie.valid?
  313. {
  314. width: movie.width,
  315. height: movie.height,
  316. frame_rate: movie.frame_rate,
  317. duration: movie.duration,
  318. bitrate: movie.bitrate,
  319. }.compact
  320. end
  321. # We call this method about 3 different times on potentially different
  322. # paths but ultimately the same file, so it makes sense to memoize the
  323. # result while disregarding the path
  324. def ffmpeg_data(path = nil)
  325. @ffmpeg_data ||= VideoMetadataExtractor.new(path)
  326. end
  327. def enqueue_processing
  328. PostProcessMediaWorker.perform_async(id) if delay_processing?
  329. end
  330. def reset_parent_cache
  331. Rails.cache.delete("v3:statuses/#{status_id}") if status_id.present?
  332. end
  333. end