1/*
2 * Copyright 2017 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#ifndef SkJpegEncoder_DEFINED
9#define SkJpegEncoder_DEFINED
10
11#include "include/encode/SkEncoder.h"
12
13class SkJpegEncoderMgr;
14class SkWStream;
15
16class SK_API SkJpegEncoder : public SkEncoder {
17public:
18
19    enum class AlphaOption {
20        kIgnore,
21        kBlendOnBlack,
22    };
23
24    enum class Downsample {
25        /**
26         *  Reduction by a factor of two in both the horizontal and vertical directions.
27         */
28        k420,
29
30        /**
31         *  Reduction by a factor of two in the horizontal direction.
32         */
33        k422,
34
35        /**
36         *  No downsampling.
37         */
38        k444,
39    };
40
41    struct Options {
42        /**
43         *  |fQuality| must be in [0, 100] where 0 corresponds to the lowest quality.
44         */
45        int fQuality = 100;
46
47        /**
48         *  Choose the downsampling factor for the U and V components.  This is only
49         *  meaningful if the |src| is not kGray, since kGray will not be encoded as YUV.
50         *
51         *  Our default value matches the libjpeg-turbo default.
52         */
53        Downsample fDownsample = Downsample::k420;
54
55        /**
56         *  Jpegs must be opaque.  This instructs the encoder on how to handle input
57         *  images with alpha.
58         *
59         *  The default is to ignore the alpha channel and treat the image as opaque.
60         *  Another option is to blend the pixels onto a black background before encoding.
61         *  In the second case, the encoder supports linear or legacy blending.
62         */
63        AlphaOption fAlphaOption = AlphaOption::kIgnore;
64    };
65
66    /**
67     *  Encode the |src| pixels to the |dst| stream.
68     *  |options| may be used to control the encoding behavior.
69     *
70     *  Returns true on success.  Returns false on an invalid or unsupported |src|.
71     */
72    static bool Encode(SkWStream* dst, const SkPixmap& src, const Options& options);
73
74    /**
75     *  Create a jpeg encoder that will encode the |src| pixels to the |dst| stream.
76     *  |options| may be used to control the encoding behavior.
77     *
78     *  |dst| is unowned but must remain valid for the lifetime of the object.
79     *
80     *  This returns nullptr on an invalid or unsupported |src|.
81     */
82    static std::unique_ptr<SkEncoder> Make(SkWStream* dst, const SkPixmap& src,
83                                           const Options& options);
84
85    ~SkJpegEncoder() override;
86
87protected:
88    bool onEncodeRows(int numRows) override;
89
90private:
91    SkJpegEncoder(std::unique_ptr<SkJpegEncoderMgr>, const SkPixmap& src);
92
93    std::unique_ptr<SkJpegEncoderMgr> fEncoderMgr;
94    using INHERITED = SkEncoder;
95};
96
97#endif
98