]> git.cworth.org Git - apitrace/blob - gui/retracer.cpp
Add gui support for trace profiling.
[apitrace] / gui / retracer.cpp
1 #include "retracer.h"
2
3 #include "apitracecall.h"
4 #include "thumbnail.h"
5
6 #include "image.hpp"
7
8 #include "trace_profiler.hpp"
9
10 #include <QDebug>
11 #include <QVariant>
12 #include <QList>
13 #include <QImage>
14
15 #include <qjson/parser.h>
16
17 /**
18  * Wrapper around a QProcess which enforces IO to block .
19  *
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.
25  *
26  * This class wraps around QProcess, providing QIODevice interface, while
27  * ensuring that all reads block.
28  *
29  * This class also works around a bug in QProcess::atEnd() implementation.
30  *
31  * See also:
32  * - http://qt-project.org/wiki/Simple_Crypt_IO_Device
33  * - http://qt-project.org/wiki/Custom_IO_Device
34  */
35 class BlockingIODevice : public QIODevice
36 {
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
39      * system. */
40 public:
41     BlockingIODevice(QProcess * io);
42     bool isSequential() const;
43     bool atEnd() const;
44     bool waitForReadyRead(int msecs = -1);
45
46 protected:
47     qint64 readData(char * data, qint64 maxSize);
48     qint64 writeData(const char * data, qint64 maxSize);
49
50 private:
51     QProcess *m_device;
52 };
53
54 BlockingIODevice::BlockingIODevice(QProcess * io) :
55     m_device(io)
56 {
57     /*
58      * We pass QIODevice::Unbuffered to prevent the base QIODevice class to do
59      * its own buffering on top of the overridden readData() method.
60      *
61      * The only buffering used will be to satisfy QIODevice::peek() and
62      * QIODevice::ungetChar().
63      */
64     setOpenMode(ReadOnly | Unbuffered);
65 }
66
67 bool BlockingIODevice::isSequential() const
68 {
69     return true;
70 }
71
72 bool BlockingIODevice::atEnd() const
73 {
74     /*
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.
77      */
78     if (m_device->atEnd()) {
79         if (m_device->state() == QProcess::Running) {
80             if (!m_device->waitForReadyRead(-1)) {
81                 return true;
82             }
83         }
84     }
85     return false;
86 }
87
88 bool BlockingIODevice::waitForReadyRead(int msecs)
89 {
90     Q_UNUSED(msecs);
91     return true;
92 }
93
94 qint64 BlockingIODevice::readData(char * data, qint64 maxSize)
95 {
96     qint64 bytesToRead = maxSize;
97     qint64 readSoFar = 0;
98     do {
99         qint64 chunkSize = m_device->read(data + readSoFar, bytesToRead);
100         if (chunkSize < 0) {
101             if (readSoFar) {
102                 return readSoFar;
103             } else {
104                 return chunkSize;
105             }
106         }
107         Q_ASSERT(chunkSize <= bytesToRead);
108         bytesToRead -= chunkSize;
109         readSoFar += chunkSize;
110         if (bytesToRead) {
111             if (!m_device->waitForReadyRead(-1)) {
112                 qDebug() << "waitForReadyRead failed\n";
113                 break;
114             }
115         }
116     } while(bytesToRead);
117
118     return readSoFar;
119 }
120
121 qint64 BlockingIODevice::writeData(const char * data, qint64 maxSize)
122 {
123     Q_ASSERT(false);
124     return -1;
125 }
126
127 Q_DECLARE_METATYPE(QList<ApiTraceError>);
128
129 Retracer::Retracer(QObject *parent)
130     : QThread(parent),
131       m_benchmarking(false),
132       m_doubleBuffered(true),
133       m_captureState(false),
134       m_captureCall(0),
135       m_profileGpu(false),
136       m_profileCpu(false),
137       m_profilePixels(false)
138 {
139     qRegisterMetaType<QList<ApiTraceError> >();
140
141 #ifdef Q_OS_WIN
142     QString format = QLatin1String("%1;");
143 #else
144     QString format = QLatin1String("%1:");
145 #endif
146     QString buildPath = format.arg(APITRACE_BINARY_DIR);
147     m_processEnvironment = QProcessEnvironment::systemEnvironment();
148     m_processEnvironment.insert("PATH", buildPath +
149                                 m_processEnvironment.value("PATH"));
150
151     qputenv("PATH",
152             m_processEnvironment.value("PATH").toLatin1());
153 }
154
155 QString Retracer::fileName() const
156 {
157     return m_fileName;
158 }
159
160 void Retracer::setFileName(const QString &name)
161 {
162     m_fileName = name;
163 }
164
165 void Retracer::setAPI(trace::API api)
166 {
167     m_api = api;
168 }
169
170 bool Retracer::isBenchmarking() const
171 {
172     return m_benchmarking;
173 }
174
175 void Retracer::setBenchmarking(bool bench)
176 {
177     m_benchmarking = bench;
178 }
179
180 bool Retracer::isDoubleBuffered() const
181 {
182     return m_doubleBuffered;
183 }
184
185 void Retracer::setDoubleBuffered(bool db)
186 {
187     m_doubleBuffered = db;
188 }
189
190 bool Retracer::isProfilingGpu() const
191 {
192     return m_profileGpu;
193 }
194
195 bool Retracer::isProfilingCpu() const
196 {
197     return m_profileCpu;
198 }
199
200 bool Retracer::isProfilingPixels() const
201 {
202     return m_profilePixels;
203 }
204
205 bool Retracer::isProfiling() const
206 {
207     return m_profileGpu || m_profileCpu || m_profilePixels;
208 }
209
210 void Retracer::setProfiling(bool gpu, bool cpu, bool pixels)
211 {
212     m_profileGpu = gpu;
213     m_profileCpu = cpu;
214     m_profilePixels = pixels;
215 }
216
217 void Retracer::setCaptureAtCallNumber(qlonglong num)
218 {
219     m_captureCall = num;
220 }
221
222 qlonglong Retracer::captureAtCallNumber() const
223 {
224     return m_captureCall;
225 }
226
227 bool Retracer::captureState() const
228 {
229     return m_captureState;
230 }
231
232 void Retracer::setCaptureState(bool enable)
233 {
234     m_captureState = enable;
235 }
236
237 bool Retracer::captureThumbnails() const
238 {
239     return m_captureThumbnails;
240 }
241
242 void Retracer::setCaptureThumbnails(bool enable)
243 {
244     m_captureThumbnails = enable;
245 }
246
247 /**
248  * Starting point for the retracing thread.
249  *
250  * Overrides QThread::run().
251  */
252 void Retracer::run()
253 {
254     QString msg = QLatin1String("Replay finished!");
255
256     /*
257      * Construct command line
258      */
259
260     QString prog;
261     QStringList arguments;
262
263     switch (m_api) {
264     case trace::API_GL:
265         prog = QLatin1String("glretrace");
266         break;
267     case trace::API_EGL:
268         prog = QLatin1String("eglretrace");
269         break;
270     case trace::API_DX:
271     case trace::API_D3D7:
272     case trace::API_D3D8:
273     case trace::API_D3D9:
274     case trace::API_D3D10:
275     case trace::API_D3D10_1:
276     case trace::API_D3D11:
277 #ifdef Q_OS_WIN
278         prog = QLatin1String("d3dretrace");
279 #else
280         prog = QLatin1String("wine");
281         arguments << QLatin1String("d3dretrace.exe");
282 #endif
283         break;
284     default:
285         emit finished(QLatin1String("Unsupported API"));
286         return;
287     }
288
289     if (m_captureState) {
290         arguments << QLatin1String("-D");
291         arguments << QString::number(m_captureCall);
292     } else if (m_captureThumbnails) {
293         arguments << QLatin1String("-s"); // emit snapshots
294         arguments << QLatin1String("-"); // emit to stdout
295     } else if (isProfiling()) {
296         if (m_profileGpu) {
297             arguments << QLatin1String("-pgpu");
298         }
299
300         if (m_profileCpu) {
301             arguments << QLatin1String("-pcpu");
302         }
303
304         if (m_profilePixels) {
305             arguments << QLatin1String("-ppd");
306         }
307     } else {
308         if (m_doubleBuffered) {
309             arguments << QLatin1String("-db");
310         } else {
311             arguments << QLatin1String("-sb");
312         }
313
314         if (m_benchmarking) {
315             arguments << QLatin1String("-b");
316         }
317     }
318
319     arguments << m_fileName;
320
321     /*
322      * Start the process.
323      */
324
325     QProcess process;
326
327     process.start(prog, arguments, QIODevice::ReadOnly);
328     if (!process.waitForStarted(-1)) {
329         emit finished(QLatin1String("Could not start process"));
330         return;
331     }
332
333     /*
334      * Process standard output
335      */
336
337     QList<QImage> thumbnails;
338     QVariantMap parsedJson;
339     trace::Profile* profile = NULL;
340
341     process.setReadChannel(QProcess::StandardOutput);
342     if (process.waitForReadyRead(-1)) {
343         BlockingIODevice io(&process);
344
345         if (m_captureState) {
346             /*
347              * Parse JSON from the output.
348              *
349              * XXX: QJSON's scanner is inneficient as it abuses single
350              * character QIODevice::peek (not cheap), instead of maintaining a
351              * lookahead character on its own.
352              */
353
354             bool ok = false;
355             QJson::Parser jsonParser;
356 #if 0
357             parsedJson = jsonParser.parse(&io, &ok).toMap();
358 #else
359             /*
360              * XXX: QJSON expects blocking IO, and it looks like
361              * BlockingIODevice does not work reliably in all cases.
362              */
363             process.waitForFinished(-1);
364             parsedJson = jsonParser.parse(&process, &ok).toMap();
365 #endif
366             if (!ok) {
367                 msg = QLatin1String("failed to parse JSON");
368             }
369         } else if (m_captureThumbnails) {
370             /*
371              * Parse concatenated PNM images from output.
372              */
373
374             while (!io.atEnd()) {
375                 unsigned channels = 0;
376                 unsigned width = 0;
377                 unsigned height = 0;
378
379                 char header[512];
380                 qint64 headerSize = 0;
381                 int headerLines = 3; // assume no optional comment line
382
383                 for (int headerLine = 0; headerLine < headerLines; ++headerLine) {
384                     qint64 headerRead = io.readLine(&header[headerSize], sizeof(header) - headerSize);
385
386                     // if header actually contains optional comment line, ...
387                     if (headerLine == 1 && header[headerSize] == '#') {
388                         ++headerLines;
389                     }
390
391                     headerSize += headerRead;
392                 }
393
394                 const char *headerEnd = image::readPNMHeader(header, headerSize, &channels, &width, &height);
395
396                 // if invalid PNM header was encountered, ...
397                 if (header == headerEnd) {
398                     qDebug() << "error: invalid snapshot stream encountered";
399                     break;
400                 }
401
402                 // qDebug() << "channels: " << channels << ", width: " << width << ", height: " << height";
403
404                 QImage snapshot = QImage(width, height, channels == 1 ? QImage::Format_Mono : QImage::Format_RGB888);
405
406                 int rowBytes = channels * width;
407                 for (int y = 0; y < height; ++y) {
408                     unsigned char *scanLine = snapshot.scanLine(y);
409                     qint64 readBytes = io.read((char *) scanLine, rowBytes);
410                     Q_ASSERT(readBytes == rowBytes);
411                 }
412
413                 QImage thumb = thumbnail(snapshot);
414                 thumbnails.append(thumb);
415             }
416
417             Q_ASSERT(process.state() != QProcess::Running);
418         } else if (isProfiling()) {
419             profile = new trace::Profile();
420             process.waitForFinished(-1);
421
422             while (!io.atEnd()) {
423                 char line[256];
424                 qint64 lineLength;
425
426                 lineLength = io.readLine(line, 256);
427
428                 if (lineLength == -1)
429                     break;
430
431                 trace::Profiler::parseLine(line, profile);
432             }
433         } else {
434             QByteArray output;
435             output = process.readAllStandardOutput();
436             if (output.length() < 80) {
437                 msg = QString::fromUtf8(output);
438             }
439         }
440     }
441
442     /*
443      * Wait for process termination
444      */
445
446     process.waitForFinished(-1);
447
448     if (process.exitStatus() != QProcess::NormalExit) {
449         msg = QLatin1String("Process crashed");
450     } else if (process.exitCode() != 0) {
451         msg = QLatin1String("Process exited with non zero exit code");
452     }
453
454     /*
455      * Parse errors.
456      */
457
458     QList<ApiTraceError> errors;
459     process.setReadChannel(QProcess::StandardError);
460     QRegExp regexp("(^\\d+): +(\\b\\w+\\b): ([^\\r\\n]+)[\\r\\n]*$");
461     while (!process.atEnd()) {
462         QString line = process.readLine();
463         if (regexp.indexIn(line) != -1) {
464             ApiTraceError error;
465             error.callIndex = regexp.cap(1).toInt();
466             error.type = regexp.cap(2);
467             error.message = regexp.cap(3);
468             errors.append(error);
469         } else if (!errors.isEmpty()) {
470             // Probably a multiligne message
471             ApiTraceError &previous = errors.last();
472             if (line.endsWith("\n")) {
473                 line.chop(1);
474             }
475             previous.message.append('\n');
476             previous.message.append(line);
477         }
478     }
479
480     /*
481      * Emit signals
482      */
483
484     if (m_captureState) {
485         ApiTraceState *state = new ApiTraceState(parsedJson);
486         emit foundState(state);
487         msg = QLatin1String("State fetched.");
488     }
489
490     if (m_captureThumbnails && !thumbnails.isEmpty()) {
491         emit foundThumbnails(thumbnails);
492     }
493
494     if (isProfiling() && profile) {
495         emit foundProfile(profile);
496     }
497
498     if (!errors.isEmpty()) {
499         emit retraceErrors(errors);
500     }
501
502     emit finished(msg);
503 }
504
505 #include "retracer.moc"