blob: 0d60f8afe96ddcd86a6a8141429a30402ea3a53b [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.com6d99de12013-08-06 18:56:53 +000025DEFINE_string(config, "None", "Preferred config to decode into. [None|8888|565|A8]");
scroggo@google.com6843bdb2013-05-08 19:14:23 +000026DEFINE_string(createExpectationsPath, "", "Path to write JSON expectations.");
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +000027DEFINE_string(mismatchPath, "", "Folder to write mismatched images to.");
scroggo@google.comb41ff952013-04-11 15:53:35 +000028DEFINE_string2(readPath, r, "", "Folder(s) and files to decode images. Required.");
scroggo@google.com6843bdb2013-05-08 19:14:23 +000029DEFINE_string(readExpectationsPath, "", "Path to read JSON expectations from.");
scroggo@google.com39edf4c2013-04-25 17:33:51 +000030DEFINE_bool(reencode, true, "Reencode the images to test encoding.");
scroggo@google.com7e6fcee2013-05-03 20:14:28 +000031DEFINE_bool(testSubsetDecoding, true, "Test decoding subsets of images.");
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +000032DEFINE_string2(writePath, w, "", "Write rendered images into this directory.");
scroggo@google.com8d239242013-10-01 17:27:15 +000033DEFINE_bool(skip, false, "Skip writing zeroes.");
scroggo@google.comb41ff952013-04-11 15:53:35 +000034
scroggo@google.com39edf4c2013-04-25 17:33:51 +000035struct Format {
36 SkImageEncoder::Type fType;
37 SkImageDecoder::Format fFormat;
38 const char* fSuffix;
39};
scroggo@google.comb41ff952013-04-11 15:53:35 +000040
scroggo@google.com39edf4c2013-04-25 17:33:51 +000041static const Format gFormats[] = {
42 { SkImageEncoder::kBMP_Type, SkImageDecoder::kBMP_Format, ".bmp" },
43 { SkImageEncoder::kGIF_Type, SkImageDecoder::kGIF_Format, ".gif" },
44 { SkImageEncoder::kICO_Type, SkImageDecoder::kICO_Format, ".ico" },
45 { SkImageEncoder::kJPEG_Type, SkImageDecoder::kJPEG_Format, ".jpg" },
46 { SkImageEncoder::kPNG_Type, SkImageDecoder::kPNG_Format, ".png" },
47 { SkImageEncoder::kWBMP_Type, SkImageDecoder::kWBMP_Format, ".wbmp" },
48 { SkImageEncoder::kWEBP_Type, SkImageDecoder::kWEBP_Format, ".webp" }
49};
50
51static SkImageEncoder::Type format_to_type(SkImageDecoder::Format format) {
52 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
53 if (gFormats[i].fFormat == format) {
54 return gFormats[i].fType;
55 }
reed@android.comaf459792009-04-24 19:52:53 +000056 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +000057 return SkImageEncoder::kUnknown_Type;
reed@android.comaf459792009-04-24 19:52:53 +000058}
59
scroggo@google.com39edf4c2013-04-25 17:33:51 +000060static const char* suffix_for_type(SkImageEncoder::Type type) {
61 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
62 if (gFormats[i].fType == type) {
63 return gFormats[i].fSuffix;
64 }
65 }
66 return "";
67}
reed@android.comaf459792009-04-24 19:52:53 +000068
scroggo@google.com39edf4c2013-04-25 17:33:51 +000069static SkImageDecoder::Format guess_format_from_suffix(const char suffix[]) {
70 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
71 if (strcmp(suffix, gFormats[i].fSuffix) == 0) {
72 return gFormats[i].fFormat;
73 }
74 }
75 return SkImageDecoder::kUnknown_Format;
76}
77
78static void make_outname(SkString* dst, const char outDir[], const char src[],
79 const char suffix[]) {
scroggo@google.comccd7afb2013-05-28 16:45:07 +000080 SkString basename = SkOSPath::SkBasename(src);
81 dst->set(SkOSPath::SkPathJoin(outDir, basename.c_str()));
scroggo@google.com39edf4c2013-04-25 17:33:51 +000082 if (!dst->endsWith(suffix)) {
scroggo@google.comb41ff952013-04-11 15:53:35 +000083 const char* cstyleDst = dst->c_str();
84 const char* dot = strrchr(cstyleDst, '.');
85 if (dot != NULL) {
86 int32_t index = SkToS32(dot - cstyleDst);
87 dst->remove(index, dst->size() - index);
88 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +000089 dst->append(suffix);
scroggo@google.comb41ff952013-04-11 15:53:35 +000090 }
91}
92
scroggo@google.com39edf4c2013-04-25 17:33:51 +000093// Store the names of the filenames to report later which ones failed, succeeded, and were
94// invalid.
95static SkTArray<SkString, false> gInvalidStreams;
96static SkTArray<SkString, false> gMissingCodecs;
97static SkTArray<SkString, false> gDecodeFailures;
98static SkTArray<SkString, false> gEncodeFailures;
99static SkTArray<SkString, false> gSuccessfulDecodes;
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000100static SkTArray<SkString, false> gSuccessfulSubsetDecodes;
101static SkTArray<SkString, false> gFailedSubsetDecodes;
scroggo@google.come339eb02013-08-06 18:51:30 +0000102// Files/subsets that do not have expectations. Not reported as a failure of the test so
103// the bots will not turn red with each new image test.
104static SkTArray<SkString, false> gMissingExpectations;
105static SkTArray<SkString, false> gMissingSubsetExpectations;
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000106
scroggo@google.com6d99de12013-08-06 18:56:53 +0000107static SkBitmap::Config gPrefConfig(SkBitmap::kNo_Config);
108
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000109// Expections read from a file specified by readExpectationsPath. The expectations must have been
110// previously written using createExpectationsPath.
111SkAutoTUnref<skiagm::JsonExpectationsSource> gJsonExpectations;
112
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000113static bool write_bitmap(const char outName[], const SkBitmap& bm) {
commit-bot@chromium.org546f70c2013-10-03 17:13:38 +0000114 const SkBitmap* bmPtr;
115 SkBitmap bm8888;
116 if (bm.config() == SkBitmap::kA8_Config) {
117 // Copy A8 into ARGB_8888, since our image encoders do not currently
118 // support A8.
119 if (!bm.copyTo(&bm8888, SkBitmap::kARGB_8888_Config)) {
120 return false;
121 }
122 bmPtr = &bm8888;
123 } else {
124 bmPtr = &bm;
125 }
126 return SkImageEncoder::EncodeFile(outName, *bmPtr, SkImageEncoder::kPNG_Type, 100);
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000127}
128
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000129/**
130 * Return a random SkIRect inside the range specified.
131 * @param rand Random number generator.
132 * @param maxX Exclusive maximum x-coordinate. SkIRect's fLeft and fRight will be
133 * in the range [0, maxX)
134 * @param maxY Exclusive maximum y-coordinate. SkIRect's fTop and fBottom will be
135 * in the range [0, maxY)
136 * @return SkIRect Non-empty, non-degenerate rectangle.
137 */
138static SkIRect generate_random_rect(SkRandom* rand, int32_t maxX, int32_t maxY) {
139 SkASSERT(maxX > 1 && maxY > 1);
140 int32_t left = rand->nextULessThan(maxX);
141 int32_t right = rand->nextULessThan(maxX);
142 int32_t top = rand->nextULessThan(maxY);
143 int32_t bottom = rand->nextULessThan(maxY);
144 SkIRect rect = SkIRect::MakeLTRB(left, top, right, bottom);
145 rect.sort();
146 // Make sure rect is not empty.
147 if (rect.fLeft == rect.fRight) {
148 if (rect.fLeft > 0) {
149 rect.fLeft--;
150 } else {
151 rect.fRight++;
152 // This branch is only taken if 0 == rect.fRight, and
153 // maxX must be at least 2, so it must still be in
154 // range.
155 SkASSERT(rect.fRight < maxX);
156 }
157 }
158 if (rect.fTop == rect.fBottom) {
159 if (rect.fTop > 0) {
160 rect.fTop--;
161 } else {
162 rect.fBottom++;
163 // Again, this must be in range.
164 SkASSERT(rect.fBottom < maxY);
165 }
166 }
167 return rect;
168}
169
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000170// Stored expectations to be written to a file if createExpectationsPath is specified.
171static Json::Value gExpectationsToWrite;
172
173/**
epoger@google.comd4993ff2013-05-24 14:33:28 +0000174 * If expectations are to be recorded, record the bitmap expectations into global
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000175 * expectations array.
176 */
177static void write_expectations(const SkBitmap& bitmap, const char* filename) {
178 if (!FLAGS_createExpectationsPath.isEmpty()) {
179 // Creates an Expectations object, and add it to the list to write.
180 skiagm::Expectations expectation(bitmap);
181 Json::Value value = expectation.asJsonValue();
182 gExpectationsToWrite[filename] = value;
183 }
184}
185
186/**
scroggo@google.combc91e8b2013-06-27 20:21:01 +0000187 * Return true if this filename is a known failure, and therefore a failure
188 * to decode should be ignored.
189 */
190static bool expect_to_fail(const char* filename) {
191 if (NULL == gJsonExpectations.get()) {
192 return false;
193 }
194 skiagm::Expectations jsExpectations = gJsonExpectations->get(filename);
195 return jsExpectations.ignoreFailure();
196}
197
198/**
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000199 * Compare against an expectation for this filename, if there is one.
scroggo@google.comcd7a73c2013-08-28 18:33:31 +0000200 * @param digest GmResultDigest, computed from the decoded bitmap, to compare to the
201 * expectation.
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000202 * @param filename String used to find the expected value.
scroggo@google.come339eb02013-08-06 18:51:30 +0000203 * @param failureArray Array to add a failure message to on failure.
204 * @param missingArray Array to add missing expectation to on failure.
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000205 * @return bool True in any of these cases:
206 * - the bitmap matches the expectation.
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000207 * False in any of these cases:
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000208 * - there is no expectations file.
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000209 * - there is an expectations file, but no expectation for this bitmap.
210 * - there is an expectation for this bitmap, but it did not match.
211 * - expectation could not be computed from the bitmap.
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000212 */
scroggo@google.comcd7a73c2013-08-28 18:33:31 +0000213static bool compare_to_expectations_if_necessary(const skiagm::GmResultDigest& digest,
214 const char* filename,
scroggo@google.come339eb02013-08-06 18:51:30 +0000215 SkTArray<SkString, false>* failureArray,
216 SkTArray<SkString, false>* missingArray) {
scroggo@google.comcd7a73c2013-08-28 18:33:31 +0000217 if (!digest.isValid()) {
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000218 if (failureArray != NULL) {
219 failureArray->push_back().printf("decoded %s, but could not create a GmResultDigest.",
220 filename);
221 }
222 return false;
223 }
224
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000225 if (NULL == gJsonExpectations.get()) {
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000226 return false;
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000227 }
228
229 skiagm::Expectations jsExpectation = gJsonExpectations->get(filename);
230 if (jsExpectation.empty()) {
scroggo@google.come339eb02013-08-06 18:51:30 +0000231 if (missingArray != NULL) {
232 missingArray->push_back().printf("decoded %s, but could not find expectation.",
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000233 filename);
234 }
235 return false;
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000236 }
237
scroggo@google.comcd7a73c2013-08-28 18:33:31 +0000238 if (jsExpectation.match(digest)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000239 return true;
240 }
241
242 if (failureArray != NULL) {
243 failureArray->push_back().printf("decoded %s, but the result does not match "
244 "expectations.",
245 filename);
246 }
247 return false;
248}
249
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000250/**
251 * Helper function to write a bitmap subset to a file. Only called if subsets were created
252 * and a writePath was provided. Creates a subdirectory called 'subsets' and writes a PNG to
253 * that directory. Also creates a subdirectory called 'extracted' and writes a bitmap created
254 * using extractSubset to a PNG in that directory. Both files will represent the same
255 * subrectangle and have the same name for comparison.
256 * @param writePath Parent directory to hold the folders for the PNG files to write. Must
257 * not be NULL.
258 * @param filename Basename of the original file. Used to name the new files. Must not be
259 * NULL.
260 * @param subsetDim String representing the dimensions of the subset. Used to name the new
261 * files. Must not be NULL.
262 * @param bitmapFromDecodeSubset Pointer to SkBitmap created by SkImageDecoder::DecodeSubset,
263 * using rect as the area to decode.
264 * @param rect Rectangle of the area decoded into bitmapFromDecodeSubset. Used to call
265 * extractSubset on originalBitmap to create a bitmap with the same dimensions/pixels as
266 * bitmapFromDecodeSubset (assuming decodeSubset worked properly).
267 * @param originalBitmap SkBitmap decoded from the same stream as bitmapFromDecodeSubset,
268 * using SkImageDecoder::decode to get the entire image. Used to create a PNG file for
269 * comparison to the PNG created by bitmapFromDecodeSubset.
270 * @return bool Whether the function succeeded at drawing the decoded subset and the extracted
271 * subset to files.
272 */
273static bool write_subset(const char* writePath, const char* filename, const char* subsetDim,
274 SkBitmap* bitmapFromDecodeSubset, SkIRect rect,
275 const SkBitmap& originalBitmap) {
276 // All parameters must be valid.
277 SkASSERT(writePath != NULL);
278 SkASSERT(filename != NULL);
279 SkASSERT(subsetDim != NULL);
280 SkASSERT(bitmapFromDecodeSubset != NULL);
281
282 // Create a subdirectory to hold the results of decodeSubset.
scroggo@google.comccd7afb2013-05-28 16:45:07 +0000283 SkString dir = SkOSPath::SkPathJoin(writePath, "subsets");
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000284 if (!sk_mkdir(dir.c_str())) {
285 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
286 "create a directory to write to.", subsetDim,
287 filename);
288 return false;
289 }
290
291 // Write the subset to a file whose name includes the dimensions.
292 SkString suffix = SkStringPrintf("_%s.png", subsetDim);
293 SkString outPath;
294 make_outname(&outPath, dir.c_str(), filename, suffix.c_str());
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000295 SkAssertResult(write_bitmap(outPath.c_str(), *bitmapFromDecodeSubset));
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000296 gSuccessfulSubsetDecodes.push_back().printf("\twrote %s", outPath.c_str());
297
298 // Also use extractSubset from the original for visual comparison.
299 // Write the result to a file in a separate subdirectory.
300 SkBitmap extractedSubset;
301 if (!originalBitmap.extractSubset(&extractedSubset, rect)) {
302 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
303 "extract a similar subset for comparison.",
304 subsetDim, filename);
305 return false;
306 }
307
scroggo@google.comccd7afb2013-05-28 16:45:07 +0000308 SkString dirExtracted = SkOSPath::SkPathJoin(writePath, "extracted");
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000309 if (!sk_mkdir(dirExtracted.c_str())) {
310 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
311 "create a directory for extractSubset comparison.",
312 subsetDim, filename);
313 return false;
314 }
315
316 make_outname(&outPath, dirExtracted.c_str(), filename, suffix.c_str());
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000317 SkAssertResult(write_bitmap(outPath.c_str(), extractedSubset));
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000318 return true;
319}
320
scroggo@google.comcd7a73c2013-08-28 18:33:31 +0000321// FIXME: This test could be run on windows/mac once we remove their dependence on
322// getLength. See https://code.google.com/p/skia/issues/detail?id=1570
323#if defined(SK_BUILD_FOR_ANDROID) || defined(SK_BUILD_FOR_UNIX)
324
325/**
326 * Dummy class for testing to ensure that a stream without a length decodes the same
327 * as a stream with a length.
328 */
329class FILEStreamWithoutLength : public SkFILEStream {
330public:
331 FILEStreamWithoutLength(const char path[])
332 : INHERITED(path) {}
333
334 virtual bool hasLength() const SK_OVERRIDE {
335 return false;
336 }
337
338private:
339 typedef SkFILEStream INHERITED;
340};
341
342/**
343 * Test that decoding a stream which reports to not have a length still results in the
344 * same image as if it did report to have a length. Assumes that codec was used to
345 * successfully decode the file using SkFILEStream.
346 * @param srcPath The path to the file, for recreating the length-less stream.
347 * @param codec The SkImageDecoder originally used to decode srcPath, which will be used
348 * again to decode the length-less stream.
349 * @param digest GmResultDigest computed from decoding the stream the first time.
350 * Decoding the length-less stream is expected to result in a matching digest.
351 */
352static void test_stream_without_length(const char srcPath[], SkImageDecoder* codec,
353 const skiagm::GmResultDigest& digest) {
354 if (!digest.isValid()) {
355 // An error was already reported.
356 return;
357 }
358 SkASSERT(srcPath);
359 SkASSERT(codec);
360 FILEStreamWithoutLength stream(srcPath);
361 // This will only be called after a successful decode. Creating a stream from the same
362 // path should never fail.
363 SkASSERT(stream.isValid());
364 SkBitmap bm;
365 if (!codec->decode(&stream, &bm, gPrefConfig, SkImageDecoder::kDecodePixels_Mode)) {
366 gDecodeFailures.push_back().appendf("Without using getLength, %s failed to decode\n",
367 srcPath);
368 return;
369 }
370 skiagm::GmResultDigest lengthLessDigest(bm);
371 if (!lengthLessDigest.isValid()) {
372 gDecodeFailures.push_back().appendf("Without using getLength, %s failed to build "
373 "a digest\n", srcPath);
374 return;
375 }
376 if (!lengthLessDigest.equals(digest)) {
377 gDecodeFailures.push_back().appendf("Without using getLength, %s did not match digest "
378 "that uses getLength\n", srcPath);
379 }
380}
381#endif // defined(SK_BUILD_FOR_ANDROID) || defined(SK_BUILD_FOR_UNIX)
382
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000383static void decodeFileAndWrite(const char srcPath[], const SkString* writePath) {
384 SkBitmap bitmap;
385 SkFILEStream stream(srcPath);
386 if (!stream.isValid()) {
387 gInvalidStreams.push_back().set(srcPath);
388 return;
389 }
390
391 SkImageDecoder* codec = SkImageDecoder::Factory(&stream);
392 if (NULL == codec) {
393 gMissingCodecs.push_back().set(srcPath);
394 return;
395 }
396
397 SkAutoTDelete<SkImageDecoder> ad(codec);
398
scroggo@google.com8d239242013-10-01 17:27:15 +0000399 codec->setSkipWritingZeroes(FLAGS_skip);
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000400 stream.rewind();
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000401
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000402 // Create a string representing just the filename itself, for use in json expectations.
scroggo@google.comccd7afb2013-05-28 16:45:07 +0000403 SkString basename = SkOSPath::SkBasename(srcPath);
404 const char* filename = basename.c_str();
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000405
scroggo@google.com6d99de12013-08-06 18:56:53 +0000406 if (!codec->decode(&stream, &bitmap, gPrefConfig,
scroggo@google.combc91e8b2013-06-27 20:21:01 +0000407 SkImageDecoder::kDecodePixels_Mode)) {
408 if (expect_to_fail(filename)) {
409 gSuccessfulDecodes.push_back().appendf(
410 "failed to decode %s, which is a known failure.", srcPath);
411 } else {
412 gDecodeFailures.push_back().set(srcPath);
413 }
414 return;
415 }
416
scroggo@google.com6f67b3b2013-07-18 20:08:26 +0000417 // Test decoding just the bounds. The bounds should always match.
418 {
419 stream.rewind();
420 SkBitmap dim;
421 if (!codec->decode(&stream, &dim, SkImageDecoder::kDecodeBounds_Mode)) {
422 SkString failure = SkStringPrintf("failed to decode bounds for %s", srcPath);
423 gDecodeFailures.push_back() = failure;
424 } else {
425 // Now check that the bounds match:
426 if (dim.width() != bitmap.width() || dim.height() != bitmap.height()) {
427 SkString failure = SkStringPrintf("bounds do not match for %s", srcPath);
428 gDecodeFailures.push_back() = failure;
429 }
430 }
431 }
432
scroggo@google.comcd7a73c2013-08-28 18:33:31 +0000433 skiagm::GmResultDigest digest(bitmap);
434 if (compare_to_expectations_if_necessary(digest, filename,
scroggo@google.come339eb02013-08-06 18:51:30 +0000435 &gDecodeFailures,
436 &gMissingExpectations)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000437 gSuccessfulDecodes.push_back().printf("%s [%d %d]", srcPath, bitmap.width(),
438 bitmap.height());
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000439 } else if (!FLAGS_mismatchPath.isEmpty()) {
440 SkString outPath;
441 make_outname(&outPath, FLAGS_mismatchPath[0], srcPath, ".png");
442 if (write_bitmap(outPath.c_str(), bitmap)) {
443 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
444 } else {
445 gEncodeFailures.push_back().set(outPath);
446 }
447 }
448
scroggo@google.comcd7a73c2013-08-28 18:33:31 +0000449// FIXME: This test could be run on windows/mac once we remove their dependence on
450// getLength. See https://code.google.com/p/skia/issues/detail?id=1570
451#if defined(SK_BUILD_FOR_ANDROID) || defined(SK_BUILD_FOR_UNIX)
452 test_stream_without_length(srcPath, codec, digest);
453#endif
454
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000455 if (writePath != NULL) {
456 SkString outPath;
457 make_outname(&outPath, writePath->c_str(), srcPath, ".png");
458 if (write_bitmap(outPath.c_str(), bitmap)) {
459 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
460 } else {
461 gEncodeFailures.push_back().set(outPath);
462 }
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000463 }
464
465 write_expectations(bitmap, filename);
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000466
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000467 if (FLAGS_testSubsetDecoding) {
scroggo@google.com0018f752013-05-03 20:39:22 +0000468 SkDEBUGCODE(bool couldRewind =) stream.rewind();
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000469 SkASSERT(couldRewind);
470 int width, height;
471 // Build the tile index for decoding subsets. If the image is 1x1, skip subset
472 // decoding since there are no smaller subsets.
473 if (codec->buildTileIndex(&stream, &width, &height) && width > 1 && height > 1) {
474 SkASSERT(bitmap.width() == width && bitmap.height() == height);
475 // Call decodeSubset multiple times:
476 SkRandom rand(0);
477 for (int i = 0; i < 5; i++) {
478 SkBitmap bitmapFromDecodeSubset;
479 // FIXME: Come up with a more representative set of rectangles.
480 SkIRect rect = generate_random_rect(&rand, width, height);
481 SkString subsetDim = SkStringPrintf("[%d,%d,%d,%d]", rect.fLeft, rect.fTop,
482 rect.fRight, rect.fBottom);
scroggo@google.com6d99de12013-08-06 18:56:53 +0000483 if (codec->decodeSubset(&bitmapFromDecodeSubset, rect, gPrefConfig)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000484 SkString subsetName = SkStringPrintf("%s_%s", filename, subsetDim.c_str());
scroggo@google.comcd7a73c2013-08-28 18:33:31 +0000485 skiagm::GmResultDigest subsetDigest(bitmapFromDecodeSubset);
486 if (compare_to_expectations_if_necessary(subsetDigest,
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000487 subsetName.c_str(),
scroggo@google.come339eb02013-08-06 18:51:30 +0000488 &gFailedSubsetDecodes,
489 &gMissingSubsetExpectations)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000490 gSuccessfulSubsetDecodes.push_back().printf("Decoded subset %s from %s",
491 subsetDim.c_str(), srcPath);
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000492 } else if (!FLAGS_mismatchPath.isEmpty()) {
493 write_subset(FLAGS_mismatchPath[0], filename, subsetDim.c_str(),
494 &bitmapFromDecodeSubset, rect, bitmap);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000495 }
496
497 write_expectations(bitmapFromDecodeSubset, subsetName.c_str());
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000498 if (writePath != NULL) {
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000499 write_subset(writePath->c_str(), filename, subsetDim.c_str(),
500 &bitmapFromDecodeSubset, rect, bitmap);
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000501 }
502 } else {
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000503 gFailedSubsetDecodes.push_back().printf("Failed to decode region %s from %s",
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000504 subsetDim.c_str(), srcPath);
505 }
506 }
507 }
508 }
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000509
commit-bot@chromium.org546f70c2013-10-03 17:13:38 +0000510 // Do not attempt to re-encode A8, since our image encoders do not support encoding to A8.
511 if (FLAGS_reencode && bitmap.config() != SkBitmap::kA8_Config) {
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000512 // Encode to the format the file was originally in, or PNG if the encoder for the same
513 // format is unavailable.
514 SkImageDecoder::Format format = codec->getFormat();
515 if (SkImageDecoder::kUnknown_Format == format) {
516 if (stream.rewind()) {
517 format = SkImageDecoder::GetStreamFormat(&stream);
518 }
519 if (SkImageDecoder::kUnknown_Format == format) {
520 const char* dot = strrchr(srcPath, '.');
521 if (NULL != dot) {
522 format = guess_format_from_suffix(dot);
523 }
524 if (SkImageDecoder::kUnknown_Format == format) {
525 SkDebugf("Could not determine type for '%s'\n", srcPath);
526 format = SkImageDecoder::kPNG_Format;
527 }
528
529 }
530 } else {
531 SkASSERT(!stream.rewind() || SkImageDecoder::GetStreamFormat(&stream) == format);
532 }
533 SkImageEncoder::Type type = format_to_type(format);
534 // format should never be kUnknown_Format, so type should never be kUnknown_Type.
535 SkASSERT(type != SkImageEncoder::kUnknown_Type);
536
537 SkImageEncoder* encoder = SkImageEncoder::Create(type);
538 if (NULL == encoder) {
539 type = SkImageEncoder::kPNG_Type;
540 encoder = SkImageEncoder::Create(type);
541 SkASSERT(encoder);
542 }
543 SkAutoTDelete<SkImageEncoder> ade(encoder);
544 // Encode to a stream.
545 SkDynamicMemoryWStream wStream;
546 if (!encoder->encodeStream(&wStream, bitmap, 100)) {
547 gEncodeFailures.push_back().printf("Failed to reencode %s to type '%s'", srcPath,
548 suffix_for_type(type));
549 return;
550 }
551
552 SkAutoTUnref<SkData> data(wStream.copyToData());
553 if (writePath != NULL && type != SkImageEncoder::kPNG_Type) {
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000554 // Write the encoded data to a file. Do not write to PNG, which was already written.
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000555 SkString outPath;
556 make_outname(&outPath, writePath->c_str(), srcPath, suffix_for_type(type));
557 SkFILEWStream file(outPath.c_str());
558 if(file.write(data->data(), data->size())) {
559 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
560 } else {
561 gEncodeFailures.push_back().printf("Failed to write %s", outPath.c_str());
562 }
563 }
564 // Ensure that the reencoded data can still be decoded.
565 SkMemoryStream memStream(data);
566 SkBitmap redecodedBitmap;
567 SkImageDecoder::Format formatOnSecondDecode;
scroggo@google.com6d99de12013-08-06 18:56:53 +0000568 if (SkImageDecoder::DecodeStream(&memStream, &redecodedBitmap, gPrefConfig,
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000569 SkImageDecoder::kDecodePixels_Mode,
570 &formatOnSecondDecode)) {
571 SkASSERT(format_to_type(formatOnSecondDecode) == type);
572 } else {
573 gDecodeFailures.push_back().printf("Failed to redecode %s after reencoding to '%s'",
574 srcPath, suffix_for_type(type));
575 }
576 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000577}
578
579///////////////////////////////////////////////////////////////////////////////
580
scroggo@google.comb41ff952013-04-11 15:53:35 +0000581// If strings is not empty, print title, followed by each string on its own line starting
582// with a tab.
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000583// @return bool True if strings had at least one entry.
584static bool print_strings(const char* title, const SkTArray<SkString, false>& strings) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000585 if (strings.count() > 0) {
586 SkDebugf("%s:\n", title);
587 for (int i = 0; i < strings.count(); i++) {
588 SkDebugf("\t%s\n", strings[i].c_str());
589 }
590 SkDebugf("\n");
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000591 return true;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000592 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000593 return false;
reed@android.comaf459792009-04-24 19:52:53 +0000594}
595
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000596/**
597 * If directory is non null and does not end with a path separator, append one.
598 * @param directory SkString representing the path to a directory. If the last character is not a
599 * path separator (specific to the current OS), append one.
600 */
601static void append_path_separator_if_necessary(SkString* directory) {
602 if (directory != NULL && directory->c_str()[directory->size() - 1] != SkPATH_SEPARATOR) {
603 directory->appendf("%c", SkPATH_SEPARATOR);
604 }
605}
606
scroggo@google.com925cdca2013-06-28 20:04:42 +0000607/**
608 * Return true if the filename represents an image.
609 */
610static bool is_image_file(const char* filename) {
611 const char* gImageExtensions[] = {
612 ".png", ".PNG", ".jpg", ".JPG", ".jpeg", ".JPEG", ".bmp", ".BMP",
613 ".webp", ".WEBP", ".ico", ".ICO", ".wbmp", ".WBMP", ".gif", ".GIF"
614 };
615 for (size_t i = 0; i < SK_ARRAY_COUNT(gImageExtensions); ++i) {
616 if (SkStrEndsWith(filename, gImageExtensions[i])) {
617 return true;
618 }
619 }
620 return false;
621}
622
caryclark@google.com5987f582012-10-02 18:33:14 +0000623int tool_main(int argc, char** argv);
624int tool_main(int argc, char** argv) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000625 SkCommandLineFlags::SetUsage("Decode files, and optionally write the results to files.");
626 SkCommandLineFlags::Parse(argc, argv);
627
628 if (FLAGS_readPath.count() < 1) {
629 SkDebugf("Folder(s) or image(s) to decode are required.\n");
630 return -1;
631 }
632
633
reed@android.comaf459792009-04-24 19:52:53 +0000634 SkAutoGraphics ag;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000635
scroggo@google.com3832da12013-06-19 19:12:53 +0000636 if (!FLAGS_readExpectationsPath.isEmpty() && sk_exists(FLAGS_readExpectationsPath[0])) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000637 gJsonExpectations.reset(SkNEW_ARGS(skiagm::JsonExpectationsSource,
638 (FLAGS_readExpectationsPath[0])));
639 }
640
reed@android.comaf459792009-04-24 19:52:53 +0000641 SkString outDir;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000642 SkString* outDirPtr;
reed@android.comaf459792009-04-24 19:52:53 +0000643
scroggo@google.comb41ff952013-04-11 15:53:35 +0000644 if (FLAGS_writePath.count() == 1) {
645 outDir.set(FLAGS_writePath[0]);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000646 append_path_separator_if_necessary(&outDir);
scroggo@google.comb41ff952013-04-11 15:53:35 +0000647 outDirPtr = &outDir;
648 } else {
649 outDirPtr = NULL;
650 }
651
scroggo@google.com6d99de12013-08-06 18:56:53 +0000652 if (FLAGS_config.count() == 1) {
653 // Only consider the first config specified on the command line.
654 const char* config = FLAGS_config[0];
655 if (0 == strcmp(config, "8888")) {
656 gPrefConfig = SkBitmap::kARGB_8888_Config;
657 } else if (0 == strcmp(config, "565")) {
658 gPrefConfig = SkBitmap::kRGB_565_Config;
659 } else if (0 == strcmp(config, "A8")) {
660 gPrefConfig = SkBitmap::kA8_Config;
661 } else if (0 != strcmp(config, "None")) {
662 SkDebugf("Invalid preferred config\n");
663 return -1;
664 }
665 }
666
scroggo@google.comb41ff952013-04-11 15:53:35 +0000667 for (int i = 0; i < FLAGS_readPath.count(); i++) {
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000668 const char* readPath = FLAGS_readPath[i];
669 if (strlen(readPath) < 1) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000670 break;
671 }
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000672 if (sk_isdir(readPath)) {
673 const char* dir = readPath;
674 SkOSFile::Iter iter(dir);
675 SkString filename;
676 while (iter.next(&filename)) {
scroggo@google.com925cdca2013-06-28 20:04:42 +0000677 if (!is_image_file(filename.c_str())) {
678 continue;
679 }
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000680 SkString fullname = SkOSPath::SkPathJoin(dir, filename.c_str());
scroggo@google.comb41ff952013-04-11 15:53:35 +0000681 decodeFileAndWrite(fullname.c_str(), outDirPtr);
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000682 }
scroggo@google.com925cdca2013-06-28 20:04:42 +0000683 } else if (sk_exists(readPath) && is_image_file(readPath)) {
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000684 decodeFileAndWrite(readPath, outDirPtr);
reed@android.comaf459792009-04-24 19:52:53 +0000685 }
686 }
687
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000688 if (!FLAGS_createExpectationsPath.isEmpty()) {
689 // Use an empty value for everything besides expectations, since the reader only cares
690 // about the expectations.
691 Json::Value nullValue;
692 Json::Value root = skiagm::CreateJsonTree(gExpectationsToWrite, nullValue, nullValue,
693 nullValue, nullValue);
694 std::string jsonStdString = root.toStyledString();
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000695 SkFILEWStream stream(FLAGS_createExpectationsPath[0]);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000696 stream.write(jsonStdString.c_str(), jsonStdString.length());
697 }
scroggo@google.comb41ff952013-04-11 15:53:35 +0000698 // Add some space, since codecs may print warnings without newline.
699 SkDebugf("\n\n");
rmistry@google.comd6176b02012-08-23 18:14:13 +0000700
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000701 bool failed = print_strings("Invalid files", gInvalidStreams);
702 failed |= print_strings("Missing codec", gMissingCodecs);
703 failed |= print_strings("Failed to decode", gDecodeFailures);
704 failed |= print_strings("Failed to encode", gEncodeFailures);
705 print_strings("Decoded", gSuccessfulDecodes);
scroggo@google.come339eb02013-08-06 18:51:30 +0000706 print_strings("Missing expectations", gMissingExpectations);
reed@android.comaf459792009-04-24 19:52:53 +0000707
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000708 if (FLAGS_testSubsetDecoding) {
709 failed |= print_strings("Failed subset decodes", gFailedSubsetDecodes);
710 print_strings("Decoded subsets", gSuccessfulSubsetDecodes);
scroggo@google.come339eb02013-08-06 18:51:30 +0000711 print_strings("Missing subset expectations", gMissingSubsetExpectations);
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000712 }
713
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000714 return failed ? -1 : 0;
reed@android.comaf459792009-04-24 19:52:53 +0000715}
716
caryclark@google.com5987f582012-10-02 18:33:14 +0000717#if !defined SK_BUILD_FOR_IOS
718int main(int argc, char * const argv[]) {
719 return tool_main(argc, (char**) argv);
720}
721#endif