2 * Copyright 2011 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #include "gm_expectations.h"
10 #include "SkColorPriv.h"
11 #include "SkCommandLineFlags.h"
13 #include "SkForceLinking.h"
14 #include "SkGraphics.h"
15 #include "SkImageDecoder.h"
16 #include "SkImageEncoder.h"
21 #include "SkTemplates.h"
23 __SK_FORCE_IMAGE_DECODER_LINKING;
25 DEFINE_string(config, "None", "Preferred config to decode into. [None|8888|565|A8]");
26 DEFINE_string(createExpectationsPath, "", "Path to write JSON expectations.");
27 DEFINE_string(mismatchPath, "", "Folder to write mismatched images to.");
28 DEFINE_string2(readPath, r, "", "Folder(s) and files to decode images. Required.");
29 DEFINE_string(readExpectationsPath, "", "Path to read JSON expectations from.");
30 DEFINE_bool(reencode, true, "Reencode the images to test encoding.");
31 DEFINE_int32(sampleSize, 1, "Set the sampleSize for decoding.");
32 DEFINE_bool(skip, false, "Skip writing zeroes.");
33 DEFINE_bool(testSubsetDecoding, true, "Test decoding subsets of images.");
34 DEFINE_bool(writeChecksumBasedFilenames, false, "When writing out actual images, use checksum-"
35 "based filenames, as rebaseline.py will use when downloading them from Google Storage");
36 DEFINE_string2(writePath, w, "", "Write rendered images into this directory.");
39 SkImageEncoder::Type fType;
40 SkImageDecoder::Format fFormat;
44 static const Format gFormats[] = {
45 { SkImageEncoder::kBMP_Type, SkImageDecoder::kBMP_Format, ".bmp" },
46 { SkImageEncoder::kGIF_Type, SkImageDecoder::kGIF_Format, ".gif" },
47 { SkImageEncoder::kICO_Type, SkImageDecoder::kICO_Format, ".ico" },
48 { SkImageEncoder::kJPEG_Type, SkImageDecoder::kJPEG_Format, ".jpg" },
49 { SkImageEncoder::kPNG_Type, SkImageDecoder::kPNG_Format, ".png" },
50 { SkImageEncoder::kWBMP_Type, SkImageDecoder::kWBMP_Format, ".wbmp" },
51 { SkImageEncoder::kWEBP_Type, SkImageDecoder::kWEBP_Format, ".webp" }
54 static SkImageEncoder::Type format_to_type(SkImageDecoder::Format format) {
55 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
56 if (gFormats[i].fFormat == format) {
57 return gFormats[i].fType;
60 return SkImageEncoder::kUnknown_Type;
63 static const char* suffix_for_type(SkImageEncoder::Type type) {
64 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
65 if (gFormats[i].fType == type) {
66 return gFormats[i].fSuffix;
72 static SkImageDecoder::Format guess_format_from_suffix(const char suffix[]) {
73 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
74 if (strcmp(suffix, gFormats[i].fSuffix) == 0) {
75 return gFormats[i].fFormat;
78 return SkImageDecoder::kUnknown_Format;
81 static void make_outname(SkString* dst, const char outDir[], const char src[],
82 const char suffix[]) {
83 SkString basename = SkOSPath::Basename(src);
84 dst->set(SkOSPath::Join(outDir, basename.c_str()));
88 // Store the names of the filenames to report later which ones failed, succeeded, and were
90 // FIXME: Add more arrays, for more specific types of errors, and make the output simpler.
91 // If each array holds one type of error, the output can change from:
94 // <image> failed for such and such reason
95 // <image> failed for some different reason
99 // Such and such failures:
102 // Different reason failures:
105 static SkTArray<SkString, false> gInvalidStreams;
106 static SkTArray<SkString, false> gMissingCodecs;
107 static SkTArray<SkString, false> gDecodeFailures;
108 static SkTArray<SkString, false> gEncodeFailures;
109 static SkTArray<SkString, false> gSuccessfulDecodes;
110 static SkTArray<SkString, false> gSuccessfulSubsetDecodes;
111 static SkTArray<SkString, false> gFailedSubsetDecodes;
112 // Files/subsets that do not have expectations. Not reported as a failure of the test so
113 // the bots will not turn red with each new image test.
114 static SkTArray<SkString, false> gMissingExpectations;
115 static SkTArray<SkString, false> gMissingSubsetExpectations;
116 // For files that are expected to fail.
117 static SkTArray<SkString, false> gKnownFailures;
118 static SkTArray<SkString, false> gKnownSubsetFailures;
120 static SkColorType gPrefColorType(kUnknown_SkColorType);
122 // Expections read from a file specified by readExpectationsPath. The expectations must have been
123 // previously written using createExpectationsPath.
124 SkAutoTUnref<skiagm::JsonExpectationsSource> gJsonExpectations;
127 * Encode the bitmap to a file, written one of two ways, depending on
128 * FLAGS_writeChecksumBasedFilenames. If true, the final image will be
130 * outDir/hashType/src/digestValue.png
131 * If false, the final image will be written out to:
133 * The function returns whether the file was successfully written.
135 static bool write_bitmap(const char outDir[], const char src[],
136 const skiagm::BitmapAndDigest& bitmapAndDigest) {
138 if (FLAGS_writeChecksumBasedFilenames) {
139 // First create the directory for the hashtype.
140 const SkString hashType = bitmapAndDigest.fDigest.getHashType();
141 const SkString hashDir = SkOSPath::Join(outDir, hashType.c_str());
142 if (!sk_mkdir(hashDir.c_str())) {
146 // Now create the name of the folder specific to this image.
147 SkString basename = SkOSPath::Basename(src);
148 const SkString imageDir = SkOSPath::Join(hashDir.c_str(), basename.c_str());
149 if (!sk_mkdir(imageDir.c_str())) {
153 // Name the file <digest>.png
154 SkString checksumBasedName = bitmapAndDigest.fDigest.getDigestValue();
155 checksumBasedName.append(".png");
157 filename = SkOSPath::Join(imageDir.c_str(), checksumBasedName.c_str());
159 make_outname(&filename, outDir, src, ".png");
162 const SkBitmap& bm = bitmapAndDigest.fBitmap;
163 if (SkImageEncoder::EncodeFile(filename.c_str(), bm, SkImageEncoder::kPNG_Type, 100)) {
167 if (bm.colorType() == kN32_SkColorType) {
168 // First attempt at encoding failed, and the bitmap was already 8888. Making
169 // a copy is not going to help.
173 // Encoding failed. Copy to 8888 and try again.
175 if (!bm.copyTo(&bm8888, kN32_SkColorType)) {
178 return SkImageEncoder::EncodeFile(filename.c_str(), bm8888, SkImageEncoder::kPNG_Type, 100);
182 * Return a random SkIRect inside the range specified.
183 * @param rand Random number generator.
184 * @param maxX Exclusive maximum x-coordinate. SkIRect's fLeft and fRight will be
185 * in the range [0, maxX)
186 * @param maxY Exclusive maximum y-coordinate. SkIRect's fTop and fBottom will be
187 * in the range [0, maxY)
188 * @return SkIRect Non-empty, non-degenerate rectangle.
190 static SkIRect generate_random_rect(SkRandom* rand, int32_t maxX, int32_t maxY) {
191 SkASSERT(maxX > 1 && maxY > 1);
192 int32_t left = rand->nextULessThan(maxX);
193 int32_t right = rand->nextULessThan(maxX);
194 int32_t top = rand->nextULessThan(maxY);
195 int32_t bottom = rand->nextULessThan(maxY);
196 SkIRect rect = SkIRect::MakeLTRB(left, top, right, bottom);
198 // Make sure rect is not empty.
199 if (rect.fLeft == rect.fRight) {
200 if (rect.fLeft > 0) {
204 // This branch is only taken if 0 == rect.fRight, and
205 // maxX must be at least 2, so it must still be in
207 SkASSERT(rect.fRight < maxX);
210 if (rect.fTop == rect.fBottom) {
215 // Again, this must be in range.
216 SkASSERT(rect.fBottom < maxY);
223 * Return a string which includes the name of the file and the preferred config,
224 * as specified by "--config". The resulting string will match the pattern of
225 * gm_json.py's IMAGE_FILENAME_PATTERN: "filename_config.png"
227 static SkString create_json_key(const char* filename) {
228 SkASSERT(FLAGS_config.count() == 1);
229 return SkStringPrintf("%s_%s.png", filename, FLAGS_config[0]);
232 // Stored expectations to be written to a file if createExpectationsPath is specified.
233 static Json::Value gExpectationsToWrite;
236 * If expectations are to be recorded, record the bitmap expectations into the global
237 * expectations array.
238 * As is the case with reading expectations, the key used will combine the filename
239 * parameter with the preferred config, as specified by "--config", matching the
240 * pattern of gm_json.py's IMAGE_FILENAME_PATTERN: "filename_config.png"
242 static void write_expectations(const skiagm::BitmapAndDigest& bitmapAndDigest,
243 const char* filename) {
244 const SkString name_config = create_json_key(filename);
245 if (!FLAGS_createExpectationsPath.isEmpty()) {
246 // Creates an Expectations object, and add it to the list to write.
247 skiagm::Expectations expectation(bitmapAndDigest);
248 Json::Value value = expectation.asJsonValue();
249 gExpectationsToWrite[name_config.c_str()] = value;
254 * If --readExpectationsPath is set, compare this bitmap to the json expectations
257 * @param digest GmResultDigest, computed from the decoded bitmap, to compare to
258 * the existing expectation.
259 * @param filename String used to find the expected value. Will be combined with the
260 * preferred config, as specified by "--config", to match the pattern of
261 * gm_json.py's IMAGE_FILENAME_PATTERN: "filename_config.png". The resulting
262 * key will be used to find the proper expectations.
263 * @param failureArray Array to add a failure message to on failure.
264 * @param missingArray Array to add failure message to when missing image
266 * @param ignoreArray Array to add failure message to when the image does not match
267 * the expectation, but this is a failure we can ignore.
268 * @return bool True in any of these cases:
269 * - the bitmap matches the expectation.
270 * False in any of these cases:
271 * - there is no expectations file.
272 * - there is an expectations file, but no expectation for this bitmap.
273 * - there is an expectation for this bitmap, but it did not match.
274 * - expectation could not be computed from the bitmap.
276 static bool compare_to_expectations_if_necessary(const skiagm::GmResultDigest& digest,
277 const char* filename,
278 SkTArray<SkString, false>* failureArray,
279 SkTArray<SkString, false>* missingArray,
280 SkTArray<SkString, false>* ignoreArray) {
281 // For both writing and reading, the key for this entry will include the name
282 // of the file and the pref config, matching the pattern of gm_json.py's
283 // IMAGE_FILENAME_PATTERN: "name_config.png"
284 const SkString name_config = create_json_key(filename);
286 if (!digest.isValid()) {
287 if (failureArray != NULL) {
288 failureArray->push_back().printf("decoded %s, but could not create a GmResultDigest.",
294 if (NULL == gJsonExpectations.get()) {
298 skiagm::Expectations jsExpectation = gJsonExpectations->get(name_config.c_str());
299 if (jsExpectation.empty()) {
300 if (missingArray != NULL) {
301 missingArray->push_back().printf("decoded %s, but could not find expectation.",
307 if (jsExpectation.match(digest)) {
311 if (jsExpectation.ignoreFailure()) {
312 ignoreArray->push_back().printf("%s does not match expectation, but this is known.",
314 } else if (failureArray != NULL) {
315 failureArray->push_back().printf("decoded %s, but the result does not match "
323 * Helper function to write a bitmap subset to a file. Only called if subsets were created
324 * and a writePath was provided. Behaves differently depending on
325 * FLAGS_writeChecksumBasedFilenames. If true:
326 * Writes the image to a PNG file named according to the digest hash, as described in
329 * Creates a subdirectory called 'subsets' and writes a PNG to that directory. Also
330 * creates a subdirectory called 'extracted' and writes a bitmap created using
331 * extractSubset to a PNG in that directory. Both files will represent the same
332 * subrectangle and have the same name for convenient comparison. In this case, the
335 * @param writePath Parent directory to hold the folders for the PNG files to write. Must
337 * @param subsetName Basename of the original file, with the dimensions of the subset tacked
338 * on. Used to name the new file/folder.
339 * @param bitmapAndDigestFromDecodeSubset SkBitmap (with digest) created by
340 * SkImageDecoder::DecodeSubset, using rect as the area to decode.
341 * @param rect Rectangle of the area decoded into bitmapFromDecodeSubset. Used to call
342 * extractSubset on originalBitmap to create a bitmap with the same dimensions/pixels as
343 * bitmapFromDecodeSubset (assuming decodeSubset worked properly).
344 * @param originalBitmap SkBitmap decoded from the same stream as bitmapFromDecodeSubset,
345 * using SkImageDecoder::decode to get the entire image. Used to create a PNG file for
346 * comparison to the PNG created by bitmapAndDigestFromDecodeSubset's bitmap.
347 * @return bool Whether the function succeeded at drawing the decoded subset and the extracted
350 static bool write_subset(const char* writePath, const SkString& subsetName,
351 const skiagm::BitmapAndDigest bitmapAndDigestFromDecodeSubset,
352 SkIRect rect, const SkBitmap& originalBitmap) {
353 // All parameters must be valid.
354 SkASSERT(writePath != NULL);
357 if (FLAGS_writeChecksumBasedFilenames) {
358 subsetPath.set(writePath);
360 // Create a subdirectory to hold the results of decodeSubset.
361 subsetPath = SkOSPath::Join(writePath, "subsets");
362 if (!sk_mkdir(subsetPath.c_str())) {
363 gFailedSubsetDecodes.push_back().printf("Successfully decoded subset %s, but "
364 "failed to create a directory to write to.",
369 SkAssertResult(write_bitmap(subsetPath.c_str(), subsetName.c_str(),
370 bitmapAndDigestFromDecodeSubset));
371 gSuccessfulSubsetDecodes.push_back().printf("\twrote %s", subsetName.c_str());
373 if (!FLAGS_writeChecksumBasedFilenames) {
374 // FIXME: The goal of extracting the subset is for visual comparison/using skdiff/skpdiff.
375 // Currently disabling for writeChecksumBasedFilenames since it will be trickier to
376 // determine which files to compare.
378 // Also use extractSubset from the original for visual comparison.
379 // Write the result to a file in a separate subdirectory.
380 SkBitmap extractedSubset;
381 if (!originalBitmap.extractSubset(&extractedSubset, rect)) {
382 gFailedSubsetDecodes.push_back().printf("Successfully decoded subset %s, but failed "
383 "to extract a similar subset for comparison.",
388 SkString dirExtracted = SkOSPath::Join(writePath, "extracted");
389 if (!sk_mkdir(dirExtracted.c_str())) {
390 gFailedSubsetDecodes.push_back().printf("Successfully decoded subset%s, but failed "
391 "to create a directory for extractSubset "
397 skiagm::BitmapAndDigest bitmapAndDigestFromExtractSubset(extractedSubset);
398 SkAssertResult(write_bitmap(dirExtracted.c_str(), subsetName.c_str(),
399 bitmapAndDigestFromExtractSubset));
404 // FIXME: This test could be run on windows/mac once we remove their dependence on
405 // getLength. See https://code.google.com/p/skia/issues/detail?id=1570
406 #if defined(SK_BUILD_FOR_ANDROID) || defined(SK_BUILD_FOR_UNIX)
409 * Dummy class for testing to ensure that a stream without a length decodes the same
410 * as a stream with a length.
412 class FILEStreamWithoutLength : public SkFILEStream {
414 FILEStreamWithoutLength(const char path[])
417 virtual bool hasLength() const SK_OVERRIDE {
422 typedef SkFILEStream INHERITED;
426 * Test that decoding a stream which reports to not have a length still results in the
427 * same image as if it did report to have a length. Assumes that codec was used to
428 * successfully decode the file using SkFILEStream.
429 * @param srcPath The path to the file, for recreating the length-less stream.
430 * @param codec The SkImageDecoder originally used to decode srcPath, which will be used
431 * again to decode the length-less stream.
432 * @param digest GmResultDigest computed from decoding the stream the first time.
433 * Decoding the length-less stream is expected to result in a matching digest.
435 static void test_stream_without_length(const char srcPath[], SkImageDecoder* codec,
436 const skiagm::GmResultDigest& digest) {
437 if (!digest.isValid()) {
438 // An error was already reported.
443 FILEStreamWithoutLength stream(srcPath);
444 // This will only be called after a successful decode. Creating a stream from the same
445 // path should never fail.
446 SkASSERT(stream.isValid());
448 if (!codec->decode(&stream, &bm, gPrefColorType, SkImageDecoder::kDecodePixels_Mode)) {
449 gDecodeFailures.push_back().appendf("Without using getLength, %s failed to decode\n",
453 skiagm::GmResultDigest lengthLessDigest(bm);
454 if (!lengthLessDigest.isValid()) {
455 gDecodeFailures.push_back().appendf("Without using getLength, %s failed to build "
456 "a digest\n", srcPath);
459 if (!lengthLessDigest.equals(digest)) {
460 gDecodeFailures.push_back().appendf("Without using getLength, %s did not match digest "
461 "that uses getLength\n", srcPath);
464 #endif // defined(SK_BUILD_FOR_ANDROID) || defined(SK_BUILD_FOR_UNIX)
467 * Replaces all instances of oldChar with newChar in str.
469 * TODO: This function appears here and in picture_utils.[cpp|h] ;
470 * we should add the implementation to src/core/SkString.cpp, write tests for it,
471 * and remove it from elsewhere.
473 static void replace_char(SkString* str, const char oldChar, const char newChar) {
477 for (size_t i = 0; i < str->size(); ++i) {
478 if (oldChar == str->operator[](i)) {
479 str->operator[](i) = newChar;
484 static void decodeFileAndWrite(const char srcPath[], const SkString* writePath) {
486 SkFILEStream stream(srcPath);
487 if (!stream.isValid()) {
488 gInvalidStreams.push_back().set(srcPath);
492 SkImageDecoder* codec = SkImageDecoder::Factory(&stream);
494 gMissingCodecs.push_back().set(srcPath);
498 SkAutoTDelete<SkImageDecoder> ad(codec);
500 codec->setSkipWritingZeroes(FLAGS_skip);
501 codec->setSampleSize(FLAGS_sampleSize);
504 // Create a string representing just the filename itself, for use in json expectations.
505 SkString basename = SkOSPath::Basename(srcPath);
506 // Replace '_' with '-', so that the names can fit gm_json.py's IMAGE_FILENAME_PATTERN
507 replace_char(&basename, '_', '-');
508 // Replace '.' with '-', so the output filename can still retain the original file extension,
509 // but still end up with only one '.', which denotes the actual extension of the final file.
510 replace_char(&basename, '.', '-');
511 const char* filename = basename.c_str();
513 if (!codec->decode(&stream, &bitmap, gPrefColorType, SkImageDecoder::kDecodePixels_Mode)) {
514 if (NULL != gJsonExpectations.get()) {
515 const SkString name_config = create_json_key(filename);
516 skiagm::Expectations jsExpectations = gJsonExpectations->get(name_config.c_str());
517 if (jsExpectations.ignoreFailure()) {
518 // This is a known failure.
519 gKnownFailures.push_back().appendf(
520 "failed to decode %s, which is a known failure.", srcPath);
523 if (jsExpectations.empty()) {
524 // This is a failure, but it is a new file. Mark it as missing, with
525 // a note that it should be marked failing.
526 gMissingExpectations.push_back().appendf(
527 "new file %s (with no expectations) FAILED to decode.", srcPath);
532 // If there was a failure, and either there was no expectations file, or
533 // the expectations file listed a valid expectation, report the failure.
534 gDecodeFailures.push_back().set(srcPath);
538 // Test decoding just the bounds. The bounds should always match.
542 if (!codec->decode(&stream, &dim, SkImageDecoder::kDecodeBounds_Mode)) {
543 SkString failure = SkStringPrintf("failed to decode bounds for %s", srcPath);
544 gDecodeFailures.push_back() = failure;
546 // Now check that the bounds match:
547 if (dim.width() != bitmap.width() || dim.height() != bitmap.height()) {
548 SkString failure = SkStringPrintf("bounds do not match for %s", srcPath);
549 gDecodeFailures.push_back() = failure;
554 skiagm::BitmapAndDigest bitmapAndDigest(bitmap);
555 if (compare_to_expectations_if_necessary(bitmapAndDigest.fDigest, filename, &gDecodeFailures,
556 &gMissingExpectations, &gKnownFailures)) {
557 gSuccessfulDecodes.push_back().printf("%s [%d %d]", srcPath, bitmap.width(),
559 } else if (!FLAGS_mismatchPath.isEmpty()) {
560 if (write_bitmap(FLAGS_mismatchPath[0], filename, bitmapAndDigest)) {
561 gSuccessfulDecodes.push_back().appendf("\twrote %s", filename);
563 gEncodeFailures.push_back().set(filename);
567 // FIXME: This test could be run on windows/mac once we remove their dependence on
568 // getLength. See https://code.google.com/p/skia/issues/detail?id=1570
569 #if defined(SK_BUILD_FOR_ANDROID) || defined(SK_BUILD_FOR_UNIX)
570 test_stream_without_length(srcPath, codec, bitmapAndDigest.fDigest);
573 if (writePath != NULL) {
574 if (write_bitmap(writePath->c_str(), filename, bitmapAndDigest)) {
575 gSuccessfulDecodes.push_back().appendf("\twrote %s", filename);
577 gEncodeFailures.push_back().set(filename);
581 write_expectations(bitmapAndDigest, filename);
583 if (FLAGS_testSubsetDecoding) {
584 SkDEBUGCODE(bool couldRewind =) stream.rewind();
585 SkASSERT(couldRewind);
587 // Build the tile index for decoding subsets. If the image is 1x1, skip subset
588 // decoding since there are no smaller subsets.
589 if (codec->buildTileIndex(&stream, &width, &height) && width > 1 && height > 1) {
590 SkASSERT((bitmap.width() == width && bitmap.height() == height)
591 || FLAGS_sampleSize != 1);
592 // Call decodeSubset multiple times:
594 for (int i = 0; i < 5; i++) {
595 SkBitmap bitmapFromDecodeSubset;
596 // FIXME: Come up with a more representative set of rectangles.
597 SkIRect rect = generate_random_rect(&rand, width, height);
598 SkString subsetDim = SkStringPrintf("%d_%d_%d_%d", rect.fLeft, rect.fTop,
599 rect.fRight, rect.fBottom);
600 if (codec->decodeSubset(&bitmapFromDecodeSubset, rect, gPrefColorType)) {
601 SkString subsetName = SkStringPrintf("%s-%s", filename, subsetDim.c_str());
602 skiagm::BitmapAndDigest subsetBitmapAndDigest(bitmapFromDecodeSubset);
603 if (compare_to_expectations_if_necessary(subsetBitmapAndDigest.fDigest,
605 &gFailedSubsetDecodes,
606 &gMissingSubsetExpectations,
607 &gKnownSubsetFailures)) {
608 gSuccessfulSubsetDecodes.push_back().printf("Decoded subset %s from %s",
609 subsetDim.c_str(), srcPath);
610 } else if (!FLAGS_mismatchPath.isEmpty()) {
611 write_subset(FLAGS_mismatchPath[0], subsetName,
612 subsetBitmapAndDigest, rect, bitmap);
615 write_expectations(subsetBitmapAndDigest, subsetName.c_str());
617 if (writePath != NULL) {
618 write_subset(writePath->c_str(), subsetName,
619 subsetBitmapAndDigest, rect, bitmap);
622 gFailedSubsetDecodes.push_back().printf("Failed to decode region %s from %s",
623 subsetDim.c_str(), srcPath);
629 // Do not attempt to re-encode A8, since our image encoders do not support encoding to A8.
630 if (FLAGS_reencode && bitmap.colorType() != kAlpha_8_SkColorType) {
631 // Encode to the format the file was originally in, or PNG if the encoder for the same
632 // format is unavailable.
633 SkImageDecoder::Format format = codec->getFormat();
634 if (SkImageDecoder::kUnknown_Format == format) {
635 if (stream.rewind()) {
636 format = SkImageDecoder::GetStreamFormat(&stream);
638 if (SkImageDecoder::kUnknown_Format == format) {
639 const char* dot = strrchr(srcPath, '.');
641 format = guess_format_from_suffix(dot);
643 if (SkImageDecoder::kUnknown_Format == format) {
644 SkDebugf("Could not determine type for '%s'\n", srcPath);
645 format = SkImageDecoder::kPNG_Format;
650 SkASSERT(!stream.rewind() || SkImageDecoder::GetStreamFormat(&stream) == format);
652 SkImageEncoder::Type type = format_to_type(format);
653 // format should never be kUnknown_Format, so type should never be kUnknown_Type.
654 SkASSERT(type != SkImageEncoder::kUnknown_Type);
656 SkImageEncoder* encoder = SkImageEncoder::Create(type);
657 if (NULL == encoder) {
658 type = SkImageEncoder::kPNG_Type;
659 encoder = SkImageEncoder::Create(type);
662 SkAutoTDelete<SkImageEncoder> ade(encoder);
663 // Encode to a stream.
664 SkDynamicMemoryWStream wStream;
665 if (!encoder->encodeStream(&wStream, bitmap, 100)) {
666 gEncodeFailures.push_back().printf("Failed to reencode %s to type '%s'", srcPath,
667 suffix_for_type(type));
671 SkAutoTUnref<SkData> data(wStream.copyToData());
672 if (writePath != NULL && type != SkImageEncoder::kPNG_Type) {
673 // Write the encoded data to a file. Do not write to PNG, which was already written.
675 make_outname(&outPath, writePath->c_str(), filename, suffix_for_type(type));
676 SkFILEWStream file(outPath.c_str());
677 if(file.write(data->data(), data->size())) {
678 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
680 gEncodeFailures.push_back().printf("Failed to write %s", outPath.c_str());
683 // Ensure that the reencoded data can still be decoded.
684 SkMemoryStream memStream(data);
685 SkBitmap redecodedBitmap;
686 SkImageDecoder::Format formatOnSecondDecode;
687 if (SkImageDecoder::DecodeStream(&memStream, &redecodedBitmap, gPrefColorType,
688 SkImageDecoder::kDecodePixels_Mode,
689 &formatOnSecondDecode)) {
690 SkASSERT(format_to_type(formatOnSecondDecode) == type);
692 gDecodeFailures.push_back().printf("Failed to redecode %s after reencoding to '%s'",
693 srcPath, suffix_for_type(type));
698 ///////////////////////////////////////////////////////////////////////////////
700 // If strings is not empty, print title, followed by each string on its own line starting
702 // @return bool True if strings had at least one entry.
703 static bool print_strings(const char* title, const SkTArray<SkString, false>& strings) {
704 if (strings.count() > 0) {
705 SkDebugf("%s:\n", title);
706 for (int i = 0; i < strings.count(); i++) {
707 SkDebugf("\t%s\n", strings[i].c_str());
716 * If directory is non null and does not end with a path separator, append one.
717 * @param directory SkString representing the path to a directory. If the last character is not a
718 * path separator (specific to the current OS), append one.
720 static void append_path_separator_if_necessary(SkString* directory) {
721 if (directory != NULL && directory->c_str()[directory->size() - 1] != SkPATH_SEPARATOR) {
722 directory->appendf("%c", SkPATH_SEPARATOR);
727 * Return true if the filename represents an image.
729 static bool is_image_file(const char* filename) {
730 const char* gImageExtensions[] = {
731 ".png", ".PNG", ".jpg", ".JPG", ".jpeg", ".JPEG", ".bmp", ".BMP",
732 ".webp", ".WEBP", ".ico", ".ICO", ".wbmp", ".WBMP", ".gif", ".GIF"
734 for (size_t i = 0; i < SK_ARRAY_COUNT(gImageExtensions); ++i) {
735 if (SkStrEndsWith(filename, gImageExtensions[i])) {
742 int tool_main(int argc, char** argv);
743 int tool_main(int argc, char** argv) {
744 SkCommandLineFlags::SetUsage("Decode files, and optionally write the results to files.");
745 SkCommandLineFlags::Parse(argc, argv);
747 if (FLAGS_readPath.count() < 1) {
748 SkDebugf("Folder(s) or image(s) to decode are required.\n");
755 if (!FLAGS_readExpectationsPath.isEmpty() && sk_exists(FLAGS_readExpectationsPath[0])) {
756 gJsonExpectations.reset(SkNEW_ARGS(skiagm::JsonExpectationsSource,
757 (FLAGS_readExpectationsPath[0])));
763 if (FLAGS_writePath.count() == 1) {
764 outDir.set(FLAGS_writePath[0]);
765 append_path_separator_if_necessary(&outDir);
771 if (FLAGS_config.count() == 1) {
772 // Only consider the first config specified on the command line.
773 const char* config = FLAGS_config[0];
774 if (0 == strcmp(config, "8888")) {
775 gPrefColorType = kN32_SkColorType;
776 } else if (0 == strcmp(config, "565")) {
777 gPrefColorType = kRGB_565_SkColorType;
778 } else if (0 == strcmp(config, "A8")) {
779 gPrefColorType = kAlpha_8_SkColorType;
780 } else if (0 != strcmp(config, "None")) {
781 SkDebugf("Invalid preferred config\n");
786 for (int i = 0; i < FLAGS_readPath.count(); i++) {
787 const char* readPath = FLAGS_readPath[i];
788 if (strlen(readPath) < 1) {
791 if (sk_isdir(readPath)) {
792 const char* dir = readPath;
793 SkOSFile::Iter iter(dir);
795 while (iter.next(&filename)) {
796 if (!is_image_file(filename.c_str())) {
799 SkString fullname = SkOSPath::Join(dir, filename.c_str());
800 decodeFileAndWrite(fullname.c_str(), outDirPtr);
802 } else if (sk_exists(readPath) && is_image_file(readPath)) {
803 decodeFileAndWrite(readPath, outDirPtr);
807 if (!FLAGS_createExpectationsPath.isEmpty()) {
808 // Use an empty value for everything besides expectations, since the reader only cares
809 // about the expectations.
810 Json::Value nullValue;
811 Json::Value root = skiagm::CreateJsonTree(gExpectationsToWrite, nullValue, nullValue,
812 nullValue, nullValue);
813 std::string jsonStdString = root.toStyledString();
814 SkFILEWStream stream(FLAGS_createExpectationsPath[0]);
815 stream.write(jsonStdString.c_str(), jsonStdString.length());
817 // Add some space, since codecs may print warnings without newline.
820 bool failed = print_strings("Invalid files", gInvalidStreams);
821 failed |= print_strings("Missing codec", gMissingCodecs);
822 failed |= print_strings("Failed to decode", gDecodeFailures);
823 failed |= print_strings("Failed to encode", gEncodeFailures);
824 print_strings("Decoded", gSuccessfulDecodes);
825 print_strings("Missing expectations", gMissingExpectations);
827 if (FLAGS_testSubsetDecoding) {
828 failed |= print_strings("Failed subset decodes", gFailedSubsetDecodes);
829 print_strings("Decoded subsets", gSuccessfulSubsetDecodes);
830 print_strings("Missing subset expectations", gMissingSubsetExpectations);
831 print_strings("Known subset failures", gKnownSubsetFailures);
834 print_strings("Known failures", gKnownFailures);
836 return failed ? -1 : 0;
839 #if !defined SK_BUILD_FOR_IOS
840 int main(int argc, char * const argv[]) {
841 return tool_main(argc, (char**) argv);