1
0

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