media_attachment.rb 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. }.merge(IMAGE_STYLES[:original]).freeze,
  73. small: {
  74. format: 'jpeg',
  75. }.merge(IMAGE_STYLES[:small]).freeze,
  76. }.freeze
  77. VIDEO_FORMAT = {
  78. format: 'mp4',
  79. content_type: 'video/mp4',
  80. vfr_frame_rate_threshold: MAX_VIDEO_FRAME_RATE,
  81. convert_options: {
  82. output: {
  83. 'loglevel' => 'fatal',
  84. 'movflags' => 'faststart',
  85. 'pix_fmt' => 'yuv420p',
  86. 'vf' => 'scale=\'trunc(iw/2)*2:trunc(ih/2)*2\'',
  87. 'vsync' => 'cfr',
  88. 'c:v' => 'h264',
  89. 'maxrate' => '1300K',
  90. 'bufsize' => '1300K',
  91. 'frames:v' => 60 * 60 * 3,
  92. 'crf' => 18,
  93. 'map_metadata' => '-1',
  94. }.freeze,
  95. }.freeze,
  96. }.freeze
  97. VIDEO_PASSTHROUGH_OPTIONS = {
  98. video_codecs: ['h264'].freeze,
  99. audio_codecs: ['aac', nil].freeze,
  100. colorspaces: ['yuv420p'].freeze,
  101. options: {
  102. format: 'mp4',
  103. convert_options: {
  104. output: {
  105. 'loglevel' => 'fatal',
  106. 'map_metadata' => '-1',
  107. 'c:v' => 'copy',
  108. 'c:a' => 'copy',
  109. }.freeze,
  110. }.freeze,
  111. }.freeze,
  112. }.freeze
  113. VIDEO_STYLES = {
  114. small: {
  115. convert_options: {
  116. output: {
  117. 'loglevel' => 'fatal',
  118. vf: 'scale=\'min(400\, iw):min(400\, ih)\':force_original_aspect_ratio=decrease',
  119. }.freeze,
  120. }.freeze,
  121. format: 'png',
  122. time: 0,
  123. file_geometry_parser: FastGeometryParser,
  124. blurhash: BLURHASH_OPTIONS,
  125. }.freeze,
  126. original: VIDEO_FORMAT.merge(passthrough_options: VIDEO_PASSTHROUGH_OPTIONS).freeze,
  127. }.freeze
  128. AUDIO_STYLES = {
  129. original: {
  130. format: 'mp3',
  131. content_type: 'audio/mpeg',
  132. convert_options: {
  133. output: {
  134. 'loglevel' => 'fatal',
  135. 'q:a' => 2,
  136. }.freeze,
  137. }.freeze,
  138. }.freeze,
  139. }.freeze
  140. VIDEO_CONVERTED_STYLES = {
  141. small: VIDEO_STYLES[:small].freeze,
  142. original: VIDEO_FORMAT.freeze,
  143. }.freeze
  144. THUMBNAIL_STYLES = {
  145. original: IMAGE_STYLES[:small].freeze,
  146. }.freeze
  147. GLOBAL_CONVERT_OPTIONS = {
  148. all: '-quality 90 -strip +set modify-date +set create-date',
  149. }.freeze
  150. belongs_to :account, inverse_of: :media_attachments, optional: true
  151. belongs_to :status, inverse_of: :media_attachments, optional: true
  152. belongs_to :scheduled_status, inverse_of: :media_attachments, optional: true
  153. has_attached_file :file,
  154. styles: ->(f) { file_styles f },
  155. processors: ->(f) { file_processors f },
  156. convert_options: GLOBAL_CONVERT_OPTIONS
  157. before_file_validate :set_type_and_extension
  158. before_file_validate :check_video_dimensions
  159. validates_attachment_content_type :file, content_type: IMAGE_MIME_TYPES + VIDEO_MIME_TYPES + AUDIO_MIME_TYPES
  160. validates_attachment_size :file, less_than: ->(m) { m.larger_media_format? ? VIDEO_LIMIT : IMAGE_LIMIT }
  161. remotable_attachment :file, VIDEO_LIMIT, suppress_errors: false, download_on_assign: false, attribute_name: :remote_url
  162. has_attached_file :thumbnail,
  163. styles: THUMBNAIL_STYLES,
  164. processors: [:lazy_thumbnail, :blurhash_transcoder, :color_extractor],
  165. convert_options: GLOBAL_CONVERT_OPTIONS
  166. validates_attachment_content_type :thumbnail, content_type: IMAGE_MIME_TYPES
  167. validates_attachment_size :thumbnail, less_than: IMAGE_LIMIT
  168. remotable_attachment :thumbnail, IMAGE_LIMIT, suppress_errors: true, download_on_assign: false
  169. validates :account, presence: true
  170. validates :description, length: { maximum: MAX_DESCRIPTION_LENGTH }
  171. validates :file, presence: true, if: :local?
  172. validates :thumbnail, absence: true, if: -> { local? && !audio_or_video? }
  173. scope :attached, -> { where.not(status_id: nil).or(where.not(scheduled_status_id: nil)) }
  174. scope :unattached, -> { where(status_id: nil, scheduled_status_id: nil) }
  175. scope :local, -> { where(remote_url: '') }
  176. scope :remote, -> { where.not(remote_url: '') }
  177. scope :cached, -> { remote.where.not(file_file_name: nil) }
  178. default_scope { order(id: :asc) }
  179. def local?
  180. remote_url.blank?
  181. end
  182. def not_processed?
  183. processing.present? && !processing_complete?
  184. end
  185. def needs_redownload?
  186. file.blank? && remote_url.present?
  187. end
  188. def significantly_changed?
  189. description_previously_changed? || thumbnail_updated_at_previously_changed? || file_meta_previously_changed?
  190. end
  191. def larger_media_format?
  192. video? || gifv? || audio?
  193. end
  194. def audio_or_video?
  195. audio? || video?
  196. end
  197. def to_param
  198. shortcode.presence || id&.to_s
  199. end
  200. def focus=(point)
  201. return if point.blank?
  202. x, y = (point.is_a?(Enumerable) ? point : point.split(',')).map(&:to_f)
  203. meta = (file.instance_read(:meta) || {}).with_indifferent_access.slice(*META_KEYS)
  204. meta['focus'] = { 'x' => x, 'y' => y }
  205. file.instance_write(:meta, meta)
  206. end
  207. def focus
  208. x = file.meta&.dig('focus', 'x')
  209. y = file.meta&.dig('focus', 'y')
  210. return if x.nil? || y.nil?
  211. "#{x},#{y}"
  212. end
  213. attr_writer :delay_processing
  214. def delay_processing?
  215. @delay_processing && larger_media_format?
  216. end
  217. def delay_processing_for_attachment?(attachment_name)
  218. delay_processing? && attachment_name == :file
  219. end
  220. after_commit :enqueue_processing, on: :create
  221. after_commit :reset_parent_cache, on: :update
  222. before_create :set_unknown_type
  223. before_create :set_processing
  224. after_post_process :set_meta
  225. class << self
  226. def supported_mime_types
  227. IMAGE_MIME_TYPES + VIDEO_MIME_TYPES + AUDIO_MIME_TYPES
  228. end
  229. def supported_file_extensions
  230. IMAGE_FILE_EXTENSIONS + VIDEO_FILE_EXTENSIONS + AUDIO_FILE_EXTENSIONS
  231. end
  232. private
  233. def file_styles(attachment)
  234. if attachment.instance.file_content_type == 'image/gif' || VIDEO_CONVERTIBLE_MIME_TYPES.include?(attachment.instance.file_content_type)
  235. VIDEO_CONVERTED_STYLES
  236. elsif IMAGE_CONVERTIBLE_MIME_TYPES.include?(attachment.instance.file_content_type)
  237. IMAGE_CONVERTED_STYLES
  238. elsif IMAGE_MIME_TYPES.include?(attachment.instance.file_content_type)
  239. IMAGE_STYLES
  240. elsif VIDEO_MIME_TYPES.include?(attachment.instance.file_content_type)
  241. VIDEO_STYLES
  242. else
  243. AUDIO_STYLES
  244. end
  245. end
  246. def file_processors(instance)
  247. if instance.file_content_type == 'image/gif'
  248. [:gif_transcoder, :blurhash_transcoder]
  249. elsif VIDEO_MIME_TYPES.include?(instance.file_content_type)
  250. [:transcoder, :blurhash_transcoder, :type_corrector]
  251. elsif AUDIO_MIME_TYPES.include?(instance.file_content_type)
  252. [:image_extractor, :transcoder, :type_corrector]
  253. else
  254. [:lazy_thumbnail, :blurhash_transcoder, :type_corrector]
  255. end
  256. end
  257. end
  258. private
  259. def set_unknown_type
  260. self.type = :unknown if file.blank? && !type_changed?
  261. end
  262. def set_type_and_extension
  263. self.type = begin
  264. if VIDEO_MIME_TYPES.include?(file_content_type)
  265. :video
  266. elsif AUDIO_MIME_TYPES.include?(file_content_type)
  267. :audio
  268. else
  269. :image
  270. end
  271. end
  272. end
  273. def set_processing
  274. self.processing = delay_processing? ? :queued : :complete
  275. end
  276. def check_video_dimensions
  277. return unless (video? || gifv?) && file.queued_for_write[:original].present?
  278. movie = ffmpeg_data(file.queued_for_write[:original].path)
  279. return unless movie.valid?
  280. raise Mastodon::StreamValidationError, 'Video has no video stream' if movie.width.nil? || movie.frame_rate.nil?
  281. raise Mastodon::DimensionsValidationError, "#{movie.width}x#{movie.height} videos are not supported" if movie.width * movie.height > MAX_VIDEO_MATRIX_LIMIT
  282. raise Mastodon::DimensionsValidationError, "#{movie.frame_rate.floor}fps videos are not supported" if movie.frame_rate.floor > MAX_VIDEO_FRAME_RATE
  283. end
  284. def set_meta
  285. file.instance_write :meta, populate_meta
  286. end
  287. def populate_meta
  288. meta = (file.instance_read(:meta) || {}).with_indifferent_access.slice(*META_KEYS)
  289. file.queued_for_write.each do |style, file|
  290. meta[style] = style == :small || image? ? image_geometry(file) : video_metadata(file)
  291. end
  292. meta[:small] = image_geometry(thumbnail.queued_for_write[:original]) if thumbnail.queued_for_write.key?(:original)
  293. meta
  294. end
  295. def image_geometry(file)
  296. width, height = FastImage.size(file.path)
  297. return {} if width.nil?
  298. {
  299. width: width,
  300. height: height,
  301. size: "#{width}x#{height}",
  302. aspect: width.to_f / height,
  303. }
  304. end
  305. def video_metadata(file)
  306. movie = ffmpeg_data(file.path)
  307. return {} unless movie.valid?
  308. {
  309. width: movie.width,
  310. height: movie.height,
  311. frame_rate: movie.frame_rate,
  312. duration: movie.duration,
  313. bitrate: movie.bitrate,
  314. }.compact
  315. end
  316. # We call this method about 3 different times on potentially different
  317. # paths but ultimately the same file, so it makes sense to memoize the
  318. # result while disregarding the path
  319. def ffmpeg_data(path = nil)
  320. @ffmpeg_data ||= VideoMetadataExtractor.new(path)
  321. end
  322. def enqueue_processing
  323. PostProcessMediaWorker.perform_async(id) if delay_processing?
  324. end
  325. def reset_parent_cache
  326. Rails.cache.delete("statuses/#{status_id}") if status_id.present?
  327. end
  328. end