blob: 98cde5044c5c53d9f32b4cb038ca77735df345c6 [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
72static void make_outname(SkString* dst, const char outDir[], const char src[],
73 const char suffix[]) {
scroggo@google.comccd7afb2013-05-28 16:45:07 +000074 SkString basename = SkOSPath::SkBasename(src);
75 dst->set(SkOSPath::SkPathJoin(outDir, basename.c_str()));
scroggo@google.com39edf4c2013-04-25 17:33:51 +000076 if (!dst->endsWith(suffix)) {
scroggo@google.comb41ff952013-04-11 15:53:35 +000077 const char* cstyleDst = dst->c_str();
78 const char* dot = strrchr(cstyleDst, '.');
79 if (dot != NULL) {
80 int32_t index = SkToS32(dot - cstyleDst);
81 dst->remove(index, dst->size() - index);
82 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +000083 dst->append(suffix);
scroggo@google.comb41ff952013-04-11 15:53:35 +000084 }
85}
86
scroggo@google.com39edf4c2013-04-25 17:33:51 +000087// Store the names of the filenames to report later which ones failed, succeeded, and were
88// invalid.
89static SkTArray<SkString, false> gInvalidStreams;
90static SkTArray<SkString, false> gMissingCodecs;
91static SkTArray<SkString, false> gDecodeFailures;
92static SkTArray<SkString, false> gEncodeFailures;
93static SkTArray<SkString, false> gSuccessfulDecodes;
scroggo@google.com7e6fcee2013-05-03 20:14:28 +000094static SkTArray<SkString, false> gSuccessfulSubsetDecodes;
95static SkTArray<SkString, false> gFailedSubsetDecodes;
scroggo@google.com39edf4c2013-04-25 17:33:51 +000096
scroggo@google.com6843bdb2013-05-08 19:14:23 +000097// Expections read from a file specified by readExpectationsPath. The expectations must have been
98// previously written using createExpectationsPath.
99SkAutoTUnref<skiagm::JsonExpectationsSource> gJsonExpectations;
100
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000101static bool write_bitmap(const char outName[], SkBitmap* bm) {
102 SkBitmap bitmap8888;
103 if (SkBitmap::kARGB_8888_Config != bm->config()) {
104 if (!bm->copyTo(&bitmap8888, SkBitmap::kARGB_8888_Config)) {
105 return false;
106 }
107 bm = &bitmap8888;
108 }
109 // FIXME: This forces all pixels to be opaque, like the many implementations
110 // of force_all_opaque. These should be unified if they cannot be eliminated.
111 SkAutoLockPixels lock(*bm);
112 for (int y = 0; y < bm->height(); y++) {
113 for (int x = 0; x < bm->width(); x++) {
114 *bm->getAddr32(x, y) |= (SK_A32_MASK << SK_A32_SHIFT);
115 }
116 }
117 return SkImageEncoder::EncodeFile(outName, *bm, SkImageEncoder::kPNG_Type, 100);
118}
119
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000120/**
121 * Return a random SkIRect inside the range specified.
122 * @param rand Random number generator.
123 * @param maxX Exclusive maximum x-coordinate. SkIRect's fLeft and fRight will be
124 * in the range [0, maxX)
125 * @param maxY Exclusive maximum y-coordinate. SkIRect's fTop and fBottom will be
126 * in the range [0, maxY)
127 * @return SkIRect Non-empty, non-degenerate rectangle.
128 */
129static SkIRect generate_random_rect(SkRandom* rand, int32_t maxX, int32_t maxY) {
130 SkASSERT(maxX > 1 && maxY > 1);
131 int32_t left = rand->nextULessThan(maxX);
132 int32_t right = rand->nextULessThan(maxX);
133 int32_t top = rand->nextULessThan(maxY);
134 int32_t bottom = rand->nextULessThan(maxY);
135 SkIRect rect = SkIRect::MakeLTRB(left, top, right, bottom);
136 rect.sort();
137 // Make sure rect is not empty.
138 if (rect.fLeft == rect.fRight) {
139 if (rect.fLeft > 0) {
140 rect.fLeft--;
141 } else {
142 rect.fRight++;
143 // This branch is only taken if 0 == rect.fRight, and
144 // maxX must be at least 2, so it must still be in
145 // range.
146 SkASSERT(rect.fRight < maxX);
147 }
148 }
149 if (rect.fTop == rect.fBottom) {
150 if (rect.fTop > 0) {
151 rect.fTop--;
152 } else {
153 rect.fBottom++;
154 // Again, this must be in range.
155 SkASSERT(rect.fBottom < maxY);
156 }
157 }
158 return rect;
159}
160
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000161// Stored expectations to be written to a file if createExpectationsPath is specified.
162static Json::Value gExpectationsToWrite;
163
164/**
epoger@google.comd4993ff2013-05-24 14:33:28 +0000165 * If expectations are to be recorded, record the bitmap expectations into global
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000166 * expectations array.
167 */
168static void write_expectations(const SkBitmap& bitmap, const char* filename) {
169 if (!FLAGS_createExpectationsPath.isEmpty()) {
170 // Creates an Expectations object, and add it to the list to write.
171 skiagm::Expectations expectation(bitmap);
172 Json::Value value = expectation.asJsonValue();
173 gExpectationsToWrite[filename] = value;
174 }
175}
176
177/**
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000178 * Compare against an expectation for this filename, if there is one.
179 * @param bitmap SkBitmap to compare to the expected value.
180 * @param filename String used to find the expected value.
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000181 * @return bool True in any of these cases:
182 * - the bitmap matches the expectation.
183 * - there is no expectations file.
184 * False in any of these cases:
185 * - there is an expectations file, but no expectation for this bitmap.
186 * - there is an expectation for this bitmap, but it did not match.
187 * - expectation could not be computed from the bitmap.
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000188 */
189static bool compare_to_expectations_if_necessary(const SkBitmap& bitmap, const char* filename,
190 SkTArray<SkString, false>* failureArray) {
191 if (NULL == gJsonExpectations.get()) {
192 return true;
193 }
194
195 skiagm::Expectations jsExpectation = gJsonExpectations->get(filename);
196 if (jsExpectation.empty()) {
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000197 if (failureArray != NULL) {
198 failureArray->push_back().printf("decoded %s, but could not find expectation.",
199 filename);
200 }
201 return false;
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000202 }
203
epoger@google.comd4993ff2013-05-24 14:33:28 +0000204 skiagm::GmResultDigest resultDigest(bitmap);
205 if (!resultDigest.isValid()) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000206 if (failureArray != NULL) {
epoger@google.comd4993ff2013-05-24 14:33:28 +0000207 failureArray->push_back().printf("decoded %s, but could not create a GmResultDigest.",
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000208 filename);
209 }
210 return false;
211 }
212
epoger@google.comd4993ff2013-05-24 14:33:28 +0000213 if (jsExpectation.match(resultDigest)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000214 return true;
215 }
216
217 if (failureArray != NULL) {
218 failureArray->push_back().printf("decoded %s, but the result does not match "
219 "expectations.",
220 filename);
221 }
222 return false;
223}
224
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000225/**
226 * Helper function to write a bitmap subset to a file. Only called if subsets were created
227 * and a writePath was provided. Creates a subdirectory called 'subsets' and writes a PNG to
228 * that directory. Also creates a subdirectory called 'extracted' and writes a bitmap created
229 * using extractSubset to a PNG in that directory. Both files will represent the same
230 * subrectangle and have the same name for comparison.
231 * @param writePath Parent directory to hold the folders for the PNG files to write. Must
232 * not be NULL.
233 * @param filename Basename of the original file. Used to name the new files. Must not be
234 * NULL.
235 * @param subsetDim String representing the dimensions of the subset. Used to name the new
236 * files. Must not be NULL.
237 * @param bitmapFromDecodeSubset Pointer to SkBitmap created by SkImageDecoder::DecodeSubset,
238 * using rect as the area to decode.
239 * @param rect Rectangle of the area decoded into bitmapFromDecodeSubset. Used to call
240 * extractSubset on originalBitmap to create a bitmap with the same dimensions/pixels as
241 * bitmapFromDecodeSubset (assuming decodeSubset worked properly).
242 * @param originalBitmap SkBitmap decoded from the same stream as bitmapFromDecodeSubset,
243 * using SkImageDecoder::decode to get the entire image. Used to create a PNG file for
244 * comparison to the PNG created by bitmapFromDecodeSubset.
245 * @return bool Whether the function succeeded at drawing the decoded subset and the extracted
246 * subset to files.
247 */
248static bool write_subset(const char* writePath, const char* filename, const char* subsetDim,
249 SkBitmap* bitmapFromDecodeSubset, SkIRect rect,
250 const SkBitmap& originalBitmap) {
251 // All parameters must be valid.
252 SkASSERT(writePath != NULL);
253 SkASSERT(filename != NULL);
254 SkASSERT(subsetDim != NULL);
255 SkASSERT(bitmapFromDecodeSubset != NULL);
256
257 // Create a subdirectory to hold the results of decodeSubset.
scroggo@google.comccd7afb2013-05-28 16:45:07 +0000258 SkString dir = SkOSPath::SkPathJoin(writePath, "subsets");
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000259 if (!sk_mkdir(dir.c_str())) {
260 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
261 "create a directory to write to.", subsetDim,
262 filename);
263 return false;
264 }
265
266 // Write the subset to a file whose name includes the dimensions.
267 SkString suffix = SkStringPrintf("_%s.png", subsetDim);
268 SkString outPath;
269 make_outname(&outPath, dir.c_str(), filename, suffix.c_str());
270 SkAssertResult(write_bitmap(outPath.c_str(), bitmapFromDecodeSubset));
271 gSuccessfulSubsetDecodes.push_back().printf("\twrote %s", outPath.c_str());
272
273 // Also use extractSubset from the original for visual comparison.
274 // Write the result to a file in a separate subdirectory.
275 SkBitmap extractedSubset;
276 if (!originalBitmap.extractSubset(&extractedSubset, rect)) {
277 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
278 "extract a similar subset for comparison.",
279 subsetDim, filename);
280 return false;
281 }
282
scroggo@google.comccd7afb2013-05-28 16:45:07 +0000283 SkString dirExtracted = SkOSPath::SkPathJoin(writePath, "extracted");
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000284 if (!sk_mkdir(dirExtracted.c_str())) {
285 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
286 "create a directory for extractSubset comparison.",
287 subsetDim, filename);
288 return false;
289 }
290
291 make_outname(&outPath, dirExtracted.c_str(), filename, suffix.c_str());
292 SkAssertResult(write_bitmap(outPath.c_str(), &extractedSubset));
293 return true;
294}
295
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000296static void decodeFileAndWrite(const char srcPath[], const SkString* writePath) {
297 SkBitmap bitmap;
298 SkFILEStream stream(srcPath);
299 if (!stream.isValid()) {
300 gInvalidStreams.push_back().set(srcPath);
301 return;
302 }
303
304 SkImageDecoder* codec = SkImageDecoder::Factory(&stream);
305 if (NULL == codec) {
306 gMissingCodecs.push_back().set(srcPath);
307 return;
308 }
309
310 SkAutoTDelete<SkImageDecoder> ad(codec);
311
312 stream.rewind();
313 if (!codec->decode(&stream, &bitmap, SkBitmap::kARGB_8888_Config,
314 SkImageDecoder::kDecodePixels_Mode)) {
315 gDecodeFailures.push_back().set(srcPath);
316 return;
317 }
318
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000319 // Create a string representing just the filename itself, for use in json expectations.
scroggo@google.comccd7afb2013-05-28 16:45:07 +0000320 SkString basename = SkOSPath::SkBasename(srcPath);
321 const char* filename = basename.c_str();
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000322
323 if (compare_to_expectations_if_necessary(bitmap, filename, &gDecodeFailures)) {
324 gSuccessfulDecodes.push_back().printf("%s [%d %d]", srcPath, bitmap.width(),
325 bitmap.height());
326 }
327
328 write_expectations(bitmap, filename);
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000329
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000330 if (FLAGS_testSubsetDecoding) {
scroggo@google.com0018f752013-05-03 20:39:22 +0000331 SkDEBUGCODE(bool couldRewind =) stream.rewind();
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000332 SkASSERT(couldRewind);
333 int width, height;
334 // Build the tile index for decoding subsets. If the image is 1x1, skip subset
335 // decoding since there are no smaller subsets.
336 if (codec->buildTileIndex(&stream, &width, &height) && width > 1 && height > 1) {
337 SkASSERT(bitmap.width() == width && bitmap.height() == height);
338 // Call decodeSubset multiple times:
339 SkRandom rand(0);
340 for (int i = 0; i < 5; i++) {
341 SkBitmap bitmapFromDecodeSubset;
342 // FIXME: Come up with a more representative set of rectangles.
343 SkIRect rect = generate_random_rect(&rand, width, height);
344 SkString subsetDim = SkStringPrintf("[%d,%d,%d,%d]", rect.fLeft, rect.fTop,
345 rect.fRight, rect.fBottom);
346 if (codec->decodeSubset(&bitmapFromDecodeSubset, rect, SkBitmap::kNo_Config)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000347 SkString subsetName = SkStringPrintf("%s_%s", filename, subsetDim.c_str());
348 if (compare_to_expectations_if_necessary(bitmapFromDecodeSubset,
349 subsetName.c_str(),
350 &gFailedSubsetDecodes)) {
351 gSuccessfulSubsetDecodes.push_back().printf("Decoded subset %s from %s",
352 subsetDim.c_str(), srcPath);
353 }
354
355 write_expectations(bitmapFromDecodeSubset, subsetName.c_str());
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000356 if (writePath != NULL) {
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000357 write_subset(writePath->c_str(), filename, subsetDim.c_str(),
358 &bitmapFromDecodeSubset, rect, bitmap);
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000359 }
360 } else {
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000361 gFailedSubsetDecodes.push_back().printf("Failed to decode region %s from %s",
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000362 subsetDim.c_str(), srcPath);
363 }
364 }
365 }
366 }
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000367
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000368 if (FLAGS_reencode) {
369 // Encode to the format the file was originally in, or PNG if the encoder for the same
370 // format is unavailable.
371 SkImageDecoder::Format format = codec->getFormat();
372 if (SkImageDecoder::kUnknown_Format == format) {
373 if (stream.rewind()) {
374 format = SkImageDecoder::GetStreamFormat(&stream);
375 }
376 if (SkImageDecoder::kUnknown_Format == format) {
377 const char* dot = strrchr(srcPath, '.');
378 if (NULL != dot) {
379 format = guess_format_from_suffix(dot);
380 }
381 if (SkImageDecoder::kUnknown_Format == format) {
382 SkDebugf("Could not determine type for '%s'\n", srcPath);
383 format = SkImageDecoder::kPNG_Format;
384 }
385
386 }
387 } else {
388 SkASSERT(!stream.rewind() || SkImageDecoder::GetStreamFormat(&stream) == format);
389 }
390 SkImageEncoder::Type type = format_to_type(format);
391 // format should never be kUnknown_Format, so type should never be kUnknown_Type.
392 SkASSERT(type != SkImageEncoder::kUnknown_Type);
393
394 SkImageEncoder* encoder = SkImageEncoder::Create(type);
395 if (NULL == encoder) {
396 type = SkImageEncoder::kPNG_Type;
397 encoder = SkImageEncoder::Create(type);
398 SkASSERT(encoder);
399 }
400 SkAutoTDelete<SkImageEncoder> ade(encoder);
401 // Encode to a stream.
402 SkDynamicMemoryWStream wStream;
403 if (!encoder->encodeStream(&wStream, bitmap, 100)) {
404 gEncodeFailures.push_back().printf("Failed to reencode %s to type '%s'", srcPath,
405 suffix_for_type(type));
406 return;
407 }
408
409 SkAutoTUnref<SkData> data(wStream.copyToData());
410 if (writePath != NULL && type != SkImageEncoder::kPNG_Type) {
411 // Write the encoded data to a file. Do not write to PNG, which will be written later,
412 // regardless of the input format.
413 SkString outPath;
414 make_outname(&outPath, writePath->c_str(), srcPath, suffix_for_type(type));
415 SkFILEWStream file(outPath.c_str());
416 if(file.write(data->data(), data->size())) {
417 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
418 } else {
419 gEncodeFailures.push_back().printf("Failed to write %s", outPath.c_str());
420 }
421 }
422 // Ensure that the reencoded data can still be decoded.
423 SkMemoryStream memStream(data);
424 SkBitmap redecodedBitmap;
425 SkImageDecoder::Format formatOnSecondDecode;
426 if (SkImageDecoder::DecodeStream(&memStream, &redecodedBitmap, SkBitmap::kNo_Config,
427 SkImageDecoder::kDecodePixels_Mode,
428 &formatOnSecondDecode)) {
429 SkASSERT(format_to_type(formatOnSecondDecode) == type);
430 } else {
431 gDecodeFailures.push_back().printf("Failed to redecode %s after reencoding to '%s'",
432 srcPath, suffix_for_type(type));
433 }
434 }
435
436 if (writePath != NULL) {
437 SkString outPath;
438 make_outname(&outPath, writePath->c_str(), srcPath, ".png");
439 if (write_bitmap(outPath.c_str(), &bitmap)) {
440 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
441 } else {
442 gEncodeFailures.push_back().set(outPath);
443 }
444 }
445}
446
447///////////////////////////////////////////////////////////////////////////////
448
scroggo@google.comb41ff952013-04-11 15:53:35 +0000449// If strings is not empty, print title, followed by each string on its own line starting
450// with a tab.
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000451// @return bool True if strings had at least one entry.
452static bool print_strings(const char* title, const SkTArray<SkString, false>& strings) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000453 if (strings.count() > 0) {
454 SkDebugf("%s:\n", title);
455 for (int i = 0; i < strings.count(); i++) {
456 SkDebugf("\t%s\n", strings[i].c_str());
457 }
458 SkDebugf("\n");
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000459 return true;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000460 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000461 return false;
reed@android.comaf459792009-04-24 19:52:53 +0000462}
463
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000464/**
465 * If directory is non null and does not end with a path separator, append one.
466 * @param directory SkString representing the path to a directory. If the last character is not a
467 * path separator (specific to the current OS), append one.
468 */
469static void append_path_separator_if_necessary(SkString* directory) {
470 if (directory != NULL && directory->c_str()[directory->size() - 1] != SkPATH_SEPARATOR) {
471 directory->appendf("%c", SkPATH_SEPARATOR);
472 }
473}
474
caryclark@google.com5987f582012-10-02 18:33:14 +0000475int tool_main(int argc, char** argv);
476int tool_main(int argc, char** argv) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000477 SkCommandLineFlags::SetUsage("Decode files, and optionally write the results to files.");
478 SkCommandLineFlags::Parse(argc, argv);
479
480 if (FLAGS_readPath.count() < 1) {
481 SkDebugf("Folder(s) or image(s) to decode are required.\n");
482 return -1;
483 }
484
485
reed@android.comaf459792009-04-24 19:52:53 +0000486 SkAutoGraphics ag;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000487
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000488 if (!FLAGS_readExpectationsPath.isEmpty()) {
489 gJsonExpectations.reset(SkNEW_ARGS(skiagm::JsonExpectationsSource,
490 (FLAGS_readExpectationsPath[0])));
491 }
492
reed@android.comaf459792009-04-24 19:52:53 +0000493 SkString outDir;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000494 SkString* outDirPtr;
reed@android.comaf459792009-04-24 19:52:53 +0000495
scroggo@google.comb41ff952013-04-11 15:53:35 +0000496 if (FLAGS_writePath.count() == 1) {
497 outDir.set(FLAGS_writePath[0]);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000498 append_path_separator_if_necessary(&outDir);
scroggo@google.comb41ff952013-04-11 15:53:35 +0000499 outDirPtr = &outDir;
500 } else {
501 outDirPtr = NULL;
502 }
503
504 for (int i = 0; i < FLAGS_readPath.count(); i++) {
505 if (strlen(FLAGS_readPath[i]) < 1) {
506 break;
507 }
508 SkOSFile::Iter iter(FLAGS_readPath[i]);
509 SkString filename;
510 if (iter.next(&filename)) {
511 SkString directory(FLAGS_readPath[i]);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000512 append_path_separator_if_necessary(&directory);
scroggo@google.comb41ff952013-04-11 15:53:35 +0000513 do {
514 SkString fullname(directory);
515 fullname.append(filename);
516 decodeFileAndWrite(fullname.c_str(), outDirPtr);
517 } while (iter.next(&filename));
518 } else {
519 decodeFileAndWrite(FLAGS_readPath[i], outDirPtr);
reed@android.comaf459792009-04-24 19:52:53 +0000520 }
521 }
522
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000523 if (!FLAGS_createExpectationsPath.isEmpty()) {
524 // Use an empty value for everything besides expectations, since the reader only cares
525 // about the expectations.
526 Json::Value nullValue;
527 Json::Value root = skiagm::CreateJsonTree(gExpectationsToWrite, nullValue, nullValue,
528 nullValue, nullValue);
529 std::string jsonStdString = root.toStyledString();
530 SkString path = SkStringPrintf("%s%cresults.json", FLAGS_createExpectationsPath[0],
531 SkPATH_SEPARATOR);
532 SkFILEWStream stream(path.c_str());
533 stream.write(jsonStdString.c_str(), jsonStdString.length());
534 }
scroggo@google.comb41ff952013-04-11 15:53:35 +0000535 // Add some space, since codecs may print warnings without newline.
536 SkDebugf("\n\n");
rmistry@google.comd6176b02012-08-23 18:14:13 +0000537
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000538 bool failed = print_strings("Invalid files", gInvalidStreams);
539 failed |= print_strings("Missing codec", gMissingCodecs);
540 failed |= print_strings("Failed to decode", gDecodeFailures);
541 failed |= print_strings("Failed to encode", gEncodeFailures);
542 print_strings("Decoded", gSuccessfulDecodes);
reed@android.comaf459792009-04-24 19:52:53 +0000543
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000544 if (FLAGS_testSubsetDecoding) {
545 failed |= print_strings("Failed subset decodes", gFailedSubsetDecodes);
546 print_strings("Decoded subsets", gSuccessfulSubsetDecodes);
547 }
548
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000549 return failed ? -1 : 0;
reed@android.comaf459792009-04-24 19:52:53 +0000550}
551
caryclark@google.com5987f582012-10-02 18:33:14 +0000552#if !defined SK_BUILD_FOR_IOS
553int main(int argc, char * const argv[]) {
554 return tool_main(argc, (char**) argv);
555}
556#endif