codekingpro's picture
Upload folder using huggingface_hub
ea55f45 verified
Raw
History Blame Contribute Delete
12 kB
/*
* Copyright 2017-2024 NVIDIA Corporation. All rights reserved.
*
* Please refer to the NVIDIA end user license agreement (EULA) associated
* with this source code for terms and conditions that govern your use of
* this software. Any use, reproduction, disclosure, or distribution of
* this software and related documentation outside the terms of the EULA
* is strictly prohibited.
*
*/
/**
* This sample application illustrates encoding of frames stored in OpenGL
* textures. The application reads frames from the input file and uploads them
* to the textures obtained from the encoder using NvEncoder::GetNextInputFrame().
* The encoder subsequently maps the textures for encoder using NvEncodeAPI and
* submits them to NVENC hardware for encoding as part of NvEncoder::EncodeFrame().
*
* The X server must be running and the DISPLAY environment variable must be
* set when attempting to run this application.
*/
#include <iostream>
#include <memory>
#include <stdint.h>
#include <cuda.h>
#include "../Utils/Logger.h"
#include "NvEncoder/NvEncoderGL.h"
#include "../Utils/NvEncoderCLIOptions.h"
#include "../Utils/NvCodecUtils.h"
#include "../Common/AppEncUtils.h"
#include "GraphicsUtils.h"
simplelogger::Logger *logger = simplelogger::LoggerFactory::CreateConsoleLogger();
void ShowEncoderGLBriefHelp()
{
std::ostringstream oss;
oss << "NVIDIA Video Encoder AppEncGL Sample Application\n";
oss << "==========================================\n\n";
oss << "Usage: AppEncGL -i <input_file> [options]\n\n";
// Brief table of core arguments
oss << "Common Arguments:\n";
oss << std::left << std::setw(25) << "Argument"
<< std::setw(12) << "Type"
<< "Default Value\n";
oss << std::string(50, '-') << "\n";
oss << std::left << std::setw(25) << "-i <path>"
<< std::setw(12) << "Required"
<< "N/A\n";
oss << std::left << std::setw(25) << "-o <path>"
<< std::setw(12) << "Optional"
<< "codec-based (out.h264/hevc/av1)\n";
oss << std::left << std::setw(25) << "-s <WxH>"
<< std::setw(12) << "Required"
<< "N/A\n";
oss << std::left << std::setw(25) << "-if <format>"
<< std::setw(12) << "Optional"
<< "iyuv\n";
oss << "\nFor detailed help, use -A/--advanced-options\n";
oss << "To view encoder capabilities, use -ec/--encode-caps\n";
std::cout << oss.str();
exit(0);
}
void ShowEncoderGLDetailedHelp()
{
std::ostringstream oss;
oss << "NVIDIA Video Encoder AppEncGL Sample Application - Detailed Help\n";
oss << "=====================================================\n\n";
oss << "Usage: AppEncGL -i <input_file> [options]\n\n";
// Full table of all arguments
oss << "All Arguments:\n";
oss << std::left << std::setw(25) << "Argument"
<< std::setw(12) << "Type"
<< std::setw(20) << "Default Value"
<< "Example\n";
oss << std::string(80, '-') << "\n";
// Required arguments
oss << std::left << std::setw(25) << "-i <path>"
<< std::setw(12) << "Required"
<< std::setw(20) << "N/A"
<< "-i input.yuv\n";
oss << std::left << std::setw(25) << "-s <WxH>"
<< std::setw(12) << "Required"
<< std::setw(20) << "N/A"
<< "-s 1920x1080\n";
// Optional arguments
oss << std::left << std::setw(25) << "-o <path>"
<< std::setw(12) << "Optional"
<< std::setw(20) << "codec-based"
<< "-o output.h264\n";
oss << std::left << std::setw(25) << "-if <format>"
<< std::setw(12) << "Optional"
<< std::setw(20) << "iyuv"
<< "-if iyuv\n";
oss << std::left << std::setw(25) << "-c <context>"
<< std::setw(12) << "Optional"
<< std::setw(20) << "glx"
<< "-c egl\n";
// Detailed descriptions
oss << "\nDetailed Descriptions:\n";
oss << "-------------------\n";
oss << std::left << std::setw(25) << "-i" << ": Input file path\n";
oss << std::left << std::setw(25) << "-o" << ": Output file path\n";
oss << std::left << std::setw(25) << "-s" << ": Input resolution in WxH format\n";
oss << std::left << std::setw(25) << "-if" << ": Input format (iyuv/nv12)\n";
oss << std::left << std::setw(25) << "-c" << ": GL context type (glx/egl)\n";
oss << std::left << std::setw(25) << "-h/--help" << ": Print basic usage information\n";
oss << std::left << std::setw(25) << "-A/--advanced-options" << ": Print detailed usage information\n";
oss << std::left << std::setw(25) << "-ec/--encode-caps" << ": Print encode capabilities of GPU\n";
// Important notes
oss << "\nNotes:\n";
oss << "------\n";
oss << "* Width and height must be specified for encoding\n";
oss << "* Default context type is glx\n";
oss << std::endl;
oss << NvEncoderInitParam().GetHelpMessage(false, false, true, false, false, true, false, false) << std::endl;
oss << "\nTo view encode capabilities, use -ec/--encode-caps\n";
std::cout << oss.str();
exit(0);
}
void ShowHelpAndExit(const char *szBadOption = NULL)
{
if (szBadOption)
{
std::ostringstream oss;
oss << "Error parsing \"" << szBadOption << "\"\n";
oss << "Use -h/--help for basic usage or -A/--advanced-options for detailed information\n";
throw std::invalid_argument(oss.str());
}
}
void ParseCommandLine(int argc, char *argv[], char *szInputFileName, int &nWidth, int &nHeight,
NV_ENC_BUFFER_FORMAT &eFormat, char *szOutputFileName, NvEncoderInitParam &initParam, char* contextType)
{
std::ostringstream oss;
int i;
if (argc == 1) {
std::cout << "No Arguments provided! Please refer to the following for options:\n";
ShowEncoderGLBriefHelp();
}
for (i = 1; i < argc; i++)
{
if (!_stricmp(argv[i], "-h") || !_stricmp(argv[i], "--help")) {
ShowEncoderGLBriefHelp();
}
if (!_stricmp(argv[i], "-A") || !_stricmp(argv[i], "--advanced-options")) {
ShowEncoderGLDetailedHelp();
}
if (!_stricmp(argv[i], "-ec") || !_stricmp(argv[i], "--encode-caps")) {
ShowEncoderCapability();
}
if (!_stricmp(argv[i], "-i"))
{
if (++i == argc)
{
ShowHelpAndExit("-i");
}
sprintf(szInputFileName, "%s", argv[i]);
continue;
}
if (!_stricmp(argv[i], "-o"))
{
if (++i == argc)
{
ShowHelpAndExit("-o");
}
sprintf(szOutputFileName, "%s", argv[i]);
continue;
}
if (!_stricmp(argv[i], "-s"))
{
if (++i == argc || 2 != sscanf(argv[i], "%dx%d", &nWidth, &nHeight))
{
ShowHelpAndExit("-s");
}
continue;
}
if (!_stricmp(argv[i], "-c"))
{
if (++i == argc)
{
ShowHelpAndExit("-c");
}
snprintf(contextType, 4, "%s", argv[i]);
continue;
}
std::vector<std::string> vszFileFormatName = { "iyuv", "nv12" };
NV_ENC_BUFFER_FORMAT aFormat[] =
{
NV_ENC_BUFFER_FORMAT_IYUV,
NV_ENC_BUFFER_FORMAT_NV12,
};
if (!_stricmp(argv[i], "-if"))
{
if (++i == argc)
{
ShowHelpAndExit("-if");
}
auto it = std::find(vszFileFormatName.begin(), vszFileFormatName.end(), argv[i]);
if (it == vszFileFormatName.end())
{
ShowHelpAndExit("-if");
}
eFormat = aFormat[it - vszFileFormatName.begin()];
continue;
}
// Regard as encoder parameter
if (argv[i][0] != '-')
{
ShowHelpAndExit(argv[i]);
}
oss << argv[i] << " ";
while (i + 1 < argc && argv[i + 1][0] != '-')
{
oss << argv[++i] << " ";
}
}
initParam = NvEncoderInitParam(oss.str().c_str());
}
void EncodeGL(char *szInFilePath, char *szOutFilePath, int nWidth, int nHeight,
NV_ENC_BUFFER_FORMAT eFormat, NvEncoderInitParam *encodeCLIOptions)
{
std::ifstream fpIn(szInFilePath, std::ifstream::in | std::ifstream::binary);
if (!fpIn)
{
std::ostringstream err;
err << "Unable to open input file: " << szInFilePath << std::endl;
throw std::invalid_argument(err.str());
}
std::ofstream fpOut(szOutFilePath, std::ios::out | std::ios::binary);
if (!fpOut)
{
std::ostringstream err;
err << "Unable to open output file: " << szOutFilePath << std::endl;
throw std::invalid_argument(err.str());
}
NvEncoderGL enc(nWidth, nHeight, eFormat);
NV_ENC_INITIALIZE_PARAMS initializeParams = { NV_ENC_INITIALIZE_PARAMS_VER };
NV_ENC_CONFIG encodeConfig = { NV_ENC_CONFIG_VER };
initializeParams.encodeConfig = &encodeConfig;
enc.CreateDefaultEncoderParams(&initializeParams, encodeCLIOptions->GetEncodeGUID(),
encodeCLIOptions->GetPresetGUID(),encodeCLIOptions->GetTuningInfo());
encodeCLIOptions->SetInitParams(&initializeParams, eFormat);
enc.CreateEncoder(&initializeParams);
int nFrameSize = enc.GetFrameSize();
std::unique_ptr<uint8_t[]> pHostFrame(new uint8_t[nFrameSize]);
int nFrame = 0;
while (true)
{
std::streamsize nRead = fpIn.read(reinterpret_cast<char*>(pHostFrame.get()), nFrameSize).gcount();
const NvEncInputFrame* encoderInputFrame = enc.GetNextInputFrame();
NV_ENC_INPUT_RESOURCE_OPENGL_TEX *pResource = (NV_ENC_INPUT_RESOURCE_OPENGL_TEX *)encoderInputFrame->inputPtr;
glBindTexture(pResource->target, pResource->texture);
glTexSubImage2D(pResource->target, 0, 0, 0,
nWidth, nHeight * 3 / 2,
GL_RED, GL_UNSIGNED_BYTE, pHostFrame.get());
glBindTexture(pResource->target, 0);
std::vector<NvEncOutputFrame> vPacket;
if (nRead == nFrameSize)
{
enc.EncodeFrame(vPacket);
}
else
{
enc.EndEncode(vPacket);
}
nFrame += (int)vPacket.size();
for (NvEncOutputFrame &packet : vPacket)
{
fpOut.write(reinterpret_cast<char*>(packet.frame.data()), packet.frame.size());
}
if (nRead != nFrameSize) break;
}
enc.DestroyEncoder();
fpOut.close();
fpIn.close();
std::cout << "Total frames encoded: " << nFrame << std::endl;
std::cout << "Saved in file " << szOutFilePath << std::endl;
}
int main(int argc, char **argv)
{
char szInFilePath[256] = "",
szOutFilePath[256] = "",
contextType[4] = "glx";
int nWidth = 0, nHeight = 0;
NV_ENC_BUFFER_FORMAT eFormat = NV_ENC_BUFFER_FORMAT_IYUV;
NvEncoderInitParam encodeCLIOptions;
try
{
ParseCommandLine(argc, argv, szInFilePath, nWidth, nHeight, eFormat,
szOutFilePath, encodeCLIOptions, contextType);
GraphicsSetupWindow(contextType);
CheckInputFile(szInFilePath);
ValidateResolution(nWidth, nHeight);
if (!*szOutFilePath)
{
sprintf(szOutFilePath, encodeCLIOptions.IsCodecH264() ? "out.h264" : encodeCLIOptions.IsCodecHEVC() ? "out.hevc" : "out.av1");
}
EncodeGL(szInFilePath, szOutFilePath, nWidth, nHeight, eFormat, &encodeCLIOptions);
}
catch (const std::exception &e)
{
std::cout << e.what();
return 1;
}
GraphicsCloseWindow(contextType);
return 0;
}