blob: 9739ced49d13df296d94f3ff19fb6dc0c0b5e5f1 [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.com6843bdb2013-05-08 19:14:23 +000010#include "SkBitmapHasher.h"
scroggo@google.com39edf4c2013-04-25 17:33:51 +000011#include "SkColorPriv.h"
scroggo@google.comb41ff952013-04-11 15:53:35 +000012#include "SkCommandLineFlags.h"
scroggo@google.com39edf4c2013-04-25 17:33:51 +000013#include "SkData.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.com6843bdb2013-05-08 19:14:23 +000023DEFINE_string(createExpectationsPath, "", "Path to write JSON expectations.");
scroggo@google.comb41ff952013-04-11 15:53:35 +000024DEFINE_string2(readPath, r, "", "Folder(s) and files to decode images. Required.");
scroggo@google.com6843bdb2013-05-08 19:14:23 +000025DEFINE_string(readExpectationsPath, "", "Path to read JSON expectations from.");
scroggo@google.comb41ff952013-04-11 15:53:35 +000026DEFINE_string2(writePath, w, "", "Write rendered images into this directory.");
scroggo@google.com39edf4c2013-04-25 17:33:51 +000027DEFINE_bool(reencode, true, "Reencode the images to test encoding.");
scroggo@google.com7e6fcee2013-05-03 20:14:28 +000028DEFINE_bool(testSubsetDecoding, true, "Test decoding subsets of images.");
scroggo@google.comb41ff952013-04-11 15:53:35 +000029
scroggo@google.com39edf4c2013-04-25 17:33:51 +000030struct Format {
31 SkImageEncoder::Type fType;
32 SkImageDecoder::Format fFormat;
33 const char* fSuffix;
34};
scroggo@google.comb41ff952013-04-11 15:53:35 +000035
scroggo@google.com39edf4c2013-04-25 17:33:51 +000036static const Format gFormats[] = {
37 { SkImageEncoder::kBMP_Type, SkImageDecoder::kBMP_Format, ".bmp" },
38 { SkImageEncoder::kGIF_Type, SkImageDecoder::kGIF_Format, ".gif" },
39 { SkImageEncoder::kICO_Type, SkImageDecoder::kICO_Format, ".ico" },
40 { SkImageEncoder::kJPEG_Type, SkImageDecoder::kJPEG_Format, ".jpg" },
41 { SkImageEncoder::kPNG_Type, SkImageDecoder::kPNG_Format, ".png" },
42 { SkImageEncoder::kWBMP_Type, SkImageDecoder::kWBMP_Format, ".wbmp" },
43 { SkImageEncoder::kWEBP_Type, SkImageDecoder::kWEBP_Format, ".webp" }
44};
45
46static SkImageEncoder::Type format_to_type(SkImageDecoder::Format format) {
47 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
48 if (gFormats[i].fFormat == format) {
49 return gFormats[i].fType;
50 }
reed@android.comaf459792009-04-24 19:52:53 +000051 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +000052 return SkImageEncoder::kUnknown_Type;
reed@android.comaf459792009-04-24 19:52:53 +000053}
54
scroggo@google.com39edf4c2013-04-25 17:33:51 +000055static const char* suffix_for_type(SkImageEncoder::Type type) {
56 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
57 if (gFormats[i].fType == type) {
58 return gFormats[i].fSuffix;
59 }
60 }
61 return "";
62}
reed@android.comaf459792009-04-24 19:52:53 +000063
scroggo@google.com39edf4c2013-04-25 17:33:51 +000064static SkImageDecoder::Format guess_format_from_suffix(const char suffix[]) {
65 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
66 if (strcmp(suffix, gFormats[i].fSuffix) == 0) {
67 return gFormats[i].fFormat;
68 }
69 }
70 return SkImageDecoder::kUnknown_Format;
71}
72
scroggo@google.com9da0e1d2013-05-15 18:14:36 +000073/**
74 * Return the name of the file, ignoring the directory structure.
75 * Does not create a new string.
76 * @param fullPath Full path to the file.
77 * @return string The basename of the file - anything beyond the final slash, or the full name
78 * if there is no slash.
79 * TODO: Might this be useful as a utility function in SkOSFile? Would it be more appropriate to
80 * create a new string?
81 */
82static const char* SkBasename(const char* fullPath) {
83 const char* filename = strrchr(fullPath, SkPATH_SEPARATOR);
84 if (NULL == filename || *++filename == '\0') {
85 filename = fullPath;
86 }
87 return filename;
88}
89
scroggo@google.com39edf4c2013-04-25 17:33:51 +000090static void make_outname(SkString* dst, const char outDir[], const char src[],
91 const char suffix[]) {
scroggo@google.com9da0e1d2013-05-15 18:14:36 +000092 const char* basename = SkBasename(src);
93 dst->set(skiagm::SkPathJoin(outDir, basename));
scroggo@google.com39edf4c2013-04-25 17:33:51 +000094 if (!dst->endsWith(suffix)) {
scroggo@google.comb41ff952013-04-11 15:53:35 +000095 const char* cstyleDst = dst->c_str();
96 const char* dot = strrchr(cstyleDst, '.');
97 if (dot != NULL) {
98 int32_t index = SkToS32(dot - cstyleDst);
99 dst->remove(index, dst->size() - index);
100 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000101 dst->append(suffix);
scroggo@google.comb41ff952013-04-11 15:53:35 +0000102 }
103}
104
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000105// Store the names of the filenames to report later which ones failed, succeeded, and were
106// invalid.
107static SkTArray<SkString, false> gInvalidStreams;
108static SkTArray<SkString, false> gMissingCodecs;
109static SkTArray<SkString, false> gDecodeFailures;
110static SkTArray<SkString, false> gEncodeFailures;
111static SkTArray<SkString, false> gSuccessfulDecodes;
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000112static SkTArray<SkString, false> gSuccessfulSubsetDecodes;
113static SkTArray<SkString, false> gFailedSubsetDecodes;
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000114
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000115// Expections read from a file specified by readExpectationsPath. The expectations must have been
116// previously written using createExpectationsPath.
117SkAutoTUnref<skiagm::JsonExpectationsSource> gJsonExpectations;
118
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000119static bool write_bitmap(const char outName[], SkBitmap* bm) {
120 SkBitmap bitmap8888;
121 if (SkBitmap::kARGB_8888_Config != bm->config()) {
122 if (!bm->copyTo(&bitmap8888, SkBitmap::kARGB_8888_Config)) {
123 return false;
124 }
125 bm = &bitmap8888;
126 }
127 // FIXME: This forces all pixels to be opaque, like the many implementations
128 // of force_all_opaque. These should be unified if they cannot be eliminated.
129 SkAutoLockPixels lock(*bm);
130 for (int y = 0; y < bm->height(); y++) {
131 for (int x = 0; x < bm->width(); x++) {
132 *bm->getAddr32(x, y) |= (SK_A32_MASK << SK_A32_SHIFT);
133 }
134 }
135 return SkImageEncoder::EncodeFile(outName, *bm, SkImageEncoder::kPNG_Type, 100);
136}
137
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000138/**
139 * Return a random SkIRect inside the range specified.
140 * @param rand Random number generator.
141 * @param maxX Exclusive maximum x-coordinate. SkIRect's fLeft and fRight will be
142 * in the range [0, maxX)
143 * @param maxY Exclusive maximum y-coordinate. SkIRect's fTop and fBottom will be
144 * in the range [0, maxY)
145 * @return SkIRect Non-empty, non-degenerate rectangle.
146 */
147static SkIRect generate_random_rect(SkRandom* rand, int32_t maxX, int32_t maxY) {
148 SkASSERT(maxX > 1 && maxY > 1);
149 int32_t left = rand->nextULessThan(maxX);
150 int32_t right = rand->nextULessThan(maxX);
151 int32_t top = rand->nextULessThan(maxY);
152 int32_t bottom = rand->nextULessThan(maxY);
153 SkIRect rect = SkIRect::MakeLTRB(left, top, right, bottom);
154 rect.sort();
155 // Make sure rect is not empty.
156 if (rect.fLeft == rect.fRight) {
157 if (rect.fLeft > 0) {
158 rect.fLeft--;
159 } else {
160 rect.fRight++;
161 // This branch is only taken if 0 == rect.fRight, and
162 // maxX must be at least 2, so it must still be in
163 // range.
164 SkASSERT(rect.fRight < maxX);
165 }
166 }
167 if (rect.fTop == rect.fBottom) {
168 if (rect.fTop > 0) {
169 rect.fTop--;
170 } else {
171 rect.fBottom++;
172 // Again, this must be in range.
173 SkASSERT(rect.fBottom < maxY);
174 }
175 }
176 return rect;
177}
178
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000179// Stored expectations to be written to a file if createExpectationsPath is specified.
180static Json::Value gExpectationsToWrite;
181
182/**
183 * If expectations are to be recorded, record the expected checksum of bitmap into global
184 * expectations array.
185 */
186static void write_expectations(const SkBitmap& bitmap, const char* filename) {
187 if (!FLAGS_createExpectationsPath.isEmpty()) {
188 // Creates an Expectations object, and add it to the list to write.
189 skiagm::Expectations expectation(bitmap);
190 Json::Value value = expectation.asJsonValue();
191 gExpectationsToWrite[filename] = value;
192 }
193}
194
195/**
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000196 * Compare against an expectation for this filename, if there is one.
197 * @param bitmap SkBitmap to compare to the expected value.
198 * @param filename String used to find the expected value.
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000199 * @return bool True in any of these cases:
200 * - the bitmap matches the expectation.
201 * - there is no expectations file.
202 * False in any of these cases:
203 * - there is an expectations file, but no expectation for this bitmap.
204 * - there is an expectation for this bitmap, but it did not match.
205 * - expectation could not be computed from the bitmap.
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000206 */
207static bool compare_to_expectations_if_necessary(const SkBitmap& bitmap, const char* filename,
208 SkTArray<SkString, false>* failureArray) {
209 if (NULL == gJsonExpectations.get()) {
210 return true;
211 }
212
213 skiagm::Expectations jsExpectation = gJsonExpectations->get(filename);
214 if (jsExpectation.empty()) {
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000215 if (failureArray != NULL) {
216 failureArray->push_back().printf("decoded %s, but could not find expectation.",
217 filename);
218 }
219 return false;
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000220 }
221
222 SkHashDigest checksum;
223 if (!SkBitmapHasher::ComputeDigest(bitmap, &checksum)) {
224 if (failureArray != NULL) {
225 failureArray->push_back().printf("decoded %s, but could not create a checksum.",
226 filename);
227 }
228 return false;
229 }
230
231 if (jsExpectation.match(checksum)) {
232 return true;
233 }
234
235 if (failureArray != NULL) {
236 failureArray->push_back().printf("decoded %s, but the result does not match "
237 "expectations.",
238 filename);
239 }
240 return false;
241}
242
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000243/**
244 * Helper function to write a bitmap subset to a file. Only called if subsets were created
245 * and a writePath was provided. Creates a subdirectory called 'subsets' and writes a PNG to
246 * that directory. Also creates a subdirectory called 'extracted' and writes a bitmap created
247 * using extractSubset to a PNG in that directory. Both files will represent the same
248 * subrectangle and have the same name for comparison.
249 * @param writePath Parent directory to hold the folders for the PNG files to write. Must
250 * not be NULL.
251 * @param filename Basename of the original file. Used to name the new files. Must not be
252 * NULL.
253 * @param subsetDim String representing the dimensions of the subset. Used to name the new
254 * files. Must not be NULL.
255 * @param bitmapFromDecodeSubset Pointer to SkBitmap created by SkImageDecoder::DecodeSubset,
256 * using rect as the area to decode.
257 * @param rect Rectangle of the area decoded into bitmapFromDecodeSubset. Used to call
258 * extractSubset on originalBitmap to create a bitmap with the same dimensions/pixels as
259 * bitmapFromDecodeSubset (assuming decodeSubset worked properly).
260 * @param originalBitmap SkBitmap decoded from the same stream as bitmapFromDecodeSubset,
261 * using SkImageDecoder::decode to get the entire image. Used to create a PNG file for
262 * comparison to the PNG created by bitmapFromDecodeSubset.
263 * @return bool Whether the function succeeded at drawing the decoded subset and the extracted
264 * subset to files.
265 */
266static bool write_subset(const char* writePath, const char* filename, const char* subsetDim,
267 SkBitmap* bitmapFromDecodeSubset, SkIRect rect,
268 const SkBitmap& originalBitmap) {
269 // All parameters must be valid.
270 SkASSERT(writePath != NULL);
271 SkASSERT(filename != NULL);
272 SkASSERT(subsetDim != NULL);
273 SkASSERT(bitmapFromDecodeSubset != NULL);
274
275 // Create a subdirectory to hold the results of decodeSubset.
276 // TODO: Move SkPathJoin into SkOSFile.h
277 SkString dir = skiagm::SkPathJoin(writePath, "subsets");
278 if (!sk_mkdir(dir.c_str())) {
279 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
280 "create a directory to write to.", subsetDim,
281 filename);
282 return false;
283 }
284
285 // Write the subset to a file whose name includes the dimensions.
286 SkString suffix = SkStringPrintf("_%s.png", subsetDim);
287 SkString outPath;
288 make_outname(&outPath, dir.c_str(), filename, suffix.c_str());
289 SkAssertResult(write_bitmap(outPath.c_str(), bitmapFromDecodeSubset));
290 gSuccessfulSubsetDecodes.push_back().printf("\twrote %s", outPath.c_str());
291
292 // Also use extractSubset from the original for visual comparison.
293 // Write the result to a file in a separate subdirectory.
294 SkBitmap extractedSubset;
295 if (!originalBitmap.extractSubset(&extractedSubset, rect)) {
296 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
297 "extract a similar subset for comparison.",
298 subsetDim, filename);
299 return false;
300 }
301
302 SkString dirExtracted = skiagm::SkPathJoin(writePath, "extracted");
303 if (!sk_mkdir(dirExtracted.c_str())) {
304 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
305 "create a directory for extractSubset comparison.",
306 subsetDim, filename);
307 return false;
308 }
309
310 make_outname(&outPath, dirExtracted.c_str(), filename, suffix.c_str());
311 SkAssertResult(write_bitmap(outPath.c_str(), &extractedSubset));
312 return true;
313}
314
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000315static void decodeFileAndWrite(const char srcPath[], const SkString* writePath) {
316 SkBitmap bitmap;
317 SkFILEStream stream(srcPath);
318 if (!stream.isValid()) {
319 gInvalidStreams.push_back().set(srcPath);
320 return;
321 }
322
323 SkImageDecoder* codec = SkImageDecoder::Factory(&stream);
324 if (NULL == codec) {
325 gMissingCodecs.push_back().set(srcPath);
326 return;
327 }
328
329 SkAutoTDelete<SkImageDecoder> ad(codec);
330
331 stream.rewind();
332 if (!codec->decode(&stream, &bitmap, SkBitmap::kARGB_8888_Config,
333 SkImageDecoder::kDecodePixels_Mode)) {
334 gDecodeFailures.push_back().set(srcPath);
335 return;
336 }
337
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000338 // Create a string representing just the filename itself, for use in json expectations.
339 const char* filename = SkBasename(srcPath);
340
341 if (compare_to_expectations_if_necessary(bitmap, filename, &gDecodeFailures)) {
342 gSuccessfulDecodes.push_back().printf("%s [%d %d]", srcPath, bitmap.width(),
343 bitmap.height());
344 }
345
346 write_expectations(bitmap, filename);
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000347
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000348 if (FLAGS_testSubsetDecoding) {
scroggo@google.com0018f752013-05-03 20:39:22 +0000349 SkDEBUGCODE(bool couldRewind =) stream.rewind();
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000350 SkASSERT(couldRewind);
351 int width, height;
352 // Build the tile index for decoding subsets. If the image is 1x1, skip subset
353 // decoding since there are no smaller subsets.
354 if (codec->buildTileIndex(&stream, &width, &height) && width > 1 && height > 1) {
355 SkASSERT(bitmap.width() == width && bitmap.height() == height);
356 // Call decodeSubset multiple times:
357 SkRandom rand(0);
358 for (int i = 0; i < 5; i++) {
359 SkBitmap bitmapFromDecodeSubset;
360 // FIXME: Come up with a more representative set of rectangles.
361 SkIRect rect = generate_random_rect(&rand, width, height);
362 SkString subsetDim = SkStringPrintf("[%d,%d,%d,%d]", rect.fLeft, rect.fTop,
363 rect.fRight, rect.fBottom);
364 if (codec->decodeSubset(&bitmapFromDecodeSubset, rect, SkBitmap::kNo_Config)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000365 SkString subsetName = SkStringPrintf("%s_%s", filename, subsetDim.c_str());
366 if (compare_to_expectations_if_necessary(bitmapFromDecodeSubset,
367 subsetName.c_str(),
368 &gFailedSubsetDecodes)) {
369 gSuccessfulSubsetDecodes.push_back().printf("Decoded subset %s from %s",
370 subsetDim.c_str(), srcPath);
371 }
372
373 write_expectations(bitmapFromDecodeSubset, subsetName.c_str());
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000374 if (writePath != NULL) {
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000375 write_subset(writePath->c_str(), filename, subsetDim.c_str(),
376 &bitmapFromDecodeSubset, rect, bitmap);
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000377 }
378 } else {
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000379 gFailedSubsetDecodes.push_back().printf("Failed to decode region %s from %s",
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000380 subsetDim.c_str(), srcPath);
381 }
382 }
383 }
384 }
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000385
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000386 if (FLAGS_reencode) {
387 // Encode to the format the file was originally in, or PNG if the encoder for the same
388 // format is unavailable.
389 SkImageDecoder::Format format = codec->getFormat();
390 if (SkImageDecoder::kUnknown_Format == format) {
391 if (stream.rewind()) {
392 format = SkImageDecoder::GetStreamFormat(&stream);
393 }
394 if (SkImageDecoder::kUnknown_Format == format) {
395 const char* dot = strrchr(srcPath, '.');
396 if (NULL != dot) {
397 format = guess_format_from_suffix(dot);
398 }
399 if (SkImageDecoder::kUnknown_Format == format) {
400 SkDebugf("Could not determine type for '%s'\n", srcPath);
401 format = SkImageDecoder::kPNG_Format;
402 }
403
404 }
405 } else {
406 SkASSERT(!stream.rewind() || SkImageDecoder::GetStreamFormat(&stream) == format);
407 }
408 SkImageEncoder::Type type = format_to_type(format);
409 // format should never be kUnknown_Format, so type should never be kUnknown_Type.
410 SkASSERT(type != SkImageEncoder::kUnknown_Type);
411
412 SkImageEncoder* encoder = SkImageEncoder::Create(type);
413 if (NULL == encoder) {
414 type = SkImageEncoder::kPNG_Type;
415 encoder = SkImageEncoder::Create(type);
416 SkASSERT(encoder);
417 }
418 SkAutoTDelete<SkImageEncoder> ade(encoder);
419 // Encode to a stream.
420 SkDynamicMemoryWStream wStream;
421 if (!encoder->encodeStream(&wStream, bitmap, 100)) {
422 gEncodeFailures.push_back().printf("Failed to reencode %s to type '%s'", srcPath,
423 suffix_for_type(type));
424 return;
425 }
426
427 SkAutoTUnref<SkData> data(wStream.copyToData());
428 if (writePath != NULL && type != SkImageEncoder::kPNG_Type) {
429 // Write the encoded data to a file. Do not write to PNG, which will be written later,
430 // regardless of the input format.
431 SkString outPath;
432 make_outname(&outPath, writePath->c_str(), srcPath, suffix_for_type(type));
433 SkFILEWStream file(outPath.c_str());
434 if(file.write(data->data(), data->size())) {
435 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
436 } else {
437 gEncodeFailures.push_back().printf("Failed to write %s", outPath.c_str());
438 }
439 }
440 // Ensure that the reencoded data can still be decoded.
441 SkMemoryStream memStream(data);
442 SkBitmap redecodedBitmap;
443 SkImageDecoder::Format formatOnSecondDecode;
444 if (SkImageDecoder::DecodeStream(&memStream, &redecodedBitmap, SkBitmap::kNo_Config,
445 SkImageDecoder::kDecodePixels_Mode,
446 &formatOnSecondDecode)) {
447 SkASSERT(format_to_type(formatOnSecondDecode) == type);
448 } else {
449 gDecodeFailures.push_back().printf("Failed to redecode %s after reencoding to '%s'",
450 srcPath, suffix_for_type(type));
451 }
452 }
453
454 if (writePath != NULL) {
455 SkString outPath;
456 make_outname(&outPath, writePath->c_str(), srcPath, ".png");
457 if (write_bitmap(outPath.c_str(), &bitmap)) {
458 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
459 } else {
460 gEncodeFailures.push_back().set(outPath);
461 }
462 }
463}
464
465///////////////////////////////////////////////////////////////////////////////
466
scroggo@google.comb41ff952013-04-11 15:53:35 +0000467// If strings is not empty, print title, followed by each string on its own line starting
468// with a tab.
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000469// @return bool True if strings had at least one entry.
470static bool print_strings(const char* title, const SkTArray<SkString, false>& strings) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000471 if (strings.count() > 0) {
472 SkDebugf("%s:\n", title);
473 for (int i = 0; i < strings.count(); i++) {
474 SkDebugf("\t%s\n", strings[i].c_str());
475 }
476 SkDebugf("\n");
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000477 return true;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000478 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000479 return false;
reed@android.comaf459792009-04-24 19:52:53 +0000480}
481
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000482/**
483 * If directory is non null and does not end with a path separator, append one.
484 * @param directory SkString representing the path to a directory. If the last character is not a
485 * path separator (specific to the current OS), append one.
486 */
487static void append_path_separator_if_necessary(SkString* directory) {
488 if (directory != NULL && directory->c_str()[directory->size() - 1] != SkPATH_SEPARATOR) {
489 directory->appendf("%c", SkPATH_SEPARATOR);
490 }
491}
492
caryclark@google.com5987f582012-10-02 18:33:14 +0000493int tool_main(int argc, char** argv);
494int tool_main(int argc, char** argv) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000495 SkCommandLineFlags::SetUsage("Decode files, and optionally write the results to files.");
496 SkCommandLineFlags::Parse(argc, argv);
497
498 if (FLAGS_readPath.count() < 1) {
499 SkDebugf("Folder(s) or image(s) to decode are required.\n");
500 return -1;
501 }
502
503
reed@android.comaf459792009-04-24 19:52:53 +0000504 SkAutoGraphics ag;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000505
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000506 if (!FLAGS_readExpectationsPath.isEmpty()) {
507 gJsonExpectations.reset(SkNEW_ARGS(skiagm::JsonExpectationsSource,
508 (FLAGS_readExpectationsPath[0])));
509 }
510
reed@android.comaf459792009-04-24 19:52:53 +0000511 SkString outDir;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000512 SkString* outDirPtr;
reed@android.comaf459792009-04-24 19:52:53 +0000513
scroggo@google.comb41ff952013-04-11 15:53:35 +0000514 if (FLAGS_writePath.count() == 1) {
515 outDir.set(FLAGS_writePath[0]);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000516 append_path_separator_if_necessary(&outDir);
scroggo@google.comb41ff952013-04-11 15:53:35 +0000517 outDirPtr = &outDir;
518 } else {
519 outDirPtr = NULL;
520 }
521
522 for (int i = 0; i < FLAGS_readPath.count(); i++) {
523 if (strlen(FLAGS_readPath[i]) < 1) {
524 break;
525 }
526 SkOSFile::Iter iter(FLAGS_readPath[i]);
527 SkString filename;
528 if (iter.next(&filename)) {
529 SkString directory(FLAGS_readPath[i]);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000530 append_path_separator_if_necessary(&directory);
scroggo@google.comb41ff952013-04-11 15:53:35 +0000531 do {
532 SkString fullname(directory);
533 fullname.append(filename);
534 decodeFileAndWrite(fullname.c_str(), outDirPtr);
535 } while (iter.next(&filename));
536 } else {
537 decodeFileAndWrite(FLAGS_readPath[i], outDirPtr);
reed@android.comaf459792009-04-24 19:52:53 +0000538 }
539 }
540
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000541 if (!FLAGS_createExpectationsPath.isEmpty()) {
542 // Use an empty value for everything besides expectations, since the reader only cares
543 // about the expectations.
544 Json::Value nullValue;
545 Json::Value root = skiagm::CreateJsonTree(gExpectationsToWrite, nullValue, nullValue,
546 nullValue, nullValue);
547 std::string jsonStdString = root.toStyledString();
548 SkString path = SkStringPrintf("%s%cresults.json", FLAGS_createExpectationsPath[0],
549 SkPATH_SEPARATOR);
550 SkFILEWStream stream(path.c_str());
551 stream.write(jsonStdString.c_str(), jsonStdString.length());
552 }
scroggo@google.comb41ff952013-04-11 15:53:35 +0000553 // Add some space, since codecs may print warnings without newline.
554 SkDebugf("\n\n");
rmistry@google.comd6176b02012-08-23 18:14:13 +0000555
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000556 bool failed = print_strings("Invalid files", gInvalidStreams);
557 failed |= print_strings("Missing codec", gMissingCodecs);
558 failed |= print_strings("Failed to decode", gDecodeFailures);
559 failed |= print_strings("Failed to encode", gEncodeFailures);
560 print_strings("Decoded", gSuccessfulDecodes);
reed@android.comaf459792009-04-24 19:52:53 +0000561
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000562 if (FLAGS_testSubsetDecoding) {
563 failed |= print_strings("Failed subset decodes", gFailedSubsetDecodes);
564 print_strings("Decoded subsets", gSuccessfulSubsetDecodes);
565 }
566
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000567 return failed ? -1 : 0;
reed@android.comaf459792009-04-24 19:52:53 +0000568}
569
caryclark@google.com5987f582012-10-02 18:33:14 +0000570#if !defined SK_BUILD_FOR_IOS
571int main(int argc, char * const argv[]) {
572 return tool_main(argc, (char**) argv);
573}
574#endif