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