media_attachment.rb 12 KB

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