blob: 572f9f54f6a8040eb0280db1742c206b98a9083c [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.com6843bdb2013-05-08 19:14:23 +0000330 if (compare_to_expectations_if_necessary(bitmap, filename, &gDecodeFailures)) {
331 gSuccessfulDecodes.push_back().printf("%s [%d %d]", srcPath, bitmap.width(),
332 bitmap.height());
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000333 } else if (!FLAGS_mismatchPath.isEmpty()) {
334 SkString outPath;
335 make_outname(&outPath, FLAGS_mismatchPath[0], srcPath, ".png");
336 if (write_bitmap(outPath.c_str(), bitmap)) {
337 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
338 } else {
339 gEncodeFailures.push_back().set(outPath);
340 }
341 }
342
343 if (writePath != NULL) {
344 SkString outPath;
345 make_outname(&outPath, writePath->c_str(), srcPath, ".png");
346 if (write_bitmap(outPath.c_str(), bitmap)) {
347 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
348 } else {
349 gEncodeFailures.push_back().set(outPath);
350 }
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000351 }
352
353 write_expectations(bitmap, filename);
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000354
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000355 if (FLAGS_testSubsetDecoding) {
scroggo@google.com0018f752013-05-03 20:39:22 +0000356 SkDEBUGCODE(bool couldRewind =) stream.rewind();
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000357 SkASSERT(couldRewind);
358 int width, height;
359 // Build the tile index for decoding subsets. If the image is 1x1, skip subset
360 // decoding since there are no smaller subsets.
361 if (codec->buildTileIndex(&stream, &width, &height) && width > 1 && height > 1) {
362 SkASSERT(bitmap.width() == width && bitmap.height() == height);
363 // Call decodeSubset multiple times:
364 SkRandom rand(0);
365 for (int i = 0; i < 5; i++) {
366 SkBitmap bitmapFromDecodeSubset;
367 // FIXME: Come up with a more representative set of rectangles.
368 SkIRect rect = generate_random_rect(&rand, width, height);
369 SkString subsetDim = SkStringPrintf("[%d,%d,%d,%d]", rect.fLeft, rect.fTop,
370 rect.fRight, rect.fBottom);
371 if (codec->decodeSubset(&bitmapFromDecodeSubset, rect, SkBitmap::kNo_Config)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000372 SkString subsetName = SkStringPrintf("%s_%s", filename, subsetDim.c_str());
373 if (compare_to_expectations_if_necessary(bitmapFromDecodeSubset,
374 subsetName.c_str(),
375 &gFailedSubsetDecodes)) {
376 gSuccessfulSubsetDecodes.push_back().printf("Decoded subset %s from %s",
377 subsetDim.c_str(), srcPath);
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000378 } else if (!FLAGS_mismatchPath.isEmpty()) {
379 write_subset(FLAGS_mismatchPath[0], filename, subsetDim.c_str(),
380 &bitmapFromDecodeSubset, rect, bitmap);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000381 }
382
383 write_expectations(bitmapFromDecodeSubset, subsetName.c_str());
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000384 if (writePath != NULL) {
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000385 write_subset(writePath->c_str(), filename, subsetDim.c_str(),
386 &bitmapFromDecodeSubset, rect, bitmap);
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000387 }
388 } else {
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000389 gFailedSubsetDecodes.push_back().printf("Failed to decode region %s from %s",
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000390 subsetDim.c_str(), srcPath);
391 }
392 }
393 }
394 }
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000395
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000396 if (FLAGS_reencode) {
397 // Encode to the format the file was originally in, or PNG if the encoder for the same
398 // format is unavailable.
399 SkImageDecoder::Format format = codec->getFormat();
400 if (SkImageDecoder::kUnknown_Format == format) {
401 if (stream.rewind()) {
402 format = SkImageDecoder::GetStreamFormat(&stream);
403 }
404 if (SkImageDecoder::kUnknown_Format == format) {
405 const char* dot = strrchr(srcPath, '.');
406 if (NULL != dot) {
407 format = guess_format_from_suffix(dot);
408 }
409 if (SkImageDecoder::kUnknown_Format == format) {
410 SkDebugf("Could not determine type for '%s'\n", srcPath);
411 format = SkImageDecoder::kPNG_Format;
412 }
413
414 }
415 } else {
416 SkASSERT(!stream.rewind() || SkImageDecoder::GetStreamFormat(&stream) == format);
417 }
418 SkImageEncoder::Type type = format_to_type(format);
419 // format should never be kUnknown_Format, so type should never be kUnknown_Type.
420 SkASSERT(type != SkImageEncoder::kUnknown_Type);
421
422 SkImageEncoder* encoder = SkImageEncoder::Create(type);
423 if (NULL == encoder) {
424 type = SkImageEncoder::kPNG_Type;
425 encoder = SkImageEncoder::Create(type);
426 SkASSERT(encoder);
427 }
428 SkAutoTDelete<SkImageEncoder> ade(encoder);
429 // Encode to a stream.
430 SkDynamicMemoryWStream wStream;
431 if (!encoder->encodeStream(&wStream, bitmap, 100)) {
432 gEncodeFailures.push_back().printf("Failed to reencode %s to type '%s'", srcPath,
433 suffix_for_type(type));
434 return;
435 }
436
437 SkAutoTUnref<SkData> data(wStream.copyToData());
438 if (writePath != NULL && type != SkImageEncoder::kPNG_Type) {
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000439 // Write the encoded data to a file. Do not write to PNG, which was already written.
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000440 SkString outPath;
441 make_outname(&outPath, writePath->c_str(), srcPath, suffix_for_type(type));
442 SkFILEWStream file(outPath.c_str());
443 if(file.write(data->data(), data->size())) {
444 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
445 } else {
446 gEncodeFailures.push_back().printf("Failed to write %s", outPath.c_str());
447 }
448 }
449 // Ensure that the reencoded data can still be decoded.
450 SkMemoryStream memStream(data);
451 SkBitmap redecodedBitmap;
452 SkImageDecoder::Format formatOnSecondDecode;
453 if (SkImageDecoder::DecodeStream(&memStream, &redecodedBitmap, SkBitmap::kNo_Config,
454 SkImageDecoder::kDecodePixels_Mode,
455 &formatOnSecondDecode)) {
456 SkASSERT(format_to_type(formatOnSecondDecode) == type);
457 } else {
458 gDecodeFailures.push_back().printf("Failed to redecode %s after reencoding to '%s'",
459 srcPath, suffix_for_type(type));
460 }
461 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000462}
463
464///////////////////////////////////////////////////////////////////////////////
465
scroggo@google.comb41ff952013-04-11 15:53:35 +0000466// If strings is not empty, print title, followed by each string on its own line starting
467// with a tab.
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000468// @return bool True if strings had at least one entry.
469static bool print_strings(const char* title, const SkTArray<SkString, false>& strings) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000470 if (strings.count() > 0) {
471 SkDebugf("%s:\n", title);
472 for (int i = 0; i < strings.count(); i++) {
473 SkDebugf("\t%s\n", strings[i].c_str());
474 }
475 SkDebugf("\n");
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000476 return true;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000477 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000478 return false;
reed@android.comaf459792009-04-24 19:52:53 +0000479}
480
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000481/**
482 * If directory is non null and does not end with a path separator, append one.
483 * @param directory SkString representing the path to a directory. If the last character is not a
484 * path separator (specific to the current OS), append one.
485 */
486static void append_path_separator_if_necessary(SkString* directory) {
487 if (directory != NULL && directory->c_str()[directory->size() - 1] != SkPATH_SEPARATOR) {
488 directory->appendf("%c", SkPATH_SEPARATOR);
489 }
490}
491
caryclark@google.com5987f582012-10-02 18:33:14 +0000492int tool_main(int argc, char** argv);
493int tool_main(int argc, char** argv) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000494 SkCommandLineFlags::SetUsage("Decode files, and optionally write the results to files.");
495 SkCommandLineFlags::Parse(argc, argv);
496
497 if (FLAGS_readPath.count() < 1) {
498 SkDebugf("Folder(s) or image(s) to decode are required.\n");
499 return -1;
500 }
501
502
reed@android.comaf459792009-04-24 19:52:53 +0000503 SkAutoGraphics ag;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000504
scroggo@google.com3832da12013-06-19 19:12:53 +0000505 if (!FLAGS_readExpectationsPath.isEmpty() && sk_exists(FLAGS_readExpectationsPath[0])) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000506 gJsonExpectations.reset(SkNEW_ARGS(skiagm::JsonExpectationsSource,
507 (FLAGS_readExpectationsPath[0])));
508 }
509
reed@android.comaf459792009-04-24 19:52:53 +0000510 SkString outDir;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000511 SkString* outDirPtr;
reed@android.comaf459792009-04-24 19:52:53 +0000512
scroggo@google.comb41ff952013-04-11 15:53:35 +0000513 if (FLAGS_writePath.count() == 1) {
514 outDir.set(FLAGS_writePath[0]);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000515 append_path_separator_if_necessary(&outDir);
scroggo@google.comb41ff952013-04-11 15:53:35 +0000516 outDirPtr = &outDir;
517 } else {
518 outDirPtr = NULL;
519 }
520
521 for (int i = 0; i < FLAGS_readPath.count(); i++) {
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000522 const char* readPath = FLAGS_readPath[i];
523 if (strlen(readPath) < 1) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000524 break;
525 }
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000526 if (sk_isdir(readPath)) {
527 const char* dir = readPath;
528 SkOSFile::Iter iter(dir);
529 SkString filename;
530 while (iter.next(&filename)) {
531 SkString fullname = SkOSPath::SkPathJoin(dir, filename.c_str());
scroggo@google.comb41ff952013-04-11 15:53:35 +0000532 decodeFileAndWrite(fullname.c_str(), outDirPtr);
scroggo@google.com2b9424b2013-06-21 19:12:47 +0000533 }
534 } else if (sk_exists(readPath)) {
535 decodeFileAndWrite(readPath, outDirPtr);
reed@android.comaf459792009-04-24 19:52:53 +0000536 }
537 }
538
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000539 if (!FLAGS_createExpectationsPath.isEmpty()) {
540 // Use an empty value for everything besides expectations, since the reader only cares
541 // about the expectations.
542 Json::Value nullValue;
543 Json::Value root = skiagm::CreateJsonTree(gExpectationsToWrite, nullValue, nullValue,
544 nullValue, nullValue);
545 std::string jsonStdString = root.toStyledString();
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000546 SkFILEWStream stream(FLAGS_createExpectationsPath[0]);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000547 stream.write(jsonStdString.c_str(), jsonStdString.length());
548 }
scroggo@google.comb41ff952013-04-11 15:53:35 +0000549 // Add some space, since codecs may print warnings without newline.
550 SkDebugf("\n\n");
rmistry@google.comd6176b02012-08-23 18:14:13 +0000551
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000552 bool failed = print_strings("Invalid files", gInvalidStreams);
553 failed |= print_strings("Missing codec", gMissingCodecs);
554 failed |= print_strings("Failed to decode", gDecodeFailures);
555 failed |= print_strings("Failed to encode", gEncodeFailures);
556 print_strings("Decoded", gSuccessfulDecodes);
reed@android.comaf459792009-04-24 19:52:53 +0000557
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000558 if (FLAGS_testSubsetDecoding) {
559 failed |= print_strings("Failed subset decodes", gFailedSubsetDecodes);
560 print_strings("Decoded subsets", gSuccessfulSubsetDecodes);
561 }
562
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000563 return failed ? -1 : 0;
reed@android.comaf459792009-04-24 19:52:53 +0000564}
565
caryclark@google.com5987f582012-10-02 18:33:14 +0000566#if !defined SK_BUILD_FOR_IOS
567int main(int argc, char * const argv[]) {
568 return tool_main(argc, (char**) argv);
569}
570#endif