blob: a6a2736e8d6852743f252c5332c52bb89ced8077 [file] [log] [blame]
epoger@google.comec3ed6a2011-07-28 14:26:00 +00001/*
2 * Copyright 2011 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
scroggo@google.comb41ff952013-04-11 15:53:35 +00007
scroggo@google.com6843bdb2013-05-08 19:14:23 +00008#include "gm_expectations.h"
reed@android.comaf459792009-04-24 19:52:53 +00009#include "SkBitmap.h"
scroggo@google.com39edf4c2013-04-25 17:33:51 +000010#include "SkColorPriv.h"
scroggo@google.comb41ff952013-04-11 15:53:35 +000011#include "SkCommandLineFlags.h"
scroggo@google.com39edf4c2013-04-25 17:33:51 +000012#include "SkData.h"
scroggo@google.com7def5e12013-05-31 14:00:10 +000013#include "SkForceLinking.h"
reed@android.comaf459792009-04-24 19:52:53 +000014#include "SkGraphics.h"
15#include "SkImageDecoder.h"
16#include "SkImageEncoder.h"
scroggo@google.comb41ff952013-04-11 15:53:35 +000017#include "SkOSFile.h"
scroggo@google.com7e6fcee2013-05-03 20:14:28 +000018#include "SkRandom.h"
reed@android.comaf459792009-04-24 19:52:53 +000019#include "SkStream.h"
scroggo@google.comb41ff952013-04-11 15:53:35 +000020#include "SkTArray.h"
reed@android.comaf459792009-04-24 19:52:53 +000021#include "SkTemplates.h"
22
scroggo@google.com7def5e12013-05-31 14:00:10 +000023__SK_FORCE_IMAGE_DECODER_LINKING;
24
scroggo@google.com6843bdb2013-05-08 19:14:23 +000025DEFINE_string(createExpectationsPath, "", "Path to write JSON expectations.");
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +000026DEFINE_string(mismatchPath, "", "Folder to write mismatched images to.");
scroggo@google.comb41ff952013-04-11 15:53:35 +000027DEFINE_string2(readPath, r, "", "Folder(s) and files to decode images. Required.");
scroggo@google.com6843bdb2013-05-08 19:14:23 +000028DEFINE_string(readExpectationsPath, "", "Path to read JSON expectations from.");
scroggo@google.com39edf4c2013-04-25 17:33:51 +000029DEFINE_bool(reencode, true, "Reencode the images to test encoding.");
scroggo@google.com7e6fcee2013-05-03 20:14:28 +000030DEFINE_bool(testSubsetDecoding, true, "Test decoding subsets of images.");
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +000031DEFINE_string2(writePath, w, "", "Write rendered images into this directory.");
scroggo@google.comb41ff952013-04-11 15:53:35 +000032
scroggo@google.com39edf4c2013-04-25 17:33:51 +000033struct Format {
34 SkImageEncoder::Type fType;
35 SkImageDecoder::Format fFormat;
36 const char* fSuffix;
37};
scroggo@google.comb41ff952013-04-11 15:53:35 +000038
scroggo@google.com39edf4c2013-04-25 17:33:51 +000039static const Format gFormats[] = {
40 { SkImageEncoder::kBMP_Type, SkImageDecoder::kBMP_Format, ".bmp" },
41 { SkImageEncoder::kGIF_Type, SkImageDecoder::kGIF_Format, ".gif" },
42 { SkImageEncoder::kICO_Type, SkImageDecoder::kICO_Format, ".ico" },
43 { SkImageEncoder::kJPEG_Type, SkImageDecoder::kJPEG_Format, ".jpg" },
44 { SkImageEncoder::kPNG_Type, SkImageDecoder::kPNG_Format, ".png" },
45 { SkImageEncoder::kWBMP_Type, SkImageDecoder::kWBMP_Format, ".wbmp" },
46 { SkImageEncoder::kWEBP_Type, SkImageDecoder::kWEBP_Format, ".webp" }
47};
48
49static SkImageEncoder::Type format_to_type(SkImageDecoder::Format format) {
50 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
51 if (gFormats[i].fFormat == format) {
52 return gFormats[i].fType;
53 }
reed@android.comaf459792009-04-24 19:52:53 +000054 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +000055 return SkImageEncoder::kUnknown_Type;
reed@android.comaf459792009-04-24 19:52:53 +000056}
57
scroggo@google.com39edf4c2013-04-25 17:33:51 +000058static const char* suffix_for_type(SkImageEncoder::Type type) {
59 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
60 if (gFormats[i].fType == type) {
61 return gFormats[i].fSuffix;
62 }
63 }
64 return "";
65}
reed@android.comaf459792009-04-24 19:52:53 +000066
scroggo@google.com39edf4c2013-04-25 17:33:51 +000067static SkImageDecoder::Format guess_format_from_suffix(const char suffix[]) {
68 for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
69 if (strcmp(suffix, gFormats[i].fSuffix) == 0) {
70 return gFormats[i].fFormat;
71 }
72 }
73 return SkImageDecoder::kUnknown_Format;
74}
75
76static void make_outname(SkString* dst, const char outDir[], const char src[],
77 const char suffix[]) {
scroggo@google.comccd7afb2013-05-28 16:45:07 +000078 SkString basename = SkOSPath::SkBasename(src);
79 dst->set(SkOSPath::SkPathJoin(outDir, basename.c_str()));
scroggo@google.com39edf4c2013-04-25 17:33:51 +000080 if (!dst->endsWith(suffix)) {
scroggo@google.comb41ff952013-04-11 15:53:35 +000081 const char* cstyleDst = dst->c_str();
82 const char* dot = strrchr(cstyleDst, '.');
83 if (dot != NULL) {
84 int32_t index = SkToS32(dot - cstyleDst);
85 dst->remove(index, dst->size() - index);
86 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +000087 dst->append(suffix);
scroggo@google.comb41ff952013-04-11 15:53:35 +000088 }
89}
90
scroggo@google.com39edf4c2013-04-25 17:33:51 +000091// Store the names of the filenames to report later which ones failed, succeeded, and were
92// invalid.
93static SkTArray<SkString, false> gInvalidStreams;
94static SkTArray<SkString, false> gMissingCodecs;
95static SkTArray<SkString, false> gDecodeFailures;
96static SkTArray<SkString, false> gEncodeFailures;
97static SkTArray<SkString, false> gSuccessfulDecodes;
scroggo@google.com7e6fcee2013-05-03 20:14:28 +000098static SkTArray<SkString, false> gSuccessfulSubsetDecodes;
99static SkTArray<SkString, false> gFailedSubsetDecodes;
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000100
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000101// Expections read from a file specified by readExpectationsPath. The expectations must have been
102// previously written using createExpectationsPath.
103SkAutoTUnref<skiagm::JsonExpectationsSource> gJsonExpectations;
104
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000105static bool write_bitmap(const char outName[], const SkBitmap& bm) {
106 return SkImageEncoder::EncodeFile(outName, bm, SkImageEncoder::kPNG_Type, 100);
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000107}
108
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000109/**
110 * Return a random SkIRect inside the range specified.
111 * @param rand Random number generator.
112 * @param maxX Exclusive maximum x-coordinate. SkIRect's fLeft and fRight will be
113 * in the range [0, maxX)
114 * @param maxY Exclusive maximum y-coordinate. SkIRect's fTop and fBottom will be
115 * in the range [0, maxY)
116 * @return SkIRect Non-empty, non-degenerate rectangle.
117 */
118static SkIRect generate_random_rect(SkRandom* rand, int32_t maxX, int32_t maxY) {
119 SkASSERT(maxX > 1 && maxY > 1);
120 int32_t left = rand->nextULessThan(maxX);
121 int32_t right = rand->nextULessThan(maxX);
122 int32_t top = rand->nextULessThan(maxY);
123 int32_t bottom = rand->nextULessThan(maxY);
124 SkIRect rect = SkIRect::MakeLTRB(left, top, right, bottom);
125 rect.sort();
126 // Make sure rect is not empty.
127 if (rect.fLeft == rect.fRight) {
128 if (rect.fLeft > 0) {
129 rect.fLeft--;
130 } else {
131 rect.fRight++;
132 // This branch is only taken if 0 == rect.fRight, and
133 // maxX must be at least 2, so it must still be in
134 // range.
135 SkASSERT(rect.fRight < maxX);
136 }
137 }
138 if (rect.fTop == rect.fBottom) {
139 if (rect.fTop > 0) {
140 rect.fTop--;
141 } else {
142 rect.fBottom++;
143 // Again, this must be in range.
144 SkASSERT(rect.fBottom < maxY);
145 }
146 }
147 return rect;
148}
149
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000150// Stored expectations to be written to a file if createExpectationsPath is specified.
151static Json::Value gExpectationsToWrite;
152
153/**
epoger@google.comd4993ff2013-05-24 14:33:28 +0000154 * If expectations are to be recorded, record the bitmap expectations into global
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000155 * expectations array.
156 */
157static void write_expectations(const SkBitmap& bitmap, const char* filename) {
158 if (!FLAGS_createExpectationsPath.isEmpty()) {
159 // Creates an Expectations object, and add it to the list to write.
160 skiagm::Expectations expectation(bitmap);
161 Json::Value value = expectation.asJsonValue();
162 gExpectationsToWrite[filename] = value;
163 }
164}
165
166/**
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000167 * Compare against an expectation for this filename, if there is one.
168 * @param bitmap SkBitmap to compare to the expected value.
169 * @param filename String used to find the expected value.
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000170 * @return bool True in any of these cases:
171 * - the bitmap matches the expectation.
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000172 * False in any of these cases:
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000173 * - there is no expectations file.
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000174 * - there is an expectations file, but no expectation for this bitmap.
175 * - there is an expectation for this bitmap, but it did not match.
176 * - expectation could not be computed from the bitmap.
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000177 */
178static bool compare_to_expectations_if_necessary(const SkBitmap& bitmap, const char* filename,
179 SkTArray<SkString, false>* failureArray) {
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000180 skiagm::GmResultDigest resultDigest(bitmap);
181 if (!resultDigest.isValid()) {
182 if (failureArray != NULL) {
183 failureArray->push_back().printf("decoded %s, but could not create a GmResultDigest.",
184 filename);
185 }
186 return false;
187 }
188
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000189 if (NULL == gJsonExpectations.get()) {
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000190 return false;
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000191 }
192
193 skiagm::Expectations jsExpectation = gJsonExpectations->get(filename);
194 if (jsExpectation.empty()) {
scroggo@google.com6ca30ca2013-05-14 17:30:17 +0000195 if (failureArray != NULL) {
196 failureArray->push_back().printf("decoded %s, but could not find expectation.",
197 filename);
198 }
199 return false;
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000200 }
201
epoger@google.comd4993ff2013-05-24 14:33:28 +0000202 if (jsExpectation.match(resultDigest)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000203 return true;
204 }
205
206 if (failureArray != NULL) {
207 failureArray->push_back().printf("decoded %s, but the result does not match "
208 "expectations.",
209 filename);
210 }
211 return false;
212}
213
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000214/**
215 * Helper function to write a bitmap subset to a file. Only called if subsets were created
216 * and a writePath was provided. Creates a subdirectory called 'subsets' and writes a PNG to
217 * that directory. Also creates a subdirectory called 'extracted' and writes a bitmap created
218 * using extractSubset to a PNG in that directory. Both files will represent the same
219 * subrectangle and have the same name for comparison.
220 * @param writePath Parent directory to hold the folders for the PNG files to write. Must
221 * not be NULL.
222 * @param filename Basename of the original file. Used to name the new files. Must not be
223 * NULL.
224 * @param subsetDim String representing the dimensions of the subset. Used to name the new
225 * files. Must not be NULL.
226 * @param bitmapFromDecodeSubset Pointer to SkBitmap created by SkImageDecoder::DecodeSubset,
227 * using rect as the area to decode.
228 * @param rect Rectangle of the area decoded into bitmapFromDecodeSubset. Used to call
229 * extractSubset on originalBitmap to create a bitmap with the same dimensions/pixels as
230 * bitmapFromDecodeSubset (assuming decodeSubset worked properly).
231 * @param originalBitmap SkBitmap decoded from the same stream as bitmapFromDecodeSubset,
232 * using SkImageDecoder::decode to get the entire image. Used to create a PNG file for
233 * comparison to the PNG created by bitmapFromDecodeSubset.
234 * @return bool Whether the function succeeded at drawing the decoded subset and the extracted
235 * subset to files.
236 */
237static bool write_subset(const char* writePath, const char* filename, const char* subsetDim,
238 SkBitmap* bitmapFromDecodeSubset, SkIRect rect,
239 const SkBitmap& originalBitmap) {
240 // All parameters must be valid.
241 SkASSERT(writePath != NULL);
242 SkASSERT(filename != NULL);
243 SkASSERT(subsetDim != NULL);
244 SkASSERT(bitmapFromDecodeSubset != NULL);
245
246 // Create a subdirectory to hold the results of decodeSubset.
scroggo@google.comccd7afb2013-05-28 16:45:07 +0000247 SkString dir = SkOSPath::SkPathJoin(writePath, "subsets");
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000248 if (!sk_mkdir(dir.c_str())) {
249 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
250 "create a directory to write to.", subsetDim,
251 filename);
252 return false;
253 }
254
255 // Write the subset to a file whose name includes the dimensions.
256 SkString suffix = SkStringPrintf("_%s.png", subsetDim);
257 SkString outPath;
258 make_outname(&outPath, dir.c_str(), filename, suffix.c_str());
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000259 SkAssertResult(write_bitmap(outPath.c_str(), *bitmapFromDecodeSubset));
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000260 gSuccessfulSubsetDecodes.push_back().printf("\twrote %s", outPath.c_str());
261
262 // Also use extractSubset from the original for visual comparison.
263 // Write the result to a file in a separate subdirectory.
264 SkBitmap extractedSubset;
265 if (!originalBitmap.extractSubset(&extractedSubset, rect)) {
266 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
267 "extract a similar subset for comparison.",
268 subsetDim, filename);
269 return false;
270 }
271
scroggo@google.comccd7afb2013-05-28 16:45:07 +0000272 SkString dirExtracted = SkOSPath::SkPathJoin(writePath, "extracted");
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000273 if (!sk_mkdir(dirExtracted.c_str())) {
274 gFailedSubsetDecodes.push_back().printf("Successfully decoded %s from %s, but failed to "
275 "create a directory for extractSubset comparison.",
276 subsetDim, filename);
277 return false;
278 }
279
280 make_outname(&outPath, dirExtracted.c_str(), filename, suffix.c_str());
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000281 SkAssertResult(write_bitmap(outPath.c_str(), extractedSubset));
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000282 return true;
283}
284
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000285static void decodeFileAndWrite(const char srcPath[], const SkString* writePath) {
286 SkBitmap bitmap;
287 SkFILEStream stream(srcPath);
288 if (!stream.isValid()) {
289 gInvalidStreams.push_back().set(srcPath);
290 return;
291 }
292
293 SkImageDecoder* codec = SkImageDecoder::Factory(&stream);
294 if (NULL == codec) {
295 gMissingCodecs.push_back().set(srcPath);
296 return;
297 }
298
299 SkAutoTDelete<SkImageDecoder> ad(codec);
300
301 stream.rewind();
302 if (!codec->decode(&stream, &bitmap, SkBitmap::kARGB_8888_Config,
303 SkImageDecoder::kDecodePixels_Mode)) {
304 gDecodeFailures.push_back().set(srcPath);
305 return;
306 }
307
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000308 // Create a string representing just the filename itself, for use in json expectations.
scroggo@google.comccd7afb2013-05-28 16:45:07 +0000309 SkString basename = SkOSPath::SkBasename(srcPath);
310 const char* filename = basename.c_str();
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000311
312 if (compare_to_expectations_if_necessary(bitmap, filename, &gDecodeFailures)) {
313 gSuccessfulDecodes.push_back().printf("%s [%d %d]", srcPath, bitmap.width(),
314 bitmap.height());
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000315 } else if (!FLAGS_mismatchPath.isEmpty()) {
316 SkString outPath;
317 make_outname(&outPath, FLAGS_mismatchPath[0], srcPath, ".png");
318 if (write_bitmap(outPath.c_str(), bitmap)) {
319 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
320 } else {
321 gEncodeFailures.push_back().set(outPath);
322 }
323 }
324
325 if (writePath != NULL) {
326 SkString outPath;
327 make_outname(&outPath, writePath->c_str(), srcPath, ".png");
328 if (write_bitmap(outPath.c_str(), bitmap)) {
329 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
330 } else {
331 gEncodeFailures.push_back().set(outPath);
332 }
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000333 }
334
335 write_expectations(bitmap, filename);
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000336
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000337 if (FLAGS_testSubsetDecoding) {
scroggo@google.com0018f752013-05-03 20:39:22 +0000338 SkDEBUGCODE(bool couldRewind =) stream.rewind();
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000339 SkASSERT(couldRewind);
340 int width, height;
341 // Build the tile index for decoding subsets. If the image is 1x1, skip subset
342 // decoding since there are no smaller subsets.
343 if (codec->buildTileIndex(&stream, &width, &height) && width > 1 && height > 1) {
344 SkASSERT(bitmap.width() == width && bitmap.height() == height);
345 // Call decodeSubset multiple times:
346 SkRandom rand(0);
347 for (int i = 0; i < 5; i++) {
348 SkBitmap bitmapFromDecodeSubset;
349 // FIXME: Come up with a more representative set of rectangles.
350 SkIRect rect = generate_random_rect(&rand, width, height);
351 SkString subsetDim = SkStringPrintf("[%d,%d,%d,%d]", rect.fLeft, rect.fTop,
352 rect.fRight, rect.fBottom);
353 if (codec->decodeSubset(&bitmapFromDecodeSubset, rect, SkBitmap::kNo_Config)) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000354 SkString subsetName = SkStringPrintf("%s_%s", filename, subsetDim.c_str());
355 if (compare_to_expectations_if_necessary(bitmapFromDecodeSubset,
356 subsetName.c_str(),
357 &gFailedSubsetDecodes)) {
358 gSuccessfulSubsetDecodes.push_back().printf("Decoded subset %s from %s",
359 subsetDim.c_str(), srcPath);
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000360 } else if (!FLAGS_mismatchPath.isEmpty()) {
361 write_subset(FLAGS_mismatchPath[0], filename, subsetDim.c_str(),
362 &bitmapFromDecodeSubset, rect, bitmap);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000363 }
364
365 write_expectations(bitmapFromDecodeSubset, subsetName.c_str());
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000366 if (writePath != NULL) {
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000367 write_subset(writePath->c_str(), filename, subsetDim.c_str(),
368 &bitmapFromDecodeSubset, rect, bitmap);
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000369 }
370 } else {
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000371 gFailedSubsetDecodes.push_back().printf("Failed to decode region %s from %s",
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000372 subsetDim.c_str(), srcPath);
373 }
374 }
375 }
376 }
scroggo@google.com9da0e1d2013-05-15 18:14:36 +0000377
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000378 if (FLAGS_reencode) {
379 // Encode to the format the file was originally in, or PNG if the encoder for the same
380 // format is unavailable.
381 SkImageDecoder::Format format = codec->getFormat();
382 if (SkImageDecoder::kUnknown_Format == format) {
383 if (stream.rewind()) {
384 format = SkImageDecoder::GetStreamFormat(&stream);
385 }
386 if (SkImageDecoder::kUnknown_Format == format) {
387 const char* dot = strrchr(srcPath, '.');
388 if (NULL != dot) {
389 format = guess_format_from_suffix(dot);
390 }
391 if (SkImageDecoder::kUnknown_Format == format) {
392 SkDebugf("Could not determine type for '%s'\n", srcPath);
393 format = SkImageDecoder::kPNG_Format;
394 }
395
396 }
397 } else {
398 SkASSERT(!stream.rewind() || SkImageDecoder::GetStreamFormat(&stream) == format);
399 }
400 SkImageEncoder::Type type = format_to_type(format);
401 // format should never be kUnknown_Format, so type should never be kUnknown_Type.
402 SkASSERT(type != SkImageEncoder::kUnknown_Type);
403
404 SkImageEncoder* encoder = SkImageEncoder::Create(type);
405 if (NULL == encoder) {
406 type = SkImageEncoder::kPNG_Type;
407 encoder = SkImageEncoder::Create(type);
408 SkASSERT(encoder);
409 }
410 SkAutoTDelete<SkImageEncoder> ade(encoder);
411 // Encode to a stream.
412 SkDynamicMemoryWStream wStream;
413 if (!encoder->encodeStream(&wStream, bitmap, 100)) {
414 gEncodeFailures.push_back().printf("Failed to reencode %s to type '%s'", srcPath,
415 suffix_for_type(type));
416 return;
417 }
418
419 SkAutoTUnref<SkData> data(wStream.copyToData());
420 if (writePath != NULL && type != SkImageEncoder::kPNG_Type) {
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000421 // Write the encoded data to a file. Do not write to PNG, which was already written.
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000422 SkString outPath;
423 make_outname(&outPath, writePath->c_str(), srcPath, suffix_for_type(type));
424 SkFILEWStream file(outPath.c_str());
425 if(file.write(data->data(), data->size())) {
426 gSuccessfulDecodes.push_back().appendf("\twrote %s", outPath.c_str());
427 } else {
428 gEncodeFailures.push_back().printf("Failed to write %s", outPath.c_str());
429 }
430 }
431 // Ensure that the reencoded data can still be decoded.
432 SkMemoryStream memStream(data);
433 SkBitmap redecodedBitmap;
434 SkImageDecoder::Format formatOnSecondDecode;
435 if (SkImageDecoder::DecodeStream(&memStream, &redecodedBitmap, SkBitmap::kNo_Config,
436 SkImageDecoder::kDecodePixels_Mode,
437 &formatOnSecondDecode)) {
438 SkASSERT(format_to_type(formatOnSecondDecode) == type);
439 } else {
440 gDecodeFailures.push_back().printf("Failed to redecode %s after reencoding to '%s'",
441 srcPath, suffix_for_type(type));
442 }
443 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000444}
445
446///////////////////////////////////////////////////////////////////////////////
447
scroggo@google.comb41ff952013-04-11 15:53:35 +0000448// If strings is not empty, print title, followed by each string on its own line starting
449// with a tab.
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000450// @return bool True if strings had at least one entry.
451static bool print_strings(const char* title, const SkTArray<SkString, false>& strings) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000452 if (strings.count() > 0) {
453 SkDebugf("%s:\n", title);
454 for (int i = 0; i < strings.count(); i++) {
455 SkDebugf("\t%s\n", strings[i].c_str());
456 }
457 SkDebugf("\n");
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000458 return true;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000459 }
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000460 return false;
reed@android.comaf459792009-04-24 19:52:53 +0000461}
462
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000463/**
464 * If directory is non null and does not end with a path separator, append one.
465 * @param directory SkString representing the path to a directory. If the last character is not a
466 * path separator (specific to the current OS), append one.
467 */
468static void append_path_separator_if_necessary(SkString* directory) {
469 if (directory != NULL && directory->c_str()[directory->size() - 1] != SkPATH_SEPARATOR) {
470 directory->appendf("%c", SkPATH_SEPARATOR);
471 }
472}
473
caryclark@google.com5987f582012-10-02 18:33:14 +0000474int tool_main(int argc, char** argv);
475int tool_main(int argc, char** argv) {
scroggo@google.comb41ff952013-04-11 15:53:35 +0000476 SkCommandLineFlags::SetUsage("Decode files, and optionally write the results to files.");
477 SkCommandLineFlags::Parse(argc, argv);
478
479 if (FLAGS_readPath.count() < 1) {
480 SkDebugf("Folder(s) or image(s) to decode are required.\n");
481 return -1;
482 }
483
484
reed@android.comaf459792009-04-24 19:52:53 +0000485 SkAutoGraphics ag;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000486
scroggo@google.com3832da12013-06-19 19:12:53 +0000487 if (!FLAGS_readExpectationsPath.isEmpty() && sk_exists(FLAGS_readExpectationsPath[0])) {
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000488 gJsonExpectations.reset(SkNEW_ARGS(skiagm::JsonExpectationsSource,
489 (FLAGS_readExpectationsPath[0])));
490 }
491
reed@android.comaf459792009-04-24 19:52:53 +0000492 SkString outDir;
scroggo@google.comb41ff952013-04-11 15:53:35 +0000493 SkString* outDirPtr;
reed@android.comaf459792009-04-24 19:52:53 +0000494
scroggo@google.comb41ff952013-04-11 15:53:35 +0000495 if (FLAGS_writePath.count() == 1) {
496 outDir.set(FLAGS_writePath[0]);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000497 append_path_separator_if_necessary(&outDir);
scroggo@google.comb41ff952013-04-11 15:53:35 +0000498 outDirPtr = &outDir;
499 } else {
500 outDirPtr = NULL;
501 }
502
503 for (int i = 0; i < FLAGS_readPath.count(); i++) {
504 if (strlen(FLAGS_readPath[i]) < 1) {
505 break;
506 }
507 SkOSFile::Iter iter(FLAGS_readPath[i]);
508 SkString filename;
509 if (iter.next(&filename)) {
510 SkString directory(FLAGS_readPath[i]);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000511 append_path_separator_if_necessary(&directory);
scroggo@google.comb41ff952013-04-11 15:53:35 +0000512 do {
513 SkString fullname(directory);
514 fullname.append(filename);
515 decodeFileAndWrite(fullname.c_str(), outDirPtr);
516 } while (iter.next(&filename));
517 } else {
epoger@google.comc7e18732013-06-18 02:53:16 +0000518 decodeFileAndWrite(FLAGS_readPath[i], outDirPtr);
reed@android.comaf459792009-04-24 19:52:53 +0000519 }
520 }
521
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000522 if (!FLAGS_createExpectationsPath.isEmpty()) {
523 // Use an empty value for everything besides expectations, since the reader only cares
524 // about the expectations.
525 Json::Value nullValue;
526 Json::Value root = skiagm::CreateJsonTree(gExpectationsToWrite, nullValue, nullValue,
527 nullValue, nullValue);
528 std::string jsonStdString = root.toStyledString();
scroggo@google.comcf5eb6a2013-06-07 12:43:15 +0000529 SkFILEWStream stream(FLAGS_createExpectationsPath[0]);
scroggo@google.com6843bdb2013-05-08 19:14:23 +0000530 stream.write(jsonStdString.c_str(), jsonStdString.length());
531 }
scroggo@google.comb41ff952013-04-11 15:53:35 +0000532 // Add some space, since codecs may print warnings without newline.
533 SkDebugf("\n\n");
rmistry@google.comd6176b02012-08-23 18:14:13 +0000534
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000535 bool failed = print_strings("Invalid files", gInvalidStreams);
536 failed |= print_strings("Missing codec", gMissingCodecs);
537 failed |= print_strings("Failed to decode", gDecodeFailures);
538 failed |= print_strings("Failed to encode", gEncodeFailures);
539 print_strings("Decoded", gSuccessfulDecodes);
reed@android.comaf459792009-04-24 19:52:53 +0000540
scroggo@google.com7e6fcee2013-05-03 20:14:28 +0000541 if (FLAGS_testSubsetDecoding) {
542 failed |= print_strings("Failed subset decodes", gFailedSubsetDecodes);
543 print_strings("Decoded subsets", gSuccessfulSubsetDecodes);
544 }
545
scroggo@google.com39edf4c2013-04-25 17:33:51 +0000546 return failed ? -1 : 0;
reed@android.comaf459792009-04-24 19:52:53 +0000547}
548
caryclark@google.com5987f582012-10-02 18:33:14 +0000549#if !defined SK_BUILD_FOR_IOS
550int main(int argc, char * const argv[]) {
551 return tool_main(argc, (char**) argv);
552}
553#endif