You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

393 lines
11 KiB

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