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