1 /**************************************************************************
3 * Copyright 2011 Jose Fonseca
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 **************************************************************************/
28 #include <limits.h> // for CHAR_MAX
32 #include "os_binary.hpp"
33 #include "os_time.hpp"
34 #include "os_thread.hpp"
36 #include "trace_callset.hpp"
37 #include "trace_dump.hpp"
38 #include "trace_option.hpp"
39 #include "retrace.hpp"
42 static bool waitOnFinish = false;
44 static const char *comparePrefix = NULL;
45 static const char *snapshotPrefix = NULL;
46 static trace::CallSet snapshotFrequency;
47 static trace::CallSet compareFrequency;
49 static unsigned dumpStateCallNo = ~0;
51 retrace::Retracer retracer;
58 trace::Profiler profiler;
63 bool dumpingState = false;
65 Driver driver = DRIVER_DEFAULT;
66 const char *driverModule = NULL;
68 bool doubleBuffer = true;
69 bool coreProfile = false;
71 bool profiling = false;
72 bool profilingGpuTimes = false;
73 bool profilingCpuTimes = false;
74 bool profilingPixelsDrawn = false;
75 bool useCallNos = true;
82 frameComplete(trace::Call &call) {
87 static Dumper defaultDumper;
89 Dumper *dumper = &defaultDumper;
93 * Take/compare snapshots.
96 takeSnapshot(unsigned call_no) {
97 static unsigned snapshot_no = 0;
99 assert(snapshotPrefix || comparePrefix);
101 image::Image *ref = NULL;
104 os::String filename = os::String::format("%s%010u.png", comparePrefix, call_no);
105 ref = image::readPNG(filename);
109 if (retrace::verbosity >= 0) {
110 std::cout << "Read " << filename << "\n";
114 image::Image *src = dumper->getSnapshot();
116 std::cout << "Failed to get snapshot\n";
120 if (snapshotPrefix) {
121 if (snapshotPrefix[0] == '-' && snapshotPrefix[1] == 0) {
123 snprintf(comment, sizeof comment, "%u",
124 useCallNos ? call_no : snapshot_no);
125 src->writePNM(std::cout, comment);
127 os::String filename = os::String::format("%s%010u.png",
129 useCallNos ? call_no : snapshot_no);
130 if (src->writePNG(filename) && retrace::verbosity >= 0) {
131 std::cout << "Wrote " << filename << "\n";
137 std::cout << "Snapshot " << call_no << " average precision of " << src->compare(*ref) << " bits\n";
152 * Take snapshots before/after retracing (as appropriate) and dispatch it to
153 * the respective handler.
156 retraceCall(trace::Call *call) {
157 bool swapRenderTarget = call->flags &
158 trace::CALL_FLAG_SWAP_RENDERTARGET;
159 bool doSnapshot = snapshotFrequency.contains(*call) ||
160 compareFrequency.contains(*call);
162 // For calls which cause rendertargets to be swaped, we take the
163 // snapshot _before_ swapping the rendertargets.
164 if (doSnapshot && swapRenderTarget) {
165 if (call->flags & trace::CALL_FLAG_END_FRAME) {
166 // For swapbuffers/presents we still use this
167 // call number, spite not have been executed yet.
168 takeSnapshot(call->no);
170 // Whereas for ordinate fbo/rendertarget changes we
171 // use the previous call's number.
172 takeSnapshot(call->no - 1);
177 retracer.retrace(*call);
179 if (doSnapshot && !swapRenderTarget)
180 takeSnapshot(call->no);
182 if (call->no >= dumpStateCallNo &&
183 dumper->dumpState(std::cout)) {
193 * Implement multi-threading by mimicking a relay race.
199 * Runners indexed by the leg they run (i.e, the thread_ids from the
202 std::vector<RelayRunner*> runners;
210 getRunner(unsigned leg);
221 passBaton(trace::Call *call);
232 * Each runner is a thread.
234 * The fore runner doesn't have its own thread, but instead uses the thread
235 * where the race started.
240 friend class RelayRace;
247 os::condition_variable wake_cond;
250 * There are protected by the mutex.
258 runnerThread(RelayRunner *_this);
261 RelayRunner(RelayRace *race, unsigned _leg) :
267 /* The fore runner does not need a new thread */
269 thread = os::thread(runnerThread, this);
278 os::unique_lock<os::mutex> lock(mutex);
281 while (!finished && !baton) {
282 wake_cond.wait(lock);
290 trace::Call *call = baton;
296 if (0) std::cerr << "leg " << leg << " actually finishing\n";
304 * Interpret successive calls.
307 runLeg(trace::Call *call) {
308 /* Consume successive calls for this thread. */
311 assert(call->thread_id == leg);
314 call = parser.parse_call();
315 } while (call && call->thread_id == leg);
319 assert(call->thread_id != leg);
321 race->passBaton(call);
323 /* Reached the finish line */
324 if (0) std::cerr << "finished on leg " << leg << "\n";
326 /* Notify the fore runner */
329 /* We are the fore runner */
336 * Called by other threads when relinquishing the baton.
339 receiveBaton(trace::Call *call) {
340 assert (call->thread_id == leg);
350 * Called by the fore runner when the race is over.
354 if (0) std::cerr << "notify finish to leg " << leg << "\n";
366 RelayRunner::runnerThread(RelayRunner *_this) {
372 RelayRace::RelayRace() {
373 runners.push_back(new RelayRunner(this, 0));
377 RelayRace::~RelayRace() {
378 assert(runners.size() >= 1);
379 std::vector<RelayRunner*>::const_iterator it;
380 for (it = runners.begin(); it != runners.end(); ++it) {
381 RelayRunner* runner = *it;
390 * Get (or instantiate) a runner for the specified leg.
393 RelayRace::getRunner(unsigned leg) {
396 if (leg >= runners.size()) {
397 runners.resize(leg + 1);
400 runner = runners[leg];
403 runner = new RelayRunner(this, leg);
404 runners[leg] = runner;
414 RelayRace::run(void) {
416 call = parser.parse_call();
422 RelayRunner *foreRunner = getForeRunner();
423 if (call->thread_id == 0) {
424 /* We are the forerunner thread, so no need to pass baton */
425 foreRunner->baton = call;
430 /* Start the forerunner thread */
431 foreRunner->runRace();
436 * Pass the baton (i.e., the call) to the appropriate thread.
439 RelayRace::passBaton(trace::Call *call) {
440 if (0) std::cerr << "switching to thread " << call->thread_id << "\n";
441 RelayRunner *runner = getRunner(call->thread_id);
442 runner->receiveBaton(call);
447 * Called when a runner other than the forerunner reaches the finish line.
449 * Only the fore runner can finish the race, so inform him that the race is
453 RelayRace::finishLine(void) {
454 RelayRunner *foreRunner = getForeRunner();
455 foreRunner->finishRace();
460 * Called by the fore runner after finish line to stop all other runners.
463 RelayRace::stopRunners(void) {
464 std::vector<RelayRunner*>::const_iterator it;
465 for (it = runners.begin() + 1; it != runners.end(); ++it) {
466 RelayRunner* runner = *it;
468 runner->finishRace();
476 addCallbacks(retracer);
478 long long startTime = 0;
481 startTime = os::getTime();
486 long long endTime = os::getTime();
487 float timeInterval = (endTime - startTime) * (1.0 / os::timeFrequency);
489 if ((retrace::verbosity >= -1) || (retrace::profiling)) {
491 "Rendered " << frameNo << " frames"
492 " in " << timeInterval << " secs,"
493 " average of " << (frameNo/timeInterval) << " fps\n";
504 } /* namespace retrace */
508 usage(const char *argv0) {
510 "Usage: " << argv0 << " [OPTION] TRACE [...]\n"
513 " -b, --benchmark benchmark mode (no error checking or warning messages)\n"
514 " --pcpu cpu profiling (cpu times per call)\n"
515 " --pgpu gpu profiling (gpu times per draw call)\n"
516 " --ppd pixels drawn profiling (pixels drawn per draw call)\n"
517 " -c, --compare=PREFIX compare against snapshots with given PREFIX\n"
518 " -C, --calls=CALLSET calls to compare (default is every frame)\n"
519 " --call-nos[=BOOL] use call numbers in snapshot filenames\n"
520 " --core use core profile\n"
521 " --db use a double buffer visual (default)\n"
522 " --driver=DRIVER force driver type (`hw`, `sw`, `ref`, `null`, or driver module name)\n"
523 " --sb use a single buffer visual\n"
524 " -s, --snapshot-prefix=PREFIX take snapshots; `-` for PNM stdout output\n"
525 " -S, --snapshot=CALLSET calls to snapshot (default is every frame)\n"
526 " -v, --verbose increase output verbosity\n"
527 " -D, --dump-state=CALL dump state at specific call no\n"
528 " -w, --wait waitOnFinish on final frame\n";
532 CALL_NOS_OPT = CHAR_MAX + 1,
543 shortOptions = "bc:C:D:hs:S:vw";
545 const static struct option
547 {"benchmark", no_argument, 0, 'b'},
548 {"call-nos", optional_argument, 0, CALL_NOS_OPT },
549 {"calls", required_argument, 0, 'C'},
550 {"compare", required_argument, 0, 'c'},
551 {"core", no_argument, 0, CORE_OPT},
552 {"db", no_argument, 0, DB_OPT},
553 {"driver", required_argument, 0, DRIVER_OPT},
554 {"dump-state", required_argument, 0, 'D'},
555 {"help", no_argument, 0, 'h'},
556 {"pcpu", no_argument, 0, PCPU_OPT},
557 {"pgpu", no_argument, 0, PGPU_OPT},
558 {"ppd", no_argument, 0, PPD_OPT},
559 {"sb", no_argument, 0, SB_OPT},
560 {"snapshot-prefix", required_argument, 0, 's'},
561 {"snapshot", required_argument, 0, 'S'},
562 {"verbose", no_argument, 0, 'v'},
563 {"wait", no_argument, 0, 'w'},
568 static void exceptionCallback(void)
570 std::cerr << retrace::callNo << ": error: caught an unhandled exception\n";
575 int main(int argc, char **argv)
577 using namespace retrace;
580 assert(compareFrequency.empty());
581 assert(snapshotFrequency.empty());
584 while ((opt = getopt_long_only(argc, argv, shortOptions, longOptions, NULL)) != -1) {
590 retrace::debug = false;
591 retrace::verbosity = -1;
594 useCallNos = trace::boolOption(optarg);
597 comparePrefix = optarg;
598 if (compareFrequency.empty()) {
599 compareFrequency = trace::CallSet(trace::FREQUENCY_FRAME);
603 compareFrequency = trace::CallSet(optarg);
604 if (comparePrefix == NULL) {
609 dumpStateCallNo = atoi(optarg);
611 retrace::verbosity = -2;
614 retrace::coreProfile = true;
617 retrace::doubleBuffer = true;
620 if (strcasecmp(optarg, "hw") == 0) {
621 driver = DRIVER_HARDWARE;
622 } else if (strcasecmp(optarg, "sw") == 0) {
623 driver = DRIVER_SOFTWARE;
624 } else if (strcasecmp(optarg, "ref") == 0) {
625 driver = DRIVER_REFERENCE;
626 } else if (strcasecmp(optarg, "null") == 0) {
627 driver = DRIVER_NULL;
629 driver = DRIVER_MODULE;
630 driverModule = optarg;
634 retrace::doubleBuffer = false;
637 snapshotPrefix = optarg;
638 if (snapshotFrequency.empty()) {
639 snapshotFrequency = trace::CallSet(trace::FREQUENCY_FRAME);
641 if (snapshotPrefix[0] == '-' && snapshotPrefix[1] == 0) {
642 os::setBinaryMode(stdout);
643 retrace::verbosity = -2;
647 snapshotFrequency = trace::CallSet(optarg);
648 if (snapshotPrefix == NULL) {
653 ++retrace::verbosity;
659 retrace::debug = false;
660 retrace::profiling = true;
661 retrace::verbosity = -1;
663 retrace::profilingGpuTimes = true;
666 retrace::debug = false;
667 retrace::profiling = true;
668 retrace::verbosity = -1;
670 retrace::profilingCpuTimes = true;
673 retrace::debug = false;
674 retrace::profiling = true;
675 retrace::verbosity = -1;
677 retrace::profilingPixelsDrawn = true;
680 std::cerr << "error: unknown option " << opt << "\n";
687 if (retrace::profiling) {
688 retrace::profiler.setup(retrace::profilingCpuTimes, retrace::profilingGpuTimes, retrace::profilingPixelsDrawn);
691 os::setExceptionCallback(exceptionCallback);
693 for (i = optind; i < argc; ++i) {
694 if (!retrace::parser.open(argv[i])) {
700 retrace::parser.close();
703 os::resetExceptionCallback();
705 // XXX: X often hangs on XCloseDisplay
706 //retrace::cleanUp();