text: /* -LICENSE-START-
   ** Copyright (c) 2018 Blackmagic Design
   **
   ** Permission is hereby granted, free of charge, to any person or organization
   ** obtaining a copy of the software and accompanying documentation covered by
   ** this license (the "Software") to use, reproduce, display, distribute,
   ** execute, and transmit the Software, and to prepare derivative works of the
   ** Software, and to permit third-parties to whom the Software is furnished to
   ** do so, all subject to the following:
   **
   ** The copyright notices in the Software and this entire statement, including
   ** the above license grant, this restriction and the following disclaimer,
   ** must be included in all copies of the Software, in whole or in part, and
   ** all derivative works of the Software, unless such copies or derivative
   ** works are solely in the form of machine-executable object code generated by
   ** a source language processor.
   **
   ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   ** FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
   ** SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
   ** FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
   ** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   ** DEALINGS IN THE SOFTWARE.
   ** -LICENSE-END-
   */
  #pragma once
  
  // DeviceManager is a class suitable for managing DeckLink devices in command line tools.
  // Asynchronous events such as DeckLink arrival are made available through blocking calls like getDeckLink().
  
  #include <atomic>
  #include <mutex>
  #include <thread>
  #include "com_ptr.h"
  #include "DeckLinkAPI.h"
  
  class DeckLinkNotificationManager : private IDeckLinkDeviceNotificationCallback
  {
  public:
  	static DeckLinkNotificationManager* CreateInstance() { return new DeckLinkNotificationManager(); }
  	com_ptr<IDeckLink>					getDeckLink()
  	{
  		std::lock_guard<std::mutex> lock(m_decklinkMutex);
  		return m_decklink;
  	}
  
  	// The reason we have separate Start() and Stop() methods rather than putting UninstallDeviceNotifications() in a destructor
  	// is that UninstallDeviceNotifications() will call Release() on this object and may cause it to be deleted twice.
  	void Start() { m_decklinkDiscovery->InstallDeviceNotifications(this); }
  	void Stop() { m_decklinkDiscovery->UninstallDeviceNotifications(); }
  
  	// IUnknown override
  	HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID* ppv) override { return E_NOINTERFACE; }
  	ULONG   STDMETHODCALLTYPE AddRef() override { return ++m_refCount; }
  	ULONG   STDMETHODCALLTYPE Release() override
  	{
  		auto result = --m_refCount;
  		if (result == 0)
  			delete this;
  		return result;
  	}
  
  private:
  	// This is a COM interface so should only be created with CreateInstance(), and managed with AddRef() and Release()
  	DeckLinkNotificationManager()
  		: m_refCount(1)
  	{
  #ifndef _WIN32
  		m_decklinkDiscovery = CreateDeckLinkDiscoveryInstance();
  #else
  		IDeckLinkDiscovery* discovery = nullptr;
  
  		CoCreateInstance(CLSID_CDeckLinkDiscovery, NULL, CLSCTX_ALL, IID_IDeckLinkDiscovery, (void**)&discovery);
  		m_decklinkDiscovery = discovery;
  #endif
  		if (!m_decklinkDiscovery)
  			throw std::runtime_error("CreateDeckLinkDiscoveryInstance failed: check driver is installed");
  	}
  
  	// IDeckLinkDeviceNotificationCallback
  	HRESULT STDMETHODCALLTYPE DeckLinkDeviceArrived(IDeckLink* decklinkDevice) override
  	{
  		std::lock_guard<std::mutex> lock(m_decklinkMutex);
  		m_decklink = decklinkDevice;
  		return S_OK;
  	}
  
  	HRESULT STDMETHODCALLTYPE DeckLinkDeviceRemoved(IDeckLink* decklinkDevice) override
  	{
  		std::lock_guard<std::mutex> lock(m_decklinkMutex);
  		m_decklink = nullptr;
  		return S_OK;
  	}
  
  private:
  	std::atomic<ULONG>			m_refCount;
  	com_ptr<IDeckLinkDiscovery>	m_decklinkDiscovery;
  	std::mutex					m_decklinkMutex;
  	com_ptr<IDeckLink>			m_decklink;
  };
  
  class DeviceManager
  {
  public:
  	DeviceManager()
  	{
  #ifdef _WIN32
  		CoInitializeEx(nullptr, COINIT_MULTITHREADED);
  #endif
  		m_notifierManager = DeckLinkNotificationManager::CreateInstance();
  		m_notifierManager->Start();
  	}
  	~DeviceManager()
  	{
  		m_notifierManager->Stop();
  	}
  	com_ptr<IDeckLink> getDeckLink()
  	{
  		return waitForDeckLink();
  	}
  	com_ptr<IDeckLinkInput> getDeckLinkInput()
  	{
  		auto deckLink = getDeckLink();
  
  		com_ptr<IDeckLinkInput> deckLinkInput;
  		if (FAILED(deckLink->QueryInterface(IID_IDeckLinkInput, (void**)deckLinkInput.releaseAndGetAddressOf())))
  			throw std::runtime_error("QueryInterface(IID_IDeckLinkInput) failed: check driver is installed");
  
  		return deckLinkInput;
  	}
  	com_ptr<IDeckLinkOutput> getDeckLinkOutput()
  	{
  		auto deckLink = getDeckLink();
  
  		com_ptr<IDeckLinkOutput> deckLinkOutput;
  		if (FAILED(deckLink->QueryInterface(IID_IDeckLinkOutput, (void**)deckLinkOutput.releaseAndGetAddressOf())))
  			throw std::runtime_error("QueryInterface(IID_IDeckLinkOutput) failed: check driver is installed");
  
  		return deckLinkOutput;
  	}
  
  private:
  	com_ptr<IDeckLink> waitForDeckLink()
  	{
  		// For command line tools it is reasonable to wait up to 3 seconds for a DeckLink device to arrive
  		for (int i = 0; i < 30; i++)
  		{
  			auto decklink = m_notifierManager->getDeckLink();
  			if (decklink)
  				return decklink;
  
  			std::this_thread::sleep_for(std::chrono::milliseconds(100));
  		}
  
  		throw std::runtime_error("No DeckLink device detected after 3 seconds");
  	}
  
  	com_ptr<DeckLinkNotificationManager> m_notifierManager;
  };
  