render_pictures_main.cpp revision cced37d2c3e49231e6a155721e0dd59e58e67bab
1/*
2 * Copyright 2012 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 */
7
8#include "LazyDecodeBitmap.h"
9#include "CopyTilesRenderer.h"
10#include "SkBitmap.h"
11#include "SkDevice.h"
12#include "SkCommandLineFlags.h"
13#include "SkGraphics.h"
14#include "SkImageDecoder.h"
15#include "SkImageEncoder.h"
16#include "SkMath.h"
17#include "SkOSFile.h"
18#include "SkPicture.h"
19#include "SkPictureRecorder.h"
20#include "SkStream.h"
21#include "SkString.h"
22#include "PictureRenderer.h"
23#include "PictureRenderingFlags.h"
24#include "picture_utils.h"
25
26// Flags used by this file, alphabetically:
27DEFINE_int32(clone, 0, "Clone the picture n times before rendering.");
28DECLARE_bool(deferImageDecoding);
29DEFINE_int32(maxComponentDiff, 256, "Maximum diff on a component, 0 - 256. Components that differ "
30             "by more than this amount are considered errors, though all diffs are reported. "
31             "Requires --validate.");
32DECLARE_string(readPath);
33DEFINE_bool(writeChecksumBasedFilenames, false,
34            "When writing out images, use checksum-based filenames.");
35DEFINE_bool(writeEncodedImages, false, "Any time the skp contains an encoded image, write it to a "
36            "file rather than decoding it. Requires writePath to be set. Skips drawing the full "
37            "skp to a file. Not compatible with deferImageDecoding.");
38DEFINE_string(writeJsonSummaryPath, "", "File to write a JSON summary of image results to. "
39              "TODO(epoger): Currently, this only works if --writePath is also specified. "
40              "See https://code.google.com/p/skia/issues/detail?id=2043 .");
41DEFINE_string2(writePath, w, "", "Directory to write the rendered images.");
42DEFINE_bool(writeWholeImage, false, "In tile mode, write the entire rendered image to a "
43            "file, instead of an image for each tile.");
44DEFINE_bool(validate, false, "Verify that the rendered image contains the same pixels as "
45            "the picture rendered in simple mode. When used in conjunction with --bbh, results "
46            "are validated against the picture rendered in the same mode, but without the bbh.");
47
48DEFINE_bool(bench_record, false, "If true, drop into an infinite loop of recording the picture.");
49
50DEFINE_bool(preprocess, false, "If true, perform device specific preprocessing before rendering.");
51
52////////////////////////////////////////////////////////////////////////////////////////////////////
53
54/**
55 *  Table for translating from format of data to a suffix.
56 */
57struct Format {
58    SkImageDecoder::Format  fFormat;
59    const char*             fSuffix;
60};
61static const Format gFormats[] = {
62    { SkImageDecoder::kBMP_Format, ".bmp" },
63    { SkImageDecoder::kGIF_Format, ".gif" },
64    { SkImageDecoder::kICO_Format, ".ico" },
65    { SkImageDecoder::kJPEG_Format, ".jpg" },
66    { SkImageDecoder::kPNG_Format, ".png" },
67    { SkImageDecoder::kWBMP_Format, ".wbmp" },
68    { SkImageDecoder::kWEBP_Format, ".webp" },
69    { SkImageDecoder::kUnknown_Format, "" },
70};
71
72/**
73 *  Get an appropriate suffix for an image format.
74 */
75static const char* get_suffix_from_format(SkImageDecoder::Format format) {
76    for (size_t i = 0; i < SK_ARRAY_COUNT(gFormats); i++) {
77        if (gFormats[i].fFormat == format) {
78            return gFormats[i].fSuffix;
79        }
80    }
81    return "";
82}
83
84/**
85 *  Base name for an image file created from the encoded data in an skp.
86 */
87static SkString gInputFileName;
88
89/**
90 *  Number to be appended to the image file name so that it is unique.
91 */
92static uint32_t gImageNo;
93
94/**
95 *  Set up the name for writing encoded data to a file.
96 *  Sets gInputFileName to name, minus any extension ".*"
97 *  Sets gImageNo to 0, so images from file "X.skp" will
98 *  look like "X_<gImageNo>.<suffix>", beginning with 0
99 *  for each new skp.
100 */
101static void reset_image_file_base_name(const SkString& name) {
102    gImageNo = 0;
103    // Remove ".skp"
104    const char* cName = name.c_str();
105    const char* dot = strrchr(cName, '.');
106    if (dot != NULL) {
107        gInputFileName.set(cName, dot - cName);
108    } else {
109        gInputFileName.set(name);
110    }
111}
112
113/**
114 *  Write the raw encoded bitmap data to a file.
115 */
116static bool write_image_to_file(const void* buffer, size_t size, SkBitmap* bitmap) {
117    SkASSERT(!FLAGS_writePath.isEmpty());
118    SkMemoryStream memStream(buffer, size);
119    SkString outPath;
120    SkImageDecoder::Format format = SkImageDecoder::GetStreamFormat(&memStream);
121    SkString name = SkStringPrintf("%s_%d%s", gInputFileName.c_str(), gImageNo++,
122                                   get_suffix_from_format(format));
123    SkString dir(FLAGS_writePath[0]);
124    sk_tools::make_filepath(&outPath, dir, name);
125    SkFILEWStream fileStream(outPath.c_str());
126    if (!(fileStream.isValid() && fileStream.write(buffer, size))) {
127        SkDebugf("Failed to write encoded data to \"%s\"\n", outPath.c_str());
128    }
129    // Put in a dummy bitmap.
130    return SkImageDecoder::DecodeStream(&memStream, bitmap, SkBitmap::kNo_Config,
131                                        SkImageDecoder::kDecodeBounds_Mode);
132}
133
134////////////////////////////////////////////////////////////////////////////////////////////////////
135
136/**
137 * Called only by render_picture().
138 */
139static bool render_picture_internal(const SkString& inputPath, const SkString* outputDir,
140                                    sk_tools::PictureRenderer& renderer,
141                                    SkBitmap** out) {
142    SkString inputFilename;
143    sk_tools::get_basename(&inputFilename, inputPath);
144    SkString outputDirString;
145    if (NULL != outputDir && outputDir->size() > 0 && !FLAGS_writeEncodedImages) {
146        outputDirString.set(*outputDir);
147    }
148
149    SkFILEStream inputStream;
150    inputStream.setPath(inputPath.c_str());
151    if (!inputStream.isValid()) {
152        SkDebugf("Could not open file %s\n", inputPath.c_str());
153        return false;
154    }
155
156    SkPicture::InstallPixelRefProc proc;
157    if (FLAGS_deferImageDecoding) {
158        proc = &sk_tools::LazyDecodeBitmap;
159    } else if (FLAGS_writeEncodedImages) {
160        SkASSERT(!FLAGS_writePath.isEmpty());
161        reset_image_file_base_name(inputFilename);
162        proc = &write_image_to_file;
163    } else {
164        proc = &SkImageDecoder::DecodeMemory;
165    }
166
167    SkDebugf("deserializing... %s\n", inputPath.c_str());
168
169    SkPicture* picture = SkPicture::CreateFromStream(&inputStream, proc);
170
171    if (NULL == picture) {
172        SkDebugf("Could not read an SkPicture from %s\n", inputPath.c_str());
173        return false;
174    }
175
176    while (FLAGS_bench_record) {
177        SkPictureRecorder recorder;
178        picture->draw(recorder.beginRecording(picture->width(), picture->height(), NULL, 0));
179        SkAutoTUnref<SkPicture> other(recorder.endRecording());
180    }
181
182    for (int i = 0; i < FLAGS_clone; ++i) {
183        SkPicture* clone = picture->clone();
184        SkDELETE(picture);
185        picture = clone;
186    }
187
188    SkDebugf("drawing... [%i %i] %s\n", picture->width(), picture->height(),
189             inputPath.c_str());
190
191    renderer.init(picture, &outputDirString, &inputFilename, FLAGS_writeChecksumBasedFilenames);
192
193    if (FLAGS_preprocess) {
194        if (NULL != renderer.getCanvas()) {
195            renderer.getCanvas()->EXPERIMENTAL_optimize(renderer.getPicture());
196        }
197    }
198
199    renderer.setup();
200
201    bool success = renderer.render(out);
202    if (!success) {
203        SkDebugf("Failed to render %s\n", inputFilename.c_str());
204    }
205
206    renderer.end();
207
208    SkDELETE(picture);
209    return success;
210}
211
212static inline int getByte(uint32_t value, int index) {
213    SkASSERT(0 <= index && index < 4);
214    return (value >> (index * 8)) & 0xFF;
215}
216
217static int MaxByteDiff(uint32_t v1, uint32_t v2) {
218    return SkMax32(SkMax32(abs(getByte(v1, 0) - getByte(v2, 0)), abs(getByte(v1, 1) - getByte(v2, 1))),
219                   SkMax32(abs(getByte(v1, 2) - getByte(v2, 2)), abs(getByte(v1, 3) - getByte(v2, 3))));
220}
221
222class AutoRestoreBbhType {
223public:
224    AutoRestoreBbhType() {
225        fRenderer = NULL;
226        fSavedBbhType = sk_tools::PictureRenderer::kNone_BBoxHierarchyType;
227    }
228
229    void set(sk_tools::PictureRenderer* renderer,
230             sk_tools::PictureRenderer::BBoxHierarchyType bbhType) {
231        fRenderer = renderer;
232        fSavedBbhType = renderer->getBBoxHierarchyType();
233        renderer->setBBoxHierarchyType(bbhType);
234    }
235
236    ~AutoRestoreBbhType() {
237        if (NULL != fRenderer) {
238            fRenderer->setBBoxHierarchyType(fSavedBbhType);
239        }
240    }
241
242private:
243    sk_tools::PictureRenderer* fRenderer;
244    sk_tools::PictureRenderer::BBoxHierarchyType fSavedBbhType;
245};
246
247/**
248 * Render the SKP file(s) within inputPath, writing their bitmap images into outputDir.
249 *
250 * @param inputPath path to an individual SKP file, or a directory of SKP files
251 * @param outputDir if not NULL, write the image(s) generated into this directory
252 * @param renderer PictureRenderer to use to render the SKPs
253 * @param jsonSummaryPtr if not NULL, add the image(s) generated to this summary
254 */
255static bool render_picture(const SkString& inputPath, const SkString* outputDir,
256                           sk_tools::PictureRenderer& renderer,
257                           sk_tools::ImageResultsSummary *jsonSummaryPtr) {
258    int diffs[256] = {0};
259    SkBitmap* bitmap = NULL;
260    renderer.setJsonSummaryPtr(jsonSummaryPtr);
261    bool success = render_picture_internal(inputPath,
262        FLAGS_writeWholeImage ? NULL : outputDir,
263        renderer,
264        FLAGS_validate || FLAGS_writeWholeImage ? &bitmap : NULL);
265
266    if (!success || ((FLAGS_validate || FLAGS_writeWholeImage) && bitmap == NULL)) {
267        SkDebugf("Failed to draw the picture.\n");
268        SkDELETE(bitmap);
269        return false;
270    }
271
272    if (FLAGS_validate) {
273        SkBitmap* referenceBitmap = NULL;
274        sk_tools::PictureRenderer* referenceRenderer;
275        // If the renderer uses a BBoxHierarchy, then the reference renderer
276        // will be the same renderer, without the bbh.
277        AutoRestoreBbhType arbbh;
278        if (sk_tools::PictureRenderer::kNone_BBoxHierarchyType !=
279            renderer.getBBoxHierarchyType()) {
280            referenceRenderer = &renderer;
281            referenceRenderer->ref();  // to match auto unref below
282            arbbh.set(referenceRenderer, sk_tools::PictureRenderer::kNone_BBoxHierarchyType);
283        } else {
284            referenceRenderer = SkNEW(sk_tools::SimplePictureRenderer);
285        }
286        SkAutoTUnref<sk_tools::PictureRenderer> aurReferenceRenderer(referenceRenderer);
287
288        success = render_picture_internal(inputPath, NULL, *referenceRenderer,
289                                          &referenceBitmap);
290
291        if (!success || NULL == referenceBitmap || NULL == referenceBitmap->getPixels()) {
292            SkDebugf("Failed to draw the reference picture.\n");
293            SkDELETE(bitmap);
294            SkDELETE(referenceBitmap);
295            return false;
296        }
297
298        if (success && (bitmap->width() != referenceBitmap->width())) {
299            SkDebugf("Expected image width: %i, actual image width %i.\n",
300                     referenceBitmap->width(), bitmap->width());
301            SkDELETE(bitmap);
302            SkDELETE(referenceBitmap);
303            return false;
304        }
305        if (success && (bitmap->height() != referenceBitmap->height())) {
306            SkDebugf("Expected image height: %i, actual image height %i",
307                     referenceBitmap->height(), bitmap->height());
308            SkDELETE(bitmap);
309            SkDELETE(referenceBitmap);
310            return false;
311        }
312
313        for (int y = 0; success && y < bitmap->height(); y++) {
314            for (int x = 0; success && x < bitmap->width(); x++) {
315                int diff = MaxByteDiff(*referenceBitmap->getAddr32(x, y),
316                                       *bitmap->getAddr32(x, y));
317                SkASSERT(diff >= 0 && diff <= 255);
318                diffs[diff]++;
319
320                if (diff > FLAGS_maxComponentDiff) {
321                    SkDebugf("Expected pixel at (%i %i) exceedds maximum "
322                                 "component diff of %i: 0x%x, actual 0x%x\n",
323                             x, y, FLAGS_maxComponentDiff,
324                             *referenceBitmap->getAddr32(x, y),
325                             *bitmap->getAddr32(x, y));
326                    SkDELETE(bitmap);
327                    SkDELETE(referenceBitmap);
328                    return false;
329                }
330            }
331        }
332        SkDELETE(referenceBitmap);
333
334        for (int i = 1; i <= 255; ++i) {
335            if(diffs[i] > 0) {
336                SkDebugf("Number of pixels with max diff of %i is %i\n", i, diffs[i]);
337            }
338        }
339    }
340
341    if (FLAGS_writeWholeImage) {
342        sk_tools::force_all_opaque(*bitmap);
343
344        // TODO(epoger): It would be better for the filename (without outputDir) to be passed in
345        // here, and used both for the checksum file and writing into outputDir.
346        SkString inputFilename, outputPath;
347        sk_tools::get_basename(&inputFilename, inputPath);
348        sk_tools::make_filepath(&outputPath, *outputDir, inputFilename);
349        sk_tools::replace_char(&outputPath, '.', '_');
350        outputPath.append(".png");
351
352        if (NULL != jsonSummaryPtr) {
353            SkString outputFileBasename;
354            sk_tools::get_basename(&outputFileBasename, outputPath);
355            jsonSummaryPtr->add(inputFilename.c_str(), outputFileBasename.c_str(), *bitmap);
356        }
357
358        if (NULL != outputDir) {
359            if (!SkImageEncoder::EncodeFile(outputPath.c_str(), *bitmap,
360                                            SkImageEncoder::kPNG_Type, 100)) {
361                SkDebugf("Failed to draw the picture.\n");
362                success = false;
363            }
364        }
365    }
366    SkDELETE(bitmap);
367
368    return success;
369}
370
371
372static int process_input(const char* input, const SkString* outputDir,
373                         sk_tools::PictureRenderer& renderer,
374                         sk_tools::ImageResultsSummary *jsonSummaryPtr) {
375    SkOSFile::Iter iter(input, "skp");
376    SkString inputFilename;
377    int failures = 0;
378    SkDebugf("process_input, %s\n", input);
379    if (iter.next(&inputFilename)) {
380        do {
381            SkString inputPath;
382            SkString inputAsSkString(input);
383            sk_tools::make_filepath(&inputPath, inputAsSkString, inputFilename);
384            if (!render_picture(inputPath, outputDir, renderer, jsonSummaryPtr)) {
385                ++failures;
386            }
387        } while(iter.next(&inputFilename));
388    } else if (SkStrEndsWith(input, ".skp")) {
389        SkString inputPath(input);
390        if (!render_picture(inputPath, outputDir, renderer, jsonSummaryPtr)) {
391            ++failures;
392        }
393    } else {
394        SkString warning;
395        warning.printf("Warning: skipping %s\n", input);
396        SkDebugf(warning.c_str());
397    }
398    return failures;
399}
400
401int tool_main(int argc, char** argv);
402int tool_main(int argc, char** argv) {
403    SkCommandLineFlags::SetUsage("Render .skp files.");
404    SkCommandLineFlags::Parse(argc, argv);
405
406    if (FLAGS_readPath.isEmpty()) {
407        SkDebugf(".skp files or directories are required.\n");
408        exit(-1);
409    }
410
411    if (FLAGS_maxComponentDiff < 0 || FLAGS_maxComponentDiff > 256) {
412        SkDebugf("--maxComponentDiff must be between 0 and 256\n");
413        exit(-1);
414    }
415
416    if (FLAGS_maxComponentDiff != 256 && !FLAGS_validate) {
417        SkDebugf("--maxComponentDiff requires --validate\n");
418        exit(-1);
419    }
420
421    if (FLAGS_clone < 0) {
422        SkDebugf("--clone must be >= 0. Was %i\n", FLAGS_clone);
423        exit(-1);
424    }
425
426    if (FLAGS_writeEncodedImages) {
427        if (FLAGS_writePath.isEmpty()) {
428            SkDebugf("--writeEncodedImages requires --writePath\n");
429            exit(-1);
430        }
431        if (FLAGS_deferImageDecoding) {
432            SkDebugf("--writeEncodedImages is not compatible with --deferImageDecoding\n");
433            exit(-1);
434        }
435    }
436
437    SkString errorString;
438    SkAutoTUnref<sk_tools::PictureRenderer> renderer(parseRenderer(errorString,
439                                                                   kRender_PictureTool));
440    if (errorString.size() > 0) {
441        SkDebugf("%s\n", errorString.c_str());
442    }
443
444    if (renderer.get() == NULL) {
445        exit(-1);
446    }
447
448    SkAutoGraphics ag;
449
450    SkString outputDir;
451    if (FLAGS_writePath.count() == 1) {
452        outputDir.set(FLAGS_writePath[0]);
453    }
454    sk_tools::ImageResultsSummary jsonSummary;
455    sk_tools::ImageResultsSummary* jsonSummaryPtr = NULL;
456    if (FLAGS_writeJsonSummaryPath.count() == 1) {
457        jsonSummaryPtr = &jsonSummary;
458    }
459
460    int failures = 0;
461    for (int i = 0; i < FLAGS_readPath.count(); i ++) {
462        failures += process_input(FLAGS_readPath[i], &outputDir, *renderer.get(), jsonSummaryPtr);
463    }
464    if (failures != 0) {
465        SkDebugf("Failed to render %i pictures.\n", failures);
466        return 1;
467    }
468#if SK_SUPPORT_GPU
469#if GR_CACHE_STATS
470    if (renderer->isUsingGpuDevice()) {
471        GrContext* ctx = renderer->getGrContext();
472        ctx->printCacheStats();
473#ifdef SK_DEVELOPER
474        ctx->dumpFontCache();
475#endif
476    }
477#endif
478#endif
479    if (FLAGS_writeJsonSummaryPath.count() == 1) {
480        jsonSummary.writeToFile(FLAGS_writeJsonSummaryPath[0]);
481    }
482    return 0;
483}
484
485#if !defined SK_BUILD_FOR_IOS
486int main(int argc, char * const argv[]) {
487    return tool_main(argc, (char**) argv);
488}
489#endif
490