/* -LICENSE-START-
 ** Copyright (c) 2015 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-
 */

#ifndef __DX11_COMPOSITE_H__
#define __DX11_COMPOSITE_H__

#include <windows.h>
#include <process.h>
#include <tchar.h>
#include <d3d11.h>

#include <objbase.h>
#include <comutil.h>
#include "DeckLinkAPI_h.h"

#include "VideoFrameTransfer.h"

#include <map>
#include <vector>
#include <deque>

class PlayoutDelegate;
class CaptureDelegate;
class PinnedMemoryAllocator;

class DX11Composite
{
public:
	DX11Composite(HWND hWnd, HDC hDC);
	~DX11Composite();

	bool InitDeckLink();
	bool Start();
	bool Stop();

	void resizeDX(WORD width, WORD height);
	void paintDX();

	void VideoFrameArrived(IDeckLinkVideoInputFrame* inputFrame, bool hasNoInputSource);
	void PlayoutFrameCompleted(IDeckLinkVideoFrame* completedFrame, BMDOutputFrameCompletionResult result);

private:
	void resizeWindow(int width, int height);

	CaptureDelegate*						mCaptureDelegate;
	PlayoutDelegate*						mPlayoutDelegate;
	HWND									mhWnd;
	HDC										mhDC;
	CRITICAL_SECTION						pMutex;

	// DeckLink
	IDeckLinkInput*							mDLInput;
	IDeckLinkOutput*						mDLOutput;
	std::deque<IDeckLinkMutableVideoFrame*>	mDLOutputVideoFrameQueue;
	PinnedMemoryAllocator*					mCaptureAllocator;
	PinnedMemoryAllocator*					mPlayoutAllocator;
	BMDTimeValue							mFrameDuration;
	BMDTimeScale							mFrameTimescale;
	unsigned								mTotalPlayoutFrames;
	unsigned								mFrameWidth;
	unsigned								mFrameHeight;
	bool									mHasNoInputSource;

	bool									mFastTransferExtensionAvailable;

	// DX data
	D3D_DRIVER_TYPE							mDriverType;
	D3D_FEATURE_LEVEL						mFeatureLevel;
	ID3D11Device*							mpD3DDevice;
	ID3D11DeviceContext*					mpImmediateContext;
	IDXGISwapChain*							mpSwapChain;
	ID3D11RenderTargetView*					mpRenderTargetView;
	ID3D11Texture2D*						mpBackBuffer;
	ID3D11Texture2D*						mpDepthStencil;
	ID3D11DepthStencilView*					mpDepthStencilView;
	ID3D11VertexShader*						mpCubeVertexShader;
	ID3D11PixelShader*						mpCubeFragmentShader;
	ID3D11VertexShader*						mpFrameVertexShader;
	ID3D11PixelShader*						mpFrameFragmentShader;
	ID3D11SamplerState*						mpSamplerLinear;
	ID3D11InputLayout*						mpVertexLayout;
	ID3D11Buffer*							mpCubeVertexBuffer;
	ID3D11Buffer*							mpCubeIndexBuffer;
	ID3D11Buffer*							mpFrameVertexBuffer;
	ID3D11Buffer*							mpFrameIndexBuffer;
	ID3D11Buffer*							mpXVertexBuffer;
	ID3D11Buffer*							mpXIndexBuffer;
	ID3D11Buffer*							mpCBViewCube;
	ID3D11Buffer*							mpCBPerspectiveProjection;
	ID3D11Buffer*							mpCBChangesEveryFrame;
	ID3D11Texture2D*						mpCaptureTexture;
	ID3D11Texture2D*						mpPlayoutTexture;
	ID3D11RenderTargetView*					mpPlayoutTextureRTV;
	ID3D11BlendState*						mpBlendStateAlphaBlend;
	ID3D11BlendState*						mpBlendStateNoBlend;
	float									mRotateAngle;
	float									mRotateAngleRate;

	int										mViewWidth;
	int										mViewHeight;

	float									mAspectRatio;

	bool CheckFastTransferAvailable();

	bool InitD3D();
	void CleanupD3D();

	bool createCubeFragmentShader();
	bool createCubeVertexShader();

	bool createFrameFragmentShader();
	bool createFrameVertexShader();

	void Render();
};

////////////////////////////////////////////
// PinnedMemoryAllocator
////////////////////////////////////////////
class PinnedMemoryAllocator : public IDeckLinkMemoryAllocator
{
public:
	PinnedMemoryAllocator(ID3D11Device* pD3DDevice, VideoFrameTransfer::Direction direction, unsigned cacheSize);
	virtual ~PinnedMemoryAllocator();

	bool transferFrame(void* address, void* gpuTexture);
	void waitSyncComplete(void* address);
	void endSyncComplete(void* address);
	void waitAPI();
	void endAPI();
	void unPinAddress(void* address);

	// IUnknown methods
	virtual HRESULT STDMETHODCALLTYPE	QueryInterface(REFIID iid, LPVOID *ppv);
	virtual ULONG STDMETHODCALLTYPE		AddRef(void);
	virtual ULONG STDMETHODCALLTYPE		Release(void);

	// IDeckLinkMemoryAllocator methods
	virtual HRESULT STDMETHODCALLTYPE	AllocateBuffer(unsigned int bufferSize, void* *allocatedBuffer);
	virtual HRESULT STDMETHODCALLTYPE	ReleaseBuffer(void* buffer);
	virtual HRESULT STDMETHODCALLTYPE	Commit();
	virtual HRESULT STDMETHODCALLTYPE	Decommit();

private:
	ID3D11Device*                               mpD3DDevice;
	LONG										mRefCount;
	VideoFrameTransfer::Direction				mDirection;
	std::map<void*, VideoFrameTransfer*>		mFrameTransfer;
	std::map<void*, unsigned long>				mAllocatedSize;
	std::vector<void*>							mFrameCache;
	unsigned									mFrameCacheSize;
};

////////////////////////////////////////////
// Capture Delegate Class
////////////////////////////////////////////

class CaptureDelegate : public IDeckLinkInputCallback
{
	DX11Composite*	m_pOwner;
	LONG			mRefCount;

public:
	CaptureDelegate(DX11Composite* pOwner);

	// IUnknown needs only a dummy implementation
	virtual HRESULT	STDMETHODCALLTYPE	QueryInterface(REFIID iid, LPVOID *ppv);
	virtual ULONG	STDMETHODCALLTYPE	AddRef();
	virtual ULONG	STDMETHODCALLTYPE	Release();

	virtual HRESULT STDMETHODCALLTYPE	VideoInputFrameArrived(IDeckLinkVideoInputFrame *videoFrame, IDeckLinkAudioInputPacket *audioPacket);
	virtual HRESULT	STDMETHODCALLTYPE	VideoInputFormatChanged(BMDVideoInputFormatChangedEvents notificationEvents, IDeckLinkDisplayMode *newDisplayMode, BMDDetectedVideoInputFormatFlags detectedSignalFlags);
};

////////////////////////////////////////////
// Render Delegate Class
////////////////////////////////////////////

class PlayoutDelegate : public IDeckLinkVideoOutputCallback
{
	DX11Composite*	m_pOwner;
	LONG			mRefCount;

public:
	PlayoutDelegate(DX11Composite* pOwner);

	// IUnknown needs only a dummy implementation
	virtual HRESULT	STDMETHODCALLTYPE	QueryInterface(REFIID iid, LPVOID *ppv);
	virtual ULONG	STDMETHODCALLTYPE	AddRef();
	virtual ULONG	STDMETHODCALLTYPE	Release();

	virtual HRESULT	STDMETHODCALLTYPE	ScheduledFrameCompleted(IDeckLinkVideoFrame* completedFrame, BMDOutputFrameCompletionResult result);
	virtual HRESULT	STDMETHODCALLTYPE	ScheduledPlaybackHasStopped();
};

#endif		// __DX11_COMPOSITE_H__
