media_attachment.rb 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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 :local, -> { where(remote_url: '') }
  178. scope :ordered, -> { order(id: :asc) }
  179. scope :remote, -> { where.not(remote_url: '') }
  180. scope :unattached, -> { where(status_id: nil, scheduled_status_id: nil) }
  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. before_create :set_unknown_type
  224. before_create :set_processing
  225. after_commit :enqueue_processing, on: :create
  226. after_commit :reset_parent_cache, on: :update
  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("v3:statuses/#{status_id}") if status_id.present?
  330. end
  331. end