1 // Copyright 2019 Google LLC.
2 // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
3 
4 #include "include/core/SkICC.h"
5 #include "include/core/SkString.h"
6 #include "tools/HashAndEncode.h"
7 #include "png.h"
8 
rec2020()9 static sk_sp<SkColorSpace> rec2020() {
10     return SkColorSpace::MakeRGB(SkNamedTransferFn::kRec2020, SkNamedGamut::kRec2020);
11 }
12 
HashAndEncode(const SkBitmap & bitmap)13 HashAndEncode::HashAndEncode(const SkBitmap& bitmap) : fSize(bitmap.info().dimensions()) {
14     skcms_AlphaFormat srcAlpha;
15     switch (bitmap.alphaType()) {
16         case kUnknown_SkAlphaType: return;
17 
18         case kOpaque_SkAlphaType:
19         case kUnpremul_SkAlphaType: srcAlpha = skcms_AlphaFormat_Unpremul;        break;
20         case kPremul_SkAlphaType:   srcAlpha = skcms_AlphaFormat_PremulAsEncoded; break;
21     }
22 
23     skcms_PixelFormat srcFmt;
24     switch (bitmap.colorType()) {
25         case kUnknown_SkColorType:            return;
26 
27         case kAlpha_8_SkColorType:            srcFmt = skcms_PixelFormat_A_8;             break;
28         case kRGB_565_SkColorType:            srcFmt = skcms_PixelFormat_BGR_565;         break;
29         case kARGB_4444_SkColorType:          srcFmt = skcms_PixelFormat_ABGR_4444;       break;
30         case kRGBA_8888_SkColorType:          srcFmt = skcms_PixelFormat_RGBA_8888;       break;
31         case kBGRA_8888_SkColorType:          srcFmt = skcms_PixelFormat_BGRA_8888;       break;
32         case kRGBA_1010102_SkColorType:       srcFmt = skcms_PixelFormat_RGBA_1010102;    break;
33         case kBGRA_1010102_SkColorType:       srcFmt = skcms_PixelFormat_BGRA_1010102;    break;
34         case kGray_8_SkColorType:             srcFmt = skcms_PixelFormat_G_8;             break;
35         case kRGBA_F16Norm_SkColorType:       srcFmt = skcms_PixelFormat_RGBA_hhhh;       break;
36         case kRGBA_F16_SkColorType:           srcFmt = skcms_PixelFormat_RGBA_hhhh;       break;
37         case kRGBA_F32_SkColorType:           srcFmt = skcms_PixelFormat_RGBA_ffff;       break;
38         case kR16G16B16A16_unorm_SkColorType: srcFmt = skcms_PixelFormat_RGBA_16161616LE; break;
39 
40         case kRGB_888x_SkColorType:           srcFmt = skcms_PixelFormat_RGBA_8888;
41                                               srcAlpha = skcms_AlphaFormat_Opaque;     break;
42         case kRGB_101010x_SkColorType:        srcFmt = skcms_PixelFormat_RGBA_1010102;
43                                               srcAlpha = skcms_AlphaFormat_Opaque;     break;
44         case kBGR_101010x_SkColorType:        srcFmt = skcms_PixelFormat_BGRA_1010102;
45                                               srcAlpha = skcms_AlphaFormat_Opaque;     break;
46 
47         case kR8G8_unorm_SkColorType:         return;
48         case kR16G16_unorm_SkColorType:       return;
49         case kR16G16_float_SkColorType:       return;
50         case kA16_unorm_SkColorType:          return;
51         case kA16_float_SkColorType:          return;
52     }
53 
54     skcms_ICCProfile srcProfile = *skcms_sRGB_profile();
55     if (auto cs = bitmap.colorSpace()) {
56         cs->toProfile(&srcProfile);
57     }
58 
59     // Our common format that can represent anything we draw and encode as a PNG:
60     //   - 16-bit big-endian RGBA
61     //   - unpremul
62     //   - Rec. 2020 gamut and transfer function
63     skcms_PixelFormat dstFmt   = skcms_PixelFormat_RGBA_16161616BE;
64     skcms_AlphaFormat dstAlpha = skcms_AlphaFormat_Unpremul;
65     skcms_ICCProfile dstProfile;
66     rec2020()->toProfile(&dstProfile);
67 
68     int N = fSize.width() * fSize.height();
69     fPixels.reset(new uint64_t[N]);
70 
71     const void* src = bitmap.getPixels();
72     void* dst = fPixels.get();
73     while (N > 0) {
74         int todo = std::min(N, 1<<27);  // Keep todo*8 <= 1B; skcms requires N*bpp < MAX_INT.
75         if (!skcms_Transform(src, srcFmt, srcAlpha, &srcProfile,
76                              dst, dstFmt, dstAlpha, &dstProfile, todo)) {
77             SkASSERT(false);
78             fPixels.reset(nullptr);
79             break;
80         }
81         src = (char*)src + todo*SkColorTypeBytesPerPixel(bitmap.colorType());
82         dst = (char*)dst + todo*sizeof(uint64_t);
83         N -= todo;
84     }
85 }
86 
feedHash(SkWStream * st) const87 void HashAndEncode::feedHash(SkWStream* st) const {
88     st->write(&fSize, sizeof(fSize));
89     if (const uint64_t* px = fPixels.get()) {
90         st->write(px, sizeof(*px) * fSize.width() * fSize.height());
91     }
92 
93     // N.B. changing salt will change the hash of all images produced by DM,
94     // and will cause tens of thousands of new images to be uploaded to Gold.
95     int salt = 1;
96     st->write(&salt, sizeof(salt));
97 }
98 
99 // NOTE: HashAndEncode uses libpng directly rather than through an abstraction
100 // like SkPngEncoder to make sure we get stable, portable results independent
101 // of any changes to Skia production encoder.
102 
encodePNG(SkWStream * st,const char * md5,CommandLineFlags::StringArray key,CommandLineFlags::StringArray properties) const103 bool HashAndEncode::encodePNG(SkWStream* st,
104                               const char* md5,
105                               CommandLineFlags::StringArray key,
106                               CommandLineFlags::StringArray properties) const {
107     if (!fPixels) {
108         return false;
109     }
110 
111     png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
112     if (!png) {
113         return false;
114     }
115 
116     png_infop info = png_create_info_struct(png);
117     if (!info) {
118         png_destroy_write_struct(&png, &info);
119         return false;
120     }
121     auto write_to_stream = +[](png_structp png, png_bytep ptr, png_size_t len) {
122         auto st = (SkWStream*)png_get_io_ptr(png);
123         if (!st->write(ptr, len)) {
124             png_error(png, "HashAndEncode::encodePNG() failed writing stream");
125         }
126     };
127     png_set_write_fn(png, st, write_to_stream, nullptr);
128 
129     SkString description;
130     description.append("Key: ");
131     for (int i = 0; i < key.count(); i++) {
132         description.appendf("%s ", key[i]);
133     }
134     description.append("Properties: ");
135     for (int i = 0; i < properties.count(); i++) {
136         description.appendf("%s ", properties[i]);
137     }
138     description.appendf("MD5: %s", md5);
139 
140     png_text text[2];
141     text[0].key  = (png_charp)"Author";
142     text[0].text = (png_charp)"DM unified Rec.2020";
143     text[0].compression = PNG_TEXT_COMPRESSION_NONE;
144     text[1].key  = (png_charp)"Description";
145     text[1].text = (png_charp)description.c_str();
146     text[1].compression = PNG_TEXT_COMPRESSION_NONE;
147     png_set_text(png, info, text, SK_ARRAY_COUNT(text));
148 
149     png_set_IHDR(png, info, (png_uint_32)fSize.width()
150                           , (png_uint_32)fSize.height()
151                           , 16/*bits per channel*/
152                           , PNG_COLOR_TYPE_RGB_ALPHA
153                           , PNG_INTERLACE_NONE
154                           , PNG_COMPRESSION_TYPE_DEFAULT
155                           , PNG_FILTER_TYPE_DEFAULT);
156 
157     // Fastest encoding and decoding, at slight file size cost is no filtering, compression 1.
158     png_set_filter(png, PNG_FILTER_TYPE_BASE, PNG_FILTER_NONE);
159     png_set_compression_level(png, 1);
160 
161     static const sk_sp<SkData> profile =
162         SkWriteICCProfile(SkNamedTransferFn::kRec2020, SkNamedGamut::kRec2020);
163     png_set_iCCP(png, info,
164                  "Rec.2020",
165                  0/*compression type... no idea what options are available here*/,
166                  (png_const_bytep)profile->data(),
167                  (png_uint_32)    profile->size());
168 
169     png_write_info(png, info);
170     for (int y = 0; y < fSize.height(); y++) {
171         png_write_row(png, (png_bytep)(fPixels.get() + y*fSize.width()));
172     }
173     png_write_end(png, info);
174 
175     png_destroy_write_struct(&png, &info);
176     return true;
177 }
178 
179