blob: ad3f2048dc5a6f6efcd131d3b8cef456aeff6d97 [file] [log] [blame]
epoger@google.comec3ed6a2011-07-28 14:26:00 +00001/*
2 * Copyright 2011 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 */
scroggo@google.comb41ff952013-04-11 15:53:35 +00007
scroggo@google.com6843bdb2013-05-08 19:14:23 +00008#include "gm_expectations.h"
reed@android.comaf459792009-04-24 19:52:53 +00009#include "SkBitmap.h"
scroggo@google.com39edf4c2013-04-25 17:33:51 +000010#include "SkColorPriv.h"
scroggo@google.comb41ff952013-04-11 15:53:35 +000011#include "SkCommandLineFlags.h"
scroggo@google.com39edf4c2013-04-25 17:33:51 +000012#include "SkData.h"
scroggo@google.com7def5e12013-05-31 14:00:10 +000013#include "SkForceLinking.h"
reed@android.comaf459792009-04-24 19:52:53 +000014#include "SkGraphics.h"
15#include "SkImageDecoder.h"
16#include "SkImageEncoder.h"
scroggo@google.comb41ff952013-04-11 15:53:35 +000017#include "SkOSFile.h"
scroggo@google.com7e6fcee2013-05-03 20:14:28 +000018#include "SkRandom.h"
reed@android.comaf459792009-04-24 19:52:53 +000019#include "SkStream.h"
scroggo@google.comb41ff952013-04-11 15:53:35 +000020#include "SkTArray.h"
reed@android.comaf459792009-04-24 19:52:53 +000021#include "SkTemplates.h"
22
scroggo@google.com7def5e12013-05-31 14:00:10 +000023__SK_FORCE_IMAGE_DECODER_LINKING;
24
scroggo@google.com6843bdb2013-05-08 19:14:23 +000025DEFINE_string(createExpectationsPath, "", "Path to write JSON expectations.");
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +000026DEFINE_string(mismatchPath, "", "Folder to write mismatched images to.");
scroggo@google.comb41ff952013-04-11 15:53:35 +000027DEFINE_string2(readPath, r, "", "Folder(s) and files to decode images. Required.");
scroggo@google.com6843bdb2013-05-08 19:14:23 +000028DEFINE_string(readExpectationsPath, "", "Path to read JSON expectations from.");
scroggo@google.com39edf4c2013-04-25 17:33:51 +000029DEFINE_bool(reencode, true, "Reencode the images to test encoding.");
scroggo@google.com7e6fcee2013-05-03 20:14:28 +000030DEFINE_bool(testSubsetDecoding, true, "Test decoding subsets of images.");
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +000031DEFINE_string2(writePath, w, "", "Write rendered images into this directory.");
scroggo@google.comb41ff952013-04-11 15:53:35 +000032
scroggo@google.com39edf4c2013-04-25 17:33:51 +000033struct Format {
34 SkImageEncoder::Type fType;
35 SkImageDecoder::Format fFormat;
36 const char* fSuffix;
37};
scroggo@google.comb41ff952013-04-11 15:53:35 +000038
scroggo@google.com39edf4c2013-04-25 17:33:51 +000039static const Format gFormats[] = {
40 { SkImageEncoder::kBMP_Type, SkImageDecoder::kBMP_Format, ".bmp" },
41 { SkImageEncoder::kGIF_Type, SkImageDecoder::kGIF_Format, ".gif" },
42 { SkImageEncoder::kICO_Type, SkImageDecoder::kICO_Format, ".ico" },
43 { SkImageEncoder::kJPEG_Type, SkImageDecoder::kJPEG_Format, ".jpg" },
44 { SkImageEncoder::kPNG_Type, SkImageDecoder::kPNG_Format, ".png" },
45 { SkImageEncoder::kWBMP_Type, SkImageDecoder::kWBMP_Format, ".wbmp" },
46 { SkImageEncoder::kWEBP_Type, SkImageDecoder::kWEBP_Format, ".webp" }
47};
48
49static SkImageEncoder::Type format_to_type(SkImageDecoder::Format format) {
50 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
51 if (gFormats[i].fFormat == format) {
52 return gFormats[i].fType;
53 }
reed@android.comaf459792009-04-24 19:52:53 +000054 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +000055 return SkImageEncoder::kUnknown_Type;
reed@android.comaf459792009-04-24 19:52:53 +000056}
57
scroggo@google.com39edf4c2013-04-25 17:33:51 +000058static const char* suffix_for_type(SkImageEncoder::Type type) {
59 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
60 if (gFormats[i].fType == type) {
61 return gFormats[i].fSuffix;
62 }
63 }
64 return "";
65}
reed@android.comaf459792009-04-24 19:52:53 +000066
scroggo@google.com39edf4c2013-04-25 17:33:51 +000067static SkImageDecoder::Format guess_format_from_suffix(const char suffix[]) {
68 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
69 if (strcmp(suffix, gFormats[i].fSuffix) == 0) {
70 return gFormats[i].fFormat;
71 }
72 }
73 return SkImageDecoder::kUnknown_Format;
74}
75
76static void make_outname(SkString* dst, const char outDir[], const char src[],
77 const char suffix[]) {
scroggo@google.comccd7afb2013-05-28 16:45:07 +000078 SkString basename = SkOSPath::SkBasename(src);
79 dst->set(SkOSPath::SkPathJoin(outDir, basename.c_str()));
scroggo@google.com39edf4c2013-04-25 17:33:51 +000080 if (!dst->endsWith(suffix)) {
scroggo@google.comb41ff952013-04-11 15:53:35 +000081 const char* cstyleDst = dst->c_str();
82 const char* dot = strrchr(cstyleDst, '.');
83 if (dot != NULL) {
84 int32_t index = SkToS32(dot - cstyleDst);
85 dst->remove(index, dst->size() - index);
86 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +000087 dst->append(suffix);
scroggo@google.comb41ff952013-04-11 15:53:35 +000088 }
89}
90
scroggo@google.com39edf4c2013-04-25 17:33:51 +000091// Store the names of the filenames to report later which ones failed, succeeded, and were
92// invalid.
93static SkTArray<SkString, false> gInvalidStreams;
94static SkTArray<SkString, false> gMissingCodecs;
95static SkTArray<SkString, false> gDecodeFailures;
96static SkTArray<SkString, false> gEncodeFailures;
97static SkTArray<SkString, false> gSuccessfulDecodes;
scroggo@google.com7e6fcee2013-05-03 20:14:28 +000098static SkTArray<SkString, false> gSuccessfulSubsetDecodes;
99static SkTArray<SkString, false> gFailedSubsetDecodes;
scroggo@google.come339eb02013-08-06 18:51:30 +0000100// Files/subsets that do not have expectations. Not reported as a failure of the test so
101// the bots will not turn red with each new image test.
102static SkTArray<SkString, false> gMissingExpectations;
103static SkTArray<SkString, false> gMissingSubsetExpectations;
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000104
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000105// Expections read from a file specified by readExpectationsPath. The expectations must have been
106// previously written using createExpectationsPath.
107SkAutoTUnref<skiagm::JsonExpectationsSource> gJsonExpectations;
108
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000109static bool write_bitmap(const char outName[], const SkBitmap& bm) {
110 return SkImageEncoder::EncodeFile(outName, bm, SkImageEncoder::kPNG_Type, 100);
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000111}
112
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000113/**
114 * Return a random SkIRect inside the range specified.
115 * @param rand Random number generator.
116 * @param maxX Exclusive maximum x-coordinate. SkIRect's fLeft and fRight will be
117 * in the range [0, maxX)
118 * @param maxY Exclusive maximum y-coordinate. SkIRect's fTop and fBottom will be
119 * in the range [0, maxY)
120 * @return SkIRect Non-empty, non-degenerate rectangle.
121 */
122static SkIRect generate_random_rect(SkRandom* rand, int32_t maxX, int32_t maxY) {
123 SkASSERT(maxX > 1 && maxY > 1);
124 int32_t left = rand->nextULessThan(maxX);
125 int32_t right = rand->nextULessThan(maxX);
126 int32_t top = rand->nextULessThan(maxY);
127 int32_t bottom = rand->nextULessThan(maxY);
128 SkIRect rect = SkIRect::MakeLTRB(left, top, right, bottom);
129 rect.sort();
130 // Make sure rect is not empty.
131 if (rect.fLeft == rect.fRight) {
132 if (rect.fLeft > 0) {
133 rect.fLeft--;
134 } else {
135 rect.fRight++;
136 // This branch is only taken if 0 == rect.fRight, and
137 // maxX must be at least 2, so it must still be in
138 // range.
139 SkASSERT(rect.fRight < maxX);
140 }
141 }
142 if (rect.fTop == rect.fBottom) {
143 if (rect.fTop > 0) {
144 rect.fTop--;
145 } else {
146 rect.fBottom++;
147 // Again, this must be in range.
148 SkASSERT(rect.fBottom < maxY);
149 }
150 }
151 return rect;
152}
153
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000154// Stored expectations to be written to a file if createExpectationsPath is specified.
155static Json::Value gExpectationsToWrite;
156
157/**
epoger@google.comd4993ff2013-05-24 14:33:28 +0000158 * If expectations are to be recorded, record the bitmap expectations into global
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000159 * expectations array.
160 */
161static void write_expectations(const SkBitmap& bitmap, const char* filename) {
162 if (!FLAGS_createExpectationsPath.isEmpty()) {
163 // Creates an Expectations object, and add it to the list to write.
164 skiagm::Expectations expectation(bitmap);
165 Json::Value value = expectation.asJsonValue();
166 gExpectationsToWrite[filename] = value;
167 }
168}
169
170/**
scroggo@google.combc91e8b2013-06-27 20:21:01 +0000171 * Return true if this filename is a known failure, and therefore a failure
172 * to decode should be ignored.
173 */
174static bool expect_to_fail(const char* filename) {
175 if (NULL == gJsonExpectations.get()) {
176 return false;
177 }
178 skiagm::Expectations jsExpectations = gJsonExpectations->get(filename);
179 return jsExpectations.ignoreFailure();
180}
181
182/**
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000183 * Compare against an expectation for this filename, if there is one.
184 * @param bitmap SkBitmap to compare to the expected value.
185 * @param filename String used to find the expected value.
scroggo@google.come339eb02013-08-06 18:51:30 +0000186 * @param failureArray Array to add a failure message to on failure.
187 * @param missingArray Array to add missing expectation to on failure.
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000188 * @return bool True in any of these cases:
189 * - the bitmap matches the expectation.
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000190 * False in any of these cases:
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000191 * - there is no expectations file.
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000192 * - there is an expectations file, but no expectation for this bitmap.
193 * - there is an expectation for this bitmap, but it did not match.
194 * - expectation could not be computed from the bitmap.
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000195 */
196static bool compare_to_expectations_if_necessary(const SkBitmap& bitmap, const char* filename,
scroggo@google.come339eb02013-08-06 18:51:30 +0000197 SkTArray<SkString, false>* failureArray,
198 SkTArray<SkString, false>* missingArray) {
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000199 skiagm::GmResultDigest resultDigest(bitmap);
200 if (!resultDigest.isValid()) {
201 if (failureArray != NULL) {
202 failureArray->push_back().printf("decoded %s, but could not create a GmResultDigest.",
203 filename);
204 }
205 return false;
206 }
207
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000208 if (NULL == gJsonExpectations.get()) {
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000209 return false;
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000210 }
211
212 skiagm::Expectations jsExpectation = gJsonExpectations->get(filename);
213 if (jsExpectation.empty()) {
scroggo@google.come339eb02013-08-06 18:51:30 +0000214 if (missingArray != NULL) {
215 missingArray->push_back().printf("decoded %s, but could not find expectation.",
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000216 filename);
217 }
218 return false;
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000219 }
220
epoger@google.comd4993ff2013-05-24 14:33:28 +0000221 if (jsExpectation.match(resultDigest)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000222 return true;
223 }
224
225 if (failureArray != NULL) {
226 failureArray->push_back().printf("decoded %s, but the result does not match "
227 "expectations.",
228 filename);
229 }
230 return false;
231}
232
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000233/**
234 * Helper function to write a bitmap subset to a file. Only called if subsets were created
235 * and a writePath was provided. Creates a subdirectory called 'subsets' and writes a PNG to
236 * that directory. Also creates a subdirectory called 'extracted' and writes a bitmap created
237 * using extractSubset to a PNG in that directory. Both files will represent the same
238 * subrectangle and have the same name for comparison.
239 * @param writePath Parent directory to hold the folders for the PNG files to write. Must
240 * not be NULL.
241 * @param filename Basename of the original file. Used to name the new files. Must not be
242 * NULL.
243 * @param subsetDim String representing the dimensions of the subset. Used to name the new
244 * files. Must not be NULL.
245 * @param bitmapFromDecodeSubset Pointer to SkBitmap created by SkImageDecoder::DecodeSubset,
246 * using rect as the area to decode.
247 * @param rect Rectangle of the area decoded into bitmapFromDecodeSubset. Used to call
248 * extractSubset on originalBitmap to create a bitmap with the same dimensions/pixels as
249 * bitmapFromDecodeSubset (assuming decodeSubset worked properly).
250 * @param originalBitmap SkBitmap decoded from the same stream as bitmapFromDecodeSubset,
251 * using SkImageDecoder::decode to get the entire image. Used to create a PNG file for
252 * comparison to the PNG created by bitmapFromDecodeSubset.
253 * @return bool Whether the function succeeded at drawing the decoded subset and the extracted
254 * subset to files.
255 */
256static bool write_subset(const char* writePath, const char* filename, const char* subsetDim,
257 SkBitmap* bitmapFromDecodeSubset, SkIRect rect,
258 const SkBitmap& originalBitmap) {
259 // All parameters must be valid.
260 SkASSERT(writePath != NULL);
261 SkASSERT(filename != NULL);
262 SkASSERT(subsetDim != NULL);
263 SkASSERT(bitmapFromDecodeSubset != NULL);
264
265 // Create a subdirectory to hold the results of decodeSubset.
scroggo@google.comccd7afb2013-05-28 16:45:07 +0000266 SkString dir = SkOSPath::SkPathJoin(writePath, "subsets");
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000267 if (!sk_mkdir(dir.c_str())) {
268 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
269 "create a directory to write to.", subsetDim,
270 filename);
271 return false;
272 }
273
274 // Write the subset to a file whose name includes the dimensions.
275 SkString suffix = SkStringPrintf("_%s.png", subsetDim);
276 SkString outPath;
277 make_outname(&outPath, dir.c_str(), filename, suffix.c_str());
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000278 SkAssertResult(write_bitmap(outPath.c_str(), *bitmapFromDecodeSubset));
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000279 gSuccessfulSubsetDecodes.push_back().printf("\twrote %s", outPath.c_str());
280
281 // Also use extractSubset from the original for visual comparison.
282 // Write the result to a file in a separate subdirectory.
283 SkBitmap extractedSubset;
284 if (!originalBitmap.extractSubset(&extractedSubset, rect)) {
285 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
286 "extract a similar subset for comparison.",
287 subsetDim, filename);
288 return false;
289 }
290
scroggo@google.comccd7afb2013-05-28 16:45:07 +0000291 SkString dirExtracted = SkOSPath::SkPathJoin(writePath, "extracted");
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000292 if (!sk_mkdir(dirExtracted.c_str())) {
293 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
294 "create a directory for extractSubset comparison.",
295 subsetDim, filename);
296 return false;
297 }
298
299 make_outname(&outPath, dirExtracted.c_str(), filename, suffix.c_str());
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000300 SkAssertResult(write_bitmap(outPath.c_str(), extractedSubset));
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000301 return true;
302}
303
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000304static void decodeFileAndWrite(const char srcPath[], const SkString* writePath) {
305 SkBitmap bitmap;
306 SkFILEStream stream(srcPath);
307 if (!stream.isValid()) {
308 gInvalidStreams.push_back().set(srcPath);
309 return;
310 }
311
312 SkImageDecoder* codec = SkImageDecoder::Factory(&stream);
313 if (NULL == codec) {
314 gMissingCodecs.push_back().set(srcPath);
315 return;
316 }
317
318 SkAutoTDelete<SkImageDecoder> ad(codec);
319
320 stream.rewind();
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000321
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000322 // Create a string representing just the filename itself, for use in json expectations.
scroggo@google.comccd7afb2013-05-28 16:45:07 +0000323 SkString basename = SkOSPath::SkBasename(srcPath);
324 const char* filename = basename.c_str();
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000325
scroggo@google.combc91e8b2013-06-27 20:21:01 +0000326 if (!codec->decode(&stream, &bitmap, SkBitmap::kARGB_8888_Config,
327 SkImageDecoder::kDecodePixels_Mode)) {
328 if (expect_to_fail(filename)) {
329 gSuccessfulDecodes.push_back().appendf(
330 "failed to decode %s, which is a known failure.", srcPath);
331 } else {
332 gDecodeFailures.push_back().set(srcPath);
333 }
334 return;
335 }
336
scroggo@google.com6f67b3b2013-07-18 20:08:26 +0000337 // Test decoding just the bounds. The bounds should always match.
338 {
339 stream.rewind();
340 SkBitmap dim;
341 if (!codec->decode(&stream, &dim, SkImageDecoder::kDecodeBounds_Mode)) {
342 SkString failure = SkStringPrintf("failed to decode bounds for %s", srcPath);
343 gDecodeFailures.push_back() = failure;
344 } else {
345 // Now check that the bounds match:
346 if (dim.width() != bitmap.width() || dim.height() != bitmap.height()) {
347 SkString failure = SkStringPrintf("bounds do not match for %s", srcPath);
348 gDecodeFailures.push_back() = failure;
349 }
350 }
351 }
352
scroggo@google.come339eb02013-08-06 18:51:30 +0000353 if (compare_to_expectations_if_necessary(bitmap, filename,
354 &gDecodeFailures,
355 &gMissingExpectations)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000356 gSuccessfulDecodes.push_back().printf("%s [%d %d]", srcPath, bitmap.width(),
357 bitmap.height());
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000358 } else if (!FLAGS_mismatchPath.isEmpty()) {
359 SkString outPath;
360 make_outname(&outPath, FLAGS_mismatchPath[0], srcPath, ".png");
361 if (write_bitmap(outPath.c_str(), bitmap)) {
362 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
363 } else {
364 gEncodeFailures.push_back().set(outPath);
365 }
366 }
367
368 if (writePath != NULL) {
369 SkString outPath;
370 make_outname(&outPath, writePath->c_str(), srcPath, ".png");
371 if (write_bitmap(outPath.c_str(), bitmap)) {
372 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
373 } else {
374 gEncodeFailures.push_back().set(outPath);
375 }
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000376 }
377
378 write_expectations(bitmap, filename);
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000379
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000380 if (FLAGS_testSubsetDecoding) {
scroggo@google.com0018f752013-05-03 20:39:22 +0000381 SkDEBUGCODE(bool couldRewind =) stream.rewind();
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000382 SkASSERT(couldRewind);
383 int width, height;
384 // Build the tile index for decoding subsets. If the image is 1x1, skip subset
385 // decoding since there are no smaller subsets.
386 if (codec->buildTileIndex(&stream, &width, &height) && width > 1 && height > 1) {
387 SkASSERT(bitmap.width() == width && bitmap.height() == height);
388 // Call decodeSubset multiple times:
389 SkRandom rand(0);
390 for (int i = 0; i < 5; i++) {
391 SkBitmap bitmapFromDecodeSubset;
392 // FIXME: Come up with a more representative set of rectangles.
393 SkIRect rect = generate_random_rect(&rand, width, height);
394 SkString subsetDim = SkStringPrintf("[%d,%d,%d,%d]", rect.fLeft, rect.fTop,
395 rect.fRight, rect.fBottom);
396 if (codec->decodeSubset(&bitmapFromDecodeSubset, rect, SkBitmap::kNo_Config)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000397 SkString subsetName = SkStringPrintf("%s_%s", filename, subsetDim.c_str());
398 if (compare_to_expectations_if_necessary(bitmapFromDecodeSubset,
399 subsetName.c_str(),
scroggo@google.come339eb02013-08-06 18:51:30 +0000400 &gFailedSubsetDecodes,
401 &gMissingSubsetExpectations)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000402 gSuccessfulSubsetDecodes.push_back().printf("Decoded subset %s from %s",
403 subsetDim.c_str(), srcPath);
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000404 } else if (!FLAGS_mismatchPath.isEmpty()) {
405 write_subset(FLAGS_mismatchPath[0], filename, subsetDim.c_str(),
406 &bitmapFromDecodeSubset, rect, bitmap);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000407 }
408
409 write_expectations(bitmapFromDecodeSubset, subsetName.c_str());
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000410 if (writePath != NULL) {
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000411 write_subset(writePath->c_str(), filename, subsetDim.c_str(),
412 &bitmapFromDecodeSubset, rect, bitmap);
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000413 }
414 } else {
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000415 gFailedSubsetDecodes.push_back().printf("Failed to decode region %s from %s",
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000416 subsetDim.c_str(), srcPath);
417 }
418 }
419 }
420 }
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000421
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000422 if (FLAGS_reencode) {
423 // Encode to the format the file was originally in, or PNG if the encoder for the same
424 // format is unavailable.
425 SkImageDecoder::Format format = codec->getFormat();
426 if (SkImageDecoder::kUnknown_Format == format) {
427 if (stream.rewind()) {
428 format = SkImageDecoder::GetStreamFormat(&stream);
429 }
430 if (SkImageDecoder::kUnknown_Format == format) {
431 const char* dot = strrchr(srcPath, '.');
432 if (NULL != dot) {
433 format = guess_format_from_suffix(dot);
434 }
435 if (SkImageDecoder::kUnknown_Format == format) {
436 SkDebugf("Could not determine type for '%s'\n", srcPath);
437 format = SkImageDecoder::kPNG_Format;
438 }
439
440 }
441 } else {
442 SkASSERT(!stream.rewind() || SkImageDecoder::GetStreamFormat(&stream) == format);
443 }
444 SkImageEncoder::Type type = format_to_type(format);
445 // format should never be kUnknown_Format, so type should never be kUnknown_Type.
446 SkASSERT(type != SkImageEncoder::kUnknown_Type);
447
448 SkImageEncoder* encoder = SkImageEncoder::Create(type);
449 if (NULL == encoder) {
450 type = SkImageEncoder::kPNG_Type;
451 encoder = SkImageEncoder::Create(type);
452 SkASSERT(encoder);
453 }
454 SkAutoTDelete<SkImageEncoder> ade(encoder);
455 // Encode to a stream.
456 SkDynamicMemoryWStream wStream;
457 if (!encoder->encodeStream(&wStream, bitmap, 100)) {
458 gEncodeFailures.push_back().printf("Failed to reencode %s to type '%s'", srcPath,
459 suffix_for_type(type));
460 return;
461 }
462
463 SkAutoTUnref<SkData> data(wStream.copyToData());
464 if (writePath != NULL && type != SkImageEncoder::kPNG_Type) {
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000465 // Write the encoded data to a file. Do not write to PNG, which was already written.
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000466 SkString outPath;
467 make_outname(&outPath, writePath->c_str(), srcPath, suffix_for_type(type));
468 SkFILEWStream file(outPath.c_str());
469 if(file.write(data->data(), data->size())) {
470 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
471 } else {
472 gEncodeFailures.push_back().printf("Failed to write %s", outPath.c_str());
473 }
474 }
475 // Ensure that the reencoded data can still be decoded.
476 SkMemoryStream memStream(data);
477 SkBitmap redecodedBitmap;
478 SkImageDecoder::Format formatOnSecondDecode;
479 if (SkImageDecoder::DecodeStream(&memStream, &redecodedBitmap, SkBitmap::kNo_Config,
480 SkImageDecoder::kDecodePixels_Mode,
481 &formatOnSecondDecode)) {
482 SkASSERT(format_to_type(formatOnSecondDecode) == type);
483 } else {
484 gDecodeFailures.push_back().printf("Failed to redecode %s after reencoding to '%s'",
485 srcPath, suffix_for_type(type));
486 }
487 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000488}
489
490///////////////////////////////////////////////////////////////////////////////
491
scroggo@google.comb41ff952013-04-11 15:53:35 +0000492// If strings is not empty, print title, followed by each string on its own line starting
493// with a tab.
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000494// @return bool True if strings had at least one entry.
495static bool print_strings(const char* title, const SkTArray<SkString, false>& strings) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000496 if (strings.count() > 0) {
497 SkDebugf("%s:\n", title);
498 for (int i = 0; i < strings.count(); i++) {
499 SkDebugf("\t%s\n", strings[i].c_str());
500 }
501 SkDebugf("\n");
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000502 return true;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000503 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000504 return false;
reed@android.comaf459792009-04-24 19:52:53 +0000505}
506
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000507/**
508 * If directory is non null and does not end with a path separator, append one.
509 * @param directory SkString representing the path to a directory. If the last character is not a
510 * path separator (specific to the current OS), append one.
511 */
512static void append_path_separator_if_necessary(SkString* directory) {
513 if (directory != NULL && directory->c_str()[directory->size() - 1] != SkPATH_SEPARATOR) {
514 directory->appendf("%c", SkPATH_SEPARATOR);
515 }
516}
517
scroggo@google.com925cdca2013-06-28 20:04:42 +0000518/**
519 * Return true if the filename represents an image.
520 */
521static bool is_image_file(const char* filename) {
522 const char* gImageExtensions[] = {
523 ".png", ".PNG", ".jpg", ".JPG", ".jpeg", ".JPEG", ".bmp", ".BMP",
524 ".webp", ".WEBP", ".ico", ".ICO", ".wbmp", ".WBMP", ".gif", ".GIF"
525 };
526 for (size_t i = 0; i < SK_ARRAY_COUNT(gImageExtensions); ++i) {
527 if (SkStrEndsWith(filename, gImageExtensions[i])) {
528 return true;
529 }
530 }
531 return false;
532}
533
caryclark@google.com5987f582012-10-02 18:33:14 +0000534int tool_main(int argc, char** argv);
535int tool_main(int argc, char** argv) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000536 SkCommandLineFlags::SetUsage("Decode files, and optionally write the results to files.");
537 SkCommandLineFlags::Parse(argc, argv);
538
539 if (FLAGS_readPath.count() < 1) {
540 SkDebugf("Folder(s) or image(s) to decode are required.\n");
541 return -1;
542 }
543
544
reed@android.comaf459792009-04-24 19:52:53 +0000545 SkAutoGraphics ag;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000546
scroggo@google.com3832da12013-06-19 19:12:53 +0000547 if (!FLAGS_readExpectationsPath.isEmpty() && sk_exists(FLAGS_readExpectationsPath[0])) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000548 gJsonExpectations.reset(SkNEW_ARGS(skiagm::JsonExpectationsSource,
549 (FLAGS_readExpectationsPath[0])));
550 }
551
reed@android.comaf459792009-04-24 19:52:53 +0000552 SkString outDir;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000553 SkString* outDirPtr;
reed@android.comaf459792009-04-24 19:52:53 +0000554
scroggo@google.comb41ff952013-04-11 15:53:35 +0000555 if (FLAGS_writePath.count() == 1) {
556 outDir.set(FLAGS_writePath[0]);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000557 append_path_separator_if_necessary(&outDir);
scroggo@google.comb41ff952013-04-11 15:53:35 +0000558 outDirPtr = &outDir;
559 } else {
560 outDirPtr = NULL;
561 }
562
563 for (int i = 0; i < FLAGS_readPath.count(); i++) {
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000564 const char* readPath = FLAGS_readPath[i];
565 if (strlen(readPath) < 1) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000566 break;
567 }
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000568 if (sk_isdir(readPath)) {
569 const char* dir = readPath;
570 SkOSFile::Iter iter(dir);
571 SkString filename;
572 while (iter.next(&filename)) {
scroggo@google.com925cdca2013-06-28 20:04:42 +0000573 if (!is_image_file(filename.c_str())) {
574 continue;
575 }
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000576 SkString fullname = SkOSPath::SkPathJoin(dir, filename.c_str());
scroggo@google.comb41ff952013-04-11 15:53:35 +0000577 decodeFileAndWrite(fullname.c_str(), outDirPtr);
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000578 }
scroggo@google.com925cdca2013-06-28 20:04:42 +0000579 } else if (sk_exists(readPath) && is_image_file(readPath)) {
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000580 decodeFileAndWrite(readPath, outDirPtr);
reed@android.comaf459792009-04-24 19:52:53 +0000581 }
582 }
583
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000584 if (!FLAGS_createExpectationsPath.isEmpty()) {
585 // Use an empty value for everything besides expectations, since the reader only cares
586 // about the expectations.
587 Json::Value nullValue;
588 Json::Value root = skiagm::CreateJsonTree(gExpectationsToWrite, nullValue, nullValue,
589 nullValue, nullValue);
590 std::string jsonStdString = root.toStyledString();
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000591 SkFILEWStream stream(FLAGS_createExpectationsPath[0]);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000592 stream.write(jsonStdString.c_str(), jsonStdString.length());
593 }
scroggo@google.comb41ff952013-04-11 15:53:35 +0000594 // Add some space, since codecs may print warnings without newline.
595 SkDebugf("\n\n");
rmistry@google.comd6176b02012-08-23 18:14:13 +0000596
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000597 bool failed = print_strings("Invalid files", gInvalidStreams);
598 failed |= print_strings("Missing codec", gMissingCodecs);
599 failed |= print_strings("Failed to decode", gDecodeFailures);
600 failed |= print_strings("Failed to encode", gEncodeFailures);
601 print_strings("Decoded", gSuccessfulDecodes);
scroggo@google.come339eb02013-08-06 18:51:30 +0000602 print_strings("Missing expectations", gMissingExpectations);
reed@android.comaf459792009-04-24 19:52:53 +0000603
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000604 if (FLAGS_testSubsetDecoding) {
605 failed |= print_strings("Failed subset decodes", gFailedSubsetDecodes);
606 print_strings("Decoded subsets", gSuccessfulSubsetDecodes);
scroggo@google.come339eb02013-08-06 18:51:30 +0000607 print_strings("Missing subset expectations", gMissingSubsetExpectations);
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000608 }
609
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000610 return failed ? -1 : 0;
reed@android.comaf459792009-04-24 19:52:53 +0000611}
612
caryclark@google.com5987f582012-10-02 18:33:14 +0000613#if !defined SK_BUILD_FOR_IOS
614int main(int argc, char * const argv[]) {
615 return tool_main(argc, (char**) argv);
616}
617#endif