blob: 7cd15e811e0ded6b566de23563888f5918c915c4 [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.comb41ff952013-04-11 15:53:35 +000033
scroggo@google.com39edf4c2013-04-25 17:33:51 +000034struct Format {
35 SkImageEncoder::Type fType;
36 SkImageDecoder::Format fFormat;
37 const char* fSuffix;
38};
scroggo@google.comb41ff952013-04-11 15:53:35 +000039
scroggo@google.com39edf4c2013-04-25 17:33:51 +000040static const Format gFormats[] = {
41 { SkImageEncoder::kBMP_Type, SkImageDecoder::kBMP_Format, ".bmp" },
42 { SkImageEncoder::kGIF_Type, SkImageDecoder::kGIF_Format, ".gif" },
43 { SkImageEncoder::kICO_Type, SkImageDecoder::kICO_Format, ".ico" },
44 { SkImageEncoder::kJPEG_Type, SkImageDecoder::kJPEG_Format, ".jpg" },
45 { SkImageEncoder::kPNG_Type, SkImageDecoder::kPNG_Format, ".png" },
46 { SkImageEncoder::kWBMP_Type, SkImageDecoder::kWBMP_Format, ".wbmp" },
47 { SkImageEncoder::kWEBP_Type, SkImageDecoder::kWEBP_Format, ".webp" }
48};
49
50static SkImageEncoder::Type format_to_type(SkImageDecoder::Format format) {
51 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
52 if (gFormats[i].fFormat == format) {
53 return gFormats[i].fType;
54 }
reed@android.comaf459792009-04-24 19:52:53 +000055 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +000056 return SkImageEncoder::kUnknown_Type;
reed@android.comaf459792009-04-24 19:52:53 +000057}
58
scroggo@google.com39edf4c2013-04-25 17:33:51 +000059static const char* suffix_for_type(SkImageEncoder::Type type) {
60 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
61 if (gFormats[i].fType == type) {
62 return gFormats[i].fSuffix;
63 }
64 }
65 return "";
66}
reed@android.comaf459792009-04-24 19:52:53 +000067
scroggo@google.com39edf4c2013-04-25 17:33:51 +000068static SkImageDecoder::Format guess_format_from_suffix(const char suffix[]) {
69 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
70 if (strcmp(suffix, gFormats[i].fSuffix) == 0) {
71 return gFormats[i].fFormat;
72 }
73 }
74 return SkImageDecoder::kUnknown_Format;
75}
76
77static void make_outname(SkString* dst, const char outDir[], const char src[],
78 const char suffix[]) {
scroggo@google.comccd7afb2013-05-28 16:45:07 +000079 SkString basename = SkOSPath::SkBasename(src);
80 dst->set(SkOSPath::SkPathJoin(outDir, basename.c_str()));
scroggo@google.com39edf4c2013-04-25 17:33:51 +000081 if (!dst->endsWith(suffix)) {
scroggo@google.comb41ff952013-04-11 15:53:35 +000082 const char* cstyleDst = dst->c_str();
83 const char* dot = strrchr(cstyleDst, '.');
84 if (dot != NULL) {
85 int32_t index = SkToS32(dot - cstyleDst);
86 dst->remove(index, dst->size() - index);
87 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +000088 dst->append(suffix);
scroggo@google.comb41ff952013-04-11 15:53:35 +000089 }
90}
91
scroggo@google.com39edf4c2013-04-25 17:33:51 +000092// Store the names of the filenames to report later which ones failed, succeeded, and were
93// invalid.
94static SkTArray<SkString, false> gInvalidStreams;
95static SkTArray<SkString, false> gMissingCodecs;
96static SkTArray<SkString, false> gDecodeFailures;
97static SkTArray<SkString, false> gEncodeFailures;
98static SkTArray<SkString, false> gSuccessfulDecodes;
scroggo@google.com7e6fcee2013-05-03 20:14:28 +000099static SkTArray<SkString, false> gSuccessfulSubsetDecodes;
100static SkTArray<SkString, false> gFailedSubsetDecodes;
scroggo@google.come339eb02013-08-06 18:51:30 +0000101// Files/subsets that do not have expectations. Not reported as a failure of the test so
102// the bots will not turn red with each new image test.
103static SkTArray<SkString, false> gMissingExpectations;
104static SkTArray<SkString, false> gMissingSubsetExpectations;
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000105
scroggo@google.com6d99de12013-08-06 18:56:53 +0000106static SkBitmap::Config gPrefConfig(SkBitmap::kNo_Config);
107
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000108// Expections read from a file specified by readExpectationsPath. The expectations must have been
109// previously written using createExpectationsPath.
110SkAutoTUnref<skiagm::JsonExpectationsSource> gJsonExpectations;
111
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000112static bool write_bitmap(const char outName[], const SkBitmap& bm) {
113 return SkImageEncoder::EncodeFile(outName, bm, SkImageEncoder::kPNG_Type, 100);
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000114}
115
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000116/**
117 * Return a random SkIRect inside the range specified.
118 * @param rand Random number generator.
119 * @param maxX Exclusive maximum x-coordinate. SkIRect's fLeft and fRight will be
120 * in the range [0, maxX)
121 * @param maxY Exclusive maximum y-coordinate. SkIRect's fTop and fBottom will be
122 * in the range [0, maxY)
123 * @return SkIRect Non-empty, non-degenerate rectangle.
124 */
125static SkIRect generate_random_rect(SkRandom* rand, int32_t maxX, int32_t maxY) {
126 SkASSERT(maxX > 1 && maxY > 1);
127 int32_t left = rand->nextULessThan(maxX);
128 int32_t right = rand->nextULessThan(maxX);
129 int32_t top = rand->nextULessThan(maxY);
130 int32_t bottom = rand->nextULessThan(maxY);
131 SkIRect rect = SkIRect::MakeLTRB(left, top, right, bottom);
132 rect.sort();
133 // Make sure rect is not empty.
134 if (rect.fLeft == rect.fRight) {
135 if (rect.fLeft > 0) {
136 rect.fLeft--;
137 } else {
138 rect.fRight++;
139 // This branch is only taken if 0 == rect.fRight, and
140 // maxX must be at least 2, so it must still be in
141 // range.
142 SkASSERT(rect.fRight < maxX);
143 }
144 }
145 if (rect.fTop == rect.fBottom) {
146 if (rect.fTop > 0) {
147 rect.fTop--;
148 } else {
149 rect.fBottom++;
150 // Again, this must be in range.
151 SkASSERT(rect.fBottom < maxY);
152 }
153 }
154 return rect;
155}
156
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000157// Stored expectations to be written to a file if createExpectationsPath is specified.
158static Json::Value gExpectationsToWrite;
159
160/**
epoger@google.comd4993ff2013-05-24 14:33:28 +0000161 * If expectations are to be recorded, record the bitmap expectations into global
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000162 * expectations array.
163 */
164static void write_expectations(const SkBitmap& bitmap, const char* filename) {
165 if (!FLAGS_createExpectationsPath.isEmpty()) {
166 // Creates an Expectations object, and add it to the list to write.
167 skiagm::Expectations expectation(bitmap);
168 Json::Value value = expectation.asJsonValue();
169 gExpectationsToWrite[filename] = value;
170 }
171}
172
173/**
scroggo@google.combc91e8b2013-06-27 20:21:01 +0000174 * Return true if this filename is a known failure, and therefore a failure
175 * to decode should be ignored.
176 */
177static bool expect_to_fail(const char* filename) {
178 if (NULL == gJsonExpectations.get()) {
179 return false;
180 }
181 skiagm::Expectations jsExpectations = gJsonExpectations->get(filename);
182 return jsExpectations.ignoreFailure();
183}
184
185/**
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000186 * Compare against an expectation for this filename, if there is one.
scroggo@google.comcd7a73c2013-08-28 18:33:31 +0000187 * @param digest GmResultDigest, computed from the decoded bitmap, to compare to the
188 * expectation.
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000189 * @param filename String used to find the expected value.
scroggo@google.come339eb02013-08-06 18:51:30 +0000190 * @param failureArray Array to add a failure message to on failure.
191 * @param missingArray Array to add missing expectation to on failure.
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000192 * @return bool True in any of these cases:
193 * - the bitmap matches the expectation.
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000194 * False in any of these cases:
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000195 * - there is no expectations file.
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000196 * - there is an expectations file, but no expectation for this bitmap.
197 * - there is an expectation for this bitmap, but it did not match.
198 * - expectation could not be computed from the bitmap.
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000199 */
scroggo@google.comcd7a73c2013-08-28 18:33:31 +0000200static bool compare_to_expectations_if_necessary(const skiagm::GmResultDigest& digest,
201 const char* filename,
scroggo@google.come339eb02013-08-06 18:51:30 +0000202 SkTArray<SkString, false>* failureArray,
203 SkTArray<SkString, false>* missingArray) {
scroggo@google.comcd7a73c2013-08-28 18:33:31 +0000204 if (!digest.isValid()) {
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000205 if (failureArray != NULL) {
206 failureArray->push_back().printf("decoded %s, but could not create a GmResultDigest.",
207 filename);
208 }
209 return false;
210 }
211
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000212 if (NULL == gJsonExpectations.get()) {
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000213 return false;
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000214 }
215
216 skiagm::Expectations jsExpectation = gJsonExpectations->get(filename);
217 if (jsExpectation.empty()) {
scroggo@google.come339eb02013-08-06 18:51:30 +0000218 if (missingArray != NULL) {
219 missingArray->push_back().printf("decoded %s, but could not find expectation.",
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000220 filename);
221 }
222 return false;
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000223 }
224
scroggo@google.comcd7a73c2013-08-28 18:33:31 +0000225 if (jsExpectation.match(digest)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000226 return true;
227 }
228
229 if (failureArray != NULL) {
230 failureArray->push_back().printf("decoded %s, but the result does not match "
231 "expectations.",
232 filename);
233 }
234 return false;
235}
236
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000237/**
238 * Helper function to write a bitmap subset to a file. Only called if subsets were created
239 * and a writePath was provided. Creates a subdirectory called 'subsets' and writes a PNG to
240 * that directory. Also creates a subdirectory called 'extracted' and writes a bitmap created
241 * using extractSubset to a PNG in that directory. Both files will represent the same
242 * subrectangle and have the same name for comparison.
243 * @param writePath Parent directory to hold the folders for the PNG files to write. Must
244 * not be NULL.
245 * @param filename Basename of the original file. Used to name the new files. Must not be
246 * NULL.
247 * @param subsetDim String representing the dimensions of the subset. Used to name the new
248 * files. Must not be NULL.
249 * @param bitmapFromDecodeSubset Pointer to SkBitmap created by SkImageDecoder::DecodeSubset,
250 * using rect as the area to decode.
251 * @param rect Rectangle of the area decoded into bitmapFromDecodeSubset. Used to call
252 * extractSubset on originalBitmap to create a bitmap with the same dimensions/pixels as
253 * bitmapFromDecodeSubset (assuming decodeSubset worked properly).
254 * @param originalBitmap SkBitmap decoded from the same stream as bitmapFromDecodeSubset,
255 * using SkImageDecoder::decode to get the entire image. Used to create a PNG file for
256 * comparison to the PNG created by bitmapFromDecodeSubset.
257 * @return bool Whether the function succeeded at drawing the decoded subset and the extracted
258 * subset to files.
259 */
260static bool write_subset(const char* writePath, const char* filename, const char* subsetDim,
261 SkBitmap* bitmapFromDecodeSubset, SkIRect rect,
262 const SkBitmap& originalBitmap) {
263 // All parameters must be valid.
264 SkASSERT(writePath != NULL);
265 SkASSERT(filename != NULL);
266 SkASSERT(subsetDim != NULL);
267 SkASSERT(bitmapFromDecodeSubset != NULL);
268
269 // Create a subdirectory to hold the results of decodeSubset.
scroggo@google.comccd7afb2013-05-28 16:45:07 +0000270 SkString dir = SkOSPath::SkPathJoin(writePath, "subsets");
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000271 if (!sk_mkdir(dir.c_str())) {
272 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
273 "create a directory to write to.", subsetDim,
274 filename);
275 return false;
276 }
277
278 // Write the subset to a file whose name includes the dimensions.
279 SkString suffix = SkStringPrintf("_%s.png", subsetDim);
280 SkString outPath;
281 make_outname(&outPath, dir.c_str(), filename, suffix.c_str());
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000282 SkAssertResult(write_bitmap(outPath.c_str(), *bitmapFromDecodeSubset));
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000283 gSuccessfulSubsetDecodes.push_back().printf("\twrote %s", outPath.c_str());
284
285 // Also use extractSubset from the original for visual comparison.
286 // Write the result to a file in a separate subdirectory.
287 SkBitmap extractedSubset;
288 if (!originalBitmap.extractSubset(&extractedSubset, rect)) {
289 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
290 "extract a similar subset for comparison.",
291 subsetDim, filename);
292 return false;
293 }
294
scroggo@google.comccd7afb2013-05-28 16:45:07 +0000295 SkString dirExtracted = SkOSPath::SkPathJoin(writePath, "extracted");
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000296 if (!sk_mkdir(dirExtracted.c_str())) {
297 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
298 "create a directory for extractSubset comparison.",
299 subsetDim, filename);
300 return false;
301 }
302
303 make_outname(&outPath, dirExtracted.c_str(), filename, suffix.c_str());
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000304 SkAssertResult(write_bitmap(outPath.c_str(), extractedSubset));
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000305 return true;
306}
307
scroggo@google.comcd7a73c2013-08-28 18:33:31 +0000308// FIXME: This test could be run on windows/mac once we remove their dependence on
309// getLength. See https://code.google.com/p/skia/issues/detail?id=1570
310#if defined(SK_BUILD_FOR_ANDROID) || defined(SK_BUILD_FOR_UNIX)
311
312/**
313 * Dummy class for testing to ensure that a stream without a length decodes the same
314 * as a stream with a length.
315 */
316class FILEStreamWithoutLength : public SkFILEStream {
317public:
318 FILEStreamWithoutLength(const char path[])
319 : INHERITED(path) {}
320
321 virtual bool hasLength() const SK_OVERRIDE {
322 return false;
323 }
324
325private:
326 typedef SkFILEStream INHERITED;
327};
328
329/**
330 * Test that decoding a stream which reports to not have a length still results in the
331 * same image as if it did report to have a length. Assumes that codec was used to
332 * successfully decode the file using SkFILEStream.
333 * @param srcPath The path to the file, for recreating the length-less stream.
334 * @param codec The SkImageDecoder originally used to decode srcPath, which will be used
335 * again to decode the length-less stream.
336 * @param digest GmResultDigest computed from decoding the stream the first time.
337 * Decoding the length-less stream is expected to result in a matching digest.
338 */
339static void test_stream_without_length(const char srcPath[], SkImageDecoder* codec,
340 const skiagm::GmResultDigest& digest) {
341 if (!digest.isValid()) {
342 // An error was already reported.
343 return;
344 }
345 SkASSERT(srcPath);
346 SkASSERT(codec);
347 FILEStreamWithoutLength stream(srcPath);
348 // This will only be called after a successful decode. Creating a stream from the same
349 // path should never fail.
350 SkASSERT(stream.isValid());
351 SkBitmap bm;
352 if (!codec->decode(&stream, &bm, gPrefConfig, SkImageDecoder::kDecodePixels_Mode)) {
353 gDecodeFailures.push_back().appendf("Without using getLength, %s failed to decode\n",
354 srcPath);
355 return;
356 }
357 skiagm::GmResultDigest lengthLessDigest(bm);
358 if (!lengthLessDigest.isValid()) {
359 gDecodeFailures.push_back().appendf("Without using getLength, %s failed to build "
360 "a digest\n", srcPath);
361 return;
362 }
363 if (!lengthLessDigest.equals(digest)) {
364 gDecodeFailures.push_back().appendf("Without using getLength, %s did not match digest "
365 "that uses getLength\n", srcPath);
366 }
367}
368#endif // defined(SK_BUILD_FOR_ANDROID) || defined(SK_BUILD_FOR_UNIX)
369
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000370static void decodeFileAndWrite(const char srcPath[], const SkString* writePath) {
371 SkBitmap bitmap;
372 SkFILEStream stream(srcPath);
373 if (!stream.isValid()) {
374 gInvalidStreams.push_back().set(srcPath);
375 return;
376 }
377
378 SkImageDecoder* codec = SkImageDecoder::Factory(&stream);
379 if (NULL == codec) {
380 gMissingCodecs.push_back().set(srcPath);
381 return;
382 }
383
384 SkAutoTDelete<SkImageDecoder> ad(codec);
385
386 stream.rewind();
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000387
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000388 // Create a string representing just the filename itself, for use in json expectations.
scroggo@google.comccd7afb2013-05-28 16:45:07 +0000389 SkString basename = SkOSPath::SkBasename(srcPath);
390 const char* filename = basename.c_str();
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000391
scroggo@google.com6d99de12013-08-06 18:56:53 +0000392 if (!codec->decode(&stream, &bitmap, gPrefConfig,
scroggo@google.combc91e8b2013-06-27 20:21:01 +0000393 SkImageDecoder::kDecodePixels_Mode)) {
394 if (expect_to_fail(filename)) {
395 gSuccessfulDecodes.push_back().appendf(
396 "failed to decode %s, which is a known failure.", srcPath);
397 } else {
398 gDecodeFailures.push_back().set(srcPath);
399 }
400 return;
401 }
402
scroggo@google.com6f67b3b2013-07-18 20:08:26 +0000403 // Test decoding just the bounds. The bounds should always match.
404 {
405 stream.rewind();
406 SkBitmap dim;
407 if (!codec->decode(&stream, &dim, SkImageDecoder::kDecodeBounds_Mode)) {
408 SkString failure = SkStringPrintf("failed to decode bounds for %s", srcPath);
409 gDecodeFailures.push_back() = failure;
410 } else {
411 // Now check that the bounds match:
412 if (dim.width() != bitmap.width() || dim.height() != bitmap.height()) {
413 SkString failure = SkStringPrintf("bounds do not match for %s", srcPath);
414 gDecodeFailures.push_back() = failure;
415 }
416 }
417 }
418
scroggo@google.comcd7a73c2013-08-28 18:33:31 +0000419 skiagm::GmResultDigest digest(bitmap);
420 if (compare_to_expectations_if_necessary(digest, filename,
scroggo@google.come339eb02013-08-06 18:51:30 +0000421 &gDecodeFailures,
422 &gMissingExpectations)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000423 gSuccessfulDecodes.push_back().printf("%s [%d %d]", srcPath, bitmap.width(),
424 bitmap.height());
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000425 } else if (!FLAGS_mismatchPath.isEmpty()) {
426 SkString outPath;
427 make_outname(&outPath, FLAGS_mismatchPath[0], srcPath, ".png");
428 if (write_bitmap(outPath.c_str(), bitmap)) {
429 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
430 } else {
431 gEncodeFailures.push_back().set(outPath);
432 }
433 }
434
scroggo@google.comcd7a73c2013-08-28 18:33:31 +0000435// FIXME: This test could be run on windows/mac once we remove their dependence on
436// getLength. See https://code.google.com/p/skia/issues/detail?id=1570
437#if defined(SK_BUILD_FOR_ANDROID) || defined(SK_BUILD_FOR_UNIX)
438 test_stream_without_length(srcPath, codec, digest);
439#endif
440
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000441 if (writePath != NULL) {
442 SkString outPath;
443 make_outname(&outPath, writePath->c_str(), srcPath, ".png");
444 if (write_bitmap(outPath.c_str(), bitmap)) {
445 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
446 } else {
447 gEncodeFailures.push_back().set(outPath);
448 }
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000449 }
450
451 write_expectations(bitmap, filename);
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000452
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000453 if (FLAGS_testSubsetDecoding) {
scroggo@google.com0018f752013-05-03 20:39:22 +0000454 SkDEBUGCODE(bool couldRewind =) stream.rewind();
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000455 SkASSERT(couldRewind);
456 int width, height;
457 // Build the tile index for decoding subsets. If the image is 1x1, skip subset
458 // decoding since there are no smaller subsets.
459 if (codec->buildTileIndex(&stream, &width, &height) && width > 1 && height > 1) {
460 SkASSERT(bitmap.width() == width && bitmap.height() == height);
461 // Call decodeSubset multiple times:
462 SkRandom rand(0);
463 for (int i = 0; i < 5; i++) {
464 SkBitmap bitmapFromDecodeSubset;
465 // FIXME: Come up with a more representative set of rectangles.
466 SkIRect rect = generate_random_rect(&rand, width, height);
467 SkString subsetDim = SkStringPrintf("[%d,%d,%d,%d]", rect.fLeft, rect.fTop,
468 rect.fRight, rect.fBottom);
scroggo@google.com6d99de12013-08-06 18:56:53 +0000469 if (codec->decodeSubset(&bitmapFromDecodeSubset, rect, gPrefConfig)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000470 SkString subsetName = SkStringPrintf("%s_%s", filename, subsetDim.c_str());
scroggo@google.comcd7a73c2013-08-28 18:33:31 +0000471 skiagm::GmResultDigest subsetDigest(bitmapFromDecodeSubset);
472 if (compare_to_expectations_if_necessary(subsetDigest,
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000473 subsetName.c_str(),
scroggo@google.come339eb02013-08-06 18:51:30 +0000474 &gFailedSubsetDecodes,
475 &gMissingSubsetExpectations)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000476 gSuccessfulSubsetDecodes.push_back().printf("Decoded subset %s from %s",
477 subsetDim.c_str(), srcPath);
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000478 } else if (!FLAGS_mismatchPath.isEmpty()) {
479 write_subset(FLAGS_mismatchPath[0], filename, subsetDim.c_str(),
480 &bitmapFromDecodeSubset, rect, bitmap);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000481 }
482
483 write_expectations(bitmapFromDecodeSubset, subsetName.c_str());
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000484 if (writePath != NULL) {
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000485 write_subset(writePath->c_str(), filename, subsetDim.c_str(),
486 &bitmapFromDecodeSubset, rect, bitmap);
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000487 }
488 } else {
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000489 gFailedSubsetDecodes.push_back().printf("Failed to decode region %s from %s",
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000490 subsetDim.c_str(), srcPath);
491 }
492 }
493 }
494 }
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000495
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000496 if (FLAGS_reencode) {
497 // Encode to the format the file was originally in, or PNG if the encoder for the same
498 // format is unavailable.
499 SkImageDecoder::Format format = codec->getFormat();
500 if (SkImageDecoder::kUnknown_Format == format) {
501 if (stream.rewind()) {
502 format = SkImageDecoder::GetStreamFormat(&stream);
503 }
504 if (SkImageDecoder::kUnknown_Format == format) {
505 const char* dot = strrchr(srcPath, '.');
506 if (NULL != dot) {
507 format = guess_format_from_suffix(dot);
508 }
509 if (SkImageDecoder::kUnknown_Format == format) {
510 SkDebugf("Could not determine type for '%s'\n", srcPath);
511 format = SkImageDecoder::kPNG_Format;
512 }
513
514 }
515 } else {
516 SkASSERT(!stream.rewind() || SkImageDecoder::GetStreamFormat(&stream) == format);
517 }
518 SkImageEncoder::Type type = format_to_type(format);
519 // format should never be kUnknown_Format, so type should never be kUnknown_Type.
520 SkASSERT(type != SkImageEncoder::kUnknown_Type);
521
522 SkImageEncoder* encoder = SkImageEncoder::Create(type);
523 if (NULL == encoder) {
524 type = SkImageEncoder::kPNG_Type;
525 encoder = SkImageEncoder::Create(type);
526 SkASSERT(encoder);
527 }
528 SkAutoTDelete<SkImageEncoder> ade(encoder);
529 // Encode to a stream.
530 SkDynamicMemoryWStream wStream;
531 if (!encoder->encodeStream(&wStream, bitmap, 100)) {
532 gEncodeFailures.push_back().printf("Failed to reencode %s to type '%s'", srcPath,
533 suffix_for_type(type));
534 return;
535 }
536
537 SkAutoTUnref<SkData> data(wStream.copyToData());
538 if (writePath != NULL && type != SkImageEncoder::kPNG_Type) {
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000539 // Write the encoded data to a file. Do not write to PNG, which was already written.
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000540 SkString outPath;
541 make_outname(&outPath, writePath->c_str(), srcPath, suffix_for_type(type));
542 SkFILEWStream file(outPath.c_str());
543 if(file.write(data->data(), data->size())) {
544 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
545 } else {
546 gEncodeFailures.push_back().printf("Failed to write %s", outPath.c_str());
547 }
548 }
549 // Ensure that the reencoded data can still be decoded.
550 SkMemoryStream memStream(data);
551 SkBitmap redecodedBitmap;
552 SkImageDecoder::Format formatOnSecondDecode;
scroggo@google.com6d99de12013-08-06 18:56:53 +0000553 if (SkImageDecoder::DecodeStream(&memStream, &redecodedBitmap, gPrefConfig,
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000554 SkImageDecoder::kDecodePixels_Mode,
555 &formatOnSecondDecode)) {
556 SkASSERT(format_to_type(formatOnSecondDecode) == type);
557 } else {
558 gDecodeFailures.push_back().printf("Failed to redecode %s after reencoding to '%s'",
559 srcPath, suffix_for_type(type));
560 }
561 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000562}
563
564///////////////////////////////////////////////////////////////////////////////
565
scroggo@google.comb41ff952013-04-11 15:53:35 +0000566// If strings is not empty, print title, followed by each string on its own line starting
567// with a tab.
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000568// @return bool True if strings had at least one entry.
569static bool print_strings(const char* title, const SkTArray<SkString, false>& strings) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000570 if (strings.count() > 0) {
571 SkDebugf("%s:\n", title);
572 for (int i = 0; i < strings.count(); i++) {
573 SkDebugf("\t%s\n", strings[i].c_str());
574 }
575 SkDebugf("\n");
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000576 return true;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000577 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000578 return false;
reed@android.comaf459792009-04-24 19:52:53 +0000579}
580
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000581/**
582 * If directory is non null and does not end with a path separator, append one.
583 * @param directory SkString representing the path to a directory. If the last character is not a
584 * path separator (specific to the current OS), append one.
585 */
586static void append_path_separator_if_necessary(SkString* directory) {
587 if (directory != NULL && directory->c_str()[directory->size() - 1] != SkPATH_SEPARATOR) {
588 directory->appendf("%c", SkPATH_SEPARATOR);
589 }
590}
591
scroggo@google.com925cdca2013-06-28 20:04:42 +0000592/**
593 * Return true if the filename represents an image.
594 */
595static bool is_image_file(const char* filename) {
596 const char* gImageExtensions[] = {
597 ".png", ".PNG", ".jpg", ".JPG", ".jpeg", ".JPEG", ".bmp", ".BMP",
598 ".webp", ".WEBP", ".ico", ".ICO", ".wbmp", ".WBMP", ".gif", ".GIF"
599 };
600 for (size_t i = 0; i < SK_ARRAY_COUNT(gImageExtensions); ++i) {
601 if (SkStrEndsWith(filename, gImageExtensions[i])) {
602 return true;
603 }
604 }
605 return false;
606}
607
caryclark@google.com5987f582012-10-02 18:33:14 +0000608int tool_main(int argc, char** argv);
609int tool_main(int argc, char** argv) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000610 SkCommandLineFlags::SetUsage("Decode files, and optionally write the results to files.");
611 SkCommandLineFlags::Parse(argc, argv);
612
613 if (FLAGS_readPath.count() < 1) {
614 SkDebugf("Folder(s) or image(s) to decode are required.\n");
615 return -1;
616 }
617
618
reed@android.comaf459792009-04-24 19:52:53 +0000619 SkAutoGraphics ag;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000620
scroggo@google.com3832da12013-06-19 19:12:53 +0000621 if (!FLAGS_readExpectationsPath.isEmpty() && sk_exists(FLAGS_readExpectationsPath[0])) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000622 gJsonExpectations.reset(SkNEW_ARGS(skiagm::JsonExpectationsSource,
623 (FLAGS_readExpectationsPath[0])));
624 }
625
reed@android.comaf459792009-04-24 19:52:53 +0000626 SkString outDir;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000627 SkString* outDirPtr;
reed@android.comaf459792009-04-24 19:52:53 +0000628
scroggo@google.comb41ff952013-04-11 15:53:35 +0000629 if (FLAGS_writePath.count() == 1) {
630 outDir.set(FLAGS_writePath[0]);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000631 append_path_separator_if_necessary(&outDir);
scroggo@google.comb41ff952013-04-11 15:53:35 +0000632 outDirPtr = &outDir;
633 } else {
634 outDirPtr = NULL;
635 }
636
scroggo@google.com6d99de12013-08-06 18:56:53 +0000637 if (FLAGS_config.count() == 1) {
638 // Only consider the first config specified on the command line.
639 const char* config = FLAGS_config[0];
640 if (0 == strcmp(config, "8888")) {
641 gPrefConfig = SkBitmap::kARGB_8888_Config;
642 } else if (0 == strcmp(config, "565")) {
643 gPrefConfig = SkBitmap::kRGB_565_Config;
644 } else if (0 == strcmp(config, "A8")) {
645 gPrefConfig = SkBitmap::kA8_Config;
646 } else if (0 != strcmp(config, "None")) {
647 SkDebugf("Invalid preferred config\n");
648 return -1;
649 }
650 }
651
scroggo@google.comb41ff952013-04-11 15:53:35 +0000652 for (int i = 0; i < FLAGS_readPath.count(); i++) {
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000653 const char* readPath = FLAGS_readPath[i];
654 if (strlen(readPath) < 1) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000655 break;
656 }
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000657 if (sk_isdir(readPath)) {
658 const char* dir = readPath;
659 SkOSFile::Iter iter(dir);
660 SkString filename;
661 while (iter.next(&filename)) {
scroggo@google.com925cdca2013-06-28 20:04:42 +0000662 if (!is_image_file(filename.c_str())) {
663 continue;
664 }
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000665 SkString fullname = SkOSPath::SkPathJoin(dir, filename.c_str());
scroggo@google.comb41ff952013-04-11 15:53:35 +0000666 decodeFileAndWrite(fullname.c_str(), outDirPtr);
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000667 }
scroggo@google.com925cdca2013-06-28 20:04:42 +0000668 } else if (sk_exists(readPath) && is_image_file(readPath)) {
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000669 decodeFileAndWrite(readPath, outDirPtr);
reed@android.comaf459792009-04-24 19:52:53 +0000670 }
671 }
672
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000673 if (!FLAGS_createExpectationsPath.isEmpty()) {
674 // Use an empty value for everything besides expectations, since the reader only cares
675 // about the expectations.
676 Json::Value nullValue;
677 Json::Value root = skiagm::CreateJsonTree(gExpectationsToWrite, nullValue, nullValue,
678 nullValue, nullValue);
679 std::string jsonStdString = root.toStyledString();
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000680 SkFILEWStream stream(FLAGS_createExpectationsPath[0]);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000681 stream.write(jsonStdString.c_str(), jsonStdString.length());
682 }
scroggo@google.comb41ff952013-04-11 15:53:35 +0000683 // Add some space, since codecs may print warnings without newline.
684 SkDebugf("\n\n");
rmistry@google.comd6176b02012-08-23 18:14:13 +0000685
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000686 bool failed = print_strings("Invalid files", gInvalidStreams);
687 failed |= print_strings("Missing codec", gMissingCodecs);
688 failed |= print_strings("Failed to decode", gDecodeFailures);
689 failed |= print_strings("Failed to encode", gEncodeFailures);
690 print_strings("Decoded", gSuccessfulDecodes);
scroggo@google.come339eb02013-08-06 18:51:30 +0000691 print_strings("Missing expectations", gMissingExpectations);
reed@android.comaf459792009-04-24 19:52:53 +0000692
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000693 if (FLAGS_testSubsetDecoding) {
694 failed |= print_strings("Failed subset decodes", gFailedSubsetDecodes);
695 print_strings("Decoded subsets", gSuccessfulSubsetDecodes);
scroggo@google.come339eb02013-08-06 18:51:30 +0000696 print_strings("Missing subset expectations", gMissingSubsetExpectations);
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000697 }
698
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000699 return failed ? -1 : 0;
reed@android.comaf459792009-04-24 19:52:53 +0000700}
701
caryclark@google.com5987f582012-10-02 18:33:14 +0000702#if !defined SK_BUILD_FOR_IOS
703int main(int argc, char * const argv[]) {
704 return tool_main(argc, (char**) argv);
705}
706#endif