media_attachment.rb 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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. 'frames:v' => 60 * 60 * 3,
  93. 'crf' => 18,
  94. 'map_metadata' => '-1',
  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(400\, iw):min(400\, 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. GLOBAL_CONVERT_OPTIONS = {
  149. all: '-quality 90 +profile "!icc,*" +set modify-date +set create-date',
  150. }.freeze
  151. belongs_to :account, inverse_of: :media_attachments, optional: true
  152. belongs_to :status, inverse_of: :media_attachments, optional: true
  153. belongs_to :scheduled_status, inverse_of: :media_attachments, optional: true
  154. has_attached_file :file,
  155. styles: ->(f) { file_styles f },
  156. processors: ->(f) { file_processors f },
  157. convert_options: GLOBAL_CONVERT_OPTIONS
  158. before_file_validate :set_type_and_extension
  159. before_file_validate :check_video_dimensions
  160. validates_attachment_content_type :file, content_type: IMAGE_MIME_TYPES + VIDEO_MIME_TYPES + AUDIO_MIME_TYPES
  161. validates_attachment_size :file, less_than: ->(m) { m.larger_media_format? ? VIDEO_LIMIT : IMAGE_LIMIT }
  162. remotable_attachment :file, VIDEO_LIMIT, suppress_errors: false, download_on_assign: false, attribute_name: :remote_url
  163. has_attached_file :thumbnail,
  164. styles: THUMBNAIL_STYLES,
  165. processors: [:lazy_thumbnail, :blurhash_transcoder, :color_extractor],
  166. convert_options: GLOBAL_CONVERT_OPTIONS
  167. validates_attachment_content_type :thumbnail, content_type: IMAGE_MIME_TYPES
  168. validates_attachment_size :thumbnail, less_than: IMAGE_LIMIT
  169. remotable_attachment :thumbnail, IMAGE_LIMIT, suppress_errors: true, download_on_assign: false
  170. validates :account, presence: true
  171. validates :description, length: { maximum: MAX_DESCRIPTION_LENGTH }
  172. validates :file, presence: true, if: :local?
  173. validates :thumbnail, absence: true, if: -> { local? && !audio_or_video? }
  174. scope :attached, -> { where.not(status_id: nil).or(where.not(scheduled_status_id: nil)) }
  175. scope :unattached, -> { where(status_id: nil, scheduled_status_id: nil) }
  176. scope :local, -> { where(remote_url: '') }
  177. scope :remote, -> { where.not(remote_url: '') }
  178. scope :cached, -> { remote.where.not(file_file_name: nil) }
  179. default_scope { order(id: :asc) }
  180. def local?
  181. remote_url.blank?
  182. end
  183. def not_processed?
  184. processing.present? && !processing_complete?
  185. end
  186. def needs_redownload?
  187. file.blank? && remote_url.present?
  188. end
  189. def significantly_changed?
  190. description_previously_changed? || thumbnail_updated_at_previously_changed? || file_meta_previously_changed?
  191. end
  192. def larger_media_format?
  193. video? || gifv? || audio?
  194. end
  195. def audio_or_video?
  196. audio? || video?
  197. end
  198. def to_param
  199. shortcode.presence || id&.to_s
  200. end
  201. def focus=(point)
  202. return if point.blank?
  203. x, y = (point.is_a?(Enumerable) ? point : point.split(',')).map(&:to_f)
  204. meta = (file.instance_read(:meta) || {}).with_indifferent_access.slice(*META_KEYS)
  205. meta['focus'] = { 'x' => x, 'y' => y }
  206. file.instance_write(:meta, meta)
  207. end
  208. def focus
  209. x = file.meta&.dig('focus', 'x')
  210. y = file.meta&.dig('focus', 'y')
  211. return if x.nil? || y.nil?
  212. "#{x},#{y}"
  213. end
  214. attr_writer :delay_processing
  215. def delay_processing?
  216. @delay_processing && larger_media_format?
  217. end
  218. def delay_processing_for_attachment?(attachment_name)
  219. delay_processing? && attachment_name == :file
  220. end
  221. after_commit :enqueue_processing, on: :create
  222. after_commit :reset_parent_cache, on: :update
  223. before_create :set_unknown_type
  224. before_create :set_processing
  225. after_post_process :set_meta
  226. class << self
  227. def supported_mime_types
  228. IMAGE_MIME_TYPES + VIDEO_MIME_TYPES + AUDIO_MIME_TYPES
  229. end
  230. def supported_file_extensions
  231. IMAGE_FILE_EXTENSIONS + VIDEO_FILE_EXTENSIONS + AUDIO_FILE_EXTENSIONS
  232. end
  233. private
  234. def file_styles(attachment)
  235. if attachment.instance.file_content_type == 'image/gif' || VIDEO_CONVERTIBLE_MIME_TYPES.include?(attachment.instance.file_content_type)
  236. VIDEO_CONVERTED_STYLES
  237. elsif IMAGE_CONVERTIBLE_MIME_TYPES.include?(attachment.instance.file_content_type)
  238. IMAGE_CONVERTED_STYLES
  239. elsif IMAGE_MIME_TYPES.include?(attachment.instance.file_content_type)
  240. IMAGE_STYLES
  241. elsif VIDEO_MIME_TYPES.include?(attachment.instance.file_content_type)
  242. VIDEO_STYLES
  243. else
  244. AUDIO_STYLES
  245. end
  246. end
  247. def file_processors(instance)
  248. if instance.file_content_type == 'image/gif'
  249. [:gif_transcoder, :blurhash_transcoder]
  250. elsif VIDEO_MIME_TYPES.include?(instance.file_content_type)
  251. [:transcoder, :blurhash_transcoder, :type_corrector]
  252. elsif AUDIO_MIME_TYPES.include?(instance.file_content_type)
  253. [:image_extractor, :transcoder, :type_corrector]
  254. else
  255. [:lazy_thumbnail, :blurhash_transcoder, :type_corrector]
  256. end
  257. end
  258. end
  259. private
  260. def set_unknown_type
  261. self.type = :unknown if file.blank? && !type_changed?
  262. end
  263. def set_type_and_extension
  264. self.type = begin
  265. if VIDEO_MIME_TYPES.include?(file_content_type)
  266. :video
  267. elsif AUDIO_MIME_TYPES.include?(file_content_type)
  268. :audio
  269. else
  270. :image
  271. end
  272. end
  273. end
  274. def set_processing
  275. self.processing = delay_processing? ? :queued : :complete
  276. end
  277. def check_video_dimensions
  278. return unless (video? || gifv?) && file.queued_for_write[:original].present?
  279. movie = ffmpeg_data(file.queued_for_write[:original].path)
  280. return unless movie.valid?
  281. raise Mastodon::StreamValidationError, 'Video has no video stream' if movie.width.nil? || movie.frame_rate.nil?
  282. raise Mastodon::DimensionsValidationError, "#{movie.width}x#{movie.height} videos are not supported" if movie.width * movie.height > MAX_VIDEO_MATRIX_LIMIT
  283. raise Mastodon::DimensionsValidationError, "#{movie.frame_rate.floor}fps videos are not supported" if movie.frame_rate.floor > MAX_VIDEO_FRAME_RATE
  284. end
  285. def set_meta
  286. file.instance_write :meta, populate_meta
  287. end
  288. def populate_meta
  289. meta = (file.instance_read(:meta) || {}).with_indifferent_access.slice(*META_KEYS)
  290. file.queued_for_write.each do |style, file|
  291. meta[style] = style == :small || image? ? image_geometry(file) : video_metadata(file)
  292. end
  293. meta[:small] = image_geometry(thumbnail.queued_for_write[:original]) if thumbnail.queued_for_write.key?(:original)
  294. meta
  295. end
  296. def image_geometry(file)
  297. width, height = FastImage.size(file.path)
  298. return {} if width.nil?
  299. {
  300. width: width,
  301. height: height,
  302. size: "#{width}x#{height}",
  303. aspect: width.to_f / height,
  304. }
  305. end
  306. def video_metadata(file)
  307. movie = ffmpeg_data(file.path)
  308. return {} unless movie.valid?
  309. {
  310. width: movie.width,
  311. height: movie.height,
  312. frame_rate: movie.frame_rate,
  313. duration: movie.duration,
  314. bitrate: movie.bitrate,
  315. }.compact
  316. end
  317. # We call this method about 3 different times on potentially different
  318. # paths but ultimately the same file, so it makes sense to memoize the
  319. # result while disregarding the path
  320. def ffmpeg_data(path = nil)
  321. @ffmpeg_data ||= VideoMetadataExtractor.new(path)
  322. end
  323. def enqueue_processing
  324. PostProcessMediaWorker.perform_async(id) if delay_processing?
  325. end
  326. def reset_parent_cache
  327. Rails.cache.delete("statuses/#{status_id}") if status_id.present?
  328. end
  329. end