forked from alvr-org/ALVR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OvrDirectModeComponent.cpp
270 lines (221 loc) · 9.39 KB
/
OvrDirectModeComponent.cpp
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
#include "OvrDirectModeComponent.h"
OvrDirectModeComponent::OvrDirectModeComponent(std::shared_ptr<CD3DRender> pD3DRender, std::shared_ptr<PoseHistory> poseHistory)
: m_pD3DRender(pD3DRender)
, m_poseHistory(poseHistory)
, m_submitLayer(0)
{
}
void OvrDirectModeComponent::SetEncoder(std::shared_ptr<CEncoder> pEncoder) {
m_pEncoder = pEncoder;
}
/** Specific to Oculus compositor support, textures supplied must be created using this method. */
void OvrDirectModeComponent::CreateSwapTextureSet(uint32_t unPid, const SwapTextureSetDesc_t *pSwapTextureSetDesc, SwapTextureSet_t *pOutSwapTextureSet)
{
Debug("CreateSwapTextureSet pid=%d Format=%d %dx%d SampleCount=%d\n", unPid, pSwapTextureSetDesc->nFormat
, pSwapTextureSetDesc->nWidth, pSwapTextureSetDesc->nHeight, pSwapTextureSetDesc->nSampleCount);
//HRESULT hr = D3D11CreateDevice(pAdapter, D3D_DRIVER_TYPE_HARDWARE, NULL, creationFlags, NULL, 0, D3D11_SDK_VERSION, &pDevice, &eFeatureLevel, &pContext);
D3D11_TEXTURE2D_DESC SharedTextureDesc = {};
SharedTextureDesc.ArraySize = 1;
SharedTextureDesc.MipLevels = 1;
SharedTextureDesc.SampleDesc.Count = pSwapTextureSetDesc->nSampleCount;
SharedTextureDesc.SampleDesc.Quality = 0;
SharedTextureDesc.Usage = D3D11_USAGE_DEFAULT;
SharedTextureDesc.Format = (DXGI_FORMAT)pSwapTextureSetDesc->nFormat;
// Some(or all?) applications request larger texture than we specified in GetRecommendedRenderTargetSize.
// But, we must create textures in requested size to prevent cropped output. And then we must shrink texture to H.264 movie size.
SharedTextureDesc.Width = pSwapTextureSetDesc->nWidth;
SharedTextureDesc.Height = pSwapTextureSetDesc->nHeight;
SharedTextureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
//SharedTextureDesc.MiscFlags = D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX | D3D11_RESOURCE_MISC_SHARED_NTHANDLE;
SharedTextureDesc.MiscFlags = D3D11_RESOURCE_MISC_SHARED;
ProcessResource *processResource = new ProcessResource();
processResource->pid = unPid;
for (int i = 0; i < 3; i++) {
HRESULT hr = m_pD3DRender->GetDevice()->CreateTexture2D(&SharedTextureDesc, NULL, &processResource->textures[i]);
//LogDriver("texture%d %p res:%d %s", i, texture[i], hr, GetDxErrorStr(hr).c_str());
IDXGIResource* pResource;
hr = processResource->textures[i]->QueryInterface(__uuidof(IDXGIResource), (void**)&pResource);
//LogDriver("QueryInterface %p res:%d %s", pResource, hr, GetDxErrorStr(hr).c_str());
hr = pResource->GetSharedHandle(&processResource->sharedHandles[i]);
//LogDriver("GetSharedHandle %p res:%d %s", processResource->sharedHandles[i], hr, GetDxErrorStr(hr).c_str());
m_handleMap.insert(std::make_pair(processResource->sharedHandles[i], std::make_pair(processResource, i)));
pOutSwapTextureSet->rSharedTextureHandles[i] = (vr::SharedTextureHandle_t)processResource->sharedHandles[i];
pResource->Release();
Debug("Created Texture %d %p\n", i, processResource->sharedHandles[i]);
}
//m_processMap.insert(std::pair<uint32_t, ProcessResource *>(unPid, processResource));
}
/** Used to textures created using CreateSwapTextureSet. Only one of the set's handles needs to be used to destroy the entire set. */
void OvrDirectModeComponent::DestroySwapTextureSet(vr::SharedTextureHandle_t sharedTextureHandle)
{
Debug("DestroySwapTextureSet %p\n", sharedTextureHandle);
auto it = m_handleMap.find((HANDLE)sharedTextureHandle);
if (it != m_handleMap.end()) {
// Release all reference (a bit forcible)
ProcessResource *p = it->second.first;
m_handleMap.erase(p->sharedHandles[0]);
m_handleMap.erase(p->sharedHandles[1]);
m_handleMap.erase(p->sharedHandles[2]);
delete p;
}
else {
Debug("Requested to destroy not managing texture. handle:%p\n", sharedTextureHandle);
}
}
/** Used to purge all texture sets for a given process. */
void OvrDirectModeComponent::DestroyAllSwapTextureSets(uint32_t unPid)
{
Debug("DestroyAllSwapTextureSets pid=%d\n", unPid);
for (auto it = m_handleMap.begin(); it != m_handleMap.end();) {
if (it->second.first->pid == unPid) {
if (it->second.second == 0) {
delete it->second.first;
}
m_handleMap.erase(it++);
}
else {
++it;
}
}
}
/** After Present returns, calls this to get the next index to use for rendering. */
void OvrDirectModeComponent::GetNextSwapTextureSetIndex(vr::SharedTextureHandle_t sharedTextureHandles[2], uint32_t(*pIndices)[2])
{
(*pIndices)[0]++;
(*pIndices)[0] %= 3;
(*pIndices)[1]++;
(*pIndices)[1] %= 3;
}
/** Call once per layer to draw for this frame. One shared texture handle per eye. Textures must be created
* using CreateSwapTextureSet and should be alternated per frame. Call Present once all layers have been submitted. */
void OvrDirectModeComponent::SubmitLayer(const SubmitLayerPerEye_t(&perEye)[2])
{
auto pPose = &perEye[0].mHmdPose; // TODO: are both poses the same? Name HMD suggests yes.
if (m_submitLayer == 0) {
// Detect FrameIndex of submitted frame by pPose.
// This is important part to achieve smooth headtracking.
// We search for history of TrackingInfo and find the TrackingInfo which have nearest matrix value.
auto pose = m_poseHistory->GetBestPoseMatch(*pPose);
if (pose) {
// found the frameIndex
m_prevTargetTimestampNs = m_targetTimestampNs;
m_targetTimestampNs = pose->targetTimestampNs;
m_prevFramePoseRotation = m_framePoseRotation;
m_framePoseRotation.x = pose->motion.orientation.x;
m_framePoseRotation.y = pose->motion.orientation.y;
m_framePoseRotation.z = pose->motion.orientation.z;
m_framePoseRotation.w = pose->motion.orientation.w;
}
else {
m_targetTimestampNs = 0;
m_framePoseRotation = HmdQuaternion_Init(0.0, 0.0, 0.0, 0.0);
}
}
if (m_submitLayer < MAX_LAYERS) {
m_submitLayers[m_submitLayer][0] = perEye[0];
m_submitLayers[m_submitLayer][1] = perEye[1];
m_submitLayer++;
}
else {
Warn("Too many layers submitted!\n");
}
if (Settings::Instance().m_DriverTestMode & 8) {
// Crash test
*(char*)0 = 1;
}
//CopyTexture();
}
/** Submits queued layers for display. */
void OvrDirectModeComponent::Present(vr::SharedTextureHandle_t syncTexture)
{
ReportPresent(m_targetTimestampNs, 0);
bool useMutex = true;
IDXGIKeyedMutex *pKeyedMutex = NULL;
uint32_t layerCount = m_submitLayer;
m_submitLayer = 0;
if (m_prevTargetTimestampNs == m_targetTimestampNs) {
Debug("Discard duplicated frame. FrameIndex=%llu (Ignoring)\n", m_targetTimestampNs);
//return;
}
ID3D11Texture2D *pSyncTexture = m_pD3DRender->GetSharedTexture((HANDLE)syncTexture);
if (!pSyncTexture)
{
Warn("[VDispDvr] SyncTexture is NULL!\n");
return;
}
if (useMutex) {
// Access to shared texture must be wrapped in AcquireSync/ReleaseSync
// to ensure the compositor has finished rendering to it before it gets used.
// This enforces scheduling of work on the gpu between processes.
if (SUCCEEDED(pSyncTexture->QueryInterface(__uuidof(IDXGIKeyedMutex), (void **)&pKeyedMutex)))
{
// TODO: Reasonable timeout and timeout handling
HRESULT hr = pKeyedMutex->AcquireSync(0, 10);
if (hr != S_OK)
{
Debug("[VDispDvr] ACQUIRESYNC FAILED!!! hr=%d %p %ls\n", hr, hr, GetErrorStr(hr).c_str());
pKeyedMutex->Release();
return;
}
}
}
CopyTexture(layerCount);
if (useMutex) {
if (pKeyedMutex)
{
pKeyedMutex->ReleaseSync(0);
pKeyedMutex->Release();
}
}
ReportComposed(m_targetTimestampNs, 0);
if (m_pEncoder) {
m_pEncoder->NewFrameReady();
}
}
void OvrDirectModeComponent::CopyTexture(uint32_t layerCount) {
uint64_t presentationTime = GetTimestampUs();
ID3D11Texture2D *pTexture[MAX_LAYERS][2];
ComPtr<ID3D11Texture2D> Texture[MAX_LAYERS][2];
vr::VRTextureBounds_t bounds[MAX_LAYERS][2];
for (uint32_t i = 0; i < layerCount; i++) {
// Find left eye texture.
HANDLE leftEyeTexture = (HANDLE)m_submitLayers[i][0].hTexture;
auto it = m_handleMap.find(leftEyeTexture);
if (it == m_handleMap.end()) {
// Ignore this layer.
Debug("Submitted texture is not found on HandleMap. eye=right layer=%d/%d Texture Handle=%p\n", i, layerCount, leftEyeTexture);
}
else {
Texture[i][0] = it->second.first->textures[it->second.second];
D3D11_TEXTURE2D_DESC desc;
Texture[i][0]->GetDesc(&desc);
// Find right eye texture.
HANDLE rightEyeTexture = (HANDLE)m_submitLayers[i][1].hTexture;
it = m_handleMap.find(rightEyeTexture);
if (it == m_handleMap.end()) {
// Ignore this layer
Debug("Submitted texture is not found on HandleMap. eye=left layer=%d/%d Texture Handle=%p\n", i, layerCount, rightEyeTexture);
Texture[i][0].Reset();
}
else {
Texture[i][1] = it->second.first->textures[it->second.second];
}
}
pTexture[i][0] = Texture[i][0].Get();
pTexture[i][1] = Texture[i][1].Get();
bounds[i][0] = m_submitLayers[i][0].bounds;
bounds[i][1] = m_submitLayers[i][1].bounds;
}
// This can go away, but is useful to see it as a separate packet on the gpu in traces.
m_pD3DRender->GetContext()->Flush();
if (m_pEncoder) {
// Wait for the encoder to be ready. This is important because the encoder thread
// blocks on transmit which uses our shared d3d context (which is not thread safe).
m_pEncoder->WaitForEncode();
std::string debugText;
uint64_t submitFrameIndex = m_targetTimestampNs + Settings::Instance().m_trackingFrameOffset;
// Copy entire texture to staging so we can read the pixels to send to remote device.
m_pEncoder->CopyToStaging(pTexture, bounds, layerCount,false, presentationTime, submitFrameIndex,"", debugText);
m_pD3DRender->GetContext()->Flush();
}
}