NVScaler.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. // The MIT License(MIT)
  2. //
  3. // Copyright(c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy of
  6. // this software and associated documentation files(the "Software"), to deal in
  7. // the Software without restriction, including without limitation the rights to
  8. // use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of
  9. // the Software, and to permit persons to whom the Software is furnished to do so,
  10. // subject to the following conditions :
  11. //
  12. // The above copyright notice and this permission notice shall be included in all
  13. // copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  17. // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR
  18. // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  19. // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  20. // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. #include "NVScaler.h"
  22. #include <iostream>
  23. #include "DXUtilities.h"
  24. #include "DeviceResources.h"
  25. #include "Utilities.h"
  26. #include <DirectXPackedVector.h>
  27. NVScaler::NVScaler(DeviceResources& deviceResources, const std::vector<std::string>& shaderPaths)
  28. : m_deviceResources(deviceResources)
  29. , m_outputWidth(1)
  30. , m_outputHeight(1)
  31. {
  32. std::string shaderName = "NIS_Main.hlsl";
  33. std::string shaderPath;
  34. for (auto& e : shaderPaths)
  35. {
  36. if (std::filesystem::exists(e + "/" + shaderName))
  37. {
  38. shaderPath = e + "/" + shaderName;
  39. break;
  40. }
  41. }
  42. if (shaderPath.empty())
  43. throw std::runtime_error("Shader file not found" + shaderName);
  44. NISOptimizer opt(true, NISGPUArchitecture::NVIDIA_Generic_fp16);
  45. m_blockWidth = opt.GetOptimalBlockWidth();
  46. m_blockHeight = opt.GetOptimalBlockHeight();
  47. uint32_t threadGroupSize = opt.GetOptimalThreadGroupSize();
  48. std::wstring wNIS_BLOCK_WIDTH = widen(toStr(m_blockWidth));
  49. std::wstring wNIS_BLOCK_HEIGHT = widen(toStr(m_blockHeight));
  50. std::wstring wNIS_THREAD_GROUP_SIZE = widen(toStr(threadGroupSize));
  51. std::wstring wNIS_HDR_MODE = widen(toStr(uint32_t(NISHDRMode::None)));
  52. std::vector<DxcDefine> defines{
  53. {L"NIS_SCALER", L"1"},
  54. {L"NIS_HDR_MODE", wNIS_HDR_MODE.c_str()},
  55. {L"NIS_BLOCK_WIDTH", wNIS_BLOCK_WIDTH.c_str()},
  56. {L"NIS_BLOCK_HEIGHT", wNIS_BLOCK_HEIGHT.c_str()},
  57. {L"NIS_THREAD_GROUP_SIZE", wNIS_THREAD_GROUP_SIZE.c_str()},
  58. {L"NIS_USE_HALF_PRECISION", L"1"},
  59. {L"NIS_HLSL_6_2", L"1"},
  60. };
  61. ComPtr<IDxcLibrary> library;
  62. DX::ThrowIfFailed(DxcCreateInstance(CLSID_DxcLibrary, __uuidof(IDxcLibrary), &library));
  63. ComPtr<IDxcCompiler> compiler;
  64. DX::ThrowIfFailed(DxcCreateInstance(CLSID_DxcCompiler, __uuidof(IDxcCompiler), &compiler));
  65. std::wstring wShaderFilename = widen(shaderPath);
  66. uint32_t codePage = CP_UTF8;
  67. ComPtr<IDxcBlobEncoding> sourceBlob;
  68. DX::ThrowIfFailed(library->CreateBlobFromFile(wShaderFilename.c_str(), &codePage, &sourceBlob));
  69. ComPtr<IDxcIncludeHandler> includeHandler;
  70. library->CreateIncludeHandler(&includeHandler);
  71. std::vector<LPCWSTR> args{ L"-O3", L"-enable-16bit-types" };
  72. ComPtr<IDxcOperationResult> result;
  73. HRESULT hr = compiler->Compile(sourceBlob.Get(), wShaderFilename.c_str(), L"main", L"cs_6_2", args.data(), uint32_t(args.size()),
  74. defines.data(), uint32_t(defines.size()), includeHandler.Get(), &result);
  75. if (SUCCEEDED(hr))
  76. result->GetStatus(&hr);
  77. if (FAILED(hr))
  78. {
  79. if (result)
  80. {
  81. ComPtr<IDxcBlobEncoding> errorsBlob;
  82. hr = result->GetErrorBuffer(&errorsBlob);
  83. if (SUCCEEDED(hr) && errorsBlob)
  84. {
  85. wprintf(L"Compilation failed with errors:\n%hs\n", (const char*)errorsBlob->GetBufferPointer());
  86. }
  87. }
  88. DX::ThrowIfFailed(hr);
  89. }
  90. ComPtr<IDxcBlob> computeShaderBlob;
  91. result->GetResult(&computeShaderBlob);
  92. m_deviceResources.CreateBuffer(sizeof(NISConfig), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, &m_stagingBuffer);
  93. m_deviceResources.CreateBuffer(sizeof(NISConfig), D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, &m_constatBuffer);
  94. // Define root table layout
  95. constexpr uint32_t nParams = 6;
  96. CD3DX12_DESCRIPTOR_RANGE descriptorRange[nParams] = {};
  97. descriptorRange[0] = CD3DX12_DESCRIPTOR_RANGE(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 0);
  98. descriptorRange[1] = CD3DX12_DESCRIPTOR_RANGE(D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 0);
  99. descriptorRange[2] = CD3DX12_DESCRIPTOR_RANGE(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0);
  100. descriptorRange[3] = CD3DX12_DESCRIPTOR_RANGE(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0);
  101. descriptorRange[4] = CD3DX12_DESCRIPTOR_RANGE(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 1);
  102. descriptorRange[5] = CD3DX12_DESCRIPTOR_RANGE(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 2);
  103. CD3DX12_ROOT_PARAMETER m_rootParams[nParams] = {};
  104. m_rootParams[0].InitAsDescriptorTable(1, &descriptorRange[0]);
  105. m_rootParams[1].InitAsDescriptorTable(1, &descriptorRange[1]);
  106. m_rootParams[2].InitAsDescriptorTable(1, &descriptorRange[2]);
  107. m_rootParams[3].InitAsDescriptorTable(1, &descriptorRange[3]);
  108. m_rootParams[4].InitAsDescriptorTable(1, &descriptorRange[4]);
  109. m_rootParams[5].InitAsDescriptorTable(1, &descriptorRange[5]);
  110. D3D12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  111. rootSignatureDesc.NumParameters = nParams;
  112. rootSignatureDesc.pParameters = m_rootParams;
  113. rootSignatureDesc.NumStaticSamplers = 0;
  114. rootSignatureDesc.pStaticSamplers = nullptr;
  115. rootSignatureDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE;
  116. ComPtr<ID3DBlob> serializedSignature;
  117. DX::ThrowIfFailed(D3D12SerializeRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &serializedSignature, nullptr));
  118. // Create the root signature
  119. DX::ThrowIfFailed(m_deviceResources.device()->CreateRootSignature(0, serializedSignature->GetBufferPointer(), serializedSignature->GetBufferSize(),
  120. __uuidof(ID3D12RootSignature), &m_computeRootSignature));
  121. m_computeRootSignature->SetName(L"NVScaler");
  122. // Create compute pipeline state
  123. D3D12_COMPUTE_PIPELINE_STATE_DESC descComputePSO = {};
  124. descComputePSO.pRootSignature = m_computeRootSignature.Get();
  125. descComputePSO.CS.pShaderBytecode = computeShaderBlob->GetBufferPointer();
  126. descComputePSO.CS.BytecodeLength = computeShaderBlob->GetBufferSize();
  127. DX::ThrowIfFailed(m_deviceResources.device()->CreateComputePipelineState(&descComputePSO, __uuidof(ID3D12PipelineState), &m_computePSO));
  128. m_computePSO->SetName(L"NVScaler Compute PSO");
  129. // Coefficients assuming DXGI_FORMAT_R32G32B32A32_FLOAT, since filter size = 8, we pack 2 float4 in one row
  130. // CopyTextureRegion requires the buffer to be aligned to D3D12_TEXTURE_DATA_PITCH_ALIGNMENT
  131. m_rowPitch = kFilterSize * 4;
  132. const int rowPitchAligned = Align(m_rowPitch, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
  133. const int coefSize = rowPitchAligned * kPhaseCount;
  134. m_deviceResources.CreateBuffer(coefSize, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, &m_coefScalerUpload);
  135. m_deviceResources.CreateTexture2D(kFilterSize / 4, kPhaseCount, DXGI_FORMAT_R16G16B16A16_FLOAT, D3D12_RESOURCE_STATE_COMMON, &m_coefScaler);
  136. m_deviceResources.CreateBuffer(coefSize, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, &m_coefUSMUpload);
  137. m_deviceResources.CreateTexture2D(kFilterSize / 4, kPhaseCount, DXGI_FORMAT_R16G16B16A16_FLOAT, D3D12_RESOURCE_STATE_COMMON, &m_coefUSM);
  138. createAlignedCoefficients((uint16_t*)coef_scale_fp16, m_coefScalerHost, rowPitchAligned);
  139. createAlignedCoefficients((uint16_t*)coef_usm_fp16, m_coefUSMHost, rowPitchAligned);
  140. }
  141. void NVScaler::createAlignedCoefficients(uint16_t* data, std::vector<uint16_t>& coef, uint32_t rowPitchAligned)
  142. {
  143. const int rowElements = rowPitchAligned / sizeof(uint16_t);
  144. const int coefSize = rowElements * kPhaseCount;
  145. coef.resize(coefSize);
  146. for (uint32_t y = 0; y < kPhaseCount; ++y)
  147. {
  148. for (uint32_t x = 0; x < kFilterSize; ++x) {
  149. coef[x + y * uint64_t(rowElements)] = data[x + y * kFilterSize];
  150. }
  151. }
  152. }
  153. void NVScaler::uploadCoefficients()
  154. {
  155. m_deviceResources.UploadTextureData((void*)m_coefScalerHost.data(), sizeof(m_coefScalerHost[0]) * uint32_t(m_coefScalerHost.size()),
  156. m_rowPitch, m_coefScaler.Get(), m_coefScalerUpload.Get());
  157. m_deviceResources.UploadTextureData((void*)m_coefUSMHost.data(), sizeof(m_coefUSMHost[0]) * uint32_t(m_coefUSMHost.size()),
  158. m_rowPitch, m_coefUSM.Get(), m_coefUSMUpload.Get());
  159. }
  160. void NVScaler::update(float sharpness, uint32_t inputWidth, uint32_t inputHeight, uint32_t outputWidth, uint32_t outputHeight)
  161. {
  162. NVScalerUpdateConfig(m_config, sharpness,
  163. 0, 0, inputWidth, inputHeight, inputWidth, inputHeight,
  164. 0, 0, outputWidth, outputHeight, outputWidth, outputHeight,
  165. NISHDRMode::None);
  166. m_deviceResources.UploadBufferData(&m_config, sizeof(NISConfig), m_constatBuffer.Get(), m_stagingBuffer.Get());
  167. m_outputWidth = outputWidth;
  168. m_outputHeight = outputHeight;
  169. }