void DirectXTileRenderer::ComputeHdrMetadata()

in cpp/AdvancedColorImages/AdvancedColorImages/DirectXTileRenderer.cpp [760:816]


void DirectXTileRenderer::ComputeHdrMetadata()
{
	// Initialize with a sentinel value.
	m_maxCLL = -1.0f;

	// MaxCLL is not meaningful for SDR or WCG images.
	if ((!m_isComputeSupported) ||
		(m_imageInfo.imageKind != AdvancedColorKind::HighDynamicRange))
	{
		return;
	}

	// MaxCLL is nominally calculated for the single brightest pixel in a frame.
	// But we take a slightly more conservative definition that takes the 99.99th percentile
	// to account for extreme outliers in the image.
	float maxCLLPercent = 0.9999f;


	m_d2dContext->BeginDraw();

	m_d2dContext->DrawImage(m_histogramEffect.get());

	// We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
	// is lost. It will be handled during the next call to Present.
	HRESULT hr = m_d2dContext->EndDraw();
	if (hr != D2DERR_RECREATE_TARGET)
	{
		check_hresult(hr);
	}

	float* histogramData = new float[sc_histNumBins];
	check_hresult(
		m_histogramEffect->GetValue(D2D1_HISTOGRAM_PROP_HISTOGRAM_OUTPUT,
			reinterpret_cast<BYTE*>(histogramData),
			sc_histNumBins * sizeof(float)
		)
	);

	unsigned int maxCLLbin = 0;
	float runningSum = 0.0f; // Cumulative sum of values in histogram is 1.0.
	for (int i = sc_histNumBins - 1; i >= 0; i--)
	{
		runningSum += histogramData[i];
		maxCLLbin = i;

		if (runningSum >= 1.0f - maxCLLPercent)
		{
			break;
		}
	}

	float binNorm = static_cast<float>(maxCLLbin) / static_cast<float>(sc_histNumBins);
	m_maxCLL = powf(binNorm, 1 / sc_histGamma) * sc_histMaxNits;

	// Some drivers have a bug where histogram will always return 0. Treat this as unknown.
	m_maxCLL = (m_maxCLL == 0.0f) ? -1.0f : m_maxCLL;
}