3 #include "apitracecall.h"
6 #include "image/image.hpp"
8 #include "trace_profiler.hpp"
15 #include <qjson/parser.h>
18 * Wrapper around a QProcess which enforces IO to block .
20 * Several QIODevice users (notably QJSON) expect blocking semantics, e.g.,
21 * they expect that QIODevice::read() will blocked until the requested ammount
22 * of bytes is read or end of file is reached. But by default QProcess, does
23 * not block. And passing QIODevice::Unbuffered mitigates but does not fully
24 * address the problem either.
26 * This class wraps around QProcess, providing QIODevice interface, while
27 * ensuring that all reads block.
29 * This class also works around a bug in QProcess::atEnd() implementation.
32 * - http://qt-project.org/wiki/Simple_Crypt_IO_Device
33 * - http://qt-project.org/wiki/Custom_IO_Device
35 class BlockingIODevice : public QIODevice
37 /* We don't use the Q_OBJECT in this class given we don't declare any
38 * signals and slots or use any other services provided by Qt's meta-object
41 BlockingIODevice(QProcess * io);
42 bool isSequential() const;
44 bool waitForReadyRead(int msecs = -1);
47 qint64 readData(char * data, qint64 maxSize);
48 qint64 writeData(const char * data, qint64 maxSize);
54 BlockingIODevice::BlockingIODevice(QProcess * io) :
58 * We pass QIODevice::Unbuffered to prevent the base QIODevice class to do
59 * its own buffering on top of the overridden readData() method.
61 * The only buffering used will be to satisfy QIODevice::peek() and
62 * QIODevice::ungetChar().
64 setOpenMode(ReadOnly | Unbuffered);
67 bool BlockingIODevice::isSequential() const
72 bool BlockingIODevice::atEnd() const
75 * XXX: QProcess::atEnd() documentation is wrong -- it will return true
76 * even when the process is running --, so we try to workaround that here.
78 if (m_device->atEnd()) {
79 if (m_device->state() == QProcess::Running) {
80 if (!m_device->waitForReadyRead(-1)) {
88 bool BlockingIODevice::waitForReadyRead(int msecs)
94 qint64 BlockingIODevice::readData(char * data, qint64 maxSize)
96 qint64 bytesToRead = maxSize;
99 qint64 chunkSize = m_device->read(data + readSoFar, bytesToRead);
107 Q_ASSERT(chunkSize <= bytesToRead);
108 bytesToRead -= chunkSize;
109 readSoFar += chunkSize;
111 if (!m_device->waitForReadyRead(-1)) {
112 qDebug() << "waitForReadyRead failed\n";
116 } while(bytesToRead);
121 qint64 BlockingIODevice::writeData(const char * data, qint64 maxSize)
127 Q_DECLARE_METATYPE(QList<ApiTraceError>);
129 Retracer::Retracer(QObject *parent)
131 m_benchmarking(false),
132 m_doubleBuffered(true),
133 m_captureState(false),
137 m_profilePixels(false)
139 qRegisterMetaType<QList<ApiTraceError> >();
142 QString Retracer::fileName() const
147 void Retracer::setFileName(const QString &name)
152 void Retracer::setAPI(trace::API api)
157 bool Retracer::isBenchmarking() const
159 return m_benchmarking;
162 void Retracer::setBenchmarking(bool bench)
164 m_benchmarking = bench;
167 bool Retracer::isDoubleBuffered() const
169 return m_doubleBuffered;
172 void Retracer::setDoubleBuffered(bool db)
174 m_doubleBuffered = db;
177 bool Retracer::isProfilingGpu() const
182 bool Retracer::isProfilingCpu() const
187 bool Retracer::isProfilingPixels() const
189 return m_profilePixels;
192 bool Retracer::isProfiling() const
194 return m_profileGpu || m_profileCpu || m_profilePixels;
197 void Retracer::setProfiling(bool gpu, bool cpu, bool pixels)
201 m_profilePixels = pixels;
204 void Retracer::setCaptureAtCallNumber(qlonglong num)
209 qlonglong Retracer::captureAtCallNumber() const
211 return m_captureCall;
214 bool Retracer::captureState() const
216 return m_captureState;
219 void Retracer::setCaptureState(bool enable)
221 m_captureState = enable;
224 bool Retracer::captureThumbnails() const
226 return m_captureThumbnails;
229 void Retracer::setCaptureThumbnails(bool enable)
231 m_captureThumbnails = enable;
235 * Starting point for the retracing thread.
237 * Overrides QThread::run().
241 QString msg = QLatin1String("Replay finished!");
244 * Construct command line
248 QStringList arguments;
252 prog = QLatin1String("glretrace");
255 prog = QLatin1String("eglretrace");
258 case trace::API_D3D7:
259 case trace::API_D3D8:
260 case trace::API_D3D9:
261 case trace::API_DXGI:
263 prog = QLatin1String("d3dretrace");
265 prog = QLatin1String("wine");
266 arguments << QLatin1String("d3dretrace.exe");
270 emit finished(QLatin1String("Unsupported API"));
274 if (m_captureState) {
275 arguments << QLatin1String("-D");
276 arguments << QString::number(m_captureCall);
277 } else if (m_captureThumbnails) {
278 arguments << QLatin1String("-s"); // emit snapshots
279 arguments << QLatin1String("-"); // emit to stdout
280 } else if (isProfiling()) {
282 arguments << QLatin1String("--pgpu");
286 arguments << QLatin1String("--pcpu");
289 if (m_profilePixels) {
290 arguments << QLatin1String("--ppd");
293 if (m_doubleBuffered) {
294 arguments << QLatin1String("--db");
296 arguments << QLatin1String("--sb");
299 if (m_benchmarking) {
300 arguments << QLatin1String("-b");
304 arguments << m_fileName;
312 process.start(prog, arguments, QIODevice::ReadOnly);
313 if (!process.waitForStarted(-1)) {
314 emit finished(QLatin1String("Could not start process"));
319 * Process standard output
322 QList<QImage> thumbnails;
323 QVariantMap parsedJson;
324 trace::Profile* profile = NULL;
326 process.setReadChannel(QProcess::StandardOutput);
327 if (process.waitForReadyRead(-1)) {
328 BlockingIODevice io(&process);
330 if (m_captureState) {
332 * Parse JSON from the output.
334 * XXX: QJSON's scanner is inneficient as it abuses single
335 * character QIODevice::peek (not cheap), instead of maintaining a
336 * lookahead character on its own.
340 QJson::Parser jsonParser;
342 // Allow Nan/Infinity
343 jsonParser.allowSpecialNumbers(true);
345 parsedJson = jsonParser.parse(&io, &ok).toMap();
348 * XXX: QJSON expects blocking IO, and it looks like
349 * BlockingIODevice does not work reliably in all cases.
351 process.waitForFinished(-1);
352 parsedJson = jsonParser.parse(&process, &ok).toMap();
355 msg = QLatin1String("failed to parse JSON");
357 } else if (m_captureThumbnails) {
359 * Parse concatenated PNM images from output.
362 while (!io.atEnd()) {
363 unsigned channels = 0;
368 qint64 headerSize = 0;
369 int headerLines = 3; // assume no optional comment line
371 for (int headerLine = 0; headerLine < headerLines; ++headerLine) {
372 qint64 headerRead = io.readLine(&header[headerSize], sizeof(header) - headerSize);
374 // if header actually contains optional comment line, ...
375 if (headerLine == 1 && header[headerSize] == '#') {
379 headerSize += headerRead;
382 const char *headerEnd = image::readPNMHeader(header, headerSize, &channels, &width, &height);
384 // if invalid PNM header was encountered, ...
385 if (header == headerEnd) {
386 qDebug() << "error: invalid snapshot stream encountered";
390 // qDebug() << "channels: " << channels << ", width: " << width << ", height: " << height";
392 QImage snapshot = QImage(width, height, channels == 1 ? QImage::Format_Mono : QImage::Format_RGB888);
394 int rowBytes = channels * width;
395 for (int y = 0; y < height; ++y) {
396 unsigned char *scanLine = snapshot.scanLine(y);
397 qint64 readBytes = io.read((char *) scanLine, rowBytes);
398 Q_ASSERT(readBytes == rowBytes);
402 QImage thumb = thumbnail(snapshot);
403 thumbnails.append(thumb);
406 Q_ASSERT(process.state() != QProcess::Running);
407 } else if (isProfiling()) {
408 profile = new trace::Profile();
410 while (!io.atEnd()) {
414 lineLength = io.readLine(line, 256);
416 if (lineLength == -1)
419 trace::Profiler::parseLine(line, profile);
423 output = process.readAllStandardOutput();
424 if (output.length() < 80) {
425 msg = QString::fromUtf8(output);
431 * Wait for process termination
434 process.waitForFinished(-1);
436 if (process.exitStatus() != QProcess::NormalExit) {
437 msg = QLatin1String("Process crashed");
438 } else if (process.exitCode() != 0) {
439 msg = QLatin1String("Process exited with non zero exit code");
446 QList<ApiTraceError> errors;
447 process.setReadChannel(QProcess::StandardError);
448 QRegExp regexp("(^\\d+): +(\\b\\w+\\b): ([^\\r\\n]+)[\\r\\n]*$");
449 while (!process.atEnd()) {
450 QString line = process.readLine();
451 if (regexp.indexIn(line) != -1) {
453 error.callIndex = regexp.cap(1).toInt();
454 error.type = regexp.cap(2);
455 error.message = regexp.cap(3);
456 errors.append(error);
457 } else if (!errors.isEmpty()) {
458 // Probably a multiligne message
459 ApiTraceError &previous = errors.last();
460 if (line.endsWith("\n")) {
463 previous.message.append('\n');
464 previous.message.append(line);
472 if (m_captureState) {
473 ApiTraceState *state = new ApiTraceState(parsedJson);
474 emit foundState(state);
475 msg = QLatin1String("State fetched.");
478 if (m_captureThumbnails && !thumbnails.isEmpty()) {
479 emit foundThumbnails(thumbnails);
482 if (isProfiling() && profile) {
483 emit foundProfile(profile);
486 if (!errors.isEmpty()) {
487 emit retraceErrors(errors);
493 #include "retracer.moc"