blob: f52cf3221764c2504757904c45c3864472978e5a [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"
reed@android.comaf459792009-04-24 19:52:53 +000013#include "SkGraphics.h"
14#include "SkImageDecoder.h"
15#include "SkImageEncoder.h"
scroggo@google.comb41ff952013-04-11 15:53:35 +000016#include "SkOSFile.h"
scroggo@google.com7e6fcee2013-05-03 20:14:28 +000017#include "SkRandom.h"
reed@android.comaf459792009-04-24 19:52:53 +000018#include "SkStream.h"
scroggo@google.comb41ff952013-04-11 15:53:35 +000019#include "SkTArray.h"
reed@android.comaf459792009-04-24 19:52:53 +000020#include "SkTemplates.h"
21
scroggo@google.com6843bdb2013-05-08 19:14:23 +000022DEFINE_string(createExpectationsPath, "", "Path to write JSON expectations.");
scroggo@google.comb41ff952013-04-11 15:53:35 +000023DEFINE_string2(readPath, r, "", "Folder(s) and files to decode images. Required.");
scroggo@google.com6843bdb2013-05-08 19:14:23 +000024DEFINE_string(readExpectationsPath, "", "Path to read JSON expectations from.");
scroggo@google.comb41ff952013-04-11 15:53:35 +000025DEFINE_string2(writePath, w, "", "Write rendered images into this directory.");
scroggo@google.com39edf4c2013-04-25 17:33:51 +000026DEFINE_bool(reencode, true, "Reencode the images to test encoding.");
scroggo@google.com7e6fcee2013-05-03 20:14:28 +000027DEFINE_bool(testSubsetDecoding, true, "Test decoding subsets of images.");
scroggo@google.comb41ff952013-04-11 15:53:35 +000028
scroggo@google.com39edf4c2013-04-25 17:33:51 +000029struct Format {
30 SkImageEncoder::Type fType;
31 SkImageDecoder::Format fFormat;
32 const char* fSuffix;
33};
scroggo@google.comb41ff952013-04-11 15:53:35 +000034
scroggo@google.com39edf4c2013-04-25 17:33:51 +000035static const Format gFormats[] = {
36 { SkImageEncoder::kBMP_Type, SkImageDecoder::kBMP_Format, ".bmp" },
37 { SkImageEncoder::kGIF_Type, SkImageDecoder::kGIF_Format, ".gif" },
38 { SkImageEncoder::kICO_Type, SkImageDecoder::kICO_Format, ".ico" },
39 { SkImageEncoder::kJPEG_Type, SkImageDecoder::kJPEG_Format, ".jpg" },
40 { SkImageEncoder::kPNG_Type, SkImageDecoder::kPNG_Format, ".png" },
41 { SkImageEncoder::kWBMP_Type, SkImageDecoder::kWBMP_Format, ".wbmp" },
42 { SkImageEncoder::kWEBP_Type, SkImageDecoder::kWEBP_Format, ".webp" }
43};
44
45static SkImageEncoder::Type format_to_type(SkImageDecoder::Format format) {
46 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
47 if (gFormats[i].fFormat == format) {
48 return gFormats[i].fType;
49 }
reed@android.comaf459792009-04-24 19:52:53 +000050 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +000051 return SkImageEncoder::kUnknown_Type;
reed@android.comaf459792009-04-24 19:52:53 +000052}
53
scroggo@google.com39edf4c2013-04-25 17:33:51 +000054static const char* suffix_for_type(SkImageEncoder::Type type) {
55 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
56 if (gFormats[i].fType == type) {
57 return gFormats[i].fSuffix;
58 }
59 }
60 return "";
61}
reed@android.comaf459792009-04-24 19:52:53 +000062
scroggo@google.com39edf4c2013-04-25 17:33:51 +000063static SkImageDecoder::Format guess_format_from_suffix(const char suffix[]) {
64 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
65 if (strcmp(suffix, gFormats[i].fSuffix) == 0) {
66 return gFormats[i].fFormat;
67 }
68 }
69 return SkImageDecoder::kUnknown_Format;
70}
71
scroggo@google.com9da0e1d2013-05-15 18:14:36 +000072/**
73 * Return the name of the file, ignoring the directory structure.
74 * Does not create a new string.
75 * @param fullPath Full path to the file.
76 * @return string The basename of the file - anything beyond the final slash, or the full name
77 * if there is no slash.
78 * TODO: Might this be useful as a utility function in SkOSFile? Would it be more appropriate to
79 * create a new string?
80 */
81static const char* SkBasename(const char* fullPath) {
82 const char* filename = strrchr(fullPath, SkPATH_SEPARATOR);
83 if (NULL == filename || *++filename == '\0') {
84 filename = fullPath;
85 }
86 return filename;
87}
88
scroggo@google.com39edf4c2013-04-25 17:33:51 +000089static void make_outname(SkString* dst, const char outDir[], const char src[],
90 const char suffix[]) {
scroggo@google.com9da0e1d2013-05-15 18:14:36 +000091 const char* basename = SkBasename(src);
92 dst->set(skiagm::SkPathJoin(outDir, basename));
scroggo@google.com39edf4c2013-04-25 17:33:51 +000093 if (!dst->endsWith(suffix)) {
scroggo@google.comb41ff952013-04-11 15:53:35 +000094 const char* cstyleDst = dst->c_str();
95 const char* dot = strrchr(cstyleDst, '.');
96 if (dot != NULL) {
97 int32_t index = SkToS32(dot - cstyleDst);
98 dst->remove(index, dst->size() - index);
99 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000100 dst->append(suffix);
scroggo@google.comb41ff952013-04-11 15:53:35 +0000101 }
102}
103
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000104// Store the names of the filenames to report later which ones failed, succeeded, and were
105// invalid.
106static SkTArray<SkString, false> gInvalidStreams;
107static SkTArray<SkString, false> gMissingCodecs;
108static SkTArray<SkString, false> gDecodeFailures;
109static SkTArray<SkString, false> gEncodeFailures;
110static SkTArray<SkString, false> gSuccessfulDecodes;
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000111static SkTArray<SkString, false> gSuccessfulSubsetDecodes;
112static SkTArray<SkString, false> gFailedSubsetDecodes;
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000113
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000114// Expections read from a file specified by readExpectationsPath. The expectations must have been
115// previously written using createExpectationsPath.
116SkAutoTUnref<skiagm::JsonExpectationsSource> gJsonExpectations;
117
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000118static bool write_bitmap(const char outName[], SkBitmap* bm) {
119 SkBitmap bitmap8888;
120 if (SkBitmap::kARGB_8888_Config != bm->config()) {
121 if (!bm->copyTo(&bitmap8888, SkBitmap::kARGB_8888_Config)) {
122 return false;
123 }
124 bm = &bitmap8888;
125 }
126 // FIXME: This forces all pixels to be opaque, like the many implementations
127 // of force_all_opaque. These should be unified if they cannot be eliminated.
128 SkAutoLockPixels lock(*bm);
129 for (int y = 0; y < bm->height(); y++) {
130 for (int x = 0; x < bm->width(); x++) {
131 *bm->getAddr32(x, y) |= (SK_A32_MASK << SK_A32_SHIFT);
132 }
133 }
134 return SkImageEncoder::EncodeFile(outName, *bm, SkImageEncoder::kPNG_Type, 100);
135}
136
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000137/**
138 * Return a random SkIRect inside the range specified.
139 * @param rand Random number generator.
140 * @param maxX Exclusive maximum x-coordinate. SkIRect's fLeft and fRight will be
141 * in the range [0, maxX)
142 * @param maxY Exclusive maximum y-coordinate. SkIRect's fTop and fBottom will be
143 * in the range [0, maxY)
144 * @return SkIRect Non-empty, non-degenerate rectangle.
145 */
146static SkIRect generate_random_rect(SkRandom* rand, int32_t maxX, int32_t maxY) {
147 SkASSERT(maxX > 1 && maxY > 1);
148 int32_t left = rand->nextULessThan(maxX);
149 int32_t right = rand->nextULessThan(maxX);
150 int32_t top = rand->nextULessThan(maxY);
151 int32_t bottom = rand->nextULessThan(maxY);
152 SkIRect rect = SkIRect::MakeLTRB(left, top, right, bottom);
153 rect.sort();
154 // Make sure rect is not empty.
155 if (rect.fLeft == rect.fRight) {
156 if (rect.fLeft > 0) {
157 rect.fLeft--;
158 } else {
159 rect.fRight++;
160 // This branch is only taken if 0 == rect.fRight, and
161 // maxX must be at least 2, so it must still be in
162 // range.
163 SkASSERT(rect.fRight < maxX);
164 }
165 }
166 if (rect.fTop == rect.fBottom) {
167 if (rect.fTop > 0) {
168 rect.fTop--;
169 } else {
170 rect.fBottom++;
171 // Again, this must be in range.
172 SkASSERT(rect.fBottom < maxY);
173 }
174 }
175 return rect;
176}
177
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000178// Stored expectations to be written to a file if createExpectationsPath is specified.
179static Json::Value gExpectationsToWrite;
180
181/**
epoger@google.comd4993ff2013-05-24 14:33:28 +0000182 * If expectations are to be recorded, record the bitmap expectations into global
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000183 * expectations array.
184 */
185static void write_expectations(const SkBitmap& bitmap, const char* filename) {
186 if (!FLAGS_createExpectationsPath.isEmpty()) {
187 // Creates an Expectations object, and add it to the list to write.
188 skiagm::Expectations expectation(bitmap);
189 Json::Value value = expectation.asJsonValue();
190 gExpectationsToWrite[filename] = value;
191 }
192}
193
194/**
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000195 * Compare against an expectation for this filename, if there is one.
196 * @param bitmap SkBitmap to compare to the expected value.
197 * @param filename String used to find the expected value.
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000198 * @return bool True in any of these cases:
199 * - the bitmap matches the expectation.
200 * - there is no expectations file.
201 * False in any of these cases:
202 * - there is an expectations file, but no expectation for this bitmap.
203 * - there is an expectation for this bitmap, but it did not match.
204 * - expectation could not be computed from the bitmap.
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000205 */
206static bool compare_to_expectations_if_necessary(const SkBitmap& bitmap, const char* filename,
207 SkTArray<SkString, false>* failureArray) {
208 if (NULL == gJsonExpectations.get()) {
209 return true;
210 }
211
212 skiagm::Expectations jsExpectation = gJsonExpectations->get(filename);
213 if (jsExpectation.empty()) {
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000214 if (failureArray != NULL) {
215 failureArray->push_back().printf("decoded %s, but could not find expectation.",
216 filename);
217 }
218 return false;
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000219 }
220
epoger@google.comd4993ff2013-05-24 14:33:28 +0000221 skiagm::GmResultDigest resultDigest(bitmap);
222 if (!resultDigest.isValid()) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000223 if (failureArray != NULL) {
epoger@google.comd4993ff2013-05-24 14:33:28 +0000224 failureArray->push_back().printf("decoded %s, but could not create a GmResultDigest.",
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000225 filename);
226 }
227 return false;
228 }
229
epoger@google.comd4993ff2013-05-24 14:33:28 +0000230 if (jsExpectation.match(resultDigest)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000231 return true;
232 }
233
234 if (failureArray != NULL) {
235 failureArray->push_back().printf("decoded %s, but the result does not match "
236 "expectations.",
237 filename);
238 }
239 return false;
240}
241
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000242/**
243 * Helper function to write a bitmap subset to a file. Only called if subsets were created
244 * and a writePath was provided. Creates a subdirectory called 'subsets' and writes a PNG to
245 * that directory. Also creates a subdirectory called 'extracted' and writes a bitmap created
246 * using extractSubset to a PNG in that directory. Both files will represent the same
247 * subrectangle and have the same name for comparison.
248 * @param writePath Parent directory to hold the folders for the PNG files to write. Must
249 * not be NULL.
250 * @param filename Basename of the original file. Used to name the new files. Must not be
251 * NULL.
252 * @param subsetDim String representing the dimensions of the subset. Used to name the new
253 * files. Must not be NULL.
254 * @param bitmapFromDecodeSubset Pointer to SkBitmap created by SkImageDecoder::DecodeSubset,
255 * using rect as the area to decode.
256 * @param rect Rectangle of the area decoded into bitmapFromDecodeSubset. Used to call
257 * extractSubset on originalBitmap to create a bitmap with the same dimensions/pixels as
258 * bitmapFromDecodeSubset (assuming decodeSubset worked properly).
259 * @param originalBitmap SkBitmap decoded from the same stream as bitmapFromDecodeSubset,
260 * using SkImageDecoder::decode to get the entire image. Used to create a PNG file for
261 * comparison to the PNG created by bitmapFromDecodeSubset.
262 * @return bool Whether the function succeeded at drawing the decoded subset and the extracted
263 * subset to files.
264 */
265static bool write_subset(const char* writePath, const char* filename, const char* subsetDim,
266 SkBitmap* bitmapFromDecodeSubset, SkIRect rect,
267 const SkBitmap& originalBitmap) {
268 // All parameters must be valid.
269 SkASSERT(writePath != NULL);
270 SkASSERT(filename != NULL);
271 SkASSERT(subsetDim != NULL);
272 SkASSERT(bitmapFromDecodeSubset != NULL);
273
274 // Create a subdirectory to hold the results of decodeSubset.
275 // TODO: Move SkPathJoin into SkOSFile.h
276 SkString dir = skiagm::SkPathJoin(writePath, "subsets");
277 if (!sk_mkdir(dir.c_str())) {
278 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
279 "create a directory to write to.", subsetDim,
280 filename);
281 return false;
282 }
283
284 // Write the subset to a file whose name includes the dimensions.
285 SkString suffix = SkStringPrintf("_%s.png", subsetDim);
286 SkString outPath;
287 make_outname(&outPath, dir.c_str(), filename, suffix.c_str());
288 SkAssertResult(write_bitmap(outPath.c_str(), bitmapFromDecodeSubset));
289 gSuccessfulSubsetDecodes.push_back().printf("\twrote %s", outPath.c_str());
290
291 // Also use extractSubset from the original for visual comparison.
292 // Write the result to a file in a separate subdirectory.
293 SkBitmap extractedSubset;
294 if (!originalBitmap.extractSubset(&extractedSubset, rect)) {
295 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
296 "extract a similar subset for comparison.",
297 subsetDim, filename);
298 return false;
299 }
300
301 SkString dirExtracted = skiagm::SkPathJoin(writePath, "extracted");
302 if (!sk_mkdir(dirExtracted.c_str())) {
303 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
304 "create a directory for extractSubset comparison.",
305 subsetDim, filename);
306 return false;
307 }
308
309 make_outname(&outPath, dirExtracted.c_str(), filename, suffix.c_str());
310 SkAssertResult(write_bitmap(outPath.c_str(), &extractedSubset));
311 return true;
312}
313
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000314static void decodeFileAndWrite(const char srcPath[], const SkString* writePath) {
315 SkBitmap bitmap;
316 SkFILEStream stream(srcPath);
317 if (!stream.isValid()) {
318 gInvalidStreams.push_back().set(srcPath);
319 return;
320 }
321
322 SkImageDecoder* codec = SkImageDecoder::Factory(&stream);
323 if (NULL == codec) {
324 gMissingCodecs.push_back().set(srcPath);
325 return;
326 }
327
328 SkAutoTDelete<SkImageDecoder> ad(codec);
329
330 stream.rewind();
331 if (!codec->decode(&stream, &bitmap, SkBitmap::kARGB_8888_Config,
332 SkImageDecoder::kDecodePixels_Mode)) {
333 gDecodeFailures.push_back().set(srcPath);
334 return;
335 }
336
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000337 // Create a string representing just the filename itself, for use in json expectations.
338 const char* filename = SkBasename(srcPath);
339
340 if (compare_to_expectations_if_necessary(bitmap, filename, &gDecodeFailures)) {
341 gSuccessfulDecodes.push_back().printf("%s [%d %d]", srcPath, bitmap.width(),
342 bitmap.height());
343 }
344
345 write_expectations(bitmap, filename);
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000346
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000347 if (FLAGS_testSubsetDecoding) {
scroggo@google.com0018f752013-05-03 20:39:22 +0000348 SkDEBUGCODE(bool couldRewind =) stream.rewind();
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000349 SkASSERT(couldRewind);
350 int width, height;
351 // Build the tile index for decoding subsets. If the image is 1x1, skip subset
352 // decoding since there are no smaller subsets.
353 if (codec->buildTileIndex(&stream, &width, &height) && width > 1 && height > 1) {
354 SkASSERT(bitmap.width() == width && bitmap.height() == height);
355 // Call decodeSubset multiple times:
356 SkRandom rand(0);
357 for (int i = 0; i < 5; i++) {
358 SkBitmap bitmapFromDecodeSubset;
359 // FIXME: Come up with a more representative set of rectangles.
360 SkIRect rect = generate_random_rect(&rand, width, height);
361 SkString subsetDim = SkStringPrintf("[%d,%d,%d,%d]", rect.fLeft, rect.fTop,
362 rect.fRight, rect.fBottom);
363 if (codec->decodeSubset(&bitmapFromDecodeSubset, rect, SkBitmap::kNo_Config)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000364 SkString subsetName = SkStringPrintf("%s_%s", filename, subsetDim.c_str());
365 if (compare_to_expectations_if_necessary(bitmapFromDecodeSubset,
366 subsetName.c_str(),
367 &gFailedSubsetDecodes)) {
368 gSuccessfulSubsetDecodes.push_back().printf("Decoded subset %s from %s",
369 subsetDim.c_str(), srcPath);
370 }
371
372 write_expectations(bitmapFromDecodeSubset, subsetName.c_str());
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000373 if (writePath != NULL) {
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000374 write_subset(writePath->c_str(), filename, subsetDim.c_str(),
375 &bitmapFromDecodeSubset, rect, bitmap);
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000376 }
377 } else {
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000378 gFailedSubsetDecodes.push_back().printf("Failed to decode region %s from %s",
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000379 subsetDim.c_str(), srcPath);
380 }
381 }
382 }
383 }
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000384
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000385 if (FLAGS_reencode) {
386 // Encode to the format the file was originally in, or PNG if the encoder for the same
387 // format is unavailable.
388 SkImageDecoder::Format format = codec->getFormat();
389 if (SkImageDecoder::kUnknown_Format == format) {
390 if (stream.rewind()) {
391 format = SkImageDecoder::GetStreamFormat(&stream);
392 }
393 if (SkImageDecoder::kUnknown_Format == format) {
394 const char* dot = strrchr(srcPath, '.');
395 if (NULL != dot) {
396 format = guess_format_from_suffix(dot);
397 }
398 if (SkImageDecoder::kUnknown_Format == format) {
399 SkDebugf("Could not determine type for '%s'\n", srcPath);
400 format = SkImageDecoder::kPNG_Format;
401 }
402
403 }
404 } else {
405 SkASSERT(!stream.rewind() || SkImageDecoder::GetStreamFormat(&stream) == format);
406 }
407 SkImageEncoder::Type type = format_to_type(format);
408 // format should never be kUnknown_Format, so type should never be kUnknown_Type.
409 SkASSERT(type != SkImageEncoder::kUnknown_Type);
410
411 SkImageEncoder* encoder = SkImageEncoder::Create(type);
412 if (NULL == encoder) {
413 type = SkImageEncoder::kPNG_Type;
414 encoder = SkImageEncoder::Create(type);
415 SkASSERT(encoder);
416 }
417 SkAutoTDelete<SkImageEncoder> ade(encoder);
418 // Encode to a stream.
419 SkDynamicMemoryWStream wStream;
420 if (!encoder->encodeStream(&wStream, bitmap, 100)) {
421 gEncodeFailures.push_back().printf("Failed to reencode %s to type '%s'", srcPath,
422 suffix_for_type(type));
423 return;
424 }
425
426 SkAutoTUnref<SkData> data(wStream.copyToData());
427 if (writePath != NULL && type != SkImageEncoder::kPNG_Type) {
428 // Write the encoded data to a file. Do not write to PNG, which will be written later,
429 // regardless of the input format.
430 SkString outPath;
431 make_outname(&outPath, writePath->c_str(), srcPath, suffix_for_type(type));
432 SkFILEWStream file(outPath.c_str());
433 if(file.write(data->data(), data->size())) {
434 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
435 } else {
436 gEncodeFailures.push_back().printf("Failed to write %s", outPath.c_str());
437 }
438 }
439 // Ensure that the reencoded data can still be decoded.
440 SkMemoryStream memStream(data);
441 SkBitmap redecodedBitmap;
442 SkImageDecoder::Format formatOnSecondDecode;
443 if (SkImageDecoder::DecodeStream(&memStream, &redecodedBitmap, SkBitmap::kNo_Config,
444 SkImageDecoder::kDecodePixels_Mode,
445 &formatOnSecondDecode)) {
446 SkASSERT(format_to_type(formatOnSecondDecode) == type);
447 } else {
448 gDecodeFailures.push_back().printf("Failed to redecode %s after reencoding to '%s'",
449 srcPath, suffix_for_type(type));
450 }
451 }
452
453 if (writePath != NULL) {
454 SkString outPath;
455 make_outname(&outPath, writePath->c_str(), srcPath, ".png");
456 if (write_bitmap(outPath.c_str(), &bitmap)) {
457 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
458 } else {
459 gEncodeFailures.push_back().set(outPath);
460 }
461 }
462}
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.com6843bdb2013-05-08 19:14:23 +0000505 if (!FLAGS_readExpectationsPath.isEmpty()) {
506 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++) {
522 if (strlen(FLAGS_readPath[i]) < 1) {
523 break;
524 }
525 SkOSFile::Iter iter(FLAGS_readPath[i]);
526 SkString filename;
527 if (iter.next(&filename)) {
528 SkString directory(FLAGS_readPath[i]);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000529 append_path_separator_if_necessary(&directory);
scroggo@google.comb41ff952013-04-11 15:53:35 +0000530 do {
531 SkString fullname(directory);
532 fullname.append(filename);
533 decodeFileAndWrite(fullname.c_str(), outDirPtr);
534 } while (iter.next(&filename));
535 } else {
536 decodeFileAndWrite(FLAGS_readPath[i], outDirPtr);
reed@android.comaf459792009-04-24 19:52:53 +0000537 }
538 }
539
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000540 if (!FLAGS_createExpectationsPath.isEmpty()) {
541 // Use an empty value for everything besides expectations, since the reader only cares
542 // about the expectations.
543 Json::Value nullValue;
544 Json::Value root = skiagm::CreateJsonTree(gExpectationsToWrite, nullValue, nullValue,
545 nullValue, nullValue);
546 std::string jsonStdString = root.toStyledString();
547 SkString path = SkStringPrintf("%s%cresults.json", FLAGS_createExpectationsPath[0],
548 SkPATH_SEPARATOR);
549 SkFILEWStream stream(path.c_str());
550 stream.write(jsonStdString.c_str(), jsonStdString.length());
551 }
scroggo@google.comb41ff952013-04-11 15:53:35 +0000552 // Add some space, since codecs may print warnings without newline.
553 SkDebugf("\n\n");
rmistry@google.comd6176b02012-08-23 18:14:13 +0000554
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000555 bool failed = print_strings("Invalid files", gInvalidStreams);
556 failed |= print_strings("Missing codec", gMissingCodecs);
557 failed |= print_strings("Failed to decode", gDecodeFailures);
558 failed |= print_strings("Failed to encode", gEncodeFailures);
559 print_strings("Decoded", gSuccessfulDecodes);
reed@android.comaf459792009-04-24 19:52:53 +0000560
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000561 if (FLAGS_testSubsetDecoding) {
562 failed |= print_strings("Failed subset decodes", gFailedSubsetDecodes);
563 print_strings("Decoded subsets", gSuccessfulSubsetDecodes);
564 }
565
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000566 return failed ? -1 : 0;
reed@android.comaf459792009-04-24 19:52:53 +0000567}
568
caryclark@google.com5987f582012-10-02 18:33:14 +0000569#if !defined SK_BUILD_FOR_IOS
570int main(int argc, char * const argv[]) {
571 return tool_main(argc, (char**) argv);
572}
573#endif