/* -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-
 */

#import "DeckLinkCoreMediaVideoFrame.h"

DeckLinkCoreMediaVideoFrame::DeckLinkCoreMediaVideoFrame() :
m_refCount(1),
m_sampleBuffer(nullptr),
m_width(0),
m_height(0),
m_rowBytes(0),
m_pixelFormat(bmdFormat8BitBGRA),
m_frameFlags(bmdFrameFlagDefault),
m_dataPtr(nullptr)
{
}

DeckLinkCoreMediaVideoFrame::~DeckLinkCoreMediaVideoFrame()
{
	reset();
}

void DeckLinkCoreMediaVideoFrame::reset()
{
	if (!m_sampleBuffer)
		return;

	CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(m_sampleBuffer);
	if (pixelBuffer)
		CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);

	CFRelease(m_sampleBuffer);
}

bool DeckLinkCoreMediaVideoFrame::setVideoBuffer(CMSampleBufferRef sampleBuffer)
{
	if (!sampleBuffer)
		return false;

	m_sampleBuffer = sampleBuffer;
	CFRetain(m_sampleBuffer);

	CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(m_sampleBuffer);
	if (!pixelBuffer || (CFGetTypeID(pixelBuffer) != CVPixelBufferGetTypeID()))
		goto bail;

	if (CVPixelBufferGetWidth(pixelBuffer) == 0 || CVPixelBufferGetHeight(pixelBuffer) == 0)
		goto bail;

	switch (CVPixelBufferGetPixelFormatType(pixelBuffer))
	{
		case kCMPixelFormat_32ARGB:
			m_pixelFormat = bmdFormat8BitARGB;
			break;
		case kCMPixelFormat_32BGRA:
			m_pixelFormat = bmdFormat8BitBGRA;
			break;
		case kCMPixelFormat_422YpCbCr8:
			m_pixelFormat = bmdFormat8BitYUV;
			break;
		case kCMPixelFormat_422YpCbCr10:
			m_pixelFormat = bmdFormat10BitYUV;
			break;
		default:
			goto bail;
	}

	m_width			= (long)CVPixelBufferGetWidth(pixelBuffer);
	m_height		= (long)CVPixelBufferGetHeight(pixelBuffer);
	m_rowBytes		= (long)CVPixelBufferGetBytesPerRow(pixelBuffer);

	CVPixelBufferLockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
	m_dataPtr = CVPixelBufferGetBaseAddress(pixelBuffer);

	return true;

bail:
	m_width		= 0;
	m_height	= 0;
	m_rowBytes	= 0;
	m_dataPtr	= nullptr;
	
	return false;
}

bool DeckLinkCoreMediaVideoFrame::getStreamTime(BMDTimeValue* frameTime, BMDTimeValue* frameDuration, BMDTimeScale timeScale)
{
	if (!m_sampleBuffer)
		return false;

	// To avoid overflow use 128-bit integers for calculations
	__int128 result;
	__int128 sampleBufferFrameTime128(CMSampleBufferGetPresentationTimeStamp(m_sampleBuffer).value);
	__int128 sampleBufferFrameDuration128(CMSampleBufferGetOutputDuration(m_sampleBuffer).value);
	int32_t  sampleBufferTimeScale(CMSampleBufferGetPresentationTimeStamp(m_sampleBuffer).timescale);

	if (frameTime)
	{
		result = (sampleBufferFrameTime128 * timeScale) / sampleBufferTimeScale;
		*frameTime = (BMDTimeValue)result;
	}

	if (frameDuration)
	{
		result = (sampleBufferFrameDuration128 * timeScale) / sampleBufferTimeScale;
		*frameDuration = (BMDTimeValue)result;
	}

	return true;
}

HRESULT DeckLinkCoreMediaVideoFrame::QueryInterface(REFIID iid, LPVOID *ppv)
{
	CFUUIDBytes	iunknown;
	HRESULT		result = E_NOINTERFACE;

	*ppv = nullptr;
	iunknown = CFUUIDGetUUIDBytes(IUnknownUUID);

	if (memcmp(&iid, &iunknown, sizeof(REFIID)) == 0)
	{
		*ppv = this;
		AddRef();
		result = S_OK;
	}
	else if (memcmp(&iid, &IID_IDeckLinkVideoFrame, sizeof(REFIID)) == 0)
	{
		*ppv = (IDeckLinkVideoFrame*)this;
		AddRef();
		result = S_OK;
	}

	return result;
}

ULONG DeckLinkCoreMediaVideoFrame::AddRef()
{
	return ++m_refCount;
}

ULONG DeckLinkCoreMediaVideoFrame::Release()
{
	ULONG newRefValue = --m_refCount;
	if (newRefValue == 0)
	{
		delete this;
		return 0;
	}

	return newRefValue;
}

long DeckLinkCoreMediaVideoFrame::GetWidth()
{
	return m_width;
}

long DeckLinkCoreMediaVideoFrame::GetHeight()
{
	return m_height;
}

long DeckLinkCoreMediaVideoFrame::GetRowBytes()
{
	return m_rowBytes;
}

BMDPixelFormat DeckLinkCoreMediaVideoFrame::GetPixelFormat()
{
	return m_pixelFormat;
}

BMDFrameFlags DeckLinkCoreMediaVideoFrame::GetFlags()
{
	return m_frameFlags;
}

HRESULT DeckLinkCoreMediaVideoFrame::GetBytes(void **buffer)
{
	if (buffer == nullptr || !m_dataPtr)
		return E_FAIL;

	*buffer = m_dataPtr;
	return S_OK;
}

HRESULT DeckLinkCoreMediaVideoFrame::GetTimecode(BMDTimecodeFormat format, IDeckLinkTimecode **timecode)
{
	(void)format;   // unused
	(void)timecode; // unused
	return E_NOTIMPL;
}

HRESULT DeckLinkCoreMediaVideoFrame::GetAncillaryData(IDeckLinkVideoFrameAncillary **ancillary)
{
	(void)ancillary; // unused
	return E_NOTIMPL;
}
