blob: ef5c133fc6ba55e8b1003efb5faa261e622cebc8 [file] [log] [blame]
epoger@google.comec3ed6a2011-07-28 14:26:00 +00001/*
2 * Copyright 2011 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
scroggo@google.comb41ff952013-04-11 15:53:35 +00007
scroggo@google.com6843bdb2013-05-08 19:14:23 +00008#include "gm_expectations.h"
reed@android.comaf459792009-04-24 19:52:53 +00009#include "SkBitmap.h"
scroggo@google.com39edf4c2013-04-25 17:33:51 +000010#include "SkColorPriv.h"
scroggo@google.comb41ff952013-04-11 15:53:35 +000011#include "SkCommandLineFlags.h"
scroggo@google.com39edf4c2013-04-25 17:33:51 +000012#include "SkData.h"
scroggo@google.com7def5e12013-05-31 14:00:10 +000013#include "SkForceLinking.h"
reed@android.comaf459792009-04-24 19:52:53 +000014#include "SkGraphics.h"
15#include "SkImageDecoder.h"
16#include "SkImageEncoder.h"
scroggo@google.comb41ff952013-04-11 15:53:35 +000017#include "SkOSFile.h"
scroggo@google.com7e6fcee2013-05-03 20:14:28 +000018#include "SkRandom.h"
reed@android.comaf459792009-04-24 19:52:53 +000019#include "SkStream.h"
scroggo@google.comb41ff952013-04-11 15:53:35 +000020#include "SkTArray.h"
reed@android.comaf459792009-04-24 19:52:53 +000021#include "SkTemplates.h"
22
scroggo@google.com7def5e12013-05-31 14:00:10 +000023__SK_FORCE_IMAGE_DECODER_LINKING;
24
scroggo@google.com6843bdb2013-05-08 19:14:23 +000025DEFINE_string(createExpectationsPath, "", "Path to write JSON expectations.");
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +000026DEFINE_string(mismatchPath, "", "Folder to write mismatched images to.");
scroggo@google.comb41ff952013-04-11 15:53:35 +000027DEFINE_string2(readPath, r, "", "Folder(s) and files to decode images. Required.");
scroggo@google.com6843bdb2013-05-08 19:14:23 +000028DEFINE_string(readExpectationsPath, "", "Path to read JSON expectations from.");
scroggo@google.com39edf4c2013-04-25 17:33:51 +000029DEFINE_bool(reencode, true, "Reencode the images to test encoding.");
scroggo@google.com7e6fcee2013-05-03 20:14:28 +000030DEFINE_bool(testSubsetDecoding, true, "Test decoding subsets of images.");
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +000031DEFINE_string2(writePath, w, "", "Write rendered images into this directory.");
scroggo@google.comb41ff952013-04-11 15:53:35 +000032
scroggo@google.com39edf4c2013-04-25 17:33:51 +000033struct Format {
34 SkImageEncoder::Type fType;
35 SkImageDecoder::Format fFormat;
36 const char* fSuffix;
37};
scroggo@google.comb41ff952013-04-11 15:53:35 +000038
scroggo@google.com39edf4c2013-04-25 17:33:51 +000039static const Format gFormats[] = {
40 { SkImageEncoder::kBMP_Type, SkImageDecoder::kBMP_Format, ".bmp" },
41 { SkImageEncoder::kGIF_Type, SkImageDecoder::kGIF_Format, ".gif" },
42 { SkImageEncoder::kICO_Type, SkImageDecoder::kICO_Format, ".ico" },
43 { SkImageEncoder::kJPEG_Type, SkImageDecoder::kJPEG_Format, ".jpg" },
44 { SkImageEncoder::kPNG_Type, SkImageDecoder::kPNG_Format, ".png" },
45 { SkImageEncoder::kWBMP_Type, SkImageDecoder::kWBMP_Format, ".wbmp" },
46 { SkImageEncoder::kWEBP_Type, SkImageDecoder::kWEBP_Format, ".webp" }
47};
48
49static SkImageEncoder::Type format_to_type(SkImageDecoder::Format format) {
50 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
51 if (gFormats[i].fFormat == format) {
52 return gFormats[i].fType;
53 }
reed@android.comaf459792009-04-24 19:52:53 +000054 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +000055 return SkImageEncoder::kUnknown_Type;
reed@android.comaf459792009-04-24 19:52:53 +000056}
57
scroggo@google.com39edf4c2013-04-25 17:33:51 +000058static const char* suffix_for_type(SkImageEncoder::Type type) {
59 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
60 if (gFormats[i].fType == type) {
61 return gFormats[i].fSuffix;
62 }
63 }
64 return "";
65}
reed@android.comaf459792009-04-24 19:52:53 +000066
scroggo@google.com39edf4c2013-04-25 17:33:51 +000067static SkImageDecoder::Format guess_format_from_suffix(const char suffix[]) {
68 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
69 if (strcmp(suffix, gFormats[i].fSuffix) == 0) {
70 return gFormats[i].fFormat;
71 }
72 }
73 return SkImageDecoder::kUnknown_Format;
74}
75
76static void make_outname(SkString* dst, const char outDir[], const char src[],
77 const char suffix[]) {
scroggo@google.comccd7afb2013-05-28 16:45:07 +000078 SkString basename = SkOSPath::SkBasename(src);
79 dst->set(SkOSPath::SkPathJoin(outDir, basename.c_str()));
scroggo@google.com39edf4c2013-04-25 17:33:51 +000080 if (!dst->endsWith(suffix)) {
scroggo@google.comb41ff952013-04-11 15:53:35 +000081 const char* cstyleDst = dst->c_str();
82 const char* dot = strrchr(cstyleDst, '.');
83 if (dot != NULL) {
84 int32_t index = SkToS32(dot - cstyleDst);
85 dst->remove(index, dst->size() - index);
86 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +000087 dst->append(suffix);
scroggo@google.comb41ff952013-04-11 15:53:35 +000088 }
89}
90
scroggo@google.com39edf4c2013-04-25 17:33:51 +000091// Store the names of the filenames to report later which ones failed, succeeded, and were
92// invalid.
93static SkTArray<SkString, false> gInvalidStreams;
94static SkTArray<SkString, false> gMissingCodecs;
95static SkTArray<SkString, false> gDecodeFailures;
96static SkTArray<SkString, false> gEncodeFailures;
97static SkTArray<SkString, false> gSuccessfulDecodes;
scroggo@google.com7e6fcee2013-05-03 20:14:28 +000098static SkTArray<SkString, false> gSuccessfulSubsetDecodes;
99static SkTArray<SkString, false> gFailedSubsetDecodes;
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000100
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000101// Expections read from a file specified by readExpectationsPath. The expectations must have been
102// previously written using createExpectationsPath.
103SkAutoTUnref<skiagm::JsonExpectationsSource> gJsonExpectations;
104
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000105static bool write_bitmap(const char outName[], const SkBitmap& bm) {
106 return SkImageEncoder::EncodeFile(outName, bm, SkImageEncoder::kPNG_Type, 100);
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000107}
108
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000109/**
110 * Return a random SkIRect inside the range specified.
111 * @param rand Random number generator.
112 * @param maxX Exclusive maximum x-coordinate. SkIRect's fLeft and fRight will be
113 * in the range [0, maxX)
114 * @param maxY Exclusive maximum y-coordinate. SkIRect's fTop and fBottom will be
115 * in the range [0, maxY)
116 * @return SkIRect Non-empty, non-degenerate rectangle.
117 */
118static SkIRect generate_random_rect(SkRandom* rand, int32_t maxX, int32_t maxY) {
119 SkASSERT(maxX > 1 && maxY > 1);
120 int32_t left = rand->nextULessThan(maxX);
121 int32_t right = rand->nextULessThan(maxX);
122 int32_t top = rand->nextULessThan(maxY);
123 int32_t bottom = rand->nextULessThan(maxY);
124 SkIRect rect = SkIRect::MakeLTRB(left, top, right, bottom);
125 rect.sort();
126 // Make sure rect is not empty.
127 if (rect.fLeft == rect.fRight) {
128 if (rect.fLeft > 0) {
129 rect.fLeft--;
130 } else {
131 rect.fRight++;
132 // This branch is only taken if 0 == rect.fRight, and
133 // maxX must be at least 2, so it must still be in
134 // range.
135 SkASSERT(rect.fRight < maxX);
136 }
137 }
138 if (rect.fTop == rect.fBottom) {
139 if (rect.fTop > 0) {
140 rect.fTop--;
141 } else {
142 rect.fBottom++;
143 // Again, this must be in range.
144 SkASSERT(rect.fBottom < maxY);
145 }
146 }
147 return rect;
148}
149
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000150// Stored expectations to be written to a file if createExpectationsPath is specified.
151static Json::Value gExpectationsToWrite;
152
153/**
epoger@google.comd4993ff2013-05-24 14:33:28 +0000154 * If expectations are to be recorded, record the bitmap expectations into global
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000155 * expectations array.
156 */
157static void write_expectations(const SkBitmap& bitmap, const char* filename) {
158 if (!FLAGS_createExpectationsPath.isEmpty()) {
159 // Creates an Expectations object, and add it to the list to write.
160 skiagm::Expectations expectation(bitmap);
161 Json::Value value = expectation.asJsonValue();
162 gExpectationsToWrite[filename] = value;
163 }
164}
165
166/**
scroggo@google.combc91e8b2013-06-27 20:21:01 +0000167 * Return true if this filename is a known failure, and therefore a failure
168 * to decode should be ignored.
169 */
170static bool expect_to_fail(const char* filename) {
171 if (NULL == gJsonExpectations.get()) {
172 return false;
173 }
174 skiagm::Expectations jsExpectations = gJsonExpectations->get(filename);
175 return jsExpectations.ignoreFailure();
176}
177
178/**
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000179 * Compare against an expectation for this filename, if there is one.
180 * @param bitmap SkBitmap to compare to the expected value.
181 * @param filename String used to find the expected value.
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000182 * @return bool True in any of these cases:
183 * - the bitmap matches the expectation.
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000184 * False in any of these cases:
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000185 * - there is no expectations file.
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000186 * - there is an expectations file, but no expectation for this bitmap.
187 * - there is an expectation for this bitmap, but it did not match.
188 * - expectation could not be computed from the bitmap.
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000189 */
190static bool compare_to_expectations_if_necessary(const SkBitmap& bitmap, const char* filename,
191 SkTArray<SkString, false>* failureArray) {
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000192 skiagm::GmResultDigest resultDigest(bitmap);
193 if (!resultDigest.isValid()) {
194 if (failureArray != NULL) {
195 failureArray->push_back().printf("decoded %s, but could not create a GmResultDigest.",
196 filename);
197 }
198 return false;
199 }
200
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000201 if (NULL == gJsonExpectations.get()) {
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000202 return false;
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000203 }
204
205 skiagm::Expectations jsExpectation = gJsonExpectations->get(filename);
206 if (jsExpectation.empty()) {
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000207 if (failureArray != NULL) {
208 failureArray->push_back().printf("decoded %s, but could not find expectation.",
209 filename);
210 }
211 return false;
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000212 }
213
epoger@google.comd4993ff2013-05-24 14:33:28 +0000214 if (jsExpectation.match(resultDigest)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000215 return true;
216 }
217
218 if (failureArray != NULL) {
219 failureArray->push_back().printf("decoded %s, but the result does not match "
220 "expectations.",
221 filename);
222 }
223 return false;
224}
225
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000226/**
227 * Helper function to write a bitmap subset to a file. Only called if subsets were created
228 * and a writePath was provided. Creates a subdirectory called 'subsets' and writes a PNG to
229 * that directory. Also creates a subdirectory called 'extracted' and writes a bitmap created
230 * using extractSubset to a PNG in that directory. Both files will represent the same
231 * subrectangle and have the same name for comparison.
232 * @param writePath Parent directory to hold the folders for the PNG files to write. Must
233 * not be NULL.
234 * @param filename Basename of the original file. Used to name the new files. Must not be
235 * NULL.
236 * @param subsetDim String representing the dimensions of the subset. Used to name the new
237 * files. Must not be NULL.
238 * @param bitmapFromDecodeSubset Pointer to SkBitmap created by SkImageDecoder::DecodeSubset,
239 * using rect as the area to decode.
240 * @param rect Rectangle of the area decoded into bitmapFromDecodeSubset. Used to call
241 * extractSubset on originalBitmap to create a bitmap with the same dimensions/pixels as
242 * bitmapFromDecodeSubset (assuming decodeSubset worked properly).
243 * @param originalBitmap SkBitmap decoded from the same stream as bitmapFromDecodeSubset,
244 * using SkImageDecoder::decode to get the entire image. Used to create a PNG file for
245 * comparison to the PNG created by bitmapFromDecodeSubset.
246 * @return bool Whether the function succeeded at drawing the decoded subset and the extracted
247 * subset to files.
248 */
249static bool write_subset(const char* writePath, const char* filename, const char* subsetDim,
250 SkBitmap* bitmapFromDecodeSubset, SkIRect rect,
251 const SkBitmap& originalBitmap) {
252 // All parameters must be valid.
253 SkASSERT(writePath != NULL);
254 SkASSERT(filename != NULL);
255 SkASSERT(subsetDim != NULL);
256 SkASSERT(bitmapFromDecodeSubset != NULL);
257
258 // Create a subdirectory to hold the results of decodeSubset.
scroggo@google.comccd7afb2013-05-28 16:45:07 +0000259 SkString dir = SkOSPath::SkPathJoin(writePath, "subsets");
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000260 if (!sk_mkdir(dir.c_str())) {
261 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
262 "create a directory to write to.", subsetDim,
263 filename);
264 return false;
265 }
266
267 // Write the subset to a file whose name includes the dimensions.
268 SkString suffix = SkStringPrintf("_%s.png", subsetDim);
269 SkString outPath;
270 make_outname(&outPath, dir.c_str(), filename, suffix.c_str());
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000271 SkAssertResult(write_bitmap(outPath.c_str(), *bitmapFromDecodeSubset));
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000272 gSuccessfulSubsetDecodes.push_back().printf("\twrote %s", outPath.c_str());
273
274 // Also use extractSubset from the original for visual comparison.
275 // Write the result to a file in a separate subdirectory.
276 SkBitmap extractedSubset;
277 if (!originalBitmap.extractSubset(&extractedSubset, rect)) {
278 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
279 "extract a similar subset for comparison.",
280 subsetDim, filename);
281 return false;
282 }
283
scroggo@google.comccd7afb2013-05-28 16:45:07 +0000284 SkString dirExtracted = SkOSPath::SkPathJoin(writePath, "extracted");
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000285 if (!sk_mkdir(dirExtracted.c_str())) {
286 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
287 "create a directory for extractSubset comparison.",
288 subsetDim, filename);
289 return false;
290 }
291
292 make_outname(&outPath, dirExtracted.c_str(), filename, suffix.c_str());
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000293 SkAssertResult(write_bitmap(outPath.c_str(), extractedSubset));
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000294 return true;
295}
296
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000297static void decodeFileAndWrite(const char srcPath[], const SkString* writePath) {
298 SkBitmap bitmap;
299 SkFILEStream stream(srcPath);
300 if (!stream.isValid()) {
301 gInvalidStreams.push_back().set(srcPath);
302 return;
303 }
304
305 SkImageDecoder* codec = SkImageDecoder::Factory(&stream);
306 if (NULL == codec) {
307 gMissingCodecs.push_back().set(srcPath);
308 return;
309 }
310
311 SkAutoTDelete<SkImageDecoder> ad(codec);
312
313 stream.rewind();
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000314
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000315 // Create a string representing just the filename itself, for use in json expectations.
scroggo@google.comccd7afb2013-05-28 16:45:07 +0000316 SkString basename = SkOSPath::SkBasename(srcPath);
317 const char* filename = basename.c_str();
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000318
scroggo@google.combc91e8b2013-06-27 20:21:01 +0000319 if (!codec->decode(&stream, &bitmap, SkBitmap::kARGB_8888_Config,
320 SkImageDecoder::kDecodePixels_Mode)) {
321 if (expect_to_fail(filename)) {
322 gSuccessfulDecodes.push_back().appendf(
323 "failed to decode %s, which is a known failure.", srcPath);
324 } else {
325 gDecodeFailures.push_back().set(srcPath);
326 }
327 return;
328 }
329
scroggo@google.com6f67b3b2013-07-18 20:08:26 +0000330 // Test decoding just the bounds. The bounds should always match.
331 {
332 stream.rewind();
333 SkBitmap dim;
334 if (!codec->decode(&stream, &dim, SkImageDecoder::kDecodeBounds_Mode)) {
335 SkString failure = SkStringPrintf("failed to decode bounds for %s", srcPath);
336 gDecodeFailures.push_back() = failure;
337 } else {
338 // Now check that the bounds match:
339 if (dim.width() != bitmap.width() || dim.height() != bitmap.height()) {
340 SkString failure = SkStringPrintf("bounds do not match for %s", srcPath);
341 gDecodeFailures.push_back() = failure;
342 }
343 }
344 }
345
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000346 if (compare_to_expectations_if_necessary(bitmap, filename, &gDecodeFailures)) {
347 gSuccessfulDecodes.push_back().printf("%s [%d %d]", srcPath, bitmap.width(),
348 bitmap.height());
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000349 } else if (!FLAGS_mismatchPath.isEmpty()) {
350 SkString outPath;
351 make_outname(&outPath, FLAGS_mismatchPath[0], srcPath, ".png");
352 if (write_bitmap(outPath.c_str(), bitmap)) {
353 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
354 } else {
355 gEncodeFailures.push_back().set(outPath);
356 }
357 }
358
359 if (writePath != NULL) {
360 SkString outPath;
361 make_outname(&outPath, writePath->c_str(), srcPath, ".png");
362 if (write_bitmap(outPath.c_str(), bitmap)) {
363 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
364 } else {
365 gEncodeFailures.push_back().set(outPath);
366 }
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000367 }
368
369 write_expectations(bitmap, filename);
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000370
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000371 if (FLAGS_testSubsetDecoding) {
scroggo@google.com0018f752013-05-03 20:39:22 +0000372 SkDEBUGCODE(bool couldRewind =) stream.rewind();
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000373 SkASSERT(couldRewind);
374 int width, height;
375 // Build the tile index for decoding subsets. If the image is 1x1, skip subset
376 // decoding since there are no smaller subsets.
377 if (codec->buildTileIndex(&stream, &width, &height) && width > 1 && height > 1) {
378 SkASSERT(bitmap.width() == width && bitmap.height() == height);
379 // Call decodeSubset multiple times:
380 SkRandom rand(0);
381 for (int i = 0; i < 5; i++) {
382 SkBitmap bitmapFromDecodeSubset;
383 // FIXME: Come up with a more representative set of rectangles.
384 SkIRect rect = generate_random_rect(&rand, width, height);
385 SkString subsetDim = SkStringPrintf("[%d,%d,%d,%d]", rect.fLeft, rect.fTop,
386 rect.fRight, rect.fBottom);
387 if (codec->decodeSubset(&bitmapFromDecodeSubset, rect, SkBitmap::kNo_Config)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000388 SkString subsetName = SkStringPrintf("%s_%s", filename, subsetDim.c_str());
389 if (compare_to_expectations_if_necessary(bitmapFromDecodeSubset,
390 subsetName.c_str(),
391 &gFailedSubsetDecodes)) {
392 gSuccessfulSubsetDecodes.push_back().printf("Decoded subset %s from %s",
393 subsetDim.c_str(), srcPath);
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000394 } else if (!FLAGS_mismatchPath.isEmpty()) {
395 write_subset(FLAGS_mismatchPath[0], filename, subsetDim.c_str(),
396 &bitmapFromDecodeSubset, rect, bitmap);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000397 }
398
399 write_expectations(bitmapFromDecodeSubset, subsetName.c_str());
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000400 if (writePath != NULL) {
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000401 write_subset(writePath->c_str(), filename, subsetDim.c_str(),
402 &bitmapFromDecodeSubset, rect, bitmap);
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000403 }
404 } else {
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000405 gFailedSubsetDecodes.push_back().printf("Failed to decode region %s from %s",
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000406 subsetDim.c_str(), srcPath);
407 }
408 }
409 }
410 }
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000411
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000412 if (FLAGS_reencode) {
413 // Encode to the format the file was originally in, or PNG if the encoder for the same
414 // format is unavailable.
415 SkImageDecoder::Format format = codec->getFormat();
416 if (SkImageDecoder::kUnknown_Format == format) {
417 if (stream.rewind()) {
418 format = SkImageDecoder::GetStreamFormat(&stream);
419 }
420 if (SkImageDecoder::kUnknown_Format == format) {
421 const char* dot = strrchr(srcPath, '.');
422 if (NULL != dot) {
423 format = guess_format_from_suffix(dot);
424 }
425 if (SkImageDecoder::kUnknown_Format == format) {
426 SkDebugf("Could not determine type for '%s'\n", srcPath);
427 format = SkImageDecoder::kPNG_Format;
428 }
429
430 }
431 } else {
432 SkASSERT(!stream.rewind() || SkImageDecoder::GetStreamFormat(&stream) == format);
433 }
434 SkImageEncoder::Type type = format_to_type(format);
435 // format should never be kUnknown_Format, so type should never be kUnknown_Type.
436 SkASSERT(type != SkImageEncoder::kUnknown_Type);
437
438 SkImageEncoder* encoder = SkImageEncoder::Create(type);
439 if (NULL == encoder) {
440 type = SkImageEncoder::kPNG_Type;
441 encoder = SkImageEncoder::Create(type);
442 SkASSERT(encoder);
443 }
444 SkAutoTDelete<SkImageEncoder> ade(encoder);
445 // Encode to a stream.
446 SkDynamicMemoryWStream wStream;
447 if (!encoder->encodeStream(&wStream, bitmap, 100)) {
448 gEncodeFailures.push_back().printf("Failed to reencode %s to type '%s'", srcPath,
449 suffix_for_type(type));
450 return;
451 }
452
453 SkAutoTUnref<SkData> data(wStream.copyToData());
454 if (writePath != NULL && type != SkImageEncoder::kPNG_Type) {
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000455 // Write the encoded data to a file. Do not write to PNG, which was already written.
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000456 SkString outPath;
457 make_outname(&outPath, writePath->c_str(), srcPath, suffix_for_type(type));
458 SkFILEWStream file(outPath.c_str());
459 if(file.write(data->data(), data->size())) {
460 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
461 } else {
462 gEncodeFailures.push_back().printf("Failed to write %s", outPath.c_str());
463 }
464 }
465 // Ensure that the reencoded data can still be decoded.
466 SkMemoryStream memStream(data);
467 SkBitmap redecodedBitmap;
468 SkImageDecoder::Format formatOnSecondDecode;
469 if (SkImageDecoder::DecodeStream(&memStream, &redecodedBitmap, SkBitmap::kNo_Config,
470 SkImageDecoder::kDecodePixels_Mode,
471 &formatOnSecondDecode)) {
472 SkASSERT(format_to_type(formatOnSecondDecode) == type);
473 } else {
474 gDecodeFailures.push_back().printf("Failed to redecode %s after reencoding to '%s'",
475 srcPath, suffix_for_type(type));
476 }
477 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000478}
479
480///////////////////////////////////////////////////////////////////////////////
481
scroggo@google.comb41ff952013-04-11 15:53:35 +0000482// If strings is not empty, print title, followed by each string on its own line starting
483// with a tab.
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000484// @return bool True if strings had at least one entry.
485static bool print_strings(const char* title, const SkTArray<SkString, false>& strings) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000486 if (strings.count() > 0) {
487 SkDebugf("%s:\n", title);
488 for (int i = 0; i < strings.count(); i++) {
489 SkDebugf("\t%s\n", strings[i].c_str());
490 }
491 SkDebugf("\n");
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000492 return true;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000493 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000494 return false;
reed@android.comaf459792009-04-24 19:52:53 +0000495}
496
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000497/**
498 * If directory is non null and does not end with a path separator, append one.
499 * @param directory SkString representing the path to a directory. If the last character is not a
500 * path separator (specific to the current OS), append one.
501 */
502static void append_path_separator_if_necessary(SkString* directory) {
503 if (directory != NULL && directory->c_str()[directory->size() - 1] != SkPATH_SEPARATOR) {
504 directory->appendf("%c", SkPATH_SEPARATOR);
505 }
506}
507
scroggo@google.com925cdca2013-06-28 20:04:42 +0000508/**
509 * Return true if the filename represents an image.
510 */
511static bool is_image_file(const char* filename) {
512 const char* gImageExtensions[] = {
513 ".png", ".PNG", ".jpg", ".JPG", ".jpeg", ".JPEG", ".bmp", ".BMP",
514 ".webp", ".WEBP", ".ico", ".ICO", ".wbmp", ".WBMP", ".gif", ".GIF"
515 };
516 for (size_t i = 0; i < SK_ARRAY_COUNT(gImageExtensions); ++i) {
517 if (SkStrEndsWith(filename, gImageExtensions[i])) {
518 return true;
519 }
520 }
521 return false;
522}
523
caryclark@google.com5987f582012-10-02 18:33:14 +0000524int tool_main(int argc, char** argv);
525int tool_main(int argc, char** argv) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000526 SkCommandLineFlags::SetUsage("Decode files, and optionally write the results to files.");
527 SkCommandLineFlags::Parse(argc, argv);
528
529 if (FLAGS_readPath.count() < 1) {
530 SkDebugf("Folder(s) or image(s) to decode are required.\n");
531 return -1;
532 }
533
534
reed@android.comaf459792009-04-24 19:52:53 +0000535 SkAutoGraphics ag;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000536
scroggo@google.com3832da12013-06-19 19:12:53 +0000537 if (!FLAGS_readExpectationsPath.isEmpty() && sk_exists(FLAGS_readExpectationsPath[0])) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000538 gJsonExpectations.reset(SkNEW_ARGS(skiagm::JsonExpectationsSource,
539 (FLAGS_readExpectationsPath[0])));
540 }
541
reed@android.comaf459792009-04-24 19:52:53 +0000542 SkString outDir;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000543 SkString* outDirPtr;
reed@android.comaf459792009-04-24 19:52:53 +0000544
scroggo@google.comb41ff952013-04-11 15:53:35 +0000545 if (FLAGS_writePath.count() == 1) {
546 outDir.set(FLAGS_writePath[0]);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000547 append_path_separator_if_necessary(&outDir);
scroggo@google.comb41ff952013-04-11 15:53:35 +0000548 outDirPtr = &outDir;
549 } else {
550 outDirPtr = NULL;
551 }
552
553 for (int i = 0; i < FLAGS_readPath.count(); i++) {
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000554 const char* readPath = FLAGS_readPath[i];
555 if (strlen(readPath) < 1) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000556 break;
557 }
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000558 if (sk_isdir(readPath)) {
559 const char* dir = readPath;
560 SkOSFile::Iter iter(dir);
561 SkString filename;
562 while (iter.next(&filename)) {
scroggo@google.com925cdca2013-06-28 20:04:42 +0000563 if (!is_image_file(filename.c_str())) {
564 continue;
565 }
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000566 SkString fullname = SkOSPath::SkPathJoin(dir, filename.c_str());
scroggo@google.comb41ff952013-04-11 15:53:35 +0000567 decodeFileAndWrite(fullname.c_str(), outDirPtr);
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000568 }
scroggo@google.com925cdca2013-06-28 20:04:42 +0000569 } else if (sk_exists(readPath) && is_image_file(readPath)) {
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000570 decodeFileAndWrite(readPath, outDirPtr);
reed@android.comaf459792009-04-24 19:52:53 +0000571 }
572 }
573
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000574 if (!FLAGS_createExpectationsPath.isEmpty()) {
575 // Use an empty value for everything besides expectations, since the reader only cares
576 // about the expectations.
577 Json::Value nullValue;
578 Json::Value root = skiagm::CreateJsonTree(gExpectationsToWrite, nullValue, nullValue,
579 nullValue, nullValue);
580 std::string jsonStdString = root.toStyledString();
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000581 SkFILEWStream stream(FLAGS_createExpectationsPath[0]);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000582 stream.write(jsonStdString.c_str(), jsonStdString.length());
583 }
scroggo@google.comb41ff952013-04-11 15:53:35 +0000584 // Add some space, since codecs may print warnings without newline.
585 SkDebugf("\n\n");
rmistry@google.comd6176b02012-08-23 18:14:13 +0000586
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000587 bool failed = print_strings("Invalid files", gInvalidStreams);
588 failed |= print_strings("Missing codec", gMissingCodecs);
589 failed |= print_strings("Failed to decode", gDecodeFailures);
590 failed |= print_strings("Failed to encode", gEncodeFailures);
591 print_strings("Decoded", gSuccessfulDecodes);
reed@android.comaf459792009-04-24 19:52:53 +0000592
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000593 if (FLAGS_testSubsetDecoding) {
594 failed |= print_strings("Failed subset decodes", gFailedSubsetDecodes);
595 print_strings("Decoded subsets", gSuccessfulSubsetDecodes);
596 }
597
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000598 return failed ? -1 : 0;
reed@android.comaf459792009-04-24 19:52:53 +0000599}
600
caryclark@google.com5987f582012-10-02 18:33:14 +0000601#if !defined SK_BUILD_FOR_IOS
602int main(int argc, char * const argv[]) {
603 return tool_main(argc, (char**) argv);
604}
605#endif