1 // Copyright 2018 The Amber Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "amber/amber.h"
16 
17 #include <stdio.h>
18 
19 #include <algorithm>
20 #include <cassert>
21 #include <cstdio>
22 #include <cstdlib>
23 #include <fstream>
24 #include <iomanip>
25 #include <iostream>
26 #include <set>
27 #include <string>
28 #include <utility>
29 #include <vector>
30 
31 #include "amber/recipe.h"
32 #include "samples/config_helper.h"
33 #include "samples/ppm.h"
34 #include "samples/timestamp.h"
35 #include "src/build-versions.h"
36 #include "src/make_unique.h"
37 
38 #if AMBER_ENABLE_SPIRV_TOOLS
39 #include "spirv-tools/libspirv.hpp"
40 #endif
41 
42 #if AMBER_ENABLE_LODEPNG
43 #include "samples/png.h"
44 #endif  // AMBER_ENABLE_LODEPNG
45 
46 namespace {
47 
48 const char* kGeneratedColorBuffer = "framebuffer";
49 
50 struct Options {
51   std::vector<std::string> input_filenames;
52 
53   std::vector<std::string> image_filenames;
54   std::string buffer_filename;
55   std::vector<std::string> fb_names;
56   std::vector<amber::BufferInfo> buffer_to_dump;
57   uint32_t engine_major = 1;
58   uint32_t engine_minor = 0;
59   int32_t fence_timeout = -1;
60   int32_t selected_device = -1;
61   bool parse_only = false;
62   bool pipeline_create_only = false;
63   bool disable_validation_layer = false;
64   bool quiet = false;
65   bool show_help = false;
66   bool show_version_info = false;
67   bool log_graphics_calls = false;
68   bool log_graphics_calls_time = false;
69   bool log_execute_calls = false;
70   bool disable_spirv_validation = false;
71   std::string shader_filename;
72   amber::EngineType engine = amber::kEngineTypeVulkan;
73   std::string spv_env;
74 };
75 
76 const char kUsage[] = R"(Usage: amber [options] SCRIPT [SCRIPTS...]
77 
78  options:
79   -p                        -- Parse input files only; Don't execute.
80   -ps                       -- Parse input files, create pipelines; Don't execute.
81   -q                        -- Disable summary output.
82   -d                        -- Disable validation layers.
83   -D <ID>                   -- ID of device to run with (Vulkan only).
84   -f <value>                -- Sets the fence timeout value to |value|
85   -t <spirv_env>            -- The target SPIR-V environment e.g., spv1.3, vulkan1.1, vulkan1.2.
86                                If a SPIR-V environment, assume the lowest version of Vulkan that
87                                requires support of that version of SPIR-V.
88                                If a Vulkan environment, use the highest version of SPIR-V required
89                                to be supported by that version of Vulkan.
90                                Use vulkan1.1spv1.4 for SPIR-V 1.4 with Vulkan 1.1.
91                                Defaults to spv1.0.
92   -i <filename>             -- Write rendering to <filename> as a PNG image if it ends with '.png',
93                                or as a PPM image otherwise.
94   -I <buffername>           -- Name of framebuffer to dump. Defaults to 'framebuffer'.
95   -b <filename>             -- Write contents of a UBO or SSBO to <filename>.
96   -B [<pipeline name>:][<desc set>:]<binding> -- Identifier of buffer to write.
97                                Default is [first pipeline:][0:]0.
98   -w <filename>             -- Write shader assembly to |filename|
99   -e <engine>               -- Specify graphics engine: vulkan, dawn. Default is vulkan.
100   -v <engine version>       -- Engine version (eg, 1.1 for Vulkan). Default 1.0.
101   -V, --version             -- Output version information for Amber and libraries.
102   --log-graphics-calls      -- Log graphics API calls (only for Vulkan so far).
103   --log-graphics-calls-time -- Log timing of graphics API calls timing (Vulkan only).
104   --log-execute-calls       -- Log each execute call before run.
105   --disable-spirv-val       -- Disable SPIR-V validation.
106   -h                        -- This help text.
107 )";
108 
109 // Parses a decimal integer from the given string, and writes it to |retval|.
110 // Returns true if parsing succeeded and consumed the whole string.
ParseOneInt(const char* str, int* retval)111 static bool ParseOneInt(const char* str, int* retval) {
112   char trailing = 0;
113 #if defined(_MSC_VER)
114   return sscanf_s(str, "%d%c", retval, &trailing, 1) == 1;
115 #else
116   return std::sscanf(str, "%d%c", retval, &trailing) == 1;
117 #endif
118 }
119 
120 // Parses a decimal integer, then a period (.), then a decimal integer  from the
121 // given string, and writes it to |retval|.  Returns true if parsing succeeded
122 // and consumed the whole string.
ParseIntDotInt(const char* str, int* retval0, int* retval1)123 static int ParseIntDotInt(const char* str, int* retval0, int* retval1) {
124   char trailing = 0;
125 #if defined(_MSC_VER)
126   return sscanf_s(str, "%d.%d%c", retval0, retval1, &trailing, 1) == 2;
127 #else
128   return std::sscanf(str, "%d.%d%c", retval0, retval1, &trailing) == 2;
129 #endif
130 }
131 
ParseArgs(const std::vector<std::string>& args, Options* opts)132 bool ParseArgs(const std::vector<std::string>& args, Options* opts) {
133   for (size_t i = 1; i < args.size(); ++i) {
134     const std::string& arg = args[i];
135     if (arg == "-i") {
136       ++i;
137       if (i >= args.size()) {
138         std::cerr << "Missing value for -i argument." << std::endl;
139         return false;
140       }
141       opts->image_filenames.push_back(args[i]);
142 
143     } else if (arg == "-I") {
144       ++i;
145       if (i >= args.size()) {
146         std::cerr << "Missing value for -I argument." << std::endl;
147         return false;
148       }
149       opts->fb_names.push_back(args[i]);
150 
151     } else if (arg == "-b") {
152       ++i;
153       if (i >= args.size()) {
154         std::cerr << "Missing value for -b argument." << std::endl;
155         return false;
156       }
157       opts->buffer_filename = args[i];
158 
159     } else if (arg == "-B") {
160       ++i;
161       if (i >= args.size()) {
162         std::cerr << "Missing value for -B argument." << std::endl;
163         return false;
164       }
165       opts->buffer_to_dump.emplace_back();
166       opts->buffer_to_dump.back().buffer_name = args[i];
167     } else if (arg == "-w") {
168       ++i;
169       if (i >= args.size()) {
170         std::cerr << "Missing value for -w argument." << std::endl;
171         return false;
172       }
173       opts->shader_filename = args[i];
174     } else if (arg == "-e") {
175       ++i;
176       if (i >= args.size()) {
177         std::cerr << "Missing value for -e argument." << std::endl;
178         return false;
179       }
180       const std::string& engine = args[i];
181       if (engine == "vulkan") {
182         opts->engine = amber::kEngineTypeVulkan;
183       } else if (engine == "dawn") {
184         opts->engine = amber::kEngineTypeDawn;
185       } else {
186         std::cerr
187             << "Invalid value for -e argument. Must be one of: vulkan dawn"
188             << std::endl;
189         return false;
190       }
191     } else if (arg == "-D") {
192       ++i;
193       if (i >= args.size()) {
194         std::cerr << "Missing ID for -D argument." << std::endl;
195         return false;
196       }
197 
198       int32_t val = 0;
199       if (!ParseOneInt(args[i].c_str(), &val)) {
200         std::cerr << "Invalid device ID: " << args[i] << std::endl;
201         return false;
202       }
203       if (val < 0) {
204         std::cerr << "Device ID must be non-negative" << std::endl;
205         return false;
206       }
207       opts->selected_device = val;
208 
209     } else if (arg == "-f") {
210       ++i;
211       if (i >= args.size()) {
212         std::cerr << "Missing value for -f argument." << std::endl;
213         return false;
214       }
215 
216       int32_t val = 0;
217       if (!ParseOneInt(args[i].c_str(), &val)) {
218         std::cerr << "Invalid fence timeout: " << args[i] << std::endl;
219         return false;
220       }
221       if (val < 0) {
222         std::cerr << "Fence timeout must be non-negative" << std::endl;
223         return false;
224       }
225       opts->fence_timeout = val;
226 
227     } else if (arg == "-t") {
228       ++i;
229       if (i >= args.size()) {
230         std::cerr << "Missing value for -t argument." << std::endl;
231         return false;
232       }
233       opts->spv_env = args[i];
234     } else if (arg == "-h" || arg == "--help") {
235       opts->show_help = true;
236     } else if (arg == "-v") {
237       ++i;
238       if (i >= args.size()) {
239         std::cerr << "Missing value for -v argument." << std::endl;
240         return false;
241       }
242       const std::string& ver = std::string(args[i]);
243 
244       int32_t major = 0;
245       int32_t minor = 0;
246       if (ParseIntDotInt(ver.c_str(), &major, &minor) ||
247           ParseOneInt(ver.c_str(), &major)) {
248         if (major < 0) {
249           std::cerr << "Version major must be non-negative" << std::endl;
250           return false;
251         }
252         if (minor < 0) {
253           std::cerr << "Version minor must be non-negative" << std::endl;
254           return false;
255         }
256         opts->engine_major = static_cast<uint32_t>(major);
257         opts->engine_minor = static_cast<uint32_t>(minor);
258       } else {
259         std::cerr << "Invalid engine version number: " << ver << std::endl;
260         return false;
261       }
262     } else if (arg == "-V" || arg == "--version") {
263       opts->show_version_info = true;
264     } else if (arg == "-p") {
265       opts->parse_only = true;
266     } else if (arg == "-ps") {
267       opts->pipeline_create_only = true;
268     } else if (arg == "-d") {
269       opts->disable_validation_layer = true;
270     } else if (arg == "-s") {
271       // -s is deprecated but still recognized, it inverts the quiet flag.
272       opts->quiet = false;
273     } else if (arg == "-q") {
274       opts->quiet = true;
275     } else if (arg == "--log-graphics-calls") {
276       opts->log_graphics_calls = true;
277     } else if (arg == "--log-graphics-calls-time") {
278       opts->log_graphics_calls_time = true;
279     } else if (arg == "--log-execute-calls") {
280       opts->log_execute_calls = true;
281     } else if (arg == "--disable-spirv-val") {
282       opts->disable_spirv_validation = true;
283     } else if (arg.size() > 0 && arg[0] == '-') {
284       std::cerr << "Unrecognized option " << arg << std::endl;
285       return false;
286     } else if (!arg.empty()) {
287       opts->input_filenames.push_back(arg);
288     }
289   }
290 
291   return true;
292 }
293 
ReadFile(const std::string& input_file)294 std::vector<char> ReadFile(const std::string& input_file) {
295   FILE* file = nullptr;
296 #if defined(_MSC_VER)
297   fopen_s(&file, input_file.c_str(), "rb");
298 #else
299   file = fopen(input_file.c_str(), "rb");
300 #endif
301   if (!file) {
302     std::cerr << "Failed to open " << input_file << std::endl;
303     return {};
304   }
305 
306   fseek(file, 0, SEEK_END);
307   uint64_t tell_file_size = static_cast<uint64_t>(ftell(file));
308   if (tell_file_size <= 0) {
309     std::cerr << "Input file of incorrect size: " << input_file << std::endl;
310     fclose(file);
311     return {};
312   }
313   fseek(file, 0, SEEK_SET);
314 
315   size_t file_size = static_cast<size_t>(tell_file_size);
316 
317   std::vector<char> data;
318   data.resize(file_size);
319 
320   size_t bytes_read = fread(data.data(), sizeof(char), file_size, file);
321   fclose(file);
322   if (bytes_read != file_size) {
323     std::cerr << "Failed to read " << input_file << std::endl;
324     return {};
325   }
326 
327   return data;
328 }
329 
330 class SampleDelegate : public amber::Delegate {
331  public:
332   SampleDelegate() = default;
333   ~SampleDelegate() override = default;
334 
335   void Log(const std::string& message) override {
336     std::cout << message << std::endl;
337   }
338 
339   bool LogGraphicsCalls() const override { return log_graphics_calls_; }
SetLogGraphicsCalls(bool log_graphics_calls)340   void SetLogGraphicsCalls(bool log_graphics_calls) {
341     log_graphics_calls_ = log_graphics_calls;
342   }
343 
344   bool LogExecuteCalls() const override { return log_execute_calls_; }
SetLogExecuteCalls(bool log_execute_calls)345   void SetLogExecuteCalls(bool log_execute_calls) {
346     log_execute_calls_ = log_execute_calls;
347   }
348 
349   bool LogGraphicsCallsTime() const override {
350     return log_graphics_calls_time_;
351   }
SetLogGraphicsCallsTime(bool log_graphics_calls_time)352   void SetLogGraphicsCallsTime(bool log_graphics_calls_time) {
353     log_graphics_calls_time_ = log_graphics_calls_time;
354     if (log_graphics_calls_time) {
355       // Make sure regular logging is also enabled
356       log_graphics_calls_ = true;
357     }
358   }
359 
360   uint64_t GetTimestampNs() const override {
361     return timestamp::SampleGetTimestampNs();
362   }
363 
SetScriptPath(std::string path)364   void SetScriptPath(std::string path) { path_ = path; }
365 
366   amber::Result LoadBufferData(const std::string file_name,
367                                amber::BufferDataFileType file_type,
368                                amber::BufferInfo* buffer) const override {
369     if (file_type == amber::BufferDataFileType::kPng) {
370 #if AMBER_ENABLE_LODEPNG
371       return png::LoadPNG(path_ + file_name, &buffer->width, &buffer->height,
372                           &buffer->values);
373 #else
374       return amber::Result("PNG support is not enabled in compile options.");
375 #endif  // AMBER_ENABLE_LODEPNG
376     } else {
377       auto data = ReadFile(path_ + file_name);
378       if (data.empty())
379         return amber::Result("Failed to load buffer data " + file_name);
380 
381       for (auto d : data) {
382         amber::Value v;
383         v.SetIntValue(static_cast<uint64_t>(d));
384         buffer->values.push_back(v);
385       }
386 
387       buffer->width = 1;
388       buffer->height = 1;
389     }
390 
391     return {};
392   }
393 
394  private:
395   bool log_graphics_calls_ = false;
396   bool log_graphics_calls_time_ = false;
397   bool log_execute_calls_ = false;
398   std::string path_ = "";
399 };
400 
disassemble(const std::string& env, const std::vector<uint32_t>& data)401 std::string disassemble(const std::string& env,
402                         const std::vector<uint32_t>& data) {
403 #if AMBER_ENABLE_SPIRV_TOOLS
404   std::string spv_errors;
405 
406   spv_target_env target_env = SPV_ENV_UNIVERSAL_1_0;
407   if (!env.empty()) {
408     if (!spvParseTargetEnv(env.c_str(), &target_env))
409       return "";
410   }
411 
412   auto msg_consumer = [&spv_errors](spv_message_level_t level, const char*,
413                                     const spv_position_t& position,
414                                     const char* message) {
415     switch (level) {
416       case SPV_MSG_FATAL:
417       case SPV_MSG_INTERNAL_ERROR:
418       case SPV_MSG_ERROR:
419         spv_errors += "error: line " + std::to_string(position.index) + ": " +
420                       message + "\n";
421         break;
422       case SPV_MSG_WARNING:
423         spv_errors += "warning: line " + std::to_string(position.index) + ": " +
424                       message + "\n";
425         break;
426       case SPV_MSG_INFO:
427         spv_errors += "info: line " + std::to_string(position.index) + ": " +
428                       message + "\n";
429         break;
430       case SPV_MSG_DEBUG:
431         break;
432     }
433   };
434 
435   spvtools::SpirvTools tools(target_env);
436   tools.SetMessageConsumer(msg_consumer);
437 
438   std::string result;
439   tools.Disassemble(data, &result,
440                     SPV_BINARY_TO_TEXT_OPTION_INDENT |
441                         SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES);
442   return result;
443 #else
444   return "";
445 #endif  // AMBER_ENABLE_SPIRV_TOOLS
446 }
447 
448 }  // namespace
449 
450 #ifdef AMBER_ANDROID_MAIN
451 #pragma clang diagnostic push
452 #pragma clang diagnostic ignored "-Wmissing-prototypes"
453 #pragma ide diagnostic ignored "OCUnusedGlobalDeclarationInspection"
android_main(int argc, const char** argv)454 int android_main(int argc, const char** argv) {
455 #pragma clang diagnostic pop
456 #else
457 int main(int argc, const char** argv) {
458 #endif
459   std::vector<std::string> args(argv, argv + argc);
460   Options options;
461   SampleDelegate delegate;
462 
463   if (!ParseArgs(args, &options)) {
464     std::cerr << "Failed to parse arguments." << std::endl;
465     return 1;
466   }
467 
468   if (options.show_version_info) {
469     std::cout << "Amber        : " << AMBER_VERSION << std::endl;
470 #if AMBER_ENABLE_SPIRV_TOOLS
471     std::cout << "SPIRV-Tools  : " << SPIRV_TOOLS_VERSION << std::endl;
472     std::cout << "SPIRV-Headers: " << SPIRV_HEADERS_VERSION << std::endl;
473 #endif  // AMBER_ENABLE_SPIRV_TOOLS
474 #if AMBER_ENABLE_SHADERC
475     std::cout << "GLSLang      : " << GLSLANG_VERSION << std::endl;
476     std::cout << "Shaderc      : " << SHADERC_VERSION << std::endl;
477 #endif  // AMBER_ENABLE_SHADERC
478   }
479 
480   if (options.show_help) {
481     std::cout << kUsage << std::endl;
482     return 0;
483   }
484 
485   amber::Result result;
486   std::vector<std::string> failures;
487   struct RecipeData {
488     std::string file;
489     std::unique_ptr<amber::Recipe> recipe;
490   };
491   std::vector<RecipeData> recipe_data;
492   for (const auto& file : options.input_filenames) {
493     auto char_data = ReadFile(file);
494     auto data = std::string(char_data.begin(), char_data.end());
495     if (data.empty()) {
496       std::cerr << file << " is empty." << std::endl;
497       failures.push_back(file);
498       continue;
499     }
500 
501     // Parse file path and set it for delegate to use when loading buffer data.
502     delegate.SetScriptPath(file.substr(0, file.find_last_of("/\\") + 1));
503 
504     amber::Amber am(&delegate);
505     std::unique_ptr<amber::Recipe> recipe = amber::MakeUnique<amber::Recipe>();
506 
507     result = am.Parse(data, recipe.get());
508     if (!result.IsSuccess()) {
509       std::cerr << file << ": " << result.Error() << std::endl;
510       failures.push_back(file);
511       continue;
512     }
513 
514     if (options.fence_timeout > -1)
515       recipe->SetFenceTimeout(static_cast<uint32_t>(options.fence_timeout));
516 
517     recipe_data.emplace_back();
518     recipe_data.back().file = file;
519     recipe_data.back().recipe = std::move(recipe);
520   }
521 
522   if (options.parse_only)
523     return 0;
524 
525   if (options.log_graphics_calls)
526     delegate.SetLogGraphicsCalls(true);
527   if (options.log_graphics_calls_time)
528     delegate.SetLogGraphicsCallsTime(true);
529   if (options.log_execute_calls)
530     delegate.SetLogExecuteCalls(true);
531 
532   amber::Options amber_options;
533   amber_options.engine = options.engine;
534   amber_options.spv_env = options.spv_env;
535   amber_options.execution_type = options.pipeline_create_only
536                                      ? amber::ExecutionType::kPipelineCreateOnly
537                                      : amber::ExecutionType::kExecute;
538   amber_options.disable_spirv_validation = options.disable_spirv_validation;
539 
540   std::set<std::string> required_features;
541   std::set<std::string> required_device_extensions;
542   std::set<std::string> required_instance_extensions;
543   for (const auto& recipe_data_elem : recipe_data) {
544     const auto features = recipe_data_elem.recipe->GetRequiredFeatures();
545     required_features.insert(features.begin(), features.end());
546 
547     const auto device_extensions =
548         recipe_data_elem.recipe->GetRequiredDeviceExtensions();
549     required_device_extensions.insert(device_extensions.begin(),
550                                       device_extensions.end());
551 
552     const auto inst_extensions =
553         recipe_data_elem.recipe->GetRequiredInstanceExtensions();
554     required_instance_extensions.insert(inst_extensions.begin(),
555                                         inst_extensions.end());
556   }
557 
558   sample::ConfigHelper config_helper;
559   std::unique_ptr<amber::EngineConfig> config;
560 
561   amber::Result r = config_helper.CreateConfig(
562       amber_options.engine, options.engine_major, options.engine_minor,
563       options.selected_device,
564       std::vector<std::string>(required_features.begin(),
565                                required_features.end()),
566       std::vector<std::string>(required_instance_extensions.begin(),
567                                required_instance_extensions.end()),
568       std::vector<std::string>(required_device_extensions.begin(),
569                                required_device_extensions.end()),
570       options.disable_validation_layer, options.show_version_info, &config);
571 
572   if (!r.IsSuccess()) {
573     std::cout << r.Error() << std::endl;
574     return 1;
575   }
576 
577   amber_options.config = config.get();
578 
579   if (!options.buffer_filename.empty()) {
580     // Have a filename to dump, but no explicit buffer, set the default of 0:0.
581     if (options.buffer_to_dump.empty()) {
582       options.buffer_to_dump.emplace_back();
583       options.buffer_to_dump.back().buffer_name = "0:0";
584     }
585 
586     amber_options.extractions.insert(amber_options.extractions.end(),
587                                      options.buffer_to_dump.begin(),
588                                      options.buffer_to_dump.end());
589   }
590 
591   if (options.image_filenames.size() - options.fb_names.size() > 1) {
592     std::cerr << "Need to specify framebuffer names using -I for each output "
593                  "image specified by -i."
594               << std::endl;
595     return 1;
596   }
597 
598   // Use default frame buffer name when not specified.
599   while (options.image_filenames.size() > options.fb_names.size())
600     options.fb_names.push_back(kGeneratedColorBuffer);
601 
602   for (const auto& fb_name : options.fb_names) {
603     amber::BufferInfo buffer_info;
604     buffer_info.buffer_name = fb_name;
605     buffer_info.is_image_buffer = true;
606     amber_options.extractions.push_back(buffer_info);
607   }
608 
609   for (const auto& recipe_data_elem : recipe_data) {
610     const auto* recipe = recipe_data_elem.recipe.get();
611     const auto& file = recipe_data_elem.file;
612 
613     amber::Amber am(&delegate);
614     result = am.Execute(recipe, &amber_options);
615     if (!result.IsSuccess()) {
616       std::cerr << file << ": " << result.Error() << std::endl;
617       failures.push_back(file);
618       // Note, we continue after failure to allow dumping the buffers which may
619       // give clues as to the failure.
620     }
621 
622     // Dump the shader assembly
623     if (!options.shader_filename.empty()) {
624 #if AMBER_ENABLE_SPIRV_TOOLS
625       std::ofstream shader_file;
626       shader_file.open(options.shader_filename, std::ios::out);
627       if (!shader_file.is_open()) {
628         std::cerr << "Cannot open file for shader dump: ";
629         std::cerr << options.shader_filename << std::endl;
630       } else {
631         auto info = recipe->GetShaderInfo();
632         for (const auto& sh : info) {
633           shader_file << ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"
634                       << std::endl;
635           shader_file << "; " << sh.shader_name << std::endl
636                       << ";" << std::endl;
637           shader_file << disassemble(options.spv_env, sh.shader_data)
638                       << std::endl;
639         }
640         shader_file.close();
641       }
642 #endif  // AMBER_ENABLE_SPIRV_TOOLS
643     }
644 
645     for (size_t i = 0; i < options.image_filenames.size(); ++i) {
646       std::vector<uint8_t> out_buf;
647       auto image_filename = options.image_filenames[i];
648       auto pos = image_filename.find_last_of('.');
649       bool usePNG =
650           pos != std::string::npos && image_filename.substr(pos + 1) == "png";
651       for (const amber::BufferInfo& buffer_info : amber_options.extractions) {
652         if (buffer_info.buffer_name == options.fb_names[i]) {
653           if (buffer_info.values.size() !=
654               (buffer_info.width * buffer_info.height)) {
655             result = amber::Result(
656                 "Framebuffer (" + buffer_info.buffer_name + ") size (" +
657                 std::to_string(buffer_info.values.size()) +
658                 ") != " + "width * height (" +
659                 std::to_string(buffer_info.width * buffer_info.height) + ")");
660             break;
661           }
662 
663           if (buffer_info.values.empty()) {
664             result = amber::Result("Framebuffer (" + buffer_info.buffer_name +
665                                    ") empty or non-existent.");
666             break;
667           }
668 
669           if (usePNG) {
670 #if AMBER_ENABLE_LODEPNG
671             result = png::ConvertToPNG(buffer_info.width, buffer_info.height,
672                                        buffer_info.values, &out_buf);
673 #else   // AMBER_ENABLE_LODEPNG
674             result = amber::Result("PNG support not enabled");
675 #endif  // AMBER_ENABLE_LODEPNG
676           } else {
677             ppm::ConvertToPPM(buffer_info.width, buffer_info.height,
678                               buffer_info.values, &out_buf);
679             result = {};
680           }
681           break;
682         }
683       }
684       if (result.IsSuccess()) {
685         std::ofstream image_file;
686         image_file.open(image_filename, std::ios::out | std::ios::binary);
687         if (!image_file.is_open()) {
688           std::cerr << "Cannot open file for image dump: ";
689           std::cerr << image_filename << std::endl;
690           continue;
691         }
692         image_file << std::string(out_buf.begin(), out_buf.end());
693         image_file.close();
694       } else {
695         std::cerr << result.Error() << std::endl;
696       }
697     }
698 
699     if (!options.buffer_filename.empty()) {
700       std::ofstream buffer_file;
701       buffer_file.open(options.buffer_filename, std::ios::out);
702       if (!buffer_file.is_open()) {
703         std::cerr << "Cannot open file for buffer dump: ";
704         std::cerr << options.buffer_filename << std::endl;
705       } else {
706         for (const amber::BufferInfo& buffer_info : amber_options.extractions) {
707           // Skip frame buffers.
708           if (std::any_of(options.fb_names.begin(), options.fb_names.end(),
709                           [&](std::string s) {
710                             return s == buffer_info.buffer_name;
711                           }) ||
712               buffer_info.buffer_name == kGeneratedColorBuffer) {
713             continue;
714           }
715 
716           buffer_file << buffer_info.buffer_name << std::endl;
717           const auto& values = buffer_info.values;
718           for (size_t i = 0; i < values.size(); ++i) {
719             buffer_file << " " << std::setfill('0') << std::setw(2) << std::hex
720                         << values[i].AsUint32();
721             if (i % 16 == 15)
722               buffer_file << std::endl;
723           }
724           buffer_file << std::endl;
725         }
726         buffer_file.close();
727       }
728     }
729   }
730 
731   if (!options.quiet) {
732     if (!failures.empty()) {
733       std::cout << "\nSummary of Failures:" << std::endl;
734 
735       for (const auto& failure : failures)
736         std::cout << "  " << failure << std::endl;
737     }
738 
739     std::cout << "\nSummary: "
740               << (options.input_filenames.size() - failures.size()) << " pass, "
741               << failures.size() << " fail" << std::endl;
742   }
743 
744   return !failures.empty();
745 }
746