summaryrefslogtreecommitdiff
path: root/lib/booru/image_processing/processor.rb
blob: 29c45a7bc974be3e766be2993a8609c7f55cde74 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# frozen_string_literal: true
module Booru
  module ImageProcessing
    class Processor
      attr_reader :rasterized # actually rasterized or still previews
      attr_reader :log

      def initialize(original_path, directory, metadata)
        @original_path = original_path
        @directory = directory
        @rasterized = original_path
        @metadata = metadata
        @log = []
      end

      # Apply pre-processing to the image. This is anything that should be done to the original
      # file, before any of the versions are generated. (eg: sanitization, rasterization)
      def pre_process
        # do nothing by default
      end

      # Generate the rasterized / still version of the image, used for intensities.
      def generate_rasterized
        # do nothing by default
      end

      # generate a version of the image with the given dimensions, and
      # write it out to the given path.
      def generate_version(dimensions, destination_path)
        # you should do something here
        raise NotImplementedError
      end

      def generate_compressed_version(dimensions, destination_path)
        write_log "generate_compressed_version #{dimensions} #{destination_path}"

        width, height = dimensions

        # thanks byte[]
        scale_filter = "scale=w=#{width}:h=#{height}:force_original_aspect_ratio=decrease,format=rgb32"

        ffmpeg '-i', @rasterized,
               '-vf', scale_filter,
               '-vcodec', 'libwebp',
               '-lossless', '0',
               '-compression_level', '6',
               '-preset', 'default',
               '-q:v', '80',
               destination_path
      end

      # generate the full version of the image; this could be multiple versions.
      def generate_full_version(destination_path)
        FileUtils.ln_sf(@original_path, destination_path)
      end

      # special case processing for eg: WebM to gif conversion.
      def additional_process
        # do nothing
      end

      # Apply post-processing to the image. This is anything that should be done to the original
      # file, after all of the versions are generated. (eg: lossless compression)
      def post_process
        # do nothing by default
      end

      def is_video?
        false
      end

      def write_log(message)
        now = DateTime.now.strftime('%d/%m/%Y %H:%M:%S')
        @log << "[#{now}] #{message}"
      end

      def platform_link(source, destination)
        FileUtils.ln_sf(source, destination)
      rescue Errno::EPROTO
        FileUtils.cp(source, destination)
      end
    end
  end
end