media_attachment.rb 9.5 KB

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