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 *comparePrefix = NULL;
48 static const char *snapshotPrefix = NULL;
52 } snapshotFormat = PNM_FMT;
54 static trace::CallSet snapshotFrequency;
55 static trace::CallSet compareFrequency;
56 static trace::ParseBookmark lastFrameStart;
58 static unsigned dumpStateCallNo = ~0;
60 retrace::Retracer retracer;
67 trace::Profiler profiler;
72 bool dumpingState = false;
74 Driver driver = DRIVER_DEFAULT;
75 const char *driverModule = NULL;
77 bool doubleBuffer = true;
78 bool coreProfile = false;
80 bool profiling = false;
81 bool profilingGpuTimes = false;
82 bool profilingCpuTimes = false;
83 bool profilingPixelsDrawn = false;
84 bool profilingMemoryUsage = false;
85 bool useCallNos = true;
86 bool singleThread = false;
93 frameComplete(trace::Call &call) {
98 static Dumper defaultDumper;
100 Dumper *dumper = &defaultDumper;
104 * Take/compare snapshots.
107 takeSnapshot(unsigned call_no) {
108 static unsigned snapshot_no = 0;
110 assert(snapshotPrefix || comparePrefix);
112 image::Image *ref = NULL;
115 os::String filename = os::String::format("%s%010u.png", comparePrefix, call_no);
116 ref = image::readPNG(filename);
120 if (retrace::verbosity >= 0) {
121 std::cout << "Read " << filename << "\n";
125 image::Image *src = dumper->getSnapshot();
127 std::cerr << call_no << ": warning: failed to get snapshot\n";
131 if (snapshotPrefix) {
132 if (snapshotPrefix[0] == '-' && snapshotPrefix[1] == 0) {
134 snprintf(comment, sizeof comment, "%u",
135 useCallNos ? call_no : snapshot_no);
136 if (snapshotFormat == RAW_RGB)
137 src->writeRAW(std::cout);
139 src->writePNM(std::cout, comment);
141 os::String filename = os::String::format("%s%010u.png",
143 useCallNos ? call_no : snapshot_no);
144 if (src->writePNG(filename) && retrace::verbosity >= 0) {
145 std::cout << "Wrote " << filename << "\n";
151 std::cout << "Snapshot " << call_no << " average precision of " << src->compare(*ref) << " bits\n";
166 * Take snapshots before/after retracing (as appropriate) and dispatch it to
167 * the respective handler.
170 retraceCall(trace::Call *call) {
171 bool swapRenderTarget = call->flags &
172 trace::CALL_FLAG_SWAP_RENDERTARGET;
173 bool doSnapshot = snapshotFrequency.contains(*call) ||
174 compareFrequency.contains(*call);
176 // For calls which cause rendertargets to be swaped, we take the
177 // snapshot _before_ swapping the rendertargets.
178 if (doSnapshot && swapRenderTarget) {
179 if (call->flags & trace::CALL_FLAG_END_FRAME) {
180 // For swapbuffers/presents we still use this
181 // call number, spite not have been executed yet.
182 takeSnapshot(call->no);
184 // Whereas for ordinate fbo/rendertarget changes we
185 // use the previous call's number.
186 takeSnapshot(call->no - 1);
191 retracer.retrace(*call);
193 if (doSnapshot && !swapRenderTarget)
194 takeSnapshot(call->no);
196 if (call->no >= dumpStateCallNo &&
197 dumper->dumpState(std::cout)) {
207 * Implement multi-threading by mimicking a relay race.
213 * Runners indexed by the leg they run (i.e, the thread_ids from the
216 std::vector<RelayRunner*> runners;
224 getRunner(unsigned leg);
235 passBaton(trace::Call *call);
246 * Each runner is a thread.
248 * The fore runner doesn't have its own thread, but instead uses the thread
249 * where the race started.
254 friend class RelayRace;
261 os::condition_variable wake_cond;
264 * There are protected by the mutex.
272 runnerThread(RelayRunner *_this);
275 RelayRunner(RelayRace *race, unsigned _leg) :
281 /* The fore runner does not need a new thread */
283 thread = os::thread(runnerThread, this);
292 os::unique_lock<os::mutex> lock(mutex);
295 while (!finished && !baton) {
296 wake_cond.wait(lock);
304 trace::Call *call = baton;
310 if (0) std::cerr << "leg " << leg << " actually finishing\n";
318 * Interpret successive calls.
321 runLeg(trace::Call *call) {
323 /* Consume successive calls for this thread. */
325 bool callEndsFrame = false;
326 static trace::ParseBookmark frameStart;
329 assert(call->thread_id == leg);
331 if (loopOnFinish && call->flags & trace::CALL_FLAG_END_FRAME) {
332 callEndsFrame = true;
333 parser.getBookmark(frameStart);
338 call = parser.parse_call();
340 /* Restart last frame if looping is requested. */
343 parser.setBookmark(lastFrameStart);
344 call = parser.parse_call();
345 } else if (callEndsFrame) {
346 lastFrameStart = frameStart;
350 } while (call && call->thread_id == leg);
354 assert(call->thread_id != leg);
356 race->passBaton(call);
358 /* Reached the finish line */
359 if (0) std::cerr << "finished on leg " << leg << "\n";
361 /* Notify the fore runner */
364 /* We are the fore runner */
371 * Called by other threads when relinquishing the baton.
374 receiveBaton(trace::Call *call) {
375 assert (call->thread_id == leg);
385 * Called by the fore runner when the race is over.
389 if (0) std::cerr << "notify finish to leg " << leg << "\n";
401 RelayRunner::runnerThread(RelayRunner *_this) {
407 RelayRace::RelayRace() {
408 runners.push_back(new RelayRunner(this, 0));
412 RelayRace::~RelayRace() {
413 assert(runners.size() >= 1);
414 std::vector<RelayRunner*>::const_iterator it;
415 for (it = runners.begin(); it != runners.end(); ++it) {
416 RelayRunner* runner = *it;
425 * Get (or instantiate) a runner for the specified leg.
428 RelayRace::getRunner(unsigned leg) {
431 if (leg >= runners.size()) {
432 runners.resize(leg + 1);
435 runner = runners[leg];
438 runner = new RelayRunner(this, leg);
439 runners[leg] = runner;
449 RelayRace::run(void) {
451 call = parser.parse_call();
457 /* If the user wants to loop we need to get a bookmark target. We
458 * usually get this after replaying a call that ends a frame, but
459 * for a trace that has only one frame we need to get it at the
462 parser.getBookmark(lastFrameStart);
465 RelayRunner *foreRunner = getForeRunner();
466 if (call->thread_id == 0) {
467 /* We are the forerunner thread, so no need to pass baton */
468 foreRunner->baton = call;
473 /* Start the forerunner thread */
474 foreRunner->runRace();
479 * Pass the baton (i.e., the call) to the appropriate thread.
482 RelayRace::passBaton(trace::Call *call) {
483 if (0) std::cerr << "switching to thread " << call->thread_id << "\n";
484 RelayRunner *runner = getRunner(call->thread_id);
485 runner->receiveBaton(call);
490 * Called when a runner other than the forerunner reaches the finish line.
492 * Only the fore runner can finish the race, so inform him that the race is
496 RelayRace::finishLine(void) {
497 RelayRunner *foreRunner = getForeRunner();
498 foreRunner->finishRace();
503 * Called by the fore runner after finish line to stop all other runners.
506 RelayRace::stopRunners(void) {
507 std::vector<RelayRunner*>::const_iterator it;
508 for (it = runners.begin() + 1; it != runners.end(); ++it) {
509 RelayRunner* runner = *it;
511 runner->finishRace();
519 addCallbacks(retracer);
521 long long startTime = 0;
524 startTime = os::getTime();
528 while ((call = parser.parse_call())) {
538 long long endTime = os::getTime();
539 float timeInterval = (endTime - startTime) * (1.0 / os::timeFrequency);
541 if ((retrace::verbosity >= -1) || (retrace::profiling)) {
543 "Rendered " << frameNo << " frames"
544 " in " << timeInterval << " secs,"
545 " average of " << (frameNo/timeInterval) << " fps\n";
556 } /* namespace retrace */
560 usage(const char *argv0) {
562 "Usage: " << argv0 << " [OPTION] TRACE [...]\n"
565 " -b, --benchmark benchmark mode (no error checking or warning messages)\n"
566 " --pcpu cpu profiling (cpu times per call)\n"
567 " --pgpu gpu profiling (gpu times per draw call)\n"
568 " --ppd pixels drawn profiling (pixels drawn per draw call)\n"
569 " --pmem memory usage profiling (vsize rss per call)\n"
570 " -c, --compare=PREFIX compare against snapshots with given PREFIX\n"
571 " -C, --calls=CALLSET calls to compare (default is every frame)\n"
572 " --call-nos[=BOOL] use call numbers in snapshot filenames\n"
573 " --core use core profile\n"
574 " --db use a double buffer visual (default)\n"
575 " --driver=DRIVER force driver type (`hw`, `sw`, `ref`, `null`, or driver module name)\n"
576 " --sb use a single buffer visual\n"
577 " -s, --snapshot-prefix=PREFIX take snapshots; `-` for PNM stdout output\n"
578 " --snapshot-format=FMT use (PNM or RGB; default is PNM) when writing to stdout output\n"
579 " -S, --snapshot=CALLSET calls to snapshot (default is every frame)\n"
580 " -v, --verbose increase output verbosity\n"
581 " -D, --dump-state=CALL dump state at specific call no\n"
582 " -w, --wait waitOnFinish on final frame\n"
583 " --loop continuously loop, replaying final frame.\n"
584 " --singlethread use a single thread to replay command stream\n";
588 CALL_NOS_OPT = CHAR_MAX + 1,
603 shortOptions = "bc:C:D:hs:S:vw";
605 const static struct option
607 {"benchmark", no_argument, 0, 'b'},
608 {"call-nos", optional_argument, 0, CALL_NOS_OPT },
609 {"calls", required_argument, 0, 'C'},
610 {"compare", required_argument, 0, 'c'},
611 {"core", no_argument, 0, CORE_OPT},
612 {"db", no_argument, 0, DB_OPT},
613 {"driver", required_argument, 0, DRIVER_OPT},
614 {"dump-state", required_argument, 0, 'D'},
615 {"help", no_argument, 0, 'h'},
616 {"pcpu", no_argument, 0, PCPU_OPT},
617 {"pgpu", no_argument, 0, PGPU_OPT},
618 {"ppd", no_argument, 0, PPD_OPT},
619 {"pmem", no_argument, 0, PMEM_OPT},
620 {"sb", no_argument, 0, SB_OPT},
621 {"snapshot-prefix", required_argument, 0, 's'},
622 {"snapshot-format", required_argument, 0, SNAPSHOT_FORMAT_OPT},
623 {"snapshot", required_argument, 0, 'S'},
624 {"verbose", no_argument, 0, 'v'},
625 {"wait", no_argument, 0, 'w'},
626 {"loop", no_argument, 0, LOOP_OPT},
627 {"singlethread", no_argument, 0, SINGLETHREAD_OPT},
632 static void exceptionCallback(void)
634 std::cerr << retrace::callNo << ": error: caught an unhandled exception\n";
639 int main(int argc, char **argv)
641 using namespace retrace;
644 assert(compareFrequency.empty());
645 assert(snapshotFrequency.empty());
648 while ((opt = getopt_long_only(argc, argv, shortOptions, longOptions, NULL)) != -1) {
654 retrace::debug = false;
655 retrace::verbosity = -1;
658 useCallNos = trace::boolOption(optarg);
661 comparePrefix = optarg;
662 if (compareFrequency.empty()) {
663 compareFrequency = trace::CallSet(trace::FREQUENCY_FRAME);
667 compareFrequency = trace::CallSet(optarg);
668 if (comparePrefix == NULL) {
673 dumpStateCallNo = atoi(optarg);
675 retrace::verbosity = -2;
678 retrace::coreProfile = true;
681 retrace::doubleBuffer = true;
684 if (strcasecmp(optarg, "hw") == 0) {
685 driver = DRIVER_HARDWARE;
686 } else if (strcasecmp(optarg, "sw") == 0) {
687 driver = DRIVER_SOFTWARE;
688 } else if (strcasecmp(optarg, "ref") == 0) {
689 driver = DRIVER_REFERENCE;
690 } else if (strcasecmp(optarg, "null") == 0) {
691 driver = DRIVER_NULL;
693 driver = DRIVER_MODULE;
694 driverModule = optarg;
698 retrace::doubleBuffer = false;
700 case SINGLETHREAD_OPT:
701 retrace::singleThread = true;
704 snapshotPrefix = optarg;
705 if (snapshotFrequency.empty()) {
706 snapshotFrequency = trace::CallSet(trace::FREQUENCY_FRAME);
708 if (snapshotPrefix[0] == '-' && snapshotPrefix[1] == 0) {
709 os::setBinaryMode(stdout);
710 retrace::verbosity = -2;
713 case SNAPSHOT_FORMAT_OPT:
714 if (strcmp(optarg, "RGB") == 0)
715 snapshotFormat = RAW_RGB;
717 snapshotFormat = PNM_FMT;
720 snapshotFrequency = trace::CallSet(optarg);
721 if (snapshotPrefix == NULL) {
726 ++retrace::verbosity;
735 retrace::debug = false;
736 retrace::profiling = true;
737 retrace::verbosity = -1;
739 retrace::profilingGpuTimes = true;
742 retrace::debug = false;
743 retrace::profiling = true;
744 retrace::verbosity = -1;
746 retrace::profilingCpuTimes = true;
749 retrace::debug = false;
750 retrace::profiling = true;
751 retrace::verbosity = -1;
753 retrace::profilingPixelsDrawn = true;
756 retrace::debug = false;
757 retrace::profiling = true;
758 retrace::verbosity = -1;
760 retrace::profilingMemoryUsage = true;
763 std::cerr << "error: unknown option " << opt << "\n";
770 if (retrace::profiling) {
771 retrace::profiler.setup(retrace::profilingCpuTimes, retrace::profilingGpuTimes, retrace::profilingPixelsDrawn, retrace::profilingMemoryUsage);
774 os::setExceptionCallback(exceptionCallback);
776 for (i = optind; i < argc; ++i) {
777 if (!retrace::parser.open(argv[i])) {
783 retrace::parser.close();
786 os::resetExceptionCallback();
788 // XXX: X often hangs on XCloseDisplay
789 //retrace::cleanUp();