summaryrefslogtreecommitdiffstats
path: root/LibOVR/Src/OVR_Win32_DeviceManager.cpp
blob: f7bb9eb4d3a0620a73b80997c981601dc4e8bcaf (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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
/************************************************************************************

Filename    :   OVR_Win32_DeviceManager.cpp
Content     :   Win32 implementation of DeviceManager.
Created     :   September 21, 2012
Authors     :   Michael Antonov

Copyright   :   Copyright 2012 Oculus VR, Inc. All Rights reserved.

Use of this software is subject to the terms of the Oculus license
agreement provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.

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

#include "OVR_Win32_DeviceManager.h"

// Sensor & HMD Factories
#include "OVR_SensorImpl.h"
#include "OVR_LatencyTestImpl.h"
#include "OVR_Win32_HMDDevice.h"
#include "OVR_Win32_DeviceStatus.h"
#include "OVR_Win32_HIDDevice.h"

#include "Kernel/OVR_Timer.h"
#include "Kernel/OVR_Std.h"
#include "Kernel/OVR_Log.h"

DWORD Debug_WaitedObjectCount = 0;

namespace OVR { namespace Win32 {


//-------------------------------------------------------------------------------------
// **** Win32::DeviceManager

DeviceManager::DeviceManager()
{
    HidDeviceManager = *HIDDeviceManager::CreateInternal(this);
}

DeviceManager::~DeviceManager()
{
    // make sure Shutdown was called.
    OVR_ASSERT(!pThread);
}

bool DeviceManager::Initialize(DeviceBase*)
{
    if (!DeviceManagerImpl::Initialize(0))
        return false;

    pThread = *new DeviceManagerThread(this);
    if (!pThread || !pThread->Start())
        return false;
         
    pCreateDesc->pDevice = this;
    LogText("OVR::DeviceManager - initialized.\n");
    return true;
}

void DeviceManager::Shutdown()
{   
    LogText("OVR::DeviceManager - shutting down.\n");

    // Set Manager shutdown marker variable; this prevents
    // any existing DeviceHandle objects from accessing device.
    pCreateDesc->pLock->pManager = 0;

    // Push for thread shutdown *WITH NO WAIT*.
    // This will have the following effect:
    //  - Exit command will get enqueued, which will be executed later on the thread itself.
    //  - Beyond this point, this DeviceManager object may be deleted by our caller.
    //  - Other commands, such as CreateDevice, may execute before ExitCommand, but they will
    //    fail gracefully due to pLock->pManager == 0. Future commands can't be enqued
    //    after pManager is null.
    //  - Once ExitCommand executes, ThreadCommand::Run loop will exit and release the last
    //    reference to the thread object.
    pThread->PushExitCommand(false);
    pThread->DetachDeviceManager();
    pThread.Clear();

    DeviceManagerImpl::Shutdown();
}

ThreadCommandQueue* DeviceManager::GetThreadQueue()
{
    return pThread;
}

bool DeviceManager::GetDeviceInfo(DeviceInfo* info) const
{
    if ((info->InfoClassType != Device_Manager) &&
        (info->InfoClassType != Device_None))
        return false;
    
    info->Type    = Device_Manager;
    info->Version = 0;
    OVR_strcpy(info->ProductName, DeviceInfo::MaxNameLength, "DeviceManager");
    OVR_strcpy(info->Manufacturer,DeviceInfo::MaxNameLength, "Oculus VR, Inc.");        
    return true;
}

DeviceEnumerator<> DeviceManager::EnumerateDevicesEx(const DeviceEnumerationArgs& args)
{
    // TBD: Can this be avoided in the future, once proper device notification is in place?
    if (GetThreadId() != OVR::GetCurrentThreadId())
    {
        pThread->PushCall((DeviceManagerImpl*)this,
            &DeviceManager::EnumerateAllFactoryDevices, true);
    }
    else
        DeviceManager::EnumerateAllFactoryDevices();

    return DeviceManagerImpl::EnumerateDevicesEx(args);
}

ThreadId DeviceManager::GetThreadId() const
{
    return pThread->GetThreadId();
}
    
bool DeviceManager::GetHIDDeviceDesc(const String& path, HIDDeviceDesc* pdevDesc) const
{
    if (GetHIDDeviceManager())
        return static_cast<HIDDeviceManager*>(GetHIDDeviceManager())->GetHIDDeviceDesc(path, pdevDesc);
    return false;
}


//-------------------------------------------------------------------------------------
// ***** DeviceManager Thread 

DeviceManagerThread::DeviceManagerThread(DeviceManager* pdevMgr)
    : Thread(ThreadStackSize), hCommandEvent(0), pDeviceMgr(pdevMgr)
{    
    // Create a non-signaled manual-reset event.
    hCommandEvent = ::CreateEvent(0, TRUE, FALSE, 0);
    if (!hCommandEvent)
        return;

    // Must add event before starting.
    AddOverlappedEvent(0, hCommandEvent);

	// Create device messages object.
	pStatusObject = *new DeviceStatus(this);
}

DeviceManagerThread::~DeviceManagerThread()
{
    // Remove overlapped event [0], after thread service exit.
    if (hCommandEvent)
    {
        RemoveOverlappedEvent(0, hCommandEvent);    
        ::CloseHandle(hCommandEvent);
        hCommandEvent = 0;
    }
}

int DeviceManagerThread::Run()
{
    ThreadCommand::PopBuffer command;

    SetThreadName("OVR::DeviceManagerThread");
    LogText("OVR::DeviceManagerThread - running (ThreadId=0x%X).\n", GetThreadId());
  
	if (!pStatusObject->Initialize())
	{
		LogText("OVR::DeviceManagerThread - failed to initialize MessageObject.\n");
	}

    while(!IsExiting())
    {
        // PopCommand will reset event on empty queue.
        if (PopCommand(&command))
        {
            command.Execute();
        }
        else
        {
            DWORD eventIndex = 0;
            do {
                UPInt numberOfWaitHandles = WaitHandles.GetSize();
				Debug_WaitedObjectCount = (DWORD)numberOfWaitHandles;

                DWORD waitMs = INFINITE;

                // If devices have time-dependent logic registered, get the longest wait
                // allowed based on current ticks.
                if (!TicksNotifiers.IsEmpty())
                {
                    UInt64 ticksMks = Timer::GetTicks();
                    DWORD  waitAllowed;
                    
                    for (UPInt j = 0; j < TicksNotifiers.GetSize(); j++)
                    {
                        waitAllowed = (DWORD)(TicksNotifiers[j]->OnTicks(ticksMks) / Timer::MksPerMs);
                        if (waitAllowed < waitMs)
                            waitMs = waitAllowed;
                    }
                }
          
				// Wait for event signals or window messages.
                eventIndex = MsgWaitForMultipleObjects((DWORD)numberOfWaitHandles, &WaitHandles[0], FALSE, waitMs, QS_ALLINPUT);
				
                if (eventIndex != WAIT_FAILED)
                {
                    if (eventIndex == WAIT_TIMEOUT)
                        continue;

                    // TBD: Does this ever apply?
                    OVR_ASSERT(eventIndex < WAIT_ABANDONED_0);

                    if (eventIndex == WAIT_OBJECT_0)
                    {
                        // Handle [0] services commands.
                        break;
                    }
					else if (eventIndex == WAIT_OBJECT_0 + numberOfWaitHandles)
					{
						// Handle Windows messages.
						pStatusObject->ProcessMessages();
					}
                    else 
                    {
                        // Notify waiting device that its event is signaled.
                        unsigned i = eventIndex - WAIT_OBJECT_0; 
                        OVR_ASSERT(i < numberOfWaitHandles);
                        if (WaitNotifiers[i])                        
                            WaitNotifiers[i]->OnOverlappedEvent(WaitHandles[i]);
                    }
                }

            } while(eventIndex != WAIT_FAILED);
                    
        }
    }

	pStatusObject->ShutDown();

    LogText("OVR::DeviceManagerThread - exiting (ThreadId=0x%X).\n", GetThreadId());
    return 0;
}

bool DeviceManagerThread::AddOverlappedEvent(Notifier* notify, HANDLE hevent)
{
    WaitNotifiers.PushBack(notify);
    WaitHandles.PushBack(hevent);

    OVR_ASSERT(WaitNotifiers.GetSize() <= MAXIMUM_WAIT_OBJECTS);
    return true;
}

bool DeviceManagerThread::RemoveOverlappedEvent(Notifier* notify, HANDLE hevent)
{
    // [0] is reserved for thread commands with notify of null, but we still
    // can use this function to remove it.
    for (UPInt i = 0; i < WaitNotifiers.GetSize(); i++)
    {
        if ((WaitNotifiers[i] == notify) && (WaitHandles[i] == hevent))
        {
            WaitNotifiers.RemoveAt(i);
            WaitHandles.RemoveAt(i);
            return true;
        }
    }
    return false;
}

bool DeviceManagerThread::AddTicksNotifier(Notifier* notify)
{
     TicksNotifiers.PushBack(notify);
     return true;
}

bool DeviceManagerThread::RemoveTicksNotifier(Notifier* notify)
{
    for (UPInt i = 0; i < TicksNotifiers.GetSize(); i++)
    {
        if (TicksNotifiers[i] == notify)
        {
            TicksNotifiers.RemoveAt(i);
            return true;
        }
    }
    return false;
}

bool DeviceManagerThread::AddMessageNotifier(Notifier* notify)
{
	MessageNotifiers.PushBack(notify);
	return true;
}

bool DeviceManagerThread::RemoveMessageNotifier(Notifier* notify)
{
	for (UPInt i = 0; i < MessageNotifiers.GetSize(); i++)
	{
		if (MessageNotifiers[i] == notify)
		{
			MessageNotifiers.RemoveAt(i);
			return true;
		}
	}
	return false;
}

bool DeviceManagerThread::OnMessage(MessageType type, const String& devicePath)
{
	Notifier::DeviceMessageType notifierMessageType = Notifier::DeviceMessage_DeviceAdded;
	if (type == DeviceAdded)
	{
	}
	else if (type == DeviceRemoved)
	{
		notifierMessageType = Notifier::DeviceMessage_DeviceRemoved;
	}
	else
	{
		OVR_ASSERT(false);
	}

	bool error = false;
    bool deviceFound = false;
	for (UPInt i = 0; i < MessageNotifiers.GetSize(); i++)
    {
		if (MessageNotifiers[i] && 
			MessageNotifiers[i]->OnDeviceMessage(notifierMessageType, devicePath, &error))
		{
			// The notifier belonged to a device with the specified device name so we're done.
            deviceFound = true;
			break;
		}
    }
    if (type == DeviceAdded && !deviceFound)
    {
        Lock::Locker devMgrLock(&DevMgrLock);
        // a new device was connected. Go through all device factories and
        // try to detect the device using HIDDeviceDesc.
        HIDDeviceDesc devDesc;
        if (pDeviceMgr->GetHIDDeviceDesc(devicePath, &devDesc))
        {
            Lock::Locker deviceLock(pDeviceMgr->GetLock());
            DeviceFactory* factory = pDeviceMgr->Factories.GetFirst();
            while(!pDeviceMgr->Factories.IsNull(factory))
            {
                if (factory->DetectHIDDevice(pDeviceMgr, devDesc))
                {
                    deviceFound = true;
                    break;
                }
                factory = factory->pNext;
            }
        }
    }

    if (!deviceFound && strstr(devicePath.ToCStr(), "#OVR00"))
    {
        Ptr<DeviceManager> pmgr;
        {
            Lock::Locker devMgrLock(&DevMgrLock);
            pmgr = pDeviceMgr;
        }
        // HMD plugged/unplugged
        // This is not a final solution to enumerate HMD devices and get
        // a first available handle. This won't work with multiple rifts.
        // @TODO (!AB)
        pmgr->EnumerateDevices<HMDDevice>();
    }

	return !error;
}

void DeviceManagerThread::DetachDeviceManager()
{
    Lock::Locker devMgrLock(&DevMgrLock);
    pDeviceMgr = NULL;
}

} // namespace Win32


//-------------------------------------------------------------------------------------
// ***** Creation


// Creates a new DeviceManager and initializes OVR.
DeviceManager* DeviceManager::Create()
{

    if (!System::IsInitialized())
    {
        // Use custom message, since Log is not yet installed.
        OVR_DEBUG_STATEMENT(Log::GetDefaultLog()->
            LogMessage(Log_Debug, "DeviceManager::Create failed - OVR::System not initialized"); );
        return 0;
    }

    Ptr<Win32::DeviceManager> manager = *new Win32::DeviceManager;

    if (manager)
    {
        if (manager->Initialize(0))
        {            
            manager->AddFactory(&SensorDeviceFactory::Instance);
            manager->AddFactory(&LatencyTestDeviceFactory::Instance);
            manager->AddFactory(&Win32::HMDDeviceFactory::Instance);

            manager->AddRef();
        }
        else
        {
            manager.Clear();
        }

    }    

    return manager.GetPtr();
}


} // namespace OVR