blob: 9262958d7187ea8257bc60cf922f63a09f5e9ead [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.comb41ff952013-04-11 15:53:35 +000026DEFINE_string2(readPath, r, "", "Folder(s) and files to decode images. Required.");
scroggo@google.com6843bdb2013-05-08 19:14:23 +000027DEFINE_string(readExpectationsPath, "", "Path to read JSON expectations from.");
scroggo@google.comb41ff952013-04-11 15:53:35 +000028DEFINE_string2(writePath, w, "", "Write rendered images into this directory.");
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.comb41ff952013-04-11 15:53:35 +000031
scroggo@google.com39edf4c2013-04-25 17:33:51 +000032struct Format {
33 SkImageEncoder::Type fType;
34 SkImageDecoder::Format fFormat;
35 const char* fSuffix;
36};
scroggo@google.comb41ff952013-04-11 15:53:35 +000037
scroggo@google.com39edf4c2013-04-25 17:33:51 +000038static const Format gFormats[] = {
39 { SkImageEncoder::kBMP_Type, SkImageDecoder::kBMP_Format, ".bmp" },
40 { SkImageEncoder::kGIF_Type, SkImageDecoder::kGIF_Format, ".gif" },
41 { SkImageEncoder::kICO_Type, SkImageDecoder::kICO_Format, ".ico" },
42 { SkImageEncoder::kJPEG_Type, SkImageDecoder::kJPEG_Format, ".jpg" },
43 { SkImageEncoder::kPNG_Type, SkImageDecoder::kPNG_Format, ".png" },
44 { SkImageEncoder::kWBMP_Type, SkImageDecoder::kWBMP_Format, ".wbmp" },
45 { SkImageEncoder::kWEBP_Type, SkImageDecoder::kWEBP_Format, ".webp" }
46};
47
48static SkImageEncoder::Type format_to_type(SkImageDecoder::Format format) {
49 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
50 if (gFormats[i].fFormat == format) {
51 return gFormats[i].fType;
52 }
reed@android.comaf459792009-04-24 19:52:53 +000053 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +000054 return SkImageEncoder::kUnknown_Type;
reed@android.comaf459792009-04-24 19:52:53 +000055}
56
scroggo@google.com39edf4c2013-04-25 17:33:51 +000057static const char* suffix_for_type(SkImageEncoder::Type type) {
58 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
59 if (gFormats[i].fType == type) {
60 return gFormats[i].fSuffix;
61 }
62 }
63 return "";
64}
reed@android.comaf459792009-04-24 19:52:53 +000065
scroggo@google.com39edf4c2013-04-25 17:33:51 +000066static SkImageDecoder::Format guess_format_from_suffix(const char suffix[]) {
67 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
68 if (strcmp(suffix, gFormats[i].fSuffix) == 0) {
69 return gFormats[i].fFormat;
70 }
71 }
72 return SkImageDecoder::kUnknown_Format;
73}
74
75static void make_outname(SkString* dst, const char outDir[], const char src[],
76 const char suffix[]) {
scroggo@google.comccd7afb2013-05-28 16:45:07 +000077 SkString basename = SkOSPath::SkBasename(src);
78 dst->set(SkOSPath::SkPathJoin(outDir, basename.c_str()));
scroggo@google.com39edf4c2013-04-25 17:33:51 +000079 if (!dst->endsWith(suffix)) {
scroggo@google.comb41ff952013-04-11 15:53:35 +000080 const char* cstyleDst = dst->c_str();
81 const char* dot = strrchr(cstyleDst, '.');
82 if (dot != NULL) {
83 int32_t index = SkToS32(dot - cstyleDst);
84 dst->remove(index, dst->size() - index);
85 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +000086 dst->append(suffix);
scroggo@google.comb41ff952013-04-11 15:53:35 +000087 }
88}
89
scroggo@google.com39edf4c2013-04-25 17:33:51 +000090// Store the names of the filenames to report later which ones failed, succeeded, and were
91// invalid.
92static SkTArray<SkString, false> gInvalidStreams;
93static SkTArray<SkString, false> gMissingCodecs;
94static SkTArray<SkString, false> gDecodeFailures;
95static SkTArray<SkString, false> gEncodeFailures;
96static SkTArray<SkString, false> gSuccessfulDecodes;
scroggo@google.com7e6fcee2013-05-03 20:14:28 +000097static SkTArray<SkString, false> gSuccessfulSubsetDecodes;
98static SkTArray<SkString, false> gFailedSubsetDecodes;
scroggo@google.com39edf4c2013-04-25 17:33:51 +000099
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000100// Expections read from a file specified by readExpectationsPath. The expectations must have been
101// previously written using createExpectationsPath.
102SkAutoTUnref<skiagm::JsonExpectationsSource> gJsonExpectations;
103
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000104static bool write_bitmap(const char outName[], SkBitmap* bm) {
105 SkBitmap bitmap8888;
106 if (SkBitmap::kARGB_8888_Config != bm->config()) {
107 if (!bm->copyTo(&bitmap8888, SkBitmap::kARGB_8888_Config)) {
108 return false;
109 }
110 bm = &bitmap8888;
111 }
112 // FIXME: This forces all pixels to be opaque, like the many implementations
113 // of force_all_opaque. These should be unified if they cannot be eliminated.
114 SkAutoLockPixels lock(*bm);
115 for (int y = 0; y < bm->height(); y++) {
116 for (int x = 0; x < bm->width(); x++) {
117 *bm->getAddr32(x, y) |= (SK_A32_MASK << SK_A32_SHIFT);
118 }
119 }
120 return SkImageEncoder::EncodeFile(outName, *bm, SkImageEncoder::kPNG_Type, 100);
121}
122
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000123/**
124 * Return a random SkIRect inside the range specified.
125 * @param rand Random number generator.
126 * @param maxX Exclusive maximum x-coordinate. SkIRect's fLeft and fRight will be
127 * in the range [0, maxX)
128 * @param maxY Exclusive maximum y-coordinate. SkIRect's fTop and fBottom will be
129 * in the range [0, maxY)
130 * @return SkIRect Non-empty, non-degenerate rectangle.
131 */
132static SkIRect generate_random_rect(SkRandom* rand, int32_t maxX, int32_t maxY) {
133 SkASSERT(maxX > 1 && maxY > 1);
134 int32_t left = rand->nextULessThan(maxX);
135 int32_t right = rand->nextULessThan(maxX);
136 int32_t top = rand->nextULessThan(maxY);
137 int32_t bottom = rand->nextULessThan(maxY);
138 SkIRect rect = SkIRect::MakeLTRB(left, top, right, bottom);
139 rect.sort();
140 // Make sure rect is not empty.
141 if (rect.fLeft == rect.fRight) {
142 if (rect.fLeft > 0) {
143 rect.fLeft--;
144 } else {
145 rect.fRight++;
146 // This branch is only taken if 0 == rect.fRight, and
147 // maxX must be at least 2, so it must still be in
148 // range.
149 SkASSERT(rect.fRight < maxX);
150 }
151 }
152 if (rect.fTop == rect.fBottom) {
153 if (rect.fTop > 0) {
154 rect.fTop--;
155 } else {
156 rect.fBottom++;
157 // Again, this must be in range.
158 SkASSERT(rect.fBottom < maxY);
159 }
160 }
161 return rect;
162}
163
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000164// Stored expectations to be written to a file if createExpectationsPath is specified.
165static Json::Value gExpectationsToWrite;
166
167/**
epoger@google.comd4993ff2013-05-24 14:33:28 +0000168 * If expectations are to be recorded, record the bitmap expectations into global
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000169 * expectations array.
170 */
171static void write_expectations(const SkBitmap& bitmap, const char* filename) {
172 if (!FLAGS_createExpectationsPath.isEmpty()) {
173 // Creates an Expectations object, and add it to the list to write.
174 skiagm::Expectations expectation(bitmap);
175 Json::Value value = expectation.asJsonValue();
176 gExpectationsToWrite[filename] = value;
177 }
178}
179
180/**
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000181 * Compare against an expectation for this filename, if there is one.
182 * @param bitmap SkBitmap to compare to the expected value.
183 * @param filename String used to find the expected value.
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000184 * @return bool True in any of these cases:
185 * - the bitmap matches the expectation.
186 * - there is no expectations file.
187 * False in any of these cases:
188 * - there is an expectations file, but no expectation for this bitmap.
189 * - there is an expectation for this bitmap, but it did not match.
190 * - expectation could not be computed from the bitmap.
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000191 */
192static bool compare_to_expectations_if_necessary(const SkBitmap& bitmap, const char* filename,
193 SkTArray<SkString, false>* failureArray) {
194 if (NULL == gJsonExpectations.get()) {
195 return true;
196 }
197
198 skiagm::Expectations jsExpectation = gJsonExpectations->get(filename);
199 if (jsExpectation.empty()) {
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000200 if (failureArray != NULL) {
201 failureArray->push_back().printf("decoded %s, but could not find expectation.",
202 filename);
203 }
204 return false;
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000205 }
206
epoger@google.comd4993ff2013-05-24 14:33:28 +0000207 skiagm::GmResultDigest resultDigest(bitmap);
208 if (!resultDigest.isValid()) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000209 if (failureArray != NULL) {
epoger@google.comd4993ff2013-05-24 14:33:28 +0000210 failureArray->push_back().printf("decoded %s, but could not create a GmResultDigest.",
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000211 filename);
212 }
213 return false;
214 }
215
epoger@google.comd4993ff2013-05-24 14:33:28 +0000216 if (jsExpectation.match(resultDigest)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000217 return true;
218 }
219
220 if (failureArray != NULL) {
221 failureArray->push_back().printf("decoded %s, but the result does not match "
222 "expectations.",
223 filename);
224 }
225 return false;
226}
227
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000228/**
229 * Helper function to write a bitmap subset to a file. Only called if subsets were created
230 * and a writePath was provided. Creates a subdirectory called 'subsets' and writes a PNG to
231 * that directory. Also creates a subdirectory called 'extracted' and writes a bitmap created
232 * using extractSubset to a PNG in that directory. Both files will represent the same
233 * subrectangle and have the same name for comparison.
234 * @param writePath Parent directory to hold the folders for the PNG files to write. Must
235 * not be NULL.
236 * @param filename Basename of the original file. Used to name the new files. Must not be
237 * NULL.
238 * @param subsetDim String representing the dimensions of the subset. Used to name the new
239 * files. Must not be NULL.
240 * @param bitmapFromDecodeSubset Pointer to SkBitmap created by SkImageDecoder::DecodeSubset,
241 * using rect as the area to decode.
242 * @param rect Rectangle of the area decoded into bitmapFromDecodeSubset. Used to call
243 * extractSubset on originalBitmap to create a bitmap with the same dimensions/pixels as
244 * bitmapFromDecodeSubset (assuming decodeSubset worked properly).
245 * @param originalBitmap SkBitmap decoded from the same stream as bitmapFromDecodeSubset,
246 * using SkImageDecoder::decode to get the entire image. Used to create a PNG file for
247 * comparison to the PNG created by bitmapFromDecodeSubset.
248 * @return bool Whether the function succeeded at drawing the decoded subset and the extracted
249 * subset to files.
250 */
251static bool write_subset(const char* writePath, const char* filename, const char* subsetDim,
252 SkBitmap* bitmapFromDecodeSubset, SkIRect rect,
253 const SkBitmap& originalBitmap) {
254 // All parameters must be valid.
255 SkASSERT(writePath != NULL);
256 SkASSERT(filename != NULL);
257 SkASSERT(subsetDim != NULL);
258 SkASSERT(bitmapFromDecodeSubset != NULL);
259
260 // Create a subdirectory to hold the results of decodeSubset.
scroggo@google.comccd7afb2013-05-28 16:45:07 +0000261 SkString dir = SkOSPath::SkPathJoin(writePath, "subsets");
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000262 if (!sk_mkdir(dir.c_str())) {
263 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
264 "create a directory to write to.", subsetDim,
265 filename);
266 return false;
267 }
268
269 // Write the subset to a file whose name includes the dimensions.
270 SkString suffix = SkStringPrintf("_%s.png", subsetDim);
271 SkString outPath;
272 make_outname(&outPath, dir.c_str(), filename, suffix.c_str());
273 SkAssertResult(write_bitmap(outPath.c_str(), bitmapFromDecodeSubset));
274 gSuccessfulSubsetDecodes.push_back().printf("\twrote %s", outPath.c_str());
275
276 // Also use extractSubset from the original for visual comparison.
277 // Write the result to a file in a separate subdirectory.
278 SkBitmap extractedSubset;
279 if (!originalBitmap.extractSubset(&extractedSubset, rect)) {
280 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
281 "extract a similar subset for comparison.",
282 subsetDim, filename);
283 return false;
284 }
285
scroggo@google.comccd7afb2013-05-28 16:45:07 +0000286 SkString dirExtracted = SkOSPath::SkPathJoin(writePath, "extracted");
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000287 if (!sk_mkdir(dirExtracted.c_str())) {
288 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
289 "create a directory for extractSubset comparison.",
290 subsetDim, filename);
291 return false;
292 }
293
294 make_outname(&outPath, dirExtracted.c_str(), filename, suffix.c_str());
295 SkAssertResult(write_bitmap(outPath.c_str(), &extractedSubset));
296 return true;
297}
298
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000299static void decodeFileAndWrite(const char srcPath[], const SkString* writePath) {
300 SkBitmap bitmap;
301 SkFILEStream stream(srcPath);
302 if (!stream.isValid()) {
303 gInvalidStreams.push_back().set(srcPath);
304 return;
305 }
306
307 SkImageDecoder* codec = SkImageDecoder::Factory(&stream);
308 if (NULL == codec) {
309 gMissingCodecs.push_back().set(srcPath);
310 return;
311 }
312
313 SkAutoTDelete<SkImageDecoder> ad(codec);
314
315 stream.rewind();
316 if (!codec->decode(&stream, &bitmap, SkBitmap::kARGB_8888_Config,
317 SkImageDecoder::kDecodePixels_Mode)) {
318 gDecodeFailures.push_back().set(srcPath);
319 return;
320 }
321
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000322 // Create a string representing just the filename itself, for use in json expectations.
scroggo@google.comccd7afb2013-05-28 16:45:07 +0000323 SkString basename = SkOSPath::SkBasename(srcPath);
324 const char* filename = basename.c_str();
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000325
326 if (compare_to_expectations_if_necessary(bitmap, filename, &gDecodeFailures)) {
327 gSuccessfulDecodes.push_back().printf("%s [%d %d]", srcPath, bitmap.width(),
328 bitmap.height());
329 }
330
331 write_expectations(bitmap, filename);
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000332
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000333 if (FLAGS_testSubsetDecoding) {
scroggo@google.com0018f752013-05-03 20:39:22 +0000334 SkDEBUGCODE(bool couldRewind =) stream.rewind();
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000335 SkASSERT(couldRewind);
336 int width, height;
337 // Build the tile index for decoding subsets. If the image is 1x1, skip subset
338 // decoding since there are no smaller subsets.
339 if (codec->buildTileIndex(&stream, &width, &height) && width > 1 && height > 1) {
340 SkASSERT(bitmap.width() == width && bitmap.height() == height);
341 // Call decodeSubset multiple times:
342 SkRandom rand(0);
343 for (int i = 0; i < 5; i++) {
344 SkBitmap bitmapFromDecodeSubset;
345 // FIXME: Come up with a more representative set of rectangles.
346 SkIRect rect = generate_random_rect(&rand, width, height);
347 SkString subsetDim = SkStringPrintf("[%d,%d,%d,%d]", rect.fLeft, rect.fTop,
348 rect.fRight, rect.fBottom);
349 if (codec->decodeSubset(&bitmapFromDecodeSubset, rect, SkBitmap::kNo_Config)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000350 SkString subsetName = SkStringPrintf("%s_%s", filename, subsetDim.c_str());
351 if (compare_to_expectations_if_necessary(bitmapFromDecodeSubset,
352 subsetName.c_str(),
353 &gFailedSubsetDecodes)) {
354 gSuccessfulSubsetDecodes.push_back().printf("Decoded subset %s from %s",
355 subsetDim.c_str(), srcPath);
356 }
357
358 write_expectations(bitmapFromDecodeSubset, subsetName.c_str());
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000359 if (writePath != NULL) {
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000360 write_subset(writePath->c_str(), filename, subsetDim.c_str(),
361 &bitmapFromDecodeSubset, rect, bitmap);
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000362 }
363 } else {
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000364 gFailedSubsetDecodes.push_back().printf("Failed to decode region %s from %s",
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000365 subsetDim.c_str(), srcPath);
366 }
367 }
368 }
369 }
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000370
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000371 if (FLAGS_reencode) {
372 // Encode to the format the file was originally in, or PNG if the encoder for the same
373 // format is unavailable.
374 SkImageDecoder::Format format = codec->getFormat();
375 if (SkImageDecoder::kUnknown_Format == format) {
376 if (stream.rewind()) {
377 format = SkImageDecoder::GetStreamFormat(&stream);
378 }
379 if (SkImageDecoder::kUnknown_Format == format) {
380 const char* dot = strrchr(srcPath, '.');
381 if (NULL != dot) {
382 format = guess_format_from_suffix(dot);
383 }
384 if (SkImageDecoder::kUnknown_Format == format) {
385 SkDebugf("Could not determine type for '%s'\n", srcPath);
386 format = SkImageDecoder::kPNG_Format;
387 }
388
389 }
390 } else {
391 SkASSERT(!stream.rewind() || SkImageDecoder::GetStreamFormat(&stream) == format);
392 }
393 SkImageEncoder::Type type = format_to_type(format);
394 // format should never be kUnknown_Format, so type should never be kUnknown_Type.
395 SkASSERT(type != SkImageEncoder::kUnknown_Type);
396
397 SkImageEncoder* encoder = SkImageEncoder::Create(type);
398 if (NULL == encoder) {
399 type = SkImageEncoder::kPNG_Type;
400 encoder = SkImageEncoder::Create(type);
401 SkASSERT(encoder);
402 }
403 SkAutoTDelete<SkImageEncoder> ade(encoder);
404 // Encode to a stream.
405 SkDynamicMemoryWStream wStream;
406 if (!encoder->encodeStream(&wStream, bitmap, 100)) {
407 gEncodeFailures.push_back().printf("Failed to reencode %s to type '%s'", srcPath,
408 suffix_for_type(type));
409 return;
410 }
411
412 SkAutoTUnref<SkData> data(wStream.copyToData());
413 if (writePath != NULL && type != SkImageEncoder::kPNG_Type) {
414 // Write the encoded data to a file. Do not write to PNG, which will be written later,
415 // regardless of the input format.
416 SkString outPath;
417 make_outname(&outPath, writePath->c_str(), srcPath, suffix_for_type(type));
418 SkFILEWStream file(outPath.c_str());
419 if(file.write(data->data(), data->size())) {
420 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
421 } else {
422 gEncodeFailures.push_back().printf("Failed to write %s", outPath.c_str());
423 }
424 }
425 // Ensure that the reencoded data can still be decoded.
426 SkMemoryStream memStream(data);
427 SkBitmap redecodedBitmap;
428 SkImageDecoder::Format formatOnSecondDecode;
429 if (SkImageDecoder::DecodeStream(&memStream, &redecodedBitmap, SkBitmap::kNo_Config,
430 SkImageDecoder::kDecodePixels_Mode,
431 &formatOnSecondDecode)) {
432 SkASSERT(format_to_type(formatOnSecondDecode) == type);
433 } else {
434 gDecodeFailures.push_back().printf("Failed to redecode %s after reencoding to '%s'",
435 srcPath, suffix_for_type(type));
436 }
437 }
438
439 if (writePath != NULL) {
440 SkString outPath;
441 make_outname(&outPath, writePath->c_str(), srcPath, ".png");
442 if (write_bitmap(outPath.c_str(), &bitmap)) {
443 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
444 } else {
445 gEncodeFailures.push_back().set(outPath);
446 }
447 }
448}
449
450///////////////////////////////////////////////////////////////////////////////
451
scroggo@google.comb41ff952013-04-11 15:53:35 +0000452// If strings is not empty, print title, followed by each string on its own line starting
453// with a tab.
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000454// @return bool True if strings had at least one entry.
455static bool print_strings(const char* title, const SkTArray<SkString, false>& strings) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000456 if (strings.count() > 0) {
457 SkDebugf("%s:\n", title);
458 for (int i = 0; i < strings.count(); i++) {
459 SkDebugf("\t%s\n", strings[i].c_str());
460 }
461 SkDebugf("\n");
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000462 return true;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000463 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000464 return false;
reed@android.comaf459792009-04-24 19:52:53 +0000465}
466
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000467/**
468 * If directory is non null and does not end with a path separator, append one.
469 * @param directory SkString representing the path to a directory. If the last character is not a
470 * path separator (specific to the current OS), append one.
471 */
472static void append_path_separator_if_necessary(SkString* directory) {
473 if (directory != NULL && directory->c_str()[directory->size() - 1] != SkPATH_SEPARATOR) {
474 directory->appendf("%c", SkPATH_SEPARATOR);
475 }
476}
477
caryclark@google.com5987f582012-10-02 18:33:14 +0000478int tool_main(int argc, char** argv);
479int tool_main(int argc, char** argv) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000480 SkCommandLineFlags::SetUsage("Decode files, and optionally write the results to files.");
481 SkCommandLineFlags::Parse(argc, argv);
482
483 if (FLAGS_readPath.count() < 1) {
484 SkDebugf("Folder(s) or image(s) to decode are required.\n");
485 return -1;
486 }
487
488
reed@android.comaf459792009-04-24 19:52:53 +0000489 SkAutoGraphics ag;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000490
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000491 if (!FLAGS_readExpectationsPath.isEmpty()) {
492 gJsonExpectations.reset(SkNEW_ARGS(skiagm::JsonExpectationsSource,
493 (FLAGS_readExpectationsPath[0])));
494 }
495
reed@android.comaf459792009-04-24 19:52:53 +0000496 SkString outDir;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000497 SkString* outDirPtr;
reed@android.comaf459792009-04-24 19:52:53 +0000498
scroggo@google.comb41ff952013-04-11 15:53:35 +0000499 if (FLAGS_writePath.count() == 1) {
500 outDir.set(FLAGS_writePath[0]);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000501 append_path_separator_if_necessary(&outDir);
scroggo@google.comb41ff952013-04-11 15:53:35 +0000502 outDirPtr = &outDir;
503 } else {
504 outDirPtr = NULL;
505 }
506
507 for (int i = 0; i < FLAGS_readPath.count(); i++) {
508 if (strlen(FLAGS_readPath[i]) < 1) {
509 break;
510 }
511 SkOSFile::Iter iter(FLAGS_readPath[i]);
512 SkString filename;
513 if (iter.next(&filename)) {
514 SkString directory(FLAGS_readPath[i]);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000515 append_path_separator_if_necessary(&directory);
scroggo@google.comb41ff952013-04-11 15:53:35 +0000516 do {
517 SkString fullname(directory);
518 fullname.append(filename);
519 decodeFileAndWrite(fullname.c_str(), outDirPtr);
520 } while (iter.next(&filename));
521 } else {
522 decodeFileAndWrite(FLAGS_readPath[i], outDirPtr);
reed@android.comaf459792009-04-24 19:52:53 +0000523 }
524 }
525
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000526 if (!FLAGS_createExpectationsPath.isEmpty()) {
527 // Use an empty value for everything besides expectations, since the reader only cares
528 // about the expectations.
529 Json::Value nullValue;
530 Json::Value root = skiagm::CreateJsonTree(gExpectationsToWrite, nullValue, nullValue,
531 nullValue, nullValue);
532 std::string jsonStdString = root.toStyledString();
533 SkString path = SkStringPrintf("%s%cresults.json", FLAGS_createExpectationsPath[0],
534 SkPATH_SEPARATOR);
535 SkFILEWStream stream(path.c_str());
536 stream.write(jsonStdString.c_str(), jsonStdString.length());
537 }
scroggo@google.comb41ff952013-04-11 15:53:35 +0000538 // Add some space, since codecs may print warnings without newline.
539 SkDebugf("\n\n");
rmistry@google.comd6176b02012-08-23 18:14:13 +0000540
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000541 bool failed = print_strings("Invalid files", gInvalidStreams);
542 failed |= print_strings("Missing codec", gMissingCodecs);
543 failed |= print_strings("Failed to decode", gDecodeFailures);
544 failed |= print_strings("Failed to encode", gEncodeFailures);
545 print_strings("Decoded", gSuccessfulDecodes);
reed@android.comaf459792009-04-24 19:52:53 +0000546
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000547 if (FLAGS_testSubsetDecoding) {
548 failed |= print_strings("Failed subset decodes", gFailedSubsetDecodes);
549 print_strings("Decoded subsets", gSuccessfulSubsetDecodes);
550 }
551
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000552 return failed ? -1 : 0;
reed@android.comaf459792009-04-24 19:52:53 +0000553}
554
caryclark@google.com5987f582012-10-02 18:33:14 +0000555#if !defined SK_BUILD_FOR_IOS
556int main(int argc, char * const argv[]) {
557 return tool_main(argc, (char**) argv);
558}
559#endif