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.

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