1 /**************************************************************************
3 * Copyright 2011 Jose Fonseca
4 * Copyright (C) 2013 Intel Corporation. All rights reversed.
5 * Author: Shuang He <shuang.he@intel.com>
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 **************************************************************************/
30 #include <limits.h> // for CHAR_MAX
34 #include "os_binary.hpp"
35 #include "os_time.hpp"
36 #include "os_thread.hpp"
38 #include "trace_callset.hpp"
39 #include "trace_dump.hpp"
40 #include "trace_option.hpp"
41 #include "retrace.hpp"
44 static bool waitOnFinish = false;
45 static bool loopOnFinish = false;
47 static const char *snapshotPrefix = NULL;
51 } snapshotFormat = PNM_FMT;
53 static trace::CallSet snapshotFrequency;
54 static trace::ParseBookmark lastFrameStart;
56 static unsigned dumpStateCallNo = ~0;
58 retrace::Retracer retracer;
65 trace::Profiler profiler;
70 bool dumpingState = false;
72 Driver driver = DRIVER_DEFAULT;
73 const char *driverModule = NULL;
75 bool doubleBuffer = true;
76 bool coreProfile = false;
78 bool profiling = false;
79 bool profilingGpuTimes = false;
80 bool profilingCpuTimes = false;
81 bool profilingPixelsDrawn = false;
82 bool profilingMemoryUsage = false;
83 bool useCallNos = true;
84 bool singleThread = false;
91 frameComplete(trace::Call &call) {
96 static Dumper defaultDumper;
98 Dumper *dumper = &defaultDumper;
105 takeSnapshot(unsigned call_no) {
106 static unsigned snapshot_no = 0;
108 assert(snapshotPrefix);
110 image::Image *src = dumper->getSnapshot();
112 std::cerr << call_no << ": warning: failed to get snapshot\n";
116 if (snapshotPrefix) {
117 if (snapshotPrefix[0] == '-' && snapshotPrefix[1] == 0) {
119 snprintf(comment, sizeof comment, "%u",
120 useCallNos ? call_no : snapshot_no);
121 if (snapshotFormat == RAW_RGB)
122 src->writeRAW(std::cout);
124 src->writePNM(std::cout, comment);
126 os::String filename = os::String::format("%s%010u.png",
128 useCallNos ? call_no : snapshot_no);
129 if (src->writePNG(filename) && retrace::verbosity >= 0) {
130 std::cout << "Wrote " << filename << "\n";
146 * Take snapshots before/after retracing (as appropriate) and dispatch it to
147 * the respective handler.
150 retraceCall(trace::Call *call) {
151 bool swapRenderTarget = call->flags &
152 trace::CALL_FLAG_SWAP_RENDERTARGET;
153 bool doSnapshot = snapshotFrequency.contains(*call);
155 // For calls which cause rendertargets to be swaped, we take the
156 // snapshot _before_ swapping the rendertargets.
157 if (doSnapshot && swapRenderTarget) {
158 if (call->flags & trace::CALL_FLAG_END_FRAME) {
159 // For swapbuffers/presents we still use this
160 // call number, spite not have been executed yet.
161 takeSnapshot(call->no);
163 // Whereas for ordinate fbo/rendertarget changes we
164 // use the previous call's number.
165 takeSnapshot(call->no - 1);
170 retracer.retrace(*call);
172 if (doSnapshot && !swapRenderTarget)
173 takeSnapshot(call->no);
175 if (call->no >= dumpStateCallNo &&
176 dumper->dumpState(std::cout)) {
186 * Implement multi-threading by mimicking a relay race.
192 * Runners indexed by the leg they run (i.e, the thread_ids from the
195 std::vector<RelayRunner*> runners;
203 getRunner(unsigned leg);
214 passBaton(trace::Call *call);
225 * Each runner is a thread.
227 * The fore runner doesn't have its own thread, but instead uses the thread
228 * where the race started.
233 friend class RelayRace;
240 os::condition_variable wake_cond;
243 * There are protected by the mutex.
251 runnerThread(RelayRunner *_this);
254 RelayRunner(RelayRace *race, unsigned _leg) :
260 /* The fore runner does not need a new thread */
262 thread = os::thread(runnerThread, this);
267 if (thread.joinable()) {
277 os::unique_lock<os::mutex> lock(mutex);
280 while (!finished && !baton) {
281 wake_cond.wait(lock);
289 trace::Call *call = baton;
295 if (0) std::cerr << "leg " << leg << " actually finishing\n";
303 * Interpret successive calls.
306 runLeg(trace::Call *call) {
308 /* Consume successive calls for this thread. */
310 bool callEndsFrame = false;
311 static trace::ParseBookmark frameStart;
314 assert(call->thread_id == leg);
316 if (loopOnFinish && call->flags & trace::CALL_FLAG_END_FRAME) {
317 callEndsFrame = true;
318 parser.getBookmark(frameStart);
323 call = parser.parse_call();
325 /* Restart last frame if looping is requested. */
328 parser.setBookmark(lastFrameStart);
329 call = parser.parse_call();
330 } else if (callEndsFrame) {
331 lastFrameStart = frameStart;
335 } while (call && call->thread_id == leg);
339 assert(call->thread_id != leg);
341 race->passBaton(call);
343 /* Reached the finish line */
344 if (0) std::cerr << "finished on leg " << leg << "\n";
346 /* Notify the fore runner */
349 /* We are the fore runner */
356 * Called by other threads when relinquishing the baton.
359 receiveBaton(trace::Call *call) {
360 assert (call->thread_id == leg);
370 * Called by the fore runner when the race is over.
374 if (0) std::cerr << "notify finish to leg " << leg << "\n";
386 RelayRunner::runnerThread(RelayRunner *_this) {
392 RelayRace::RelayRace() {
393 runners.push_back(new RelayRunner(this, 0));
397 RelayRace::~RelayRace() {
398 assert(runners.size() >= 1);
399 std::vector<RelayRunner*>::const_iterator it;
400 for (it = runners.begin(); it != runners.end(); ++it) {
401 RelayRunner* runner = *it;
410 * Get (or instantiate) a runner for the specified leg.
413 RelayRace::getRunner(unsigned leg) {
416 if (leg >= runners.size()) {
417 runners.resize(leg + 1);
420 runner = runners[leg];
423 runner = new RelayRunner(this, leg);
424 runners[leg] = runner;
434 RelayRace::run(void) {
436 call = parser.parse_call();
442 /* If the user wants to loop we need to get a bookmark target. We
443 * usually get this after replaying a call that ends a frame, but
444 * for a trace that has only one frame we need to get it at the
447 parser.getBookmark(lastFrameStart);
450 RelayRunner *foreRunner = getForeRunner();
451 if (call->thread_id == 0) {
452 /* We are the forerunner thread, so no need to pass baton */
453 foreRunner->baton = call;
458 /* Start the forerunner thread */
459 foreRunner->runRace();
464 * Pass the baton (i.e., the call) to the appropriate thread.
467 RelayRace::passBaton(trace::Call *call) {
468 if (0) std::cerr << "switching to thread " << call->thread_id << "\n";
469 RelayRunner *runner = getRunner(call->thread_id);
470 runner->receiveBaton(call);
475 * Called when a runner other than the forerunner reaches the finish line.
477 * Only the fore runner can finish the race, so inform him that the race is
481 RelayRace::finishLine(void) {
482 RelayRunner *foreRunner = getForeRunner();
483 foreRunner->finishRace();
488 * Called by the fore runner after finish line to stop all other runners.
491 RelayRace::stopRunners(void) {
492 std::vector<RelayRunner*>::const_iterator it;
493 for (it = runners.begin() + 1; it != runners.end(); ++it) {
494 RelayRunner* runner = *it;
496 runner->finishRace();
504 addCallbacks(retracer);
506 long long startTime = 0;
509 startTime = os::getTime();
513 while ((call = parser.parse_call())) {
523 long long endTime = os::getTime();
524 float timeInterval = (endTime - startTime) * (1.0 / os::timeFrequency);
526 if ((retrace::verbosity >= -1) || (retrace::profiling)) {
528 "Rendered " << frameNo << " frames"
529 " in " << timeInterval << " secs,"
530 " average of " << (frameNo/timeInterval) << " fps\n";
541 } /* namespace retrace */
545 usage(const char *argv0) {
547 "Usage: " << argv0 << " [OPTION] TRACE [...]\n"
550 " -b, --benchmark benchmark mode (no error checking or warning messages)\n"
551 " --pcpu cpu profiling (cpu times per call)\n"
552 " --pgpu gpu profiling (gpu times per draw call)\n"
553 " --ppd pixels drawn profiling (pixels drawn per draw call)\n"
554 " --pmem memory usage profiling (vsize rss per call)\n"
555 " --call-nos[=BOOL] use call numbers in snapshot filenames\n"
556 " --core use core profile\n"
557 " --db use a double buffer visual (default)\n"
558 " --driver=DRIVER force driver type (`hw`, `sw`, `ref`, `null`, or driver module name)\n"
559 " --sb use a single buffer visual\n"
560 " -s, --snapshot-prefix=PREFIX take snapshots; `-` for PNM stdout output\n"
561 " --snapshot-format=FMT use (PNM or RGB; default is PNM) when writing to stdout output\n"
562 " -S, --snapshot=CALLSET calls to snapshot (default is every frame)\n"
563 " -v, --verbose increase output verbosity\n"
564 " -D, --dump-state=CALL dump state at specific call no\n"
565 " -w, --wait waitOnFinish on final frame\n"
566 " --loop continuously loop, replaying final frame.\n"
567 " --singlethread use a single thread to replay command stream\n";
571 CALL_NOS_OPT = CHAR_MAX + 1,
586 shortOptions = "bD:hs:S:vw";
588 const static struct option
590 {"benchmark", no_argument, 0, 'b'},
591 {"call-nos", optional_argument, 0, CALL_NOS_OPT },
592 {"core", no_argument, 0, CORE_OPT},
593 {"db", no_argument, 0, DB_OPT},
594 {"driver", required_argument, 0, DRIVER_OPT},
595 {"dump-state", required_argument, 0, 'D'},
596 {"help", no_argument, 0, 'h'},
597 {"pcpu", no_argument, 0, PCPU_OPT},
598 {"pgpu", no_argument, 0, PGPU_OPT},
599 {"ppd", no_argument, 0, PPD_OPT},
600 {"pmem", no_argument, 0, PMEM_OPT},
601 {"sb", no_argument, 0, SB_OPT},
602 {"snapshot-prefix", required_argument, 0, 's'},
603 {"snapshot-format", required_argument, 0, SNAPSHOT_FORMAT_OPT},
604 {"snapshot", required_argument, 0, 'S'},
605 {"verbose", no_argument, 0, 'v'},
606 {"wait", no_argument, 0, 'w'},
607 {"loop", no_argument, 0, LOOP_OPT},
608 {"singlethread", no_argument, 0, SINGLETHREAD_OPT},
613 static void exceptionCallback(void)
615 std::cerr << retrace::callNo << ": error: caught an unhandled exception\n";
620 int main(int argc, char **argv)
622 using namespace retrace;
625 assert(snapshotFrequency.empty());
628 while ((opt = getopt_long_only(argc, argv, shortOptions, longOptions, NULL)) != -1) {
634 retrace::debug = false;
635 retrace::verbosity = -1;
638 useCallNos = trace::boolOption(optarg);
641 dumpStateCallNo = atoi(optarg);
643 retrace::verbosity = -2;
646 retrace::coreProfile = true;
649 retrace::doubleBuffer = true;
652 if (strcasecmp(optarg, "hw") == 0) {
653 driver = DRIVER_HARDWARE;
654 } else if (strcasecmp(optarg, "sw") == 0) {
655 driver = DRIVER_SOFTWARE;
656 } else if (strcasecmp(optarg, "ref") == 0) {
657 driver = DRIVER_REFERENCE;
658 } else if (strcasecmp(optarg, "null") == 0) {
659 driver = DRIVER_NULL;
661 driver = DRIVER_MODULE;
662 driverModule = optarg;
666 retrace::doubleBuffer = false;
668 case SINGLETHREAD_OPT:
669 retrace::singleThread = true;
672 snapshotPrefix = optarg;
673 if (snapshotFrequency.empty()) {
674 snapshotFrequency = trace::CallSet(trace::FREQUENCY_FRAME);
676 if (snapshotPrefix[0] == '-' && snapshotPrefix[1] == 0) {
677 os::setBinaryMode(stdout);
678 retrace::verbosity = -2;
681 * Create the snapshot directory if it does not exist.
683 * We can't just use trimFilename() because when applied to
684 * "/foo/boo/" it would merely return "/foo".
686 * XXX: create nested directories.
688 os::String prefix(snapshotPrefix);
689 os::String::iterator sep = prefix.rfindSep(false);
690 if (sep != prefix.end()) {
691 prefix.erase(sep, prefix.end());
692 if (!prefix.exists() && !os::createDirectory(prefix)) {
693 std::cerr << "error: failed to create `" << prefix.str() << "` directory\n";
698 case SNAPSHOT_FORMAT_OPT:
699 if (strcmp(optarg, "RGB") == 0)
700 snapshotFormat = RAW_RGB;
702 snapshotFormat = PNM_FMT;
705 snapshotFrequency = trace::CallSet(optarg);
706 if (snapshotPrefix == NULL) {
711 ++retrace::verbosity;
720 retrace::debug = false;
721 retrace::profiling = true;
722 retrace::verbosity = -1;
724 retrace::profilingGpuTimes = true;
727 retrace::debug = false;
728 retrace::profiling = true;
729 retrace::verbosity = -1;
731 retrace::profilingCpuTimes = true;
734 retrace::debug = false;
735 retrace::profiling = true;
736 retrace::verbosity = -1;
738 retrace::profilingPixelsDrawn = true;
741 retrace::debug = false;
742 retrace::profiling = true;
743 retrace::verbosity = -1;
745 retrace::profilingMemoryUsage = true;
748 std::cerr << "error: unknown option " << opt << "\n";
755 if (retrace::profiling) {
756 retrace::profiler.setup(retrace::profilingCpuTimes, retrace::profilingGpuTimes, retrace::profilingPixelsDrawn, retrace::profilingMemoryUsage);
759 os::setExceptionCallback(exceptionCallback);
761 for (i = optind; i < argc; ++i) {
762 if (!retrace::parser.open(argv[i])) {
768 retrace::parser.close();
771 os::resetExceptionCallback();
773 // XXX: X often hangs on XCloseDisplay
774 //retrace::cleanUp();