summaryrefslogtreecommitdiffstats
path: root/LibOVR/Src/CAPI/CAPI_LatencyStatistics.cpp
blob: c43418a2676ee3ba3d3e005ea0f6dbe2bf766d48 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
/************************************************************************************

Filename    :   CAPI_LatencyStatistics.cpp
Content     :   Record latency statistics during rendering
Created     :   Sept 23, 2014
Authors     :   Chris Taylor, Kevin Jenkins

Copyright   :   Copyright 2014 Oculus VR, LLC All Rights reserved.

Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); 
you may not use the Oculus VR Rift SDK except in compliance with the License, 
which is provided at the time of installation or download, or which 
otherwise accompanies this software in either electronic or hard copy form.

You may obtain a copy of the License at

http://www.oculusvr.com/licenses/LICENSE-3.2 

Unless required by applicable law or agreed to in writing, the Oculus VR SDK 
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

************************************************************************************/

#include "CAPI_LatencyStatistics.h"

#include "../Kernel/OVR_Log.h"
#include "../Kernel/OVR_Threads.h"
#include "../Util/Util_SystemInfo.h"

namespace OVR { namespace CAPI {

//-----------------------------------------------------------------------------
// ***** LatencyStatisticsObserver

LatencyStatisticsCSV::LatencyStatisticsCSV()
{
}

LatencyStatisticsCSV::~LatencyStatisticsCSV()
{
    Stop();
}

bool LatencyStatisticsCSV::Start(String fileName, String userData1)
{
    if (_File.IsValid())
    {
        if (fileName == FileName)
        {
            UserData1 = userData1;
            return true;
        }
        else
        {
            Stop();
        }
    }

    OVR::String basePath = OVR::GetBaseOVRPath(true);
    OVR::String path = basePath;
    path.AppendString("\\");
    path.AppendString(fileName);
    OS = OVR::Util::OSAsString();
    OSVersion = OVR::Util::OSVersionAsString();
#if defined (OVR_OS_WIN64) || defined (OVR_OS_WIN32)
    ProcessInfo = OVR::Util::GetProcessInfo();
    DisplayDriverVersion = OVR::Util::GetDisplayDriverVersion();
    CameraDriverVersion = OVR::Util::GetCameraDriverVersion();
    OVR::Array< OVR::String > gpus;
    OVR::Util::GetGraphicsCardList(gpus);
    StringBuffer sb;
    size_t gpuIdx;
    for (gpuIdx = 0; gpuIdx < gpus.GetSize(); gpuIdx++)
    {
        sb.AppendString(gpus[gpuIdx]);
        if (gpuIdx + 1 < gpus.GetSize())
            sb.AppendString("; ");
    }
    GPUVersion = sb;
#endif
    Guid = OVR::Util::GetGuidString();

    if (!_File.Open(path, OVR::File::Open_Write, OVR::File::Mode_Write))
    {
        _File.Create(path, OVR::File::Mode_Write);
        WriteHeaderV1();
    }
    else
    {
        _File.Seek(0, FileConstants::Seek_End);
    }

    if (_File.IsValid())
    {
        UserData1 = userData1;
        FileName = fileName;
        _Observer.SetHandler(LatencyStatisticsSlot::FromMember<LatencyStatisticsCSV, &LatencyStatisticsCSV::OnResults>(this));

        return true;
    }

    return false;
}
bool LatencyStatisticsCSV::Stop()
{
    if (_File.IsValid())
    {
        _File.Flush();
        _File.Close();
        _Observer.ReleaseAll();

        Guid.Clear();
        FileName.Clear();
        return true;
    }
    return false;
}
void LatencyStatisticsCSV::WriteHeaderV1()
{
    if (_File.IsValid())
    {
        // Write header if creating the file
        const char *str = "GUID,OS,OSVersion,Process,DisplayDriver,CameraDriver,GPU,Time,Interval,FPS,EndFrameExecutionTime,LatencyRender,LatencyTimewarp,LatencyPostPresent,LatencyVisionProc,LatencyVisionFrame,UserData1\n";
        _File.Write((const uint8_t *) str, (int)OVR_strlen(str));
    }
}

void LatencyStatisticsCSV::WriteResultsV1(LatencyStatisticsResults *results)
{
    if (_File.IsValid())
    {
        char str[512];
        OVR_sprintf(str, sizeof(str),
            "%s,%s,%s,%s,%s,%s,%s,%f,%f,%f,%f,%f,%f,%f,%f,%f,%s\n",
            Guid.ToCStr(),
            OS.ToCStr(),
            OSVersion.ToCStr(),
            ProcessInfo.ToCStr(),
            DisplayDriverVersion.ToCStr(),
            CameraDriverVersion.ToCStr(),
            GPUVersion.ToCStr(),
            ovr_GetTimeInSeconds(),
            results->IntervalSeconds,
            results->FPS,
            results->EndFrameExecutionTime,
            results->LatencyRender,
            results->LatencyTimewarp,
            results->LatencyPostPresent,
            results->LatencyVisionProc,
            results->LatencyVisionFrame,
            UserData1.ToCStr());
        str[sizeof(str)-1] = 0;
        _File.Write((const uint8_t *)str, (int)OVR_strlen(str));
    }
}
void LatencyStatisticsCSV::OnResults(LatencyStatisticsResults *results)
{
    WriteResultsV1(results);
}
//-------------------------------------------------------------------------------------
// ***** LatencyStatisticsCalculator
    
LagStatsCalculator::LagStatsCalculator()
{
    resetPerfStats();
}

void LagStatsCalculator::resetPerfStats(double resetTime)
{
    EndFrameStartTime = 0.;
    EndFrameEndTime = 0.;

    LastCameraFrameCounter = ~(uint32_t)0;

    EpochBegin = resetTime; // Set epoch start to now

    FrameCount = 0;
    //EndFrameSum = 0.;

    //VisionProcSum = 0.;
    //VisionLagSum = 0.;
    VisionFrames = 0;

    //for (int i = 0; i < 3; ++i)
    //{
    //    LatencyData[i] = 0.f;
    //    LatencySum[i] = 0.;
    //}

    latencyStatisticsData.EndFrameExecutionTime = 0;
    latencyStatisticsData.LatencyRender = 0;
    latencyStatisticsData.LatencyTimewarp = 0;
    latencyStatisticsData.LatencyPostPresent = 0;
    latencyStatisticsData.LatencyVisionProc = 0;
    latencyStatisticsData.LatencyVisionFrame = 0;
}

void LagStatsCalculator::GetLatestResults(LatencyStatisticsResults* results)
{
    *results = Results.GetState();
}
void LagStatsCalculator::AddResultsObserver(ObserverScope<LatencyStatisticsSlot> *calculateResultsObserver)
{
    Lock::Locker locker(&calculateResultsLock);
    calculateResultsObserver->GetPtr()->Observe(calculateResultsSubject);
}
void LagStatsCalculator::InstrumentEndFrameStart(double timestamp)
{
    EndFrameStartTime = timestamp;
}

void LagStatsCalculator::InstrumentLatencyTimings(FrameTimeManager& ftm)
{
    //latencies[0] = (float)RenderLatencySeconds;
    //latencies[1] = (float)TimewarpLatencySeconds;
    //latencies[2] = (float)FrameDeltas.GetMedianTimeDelta();

    // Note: This assumes that it is called right before InstrumentEndFrameEnd()
	float latencyRender, latencyTimewarp, latencyPostPresent;
    ftm.GetLatencyTimings(latencyRender, latencyTimewarp, latencyPostPresent);
	latencyStatisticsData.LatencyRender += latencyRender;
	latencyStatisticsData.LatencyTimewarp += latencyTimewarp;
	latencyStatisticsData.LatencyPostPresent += latencyPostPresent;
}

void LagStatsCalculator::InstrumentEndFrameEnd(double timestamp)
{
    EndFrameEndTime = timestamp;

    calculateResults();
}

void LagStatsCalculator::InstrumentEyePose(const ovrTrackingState& state)
{
    // If the camera frame counter has rolled,
    if (LastCameraFrameCounter != state.LastCameraFrameCounter)
    {
        // Accumulate eye pose data
        if (state.StatusFlags != 0)
        {
            latencyStatisticsData.LatencyVisionProc += state.LastVisionProcessingTime;
            latencyStatisticsData.LatencyVisionFrame += state.LastVisionFrameLatency;
        }
        ++VisionFrames;

        LastCameraFrameCounter = state.LastCameraFrameCounter;
    }
}

// Note: Currently assumes this is being called from OnEndFrameEnd() above.
void LagStatsCalculator::calculateResults()
{
    // Calculate time in the current epoch so far
    double intervalDuration = EndFrameEndTime - EpochBegin;

    // If stats should be reset due to inactivity,
    if (intervalDuration >= OVR_LAG_STATS_RESET_LIMIT)
    {
        resetPerfStats(EndFrameEndTime);
        return;
    }

    // Calculate EndFrame() duration
    double endFrameDuration = EndFrameEndTime - EndFrameStartTime;

    // Incorporate EndFrame() duration into the running sum
    latencyStatisticsData.EndFrameExecutionTime += endFrameDuration;

    //for (int i = 0; i < 3; ++i)
    //{
    //    LatencySum[i] += LatencyData[i];
    //}

    // Increment frame counter
    ++FrameCount;

    // If enough time has passed,
    if (intervalDuration >= OVR_LAG_STATS_EPOCH)
    {
        LatencyStatisticsResults results;

        float invFrameCount = 1.0f / (float) FrameCount;

        // EndFrame() instrumentation
        results.IntervalSeconds = intervalDuration;
        results.FPS = FrameCount / intervalDuration;
        results.EndFrameExecutionTime = latencyStatisticsData.EndFrameExecutionTime * invFrameCount;

        // Latency data
        results.LatencyRender = latencyStatisticsData.LatencyRender * invFrameCount;
        results.LatencyTimewarp = latencyStatisticsData.LatencyTimewarp * invFrameCount;
        results.LatencyPostPresent = latencyStatisticsData.LatencyPostPresent * invFrameCount;

        double invVisionFrameCount = 1. / VisionFrames;

        // Eye pose instrumentation
        results.LatencyVisionProc = latencyStatisticsData.LatencyVisionProc * invVisionFrameCount;
        results.LatencyVisionFrame = latencyStatisticsData.LatencyVisionFrame * invVisionFrameCount;

        Results.SetState(results);

        {
            Lock::Locker locker(&calculateResultsLock);
            calculateResultsSubject.GetPtr()->Call(&results);
        }

        // Reset for next frame
        resetPerfStats();
    }
}


}} // namespace OVR::CAPI