texture-amf.cpp 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277
  1. #include <util/threading.h>
  2. #include <opts-parser.h>
  3. #include <obs-module.h>
  4. #include <obs-avc.h>
  5. #include "obs-ffmpeg-config.h"
  6. #include <unordered_map>
  7. #include <cstdlib>
  8. #include <memory>
  9. #include <string>
  10. #include <vector>
  11. #include <mutex>
  12. #include <deque>
  13. #include <map>
  14. #include "external/AMF/include/components/VideoEncoderHEVC.h"
  15. #include "external/AMF/include/components/VideoEncoderVCE.h"
  16. #include "external/AMF/include/components/VideoEncoderAV1.h"
  17. #include "external/AMF/include/core/Factory.h"
  18. #include "external/AMF/include/core/Trace.h"
  19. #include <dxgi.h>
  20. #include <d3d11.h>
  21. #include <d3d11_1.h>
  22. #include <util/windows/HRError.hpp>
  23. #include <util/windows/ComPtr.hpp>
  24. #include <util/platform.h>
  25. #include <util/util.hpp>
  26. #include <util/pipe.h>
  27. #include <util/dstr.h>
  28. using namespace amf;
  29. /* ========================================================================= */
  30. /* Junk */
  31. #define do_log(level, format, ...) \
  32. blog(level, "[%s: '%s'] " format, enc->encoder_str, \
  33. obs_encoder_get_name(enc->encoder), ##__VA_ARGS__)
  34. #define error(format, ...) do_log(LOG_ERROR, format, ##__VA_ARGS__)
  35. #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
  36. #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
  37. #define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
  38. struct amf_error {
  39. const char *str;
  40. AMF_RESULT res;
  41. inline amf_error(const char *str, AMF_RESULT res) : str(str), res(res)
  42. {
  43. }
  44. };
  45. struct handle_tex {
  46. uint32_t handle;
  47. ComPtr<ID3D11Texture2D> tex;
  48. ComPtr<IDXGIKeyedMutex> km;
  49. };
  50. struct adapter_caps {
  51. bool is_amd = false;
  52. bool supports_avc = false;
  53. bool supports_hevc = false;
  54. bool supports_av1 = false;
  55. };
  56. /* ------------------------------------------------------------------------- */
  57. static std::map<uint32_t, adapter_caps> caps;
  58. static bool h264_supported = false;
  59. static AMFFactory *amf_factory = nullptr;
  60. static AMFTrace *amf_trace = nullptr;
  61. static HMODULE amf_module = nullptr;
  62. static uint64_t amf_version = 0;
  63. /* ========================================================================= */
  64. /* Main Implementation */
  65. enum class amf_codec_type {
  66. AVC,
  67. HEVC,
  68. AV1,
  69. };
  70. struct amf_base {
  71. obs_encoder_t *encoder;
  72. const char *encoder_str;
  73. amf_codec_type codec;
  74. bool fallback;
  75. AMFContextPtr amf_context;
  76. AMFComponentPtr amf_encoder;
  77. AMFBufferPtr packet_data;
  78. AMFRate amf_frame_rate;
  79. AMFBufferPtr header;
  80. std::deque<AMFDataPtr> queued_packets;
  81. AMF_VIDEO_CONVERTER_COLOR_PROFILE_ENUM amf_color_profile;
  82. AMF_COLOR_TRANSFER_CHARACTERISTIC_ENUM amf_characteristic;
  83. AMF_COLOR_PRIMARIES_ENUM amf_primaries;
  84. AMF_SURFACE_FORMAT amf_format;
  85. amf_int64 max_throughput = 0;
  86. amf_int64 throughput = 0;
  87. int64_t dts_offset = 0;
  88. uint32_t cx;
  89. uint32_t cy;
  90. uint32_t linesize = 0;
  91. int fps_num;
  92. int fps_den;
  93. bool full_range;
  94. bool bframes_supported = false;
  95. bool first_update = true;
  96. inline amf_base(bool fallback) : fallback(fallback) {}
  97. virtual ~amf_base() = default;
  98. virtual void init() = 0;
  99. };
  100. using d3dtex_t = ComPtr<ID3D11Texture2D>;
  101. using buf_t = std::vector<uint8_t>;
  102. struct amf_texencode : amf_base, public AMFSurfaceObserver {
  103. volatile bool destroying = false;
  104. std::vector<handle_tex> input_textures;
  105. std::mutex textures_mutex;
  106. std::vector<d3dtex_t> available_textures;
  107. std::unordered_map<AMFSurface *, d3dtex_t> active_textures;
  108. ComPtr<ID3D11Device> device;
  109. ComPtr<ID3D11DeviceContext> context;
  110. inline amf_texencode() : amf_base(false) {}
  111. ~amf_texencode() { os_atomic_set_bool(&destroying, true); }
  112. void AMF_STD_CALL OnSurfaceDataRelease(amf::AMFSurface *surf) override
  113. {
  114. if (os_atomic_load_bool(&destroying))
  115. return;
  116. std::scoped_lock lock(textures_mutex);
  117. auto it = active_textures.find(surf);
  118. if (it != active_textures.end()) {
  119. available_textures.push_back(it->second);
  120. active_textures.erase(it);
  121. }
  122. }
  123. void init() override
  124. {
  125. AMF_RESULT res = amf_context->InitDX11(device, AMF_DX11_1);
  126. if (res != AMF_OK)
  127. throw amf_error("InitDX11 failed", res);
  128. }
  129. };
  130. struct amf_fallback : amf_base, public AMFSurfaceObserver {
  131. volatile bool destroying = false;
  132. std::mutex buffers_mutex;
  133. std::vector<buf_t> available_buffers;
  134. std::unordered_map<AMFSurface *, buf_t> active_buffers;
  135. inline amf_fallback() : amf_base(true) {}
  136. ~amf_fallback() { os_atomic_set_bool(&destroying, true); }
  137. void AMF_STD_CALL OnSurfaceDataRelease(amf::AMFSurface *surf) override
  138. {
  139. if (os_atomic_load_bool(&destroying))
  140. return;
  141. std::scoped_lock lock(buffers_mutex);
  142. auto it = active_buffers.find(surf);
  143. if (it != active_buffers.end()) {
  144. available_buffers.push_back(std::move(it->second));
  145. active_buffers.erase(it);
  146. }
  147. }
  148. void init() override
  149. {
  150. AMF_RESULT res = amf_context->InitDX11(nullptr, AMF_DX11_1);
  151. if (res != AMF_OK)
  152. throw amf_error("InitDX11 failed", res);
  153. }
  154. };
  155. /* ------------------------------------------------------------------------- */
  156. /* More garbage */
  157. template<typename T>
  158. static bool get_amf_property(amf_base *enc, const wchar_t *name, T *value)
  159. {
  160. AMF_RESULT res = enc->amf_encoder->GetProperty(name, value);
  161. return res == AMF_OK;
  162. }
  163. template<typename T>
  164. static void set_amf_property(amf_base *enc, const wchar_t *name, const T &value)
  165. {
  166. AMF_RESULT res = enc->amf_encoder->SetProperty(name, value);
  167. if (res != AMF_OK)
  168. error("Failed to set property '%ls': %ls", name,
  169. amf_trace->GetResultText(res));
  170. }
  171. #define set_avc_property(enc, name, value) \
  172. set_amf_property(enc, AMF_VIDEO_ENCODER_##name, value)
  173. #define set_hevc_property(enc, name, value) \
  174. set_amf_property(enc, AMF_VIDEO_ENCODER_HEVC_##name, value)
  175. #define set_av1_property(enc, name, value) \
  176. set_amf_property(enc, AMF_VIDEO_ENCODER_AV1_##name, value)
  177. #define get_avc_property(enc, name, value) \
  178. get_amf_property(enc, AMF_VIDEO_ENCODER_##name, value)
  179. #define get_hevc_property(enc, name, value) \
  180. get_amf_property(enc, AMF_VIDEO_ENCODER_HEVC_##name, value)
  181. #define get_av1_property(enc, name, value) \
  182. get_amf_property(enc, AMF_VIDEO_ENCODER_AV1_##name, value)
  183. #define get_opt_name(name) \
  184. ((enc->codec == amf_codec_type::AVC) ? AMF_VIDEO_ENCODER_##name \
  185. : (enc->codec == amf_codec_type::HEVC) \
  186. ? AMF_VIDEO_ENCODER_HEVC_##name \
  187. : AMF_VIDEO_ENCODER_AV1_##name)
  188. #define set_opt(name, value) set_amf_property(enc, get_opt_name(name), value)
  189. #define get_opt(name, value) get_amf_property(enc, get_opt_name(name), value)
  190. #define set_avc_opt(name, value) set_avc_property(enc, name, value)
  191. #define set_hevc_opt(name, value) set_hevc_property(enc, name, value)
  192. #define set_av1_opt(name, value) set_av1_property(enc, name, value)
  193. #define set_enum_opt(name, value) \
  194. set_amf_property(enc, get_opt_name(name), get_opt_name(name##_##value))
  195. #define set_avc_enum(name, value) \
  196. set_avc_property(enc, name, AMF_VIDEO_ENCODER_##name##_##value)
  197. #define set_hevc_enum(name, value) \
  198. set_hevc_property(enc, name, AMF_VIDEO_ENCODER_HEVC_##name##_##value)
  199. #define set_av1_enum(name, value) \
  200. set_av1_property(enc, name, AMF_VIDEO_ENCODER_AV1_##name##_##value)
  201. /* ------------------------------------------------------------------------- */
  202. /* Implementation */
  203. static HMODULE get_lib(const char *lib)
  204. {
  205. HMODULE mod = GetModuleHandleA(lib);
  206. if (mod)
  207. return mod;
  208. return LoadLibraryA(lib);
  209. }
  210. #define AMD_VENDOR_ID 0x1002
  211. typedef HRESULT(WINAPI *CREATEDXGIFACTORY1PROC)(REFIID, void **);
  212. static bool amf_init_d3d11(amf_texencode *enc)
  213. try {
  214. HMODULE dxgi = get_lib("DXGI.dll");
  215. HMODULE d3d11 = get_lib("D3D11.dll");
  216. CREATEDXGIFACTORY1PROC create_dxgi;
  217. PFN_D3D11_CREATE_DEVICE create_device;
  218. ComPtr<IDXGIFactory> factory;
  219. ComPtr<ID3D11Device> device;
  220. ComPtr<ID3D11DeviceContext> context;
  221. ComPtr<IDXGIAdapter> adapter;
  222. DXGI_ADAPTER_DESC desc;
  223. HRESULT hr;
  224. if (!dxgi || !d3d11)
  225. throw "Couldn't get D3D11/DXGI libraries? "
  226. "That definitely shouldn't be possible.";
  227. create_dxgi = (CREATEDXGIFACTORY1PROC)GetProcAddress(
  228. dxgi, "CreateDXGIFactory1");
  229. create_device = (PFN_D3D11_CREATE_DEVICE)GetProcAddress(
  230. d3d11, "D3D11CreateDevice");
  231. if (!create_dxgi || !create_device)
  232. throw "Failed to load D3D11/DXGI procedures";
  233. hr = create_dxgi(__uuidof(IDXGIFactory2), (void **)&factory);
  234. if (FAILED(hr))
  235. throw HRError("CreateDXGIFactory1 failed", hr);
  236. obs_video_info ovi;
  237. obs_get_video_info(&ovi);
  238. hr = factory->EnumAdapters(ovi.adapter, &adapter);
  239. if (FAILED(hr))
  240. throw HRError("EnumAdapters failed", hr);
  241. adapter->GetDesc(&desc);
  242. if (desc.VendorId != AMD_VENDOR_ID)
  243. throw "Seems somehow AMF is trying to initialize "
  244. "on a non-AMD adapter";
  245. hr = create_device(adapter, D3D_DRIVER_TYPE_UNKNOWN, nullptr, 0,
  246. nullptr, 0, D3D11_SDK_VERSION, &device, nullptr,
  247. &context);
  248. if (FAILED(hr))
  249. throw HRError("D3D11CreateDevice failed", hr);
  250. enc->device = device;
  251. enc->context = context;
  252. return true;
  253. } catch (const HRError &err) {
  254. error("%s: %s: 0x%lX", __FUNCTION__, err.str, err.hr);
  255. return false;
  256. } catch (const char *err) {
  257. error("%s: %s", __FUNCTION__, err);
  258. return false;
  259. }
  260. static void add_output_tex(amf_texencode *enc,
  261. ComPtr<ID3D11Texture2D> &output_tex,
  262. ID3D11Texture2D *from)
  263. {
  264. ID3D11Device *device = enc->device;
  265. HRESULT hr;
  266. D3D11_TEXTURE2D_DESC desc;
  267. from->GetDesc(&desc);
  268. desc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
  269. desc.MiscFlags = 0;
  270. hr = device->CreateTexture2D(&desc, nullptr, &output_tex);
  271. if (FAILED(hr))
  272. throw HRError("Failed to create texture", hr);
  273. }
  274. static inline bool get_available_tex(amf_texencode *enc,
  275. ComPtr<ID3D11Texture2D> &output_tex)
  276. {
  277. std::scoped_lock lock(enc->textures_mutex);
  278. if (enc->available_textures.size()) {
  279. output_tex = enc->available_textures.back();
  280. enc->available_textures.pop_back();
  281. return true;
  282. }
  283. return false;
  284. }
  285. static inline void get_output_tex(amf_texencode *enc,
  286. ComPtr<ID3D11Texture2D> &output_tex,
  287. ID3D11Texture2D *from)
  288. {
  289. if (!get_available_tex(enc, output_tex))
  290. add_output_tex(enc, output_tex, from);
  291. }
  292. static void get_tex_from_handle(amf_texencode *enc, uint32_t handle,
  293. IDXGIKeyedMutex **km_out,
  294. ID3D11Texture2D **tex_out)
  295. {
  296. ID3D11Device *device = enc->device;
  297. ComPtr<ID3D11Texture2D> tex;
  298. HRESULT hr;
  299. for (size_t i = 0; i < enc->input_textures.size(); i++) {
  300. struct handle_tex &ht = enc->input_textures[i];
  301. if (ht.handle == handle) {
  302. ht.km.CopyTo(km_out);
  303. ht.tex.CopyTo(tex_out);
  304. return;
  305. }
  306. }
  307. hr = device->OpenSharedResource((HANDLE)(uintptr_t)handle,
  308. __uuidof(ID3D11Resource),
  309. (void **)&tex);
  310. if (FAILED(hr))
  311. throw HRError("OpenSharedResource failed", hr);
  312. ComQIPtr<IDXGIKeyedMutex> km(tex);
  313. if (!km)
  314. throw "QueryInterface(IDXGIKeyedMutex) failed";
  315. tex->SetEvictionPriority(DXGI_RESOURCE_PRIORITY_MAXIMUM);
  316. struct handle_tex new_ht = {handle, tex, km};
  317. enc->input_textures.push_back(std::move(new_ht));
  318. *km_out = km.Detach();
  319. *tex_out = tex.Detach();
  320. }
  321. static constexpr amf_int64 macroblock_size = 16;
  322. static inline void calc_throughput(amf_base *enc)
  323. {
  324. amf_int64 mb_cx =
  325. ((amf_int64)enc->cx + (macroblock_size - 1)) / macroblock_size;
  326. amf_int64 mb_cy =
  327. ((amf_int64)enc->cy + (macroblock_size - 1)) / macroblock_size;
  328. amf_int64 mb_frame = mb_cx * mb_cy;
  329. enc->throughput =
  330. mb_frame * (amf_int64)enc->fps_num / (amf_int64)enc->fps_den;
  331. }
  332. static inline int get_avc_preset(amf_base *enc, const char *preset);
  333. #if ENABLE_HEVC
  334. static inline int get_hevc_preset(amf_base *enc, const char *preset);
  335. #endif
  336. static inline int get_av1_preset(amf_base *enc, const char *preset);
  337. static inline int get_preset(amf_base *enc, const char *preset)
  338. {
  339. if (enc->codec == amf_codec_type::AVC)
  340. return get_avc_preset(enc, preset);
  341. #if ENABLE_HEVC
  342. else if (enc->codec == amf_codec_type::HEVC)
  343. return get_hevc_preset(enc, preset);
  344. #endif
  345. else if (enc->codec == amf_codec_type::AV1)
  346. return get_av1_preset(enc, preset);
  347. return 0;
  348. }
  349. static inline void refresh_throughput_caps(amf_base *enc, const char *&preset)
  350. {
  351. AMF_RESULT res = AMF_OK;
  352. AMFCapsPtr caps;
  353. set_opt(QUALITY_PRESET, get_preset(enc, preset));
  354. res = enc->amf_encoder->GetCaps(&caps);
  355. if (res == AMF_OK) {
  356. caps->GetProperty(get_opt_name(CAP_MAX_THROUGHPUT),
  357. &enc->max_throughput);
  358. }
  359. }
  360. static inline void check_preset_compatibility(amf_base *enc,
  361. const char *&preset)
  362. {
  363. /* The throughput depends on the current preset and the other static
  364. * encoder properties. If the throughput is lower than the max
  365. * throughput, switch to a lower preset. */
  366. if (astrcmpi(preset, "highQuality") == 0) {
  367. if (!enc->max_throughput) {
  368. preset = "quality";
  369. set_opt(QUALITY_PRESET, get_preset(enc, preset));
  370. } else {
  371. if (enc->max_throughput < enc->throughput) {
  372. preset = "quality";
  373. refresh_throughput_caps(enc, preset);
  374. }
  375. }
  376. }
  377. if (astrcmpi(preset, "quality") == 0) {
  378. if (!enc->max_throughput) {
  379. preset = "balanced";
  380. set_opt(QUALITY_PRESET, get_preset(enc, preset));
  381. } else {
  382. if (enc->max_throughput < enc->throughput) {
  383. preset = "balanced";
  384. refresh_throughput_caps(enc, preset);
  385. }
  386. }
  387. }
  388. if (astrcmpi(preset, "balanced") == 0) {
  389. if (enc->max_throughput &&
  390. enc->max_throughput < enc->throughput) {
  391. preset = "speed";
  392. refresh_throughput_caps(enc, preset);
  393. }
  394. }
  395. }
  396. static inline int64_t convert_to_amf_ts(amf_base *enc, int64_t ts)
  397. {
  398. constexpr int64_t amf_timebase = AMF_SECOND;
  399. return ts * amf_timebase / (int64_t)enc->fps_den;
  400. }
  401. static inline int64_t convert_to_obs_ts(amf_base *enc, int64_t ts)
  402. {
  403. constexpr int64_t amf_timebase = AMF_SECOND;
  404. return ts * (int64_t)enc->fps_den / amf_timebase;
  405. }
  406. static void convert_to_encoder_packet(amf_base *enc, AMFDataPtr &data,
  407. encoder_packet *packet)
  408. {
  409. if (!data)
  410. return;
  411. enc->packet_data = AMFBufferPtr(data);
  412. data->GetProperty(L"PTS", &packet->pts);
  413. const wchar_t *get_output_type;
  414. switch (enc->codec) {
  415. case amf_codec_type::AVC:
  416. get_output_type = AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE;
  417. break;
  418. case amf_codec_type::HEVC:
  419. get_output_type = AMF_VIDEO_ENCODER_HEVC_OUTPUT_DATA_TYPE;
  420. break;
  421. case amf_codec_type::AV1:
  422. get_output_type = AMF_VIDEO_ENCODER_AV1_OUTPUT_FRAME_TYPE;
  423. break;
  424. }
  425. uint64_t type = 0;
  426. AMF_RESULT res = data->GetProperty(get_output_type, &type);
  427. if (res != AMF_OK)
  428. throw amf_error("Failed to GetProperty(): encoder output "
  429. "data type",
  430. res);
  431. if (enc->codec == amf_codec_type::AVC ||
  432. enc->codec == amf_codec_type::HEVC) {
  433. switch (type) {
  434. case AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_IDR:
  435. packet->priority = OBS_NAL_PRIORITY_HIGHEST;
  436. break;
  437. case AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_I:
  438. packet->priority = OBS_NAL_PRIORITY_HIGH;
  439. break;
  440. case AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_P:
  441. packet->priority = OBS_NAL_PRIORITY_LOW;
  442. break;
  443. case AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_B:
  444. packet->priority = OBS_NAL_PRIORITY_DISPOSABLE;
  445. break;
  446. }
  447. } else if (enc->codec == amf_codec_type::AV1) {
  448. switch (type) {
  449. case AMF_VIDEO_ENCODER_AV1_OUTPUT_FRAME_TYPE_KEY:
  450. packet->priority = OBS_NAL_PRIORITY_HIGHEST;
  451. break;
  452. case AMF_VIDEO_ENCODER_AV1_OUTPUT_FRAME_TYPE_INTRA_ONLY:
  453. packet->priority = OBS_NAL_PRIORITY_HIGH;
  454. break;
  455. case AMF_VIDEO_ENCODER_AV1_OUTPUT_FRAME_TYPE_INTER:
  456. packet->priority = OBS_NAL_PRIORITY_LOW;
  457. break;
  458. case AMF_VIDEO_ENCODER_AV1_OUTPUT_FRAME_TYPE_SWITCH:
  459. packet->priority = OBS_NAL_PRIORITY_DISPOSABLE;
  460. break;
  461. case AMF_VIDEO_ENCODER_AV1_OUTPUT_FRAME_TYPE_SHOW_EXISTING:
  462. packet->priority = OBS_NAL_PRIORITY_DISPOSABLE;
  463. break;
  464. }
  465. }
  466. packet->data = (uint8_t *)enc->packet_data->GetNative();
  467. packet->size = enc->packet_data->GetSize();
  468. packet->type = OBS_ENCODER_VIDEO;
  469. packet->dts = convert_to_obs_ts(enc, data->GetPts());
  470. packet->keyframe = type == AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_IDR;
  471. if (enc->dts_offset)
  472. packet->dts -= enc->dts_offset;
  473. }
  474. #ifndef SEC_TO_NSEC
  475. #define SEC_TO_NSEC 1000000000ULL
  476. #endif
  477. static void amf_encode_base(amf_base *enc, AMFSurface *amf_surf,
  478. encoder_packet *packet, bool *received_packet)
  479. {
  480. auto &queued_packets = enc->queued_packets;
  481. uint64_t ts_start = os_gettime_ns();
  482. AMF_RESULT res;
  483. *received_packet = false;
  484. bool waiting = true;
  485. while (waiting) {
  486. /* ----------------------------------- */
  487. /* submit frame */
  488. res = enc->amf_encoder->SubmitInput(amf_surf);
  489. if (res == AMF_OK || res == AMF_NEED_MORE_INPUT) {
  490. waiting = false;
  491. } else if (res == AMF_INPUT_FULL) {
  492. os_sleep_ms(1);
  493. uint64_t duration = os_gettime_ns() - ts_start;
  494. constexpr uint64_t timeout = 5 * SEC_TO_NSEC;
  495. if (duration >= timeout) {
  496. throw amf_error("SubmitInput timed out", res);
  497. }
  498. } else {
  499. throw amf_error("SubmitInput failed", res);
  500. }
  501. /* ----------------------------------- */
  502. /* query as many packets as possible */
  503. AMFDataPtr new_packet;
  504. do {
  505. res = enc->amf_encoder->QueryOutput(&new_packet);
  506. if (new_packet)
  507. queued_packets.push_back(new_packet);
  508. if (res != AMF_REPEAT && res != AMF_OK) {
  509. throw amf_error("QueryOutput failed", res);
  510. }
  511. } while (!!new_packet);
  512. }
  513. /* ----------------------------------- */
  514. /* return a packet if available */
  515. if (queued_packets.size()) {
  516. AMFDataPtr amf_out;
  517. amf_out = queued_packets.front();
  518. queued_packets.pop_front();
  519. *received_packet = true;
  520. convert_to_encoder_packet(enc, amf_out, packet);
  521. }
  522. }
  523. static bool amf_encode_tex(void *data, uint32_t handle, int64_t pts,
  524. uint64_t lock_key, uint64_t *next_key,
  525. encoder_packet *packet, bool *received_packet)
  526. try {
  527. amf_texencode *enc = (amf_texencode *)data;
  528. ID3D11DeviceContext *context = enc->context;
  529. ComPtr<ID3D11Texture2D> output_tex;
  530. ComPtr<ID3D11Texture2D> input_tex;
  531. ComPtr<IDXGIKeyedMutex> km;
  532. AMFSurfacePtr amf_surf;
  533. AMF_RESULT res;
  534. if (handle == GS_INVALID_HANDLE) {
  535. *next_key = lock_key;
  536. throw "Encode failed: bad texture handle";
  537. }
  538. /* ------------------------------------ */
  539. /* get the input tex */
  540. get_tex_from_handle(enc, handle, &km, &input_tex);
  541. /* ------------------------------------ */
  542. /* get an output tex */
  543. get_output_tex(enc, output_tex, input_tex);
  544. /* ------------------------------------ */
  545. /* copy to output tex */
  546. km->AcquireSync(lock_key, INFINITE);
  547. context->CopyResource((ID3D11Resource *)output_tex.Get(),
  548. (ID3D11Resource *)input_tex.Get());
  549. context->Flush();
  550. km->ReleaseSync(*next_key);
  551. /* ------------------------------------ */
  552. /* map output tex to amf surface */
  553. res = enc->amf_context->CreateSurfaceFromDX11Native(output_tex,
  554. &amf_surf, enc);
  555. if (res != AMF_OK)
  556. throw amf_error("CreateSurfaceFromDX11Native failed", res);
  557. int64_t last_ts = convert_to_amf_ts(enc, pts - 1);
  558. int64_t cur_ts = convert_to_amf_ts(enc, pts);
  559. amf_surf->SetPts(cur_ts);
  560. amf_surf->SetProperty(L"PTS", pts);
  561. {
  562. std::scoped_lock lock(enc->textures_mutex);
  563. enc->active_textures[amf_surf.GetPtr()] = output_tex;
  564. }
  565. /* ------------------------------------ */
  566. /* do actual encode */
  567. amf_encode_base(enc, amf_surf, packet, received_packet);
  568. return true;
  569. } catch (const char *err) {
  570. amf_texencode *enc = (amf_texencode *)data;
  571. error("%s: %s", __FUNCTION__, err);
  572. return false;
  573. } catch (const amf_error &err) {
  574. amf_texencode *enc = (amf_texencode *)data;
  575. error("%s: %s: %ls", __FUNCTION__, err.str,
  576. amf_trace->GetResultText(err.res));
  577. *received_packet = false;
  578. return false;
  579. } catch (const HRError &err) {
  580. amf_texencode *enc = (amf_texencode *)data;
  581. error("%s: %s: 0x%lX", __FUNCTION__, err.str, err.hr);
  582. *received_packet = false;
  583. return false;
  584. }
  585. static buf_t alloc_buf(amf_fallback *enc)
  586. {
  587. buf_t buf;
  588. size_t size;
  589. if (enc->amf_format == AMF_SURFACE_NV12) {
  590. size = enc->linesize * enc->cy * 2;
  591. } else if (enc->amf_format == AMF_SURFACE_RGBA) {
  592. size = enc->linesize * enc->cy * 4;
  593. } else if (enc->amf_format == AMF_SURFACE_P010) {
  594. size = enc->linesize * enc->cy * 2 * 2;
  595. } else {
  596. throw "Invalid amf_format";
  597. }
  598. buf.resize(size);
  599. return buf;
  600. }
  601. static buf_t get_buf(amf_fallback *enc)
  602. {
  603. std::scoped_lock lock(enc->buffers_mutex);
  604. buf_t buf;
  605. if (enc->available_buffers.size()) {
  606. buf = std::move(enc->available_buffers.back());
  607. enc->available_buffers.pop_back();
  608. } else {
  609. buf = alloc_buf(enc);
  610. }
  611. return buf;
  612. }
  613. static inline void copy_frame_data(amf_fallback *enc, buf_t &buf,
  614. struct encoder_frame *frame)
  615. {
  616. uint8_t *dst = &buf[0];
  617. if (enc->amf_format == AMF_SURFACE_NV12 ||
  618. enc->amf_format == AMF_SURFACE_P010) {
  619. size_t size = enc->linesize * enc->cy;
  620. memcpy(&buf[0], frame->data[0], size);
  621. memcpy(&buf[size], frame->data[1], size / 2);
  622. } else if (enc->amf_format == AMF_SURFACE_RGBA) {
  623. memcpy(dst, frame->data[0], enc->linesize * enc->cy);
  624. }
  625. }
  626. static bool amf_encode_fallback(void *data, struct encoder_frame *frame,
  627. struct encoder_packet *packet,
  628. bool *received_packet)
  629. try {
  630. amf_fallback *enc = (amf_fallback *)data;
  631. AMFSurfacePtr amf_surf;
  632. AMF_RESULT res;
  633. buf_t buf;
  634. if (!enc->linesize)
  635. enc->linesize = frame->linesize[0];
  636. buf = get_buf(enc);
  637. copy_frame_data(enc, buf, frame);
  638. res = enc->amf_context->CreateSurfaceFromHostNative(
  639. enc->amf_format, enc->cx, enc->cy, enc->linesize, 0, &buf[0],
  640. &amf_surf, enc);
  641. if (res != AMF_OK)
  642. throw amf_error("CreateSurfaceFromHostNative failed", res);
  643. int64_t last_ts = convert_to_amf_ts(enc, frame->pts - 1);
  644. int64_t cur_ts = convert_to_amf_ts(enc, frame->pts);
  645. amf_surf->SetPts(cur_ts);
  646. amf_surf->SetProperty(L"PTS", frame->pts);
  647. {
  648. std::scoped_lock lock(enc->buffers_mutex);
  649. enc->active_buffers[amf_surf.GetPtr()] = std::move(buf);
  650. }
  651. /* ------------------------------------ */
  652. /* do actual encode */
  653. amf_encode_base(enc, amf_surf, packet, received_packet);
  654. return true;
  655. } catch (const amf_error &err) {
  656. amf_fallback *enc = (amf_fallback *)data;
  657. error("%s: %s: %ls", __FUNCTION__, err.str,
  658. amf_trace->GetResultText(err.res));
  659. *received_packet = false;
  660. return false;
  661. } catch (const char *err) {
  662. amf_fallback *enc = (amf_fallback *)data;
  663. error("%s: %s", __FUNCTION__, err);
  664. *received_packet = false;
  665. return false;
  666. }
  667. static bool amf_extra_data(void *data, uint8_t **header, size_t *size)
  668. {
  669. amf_base *enc = (amf_base *)data;
  670. if (!enc->header)
  671. return false;
  672. *header = (uint8_t *)enc->header->GetNative();
  673. *size = enc->header->GetSize();
  674. return true;
  675. }
  676. static void h264_video_info_fallback(void *, struct video_scale_info *info)
  677. {
  678. switch (info->format) {
  679. case VIDEO_FORMAT_RGBA:
  680. case VIDEO_FORMAT_BGRA:
  681. case VIDEO_FORMAT_BGRX:
  682. info->format = VIDEO_FORMAT_RGBA;
  683. break;
  684. default:
  685. info->format = VIDEO_FORMAT_NV12;
  686. break;
  687. }
  688. }
  689. static void h265_video_info_fallback(void *, struct video_scale_info *info)
  690. {
  691. switch (info->format) {
  692. case VIDEO_FORMAT_RGBA:
  693. case VIDEO_FORMAT_BGRA:
  694. case VIDEO_FORMAT_BGRX:
  695. info->format = VIDEO_FORMAT_RGBA;
  696. break;
  697. case VIDEO_FORMAT_I010:
  698. case VIDEO_FORMAT_P010:
  699. info->format = VIDEO_FORMAT_P010;
  700. break;
  701. default:
  702. info->format = VIDEO_FORMAT_NV12;
  703. }
  704. }
  705. static void av1_video_info_fallback(void *, struct video_scale_info *info)
  706. {
  707. switch (info->format) {
  708. case VIDEO_FORMAT_RGBA:
  709. case VIDEO_FORMAT_BGRA:
  710. case VIDEO_FORMAT_BGRX:
  711. info->format = VIDEO_FORMAT_RGBA;
  712. break;
  713. case VIDEO_FORMAT_I010:
  714. case VIDEO_FORMAT_P010:
  715. info->format = VIDEO_FORMAT_P010;
  716. break;
  717. default:
  718. info->format = VIDEO_FORMAT_NV12;
  719. }
  720. }
  721. static bool amf_create_encoder(amf_base *enc)
  722. try {
  723. AMF_RESULT res;
  724. /* ------------------------------------ */
  725. /* get video info */
  726. struct obs_video_info ovi;
  727. obs_get_video_info(&ovi);
  728. struct video_scale_info info;
  729. info.format = ovi.output_format;
  730. info.colorspace = ovi.colorspace;
  731. info.range = ovi.range;
  732. if (enc->fallback) {
  733. if (enc->codec == amf_codec_type::AVC)
  734. h264_video_info_fallback(NULL, &info);
  735. else if (enc->codec == amf_codec_type::HEVC)
  736. h265_video_info_fallback(NULL, &info);
  737. else
  738. av1_video_info_fallback(NULL, &info);
  739. }
  740. enc->cx = obs_encoder_get_width(enc->encoder);
  741. enc->cy = obs_encoder_get_height(enc->encoder);
  742. enc->amf_frame_rate = AMFConstructRate(ovi.fps_num, ovi.fps_den);
  743. enc->fps_num = (int)ovi.fps_num;
  744. enc->fps_den = (int)ovi.fps_den;
  745. enc->full_range = info.range == VIDEO_RANGE_FULL;
  746. switch (info.colorspace) {
  747. case VIDEO_CS_601:
  748. enc->amf_color_profile =
  749. enc->full_range
  750. ? AMF_VIDEO_CONVERTER_COLOR_PROFILE_FULL_601
  751. : AMF_VIDEO_CONVERTER_COLOR_PROFILE_601;
  752. enc->amf_primaries = AMF_COLOR_PRIMARIES_SMPTE170M;
  753. enc->amf_characteristic =
  754. AMF_COLOR_TRANSFER_CHARACTERISTIC_SMPTE170M;
  755. break;
  756. case VIDEO_CS_DEFAULT:
  757. case VIDEO_CS_709:
  758. enc->amf_color_profile =
  759. enc->full_range
  760. ? AMF_VIDEO_CONVERTER_COLOR_PROFILE_FULL_709
  761. : AMF_VIDEO_CONVERTER_COLOR_PROFILE_709;
  762. enc->amf_primaries = AMF_COLOR_PRIMARIES_BT709;
  763. enc->amf_characteristic =
  764. AMF_COLOR_TRANSFER_CHARACTERISTIC_BT709;
  765. break;
  766. case VIDEO_CS_SRGB:
  767. enc->amf_color_profile =
  768. enc->full_range
  769. ? AMF_VIDEO_CONVERTER_COLOR_PROFILE_FULL_709
  770. : AMF_VIDEO_CONVERTER_COLOR_PROFILE_709;
  771. enc->amf_primaries = AMF_COLOR_PRIMARIES_BT709;
  772. enc->amf_characteristic =
  773. AMF_COLOR_TRANSFER_CHARACTERISTIC_IEC61966_2_1;
  774. break;
  775. case VIDEO_CS_2100_HLG:
  776. enc->amf_color_profile =
  777. enc->full_range
  778. ? AMF_VIDEO_CONVERTER_COLOR_PROFILE_FULL_2020
  779. : AMF_VIDEO_CONVERTER_COLOR_PROFILE_2020;
  780. enc->amf_primaries = AMF_COLOR_PRIMARIES_BT2020;
  781. enc->amf_characteristic =
  782. AMF_COLOR_TRANSFER_CHARACTERISTIC_ARIB_STD_B67;
  783. break;
  784. case VIDEO_CS_2100_PQ:
  785. enc->amf_color_profile =
  786. enc->full_range
  787. ? AMF_VIDEO_CONVERTER_COLOR_PROFILE_FULL_2020
  788. : AMF_VIDEO_CONVERTER_COLOR_PROFILE_2020;
  789. enc->amf_primaries = AMF_COLOR_PRIMARIES_BT2020;
  790. enc->amf_characteristic =
  791. AMF_COLOR_TRANSFER_CHARACTERISTIC_SMPTE2084;
  792. break;
  793. }
  794. switch (info.format) {
  795. case VIDEO_FORMAT_NV12:
  796. enc->amf_format = AMF_SURFACE_NV12;
  797. break;
  798. case VIDEO_FORMAT_P010:
  799. enc->amf_format = AMF_SURFACE_P010;
  800. break;
  801. case VIDEO_FORMAT_RGBA:
  802. enc->amf_format = AMF_SURFACE_RGBA;
  803. break;
  804. }
  805. /* ------------------------------------ */
  806. /* create encoder */
  807. res = amf_factory->CreateContext(&enc->amf_context);
  808. if (res != AMF_OK)
  809. throw amf_error("CreateContext failed", res);
  810. enc->init();
  811. const wchar_t *codec = nullptr;
  812. switch (enc->codec) {
  813. case (amf_codec_type::AVC):
  814. codec = AMFVideoEncoderVCE_AVC;
  815. break;
  816. case (amf_codec_type::HEVC):
  817. codec = AMFVideoEncoder_HEVC;
  818. break;
  819. case (amf_codec_type::AV1):
  820. codec = AMFVideoEncoder_AV1;
  821. break;
  822. default:
  823. codec = AMFVideoEncoder_HEVC;
  824. }
  825. res = amf_factory->CreateComponent(enc->amf_context, codec,
  826. &enc->amf_encoder);
  827. if (res != AMF_OK)
  828. throw amf_error("CreateComponent failed", res);
  829. calc_throughput(enc);
  830. return true;
  831. } catch (const amf_error &err) {
  832. error("%s: %s: %ls", __FUNCTION__, err.str,
  833. amf_trace->GetResultText(err.res));
  834. return false;
  835. }
  836. static void amf_destroy(void *data)
  837. {
  838. amf_base *enc = (amf_base *)data;
  839. delete enc;
  840. }
  841. static void check_texture_encode_capability(obs_encoder_t *encoder,
  842. amf_codec_type codec)
  843. {
  844. obs_video_info ovi;
  845. obs_get_video_info(&ovi);
  846. bool avc = amf_codec_type::AVC == codec;
  847. bool hevc = amf_codec_type::HEVC == codec;
  848. bool av1 = amf_codec_type::AV1 == codec;
  849. if (obs_encoder_scaling_enabled(encoder))
  850. throw "Encoder scaling is active";
  851. if (hevc || av1) {
  852. if (!obs_nv12_tex_active() && !obs_p010_tex_active())
  853. throw "NV12/P010 textures aren't active";
  854. } else if (!obs_nv12_tex_active()) {
  855. throw "NV12 textures aren't active";
  856. }
  857. video_t *video = obs_encoder_video(encoder);
  858. const struct video_output_info *voi = video_output_get_info(video);
  859. switch (voi->format) {
  860. case VIDEO_FORMAT_I010:
  861. case VIDEO_FORMAT_P010:
  862. break;
  863. default:
  864. switch (voi->colorspace) {
  865. case VIDEO_CS_2100_PQ:
  866. case VIDEO_CS_2100_HLG:
  867. throw "OBS does not support 8-bit output of Rec. 2100";
  868. }
  869. }
  870. if ((avc && !caps[ovi.adapter].supports_avc) ||
  871. (hevc && !caps[ovi.adapter].supports_hevc) ||
  872. (av1 && !caps[ovi.adapter].supports_av1))
  873. throw "Wrong adapter";
  874. }
  875. #include "texture-amf-opts.hpp"
  876. static void amf_defaults(obs_data_t *settings)
  877. {
  878. obs_data_set_default_int(settings, "bitrate", 2500);
  879. obs_data_set_default_int(settings, "cqp", 20);
  880. obs_data_set_default_string(settings, "rate_control", "CBR");
  881. obs_data_set_default_string(settings, "preset", "quality");
  882. obs_data_set_default_string(settings, "profile", "high");
  883. }
  884. static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p,
  885. obs_data_t *settings)
  886. {
  887. const char *rc = obs_data_get_string(settings, "rate_control");
  888. bool cqp = astrcmpi(rc, "CQP") == 0;
  889. p = obs_properties_get(ppts, "bitrate");
  890. obs_property_set_visible(p, !cqp);
  891. p = obs_properties_get(ppts, "cqp");
  892. obs_property_set_visible(p, cqp);
  893. return true;
  894. }
  895. static obs_properties_t *amf_properties_internal(amf_codec_type codec)
  896. {
  897. obs_properties_t *props = obs_properties_create();
  898. obs_property_t *p;
  899. p = obs_properties_add_list(props, "rate_control",
  900. obs_module_text("RateControl"),
  901. OBS_COMBO_TYPE_LIST,
  902. OBS_COMBO_FORMAT_STRING);
  903. obs_property_list_add_string(p, "CBR", "CBR");
  904. obs_property_list_add_string(p, "CQP", "CQP");
  905. obs_property_list_add_string(p, "VBR", "VBR");
  906. if (amf_codec_type::AV1 == codec) {
  907. obs_property_list_add_string(p, "VBR_LAT", "VBR_LAT");
  908. obs_property_list_add_string(p, "QVBR", "QVBR");
  909. obs_property_list_add_string(p, "HQVBR", "HQVBR");
  910. obs_property_list_add_string(p, "HQCBR", "HQCBR");
  911. }
  912. obs_property_set_modified_callback(p, rate_control_modified);
  913. p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"),
  914. 50, 100000, 50);
  915. obs_property_int_set_suffix(p, " Kbps");
  916. obs_properties_add_int(props, "cqp", obs_module_text("NVENC.CQLevel"),
  917. 0, codec == amf_codec_type::AV1 ? 63 : 51, 1);
  918. p = obs_properties_add_int(props, "keyint_sec",
  919. obs_module_text("KeyframeIntervalSec"), 0,
  920. 10, 1);
  921. obs_property_int_set_suffix(p, " s");
  922. p = obs_properties_add_list(props, "preset", obs_module_text("Preset"),
  923. OBS_COMBO_TYPE_LIST,
  924. OBS_COMBO_FORMAT_STRING);
  925. #define add_preset(val) \
  926. obs_property_list_add_string(p, obs_module_text("AMF.Preset." val), val)
  927. if (amf_codec_type::AV1 == codec) {
  928. add_preset("highQuality");
  929. }
  930. add_preset("quality");
  931. add_preset("balanced");
  932. add_preset("speed");
  933. #undef add_preset
  934. if (amf_codec_type::AVC == codec || amf_codec_type::AV1 == codec) {
  935. p = obs_properties_add_list(props, "profile",
  936. obs_module_text("Profile"),
  937. OBS_COMBO_TYPE_LIST,
  938. OBS_COMBO_FORMAT_STRING);
  939. #define add_profile(val) obs_property_list_add_string(p, val, val)
  940. if (amf_codec_type::AVC == codec)
  941. add_profile("high");
  942. add_profile("main");
  943. if (amf_codec_type::AVC == codec)
  944. add_profile("baseline");
  945. #undef add_profile
  946. }
  947. if (amf_codec_type::AVC == codec) {
  948. obs_properties_add_int(props, "bf", obs_module_text("BFrames"),
  949. 0, 5, 1);
  950. }
  951. p = obs_properties_add_text(props, "ffmpeg_opts",
  952. obs_module_text("AMFOpts"),
  953. OBS_TEXT_DEFAULT);
  954. obs_property_set_long_description(p,
  955. obs_module_text("AMFOpts.ToolTip"));
  956. return props;
  957. }
  958. static obs_properties_t *amf_avc_properties(void *unused)
  959. {
  960. UNUSED_PARAMETER(unused);
  961. return amf_properties_internal(amf_codec_type::AVC);
  962. }
  963. static obs_properties_t *amf_hevc_properties(void *unused)
  964. {
  965. UNUSED_PARAMETER(unused);
  966. return amf_properties_internal(amf_codec_type::HEVC);
  967. }
  968. static obs_properties_t *amf_av1_properties(void *unused)
  969. {
  970. UNUSED_PARAMETER(unused);
  971. return amf_properties_internal(amf_codec_type::AV1);
  972. }
  973. /* ========================================================================= */
  974. /* AVC Implementation */
  975. static const char *amf_avc_get_name(void *)
  976. {
  977. return "AMD HW H.264 (AVC)";
  978. }
  979. static inline int get_avc_preset(amf_base *enc, const char *preset)
  980. {
  981. if (astrcmpi(preset, "quality") == 0)
  982. return AMF_VIDEO_ENCODER_QUALITY_PRESET_QUALITY;
  983. else if (astrcmpi(preset, "speed") == 0)
  984. return AMF_VIDEO_ENCODER_QUALITY_PRESET_SPEED;
  985. return AMF_VIDEO_ENCODER_QUALITY_PRESET_BALANCED;
  986. }
  987. static inline int get_avc_rate_control(const char *rc_str)
  988. {
  989. if (astrcmpi(rc_str, "cqp") == 0)
  990. return AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CONSTANT_QP;
  991. else if (astrcmpi(rc_str, "vbr") == 0)
  992. return AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR;
  993. return AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CBR;
  994. }
  995. static inline int get_avc_profile(obs_data_t *settings)
  996. {
  997. const char *profile = obs_data_get_string(settings, "profile");
  998. if (astrcmpi(profile, "baseline") == 0)
  999. return AMF_VIDEO_ENCODER_PROFILE_BASELINE;
  1000. else if (astrcmpi(profile, "main") == 0)
  1001. return AMF_VIDEO_ENCODER_PROFILE_MAIN;
  1002. else if (astrcmpi(profile, "constrained_baseline") == 0)
  1003. return AMF_VIDEO_ENCODER_PROFILE_CONSTRAINED_BASELINE;
  1004. else if (astrcmpi(profile, "constrained_high") == 0)
  1005. return AMF_VIDEO_ENCODER_PROFILE_CONSTRAINED_HIGH;
  1006. return AMF_VIDEO_ENCODER_PROFILE_HIGH;
  1007. }
  1008. static void amf_avc_update_data(amf_base *enc, int rc, int64_t bitrate,
  1009. int64_t qp)
  1010. {
  1011. if (rc != AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CONSTANT_QP) {
  1012. set_avc_property(enc, TARGET_BITRATE, bitrate);
  1013. set_avc_property(enc, PEAK_BITRATE, bitrate);
  1014. set_avc_property(enc, VBV_BUFFER_SIZE, bitrate);
  1015. if (rc == AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CBR) {
  1016. set_avc_property(enc, FILLER_DATA_ENABLE, true);
  1017. }
  1018. } else {
  1019. set_avc_property(enc, QP_I, qp);
  1020. set_avc_property(enc, QP_P, qp);
  1021. set_avc_property(enc, QP_B, qp);
  1022. }
  1023. }
  1024. static bool amf_avc_update(void *data, obs_data_t *settings)
  1025. try {
  1026. amf_base *enc = (amf_base *)data;
  1027. if (enc->first_update) {
  1028. enc->first_update = false;
  1029. return true;
  1030. }
  1031. int64_t bitrate = obs_data_get_int(settings, "bitrate");
  1032. int64_t qp = obs_data_get_int(settings, "cqp");
  1033. const char *rc_str = obs_data_get_string(settings, "rate_control");
  1034. int rc = get_avc_rate_control(rc_str);
  1035. AMF_RESULT res;
  1036. amf_avc_update_data(enc, rc, bitrate * 1000, qp);
  1037. res = enc->amf_encoder->ReInit(enc->cx, enc->cy);
  1038. if (res != AMF_OK)
  1039. throw amf_error("AMFComponent::Init failed", res);
  1040. return true;
  1041. } catch (const amf_error &err) {
  1042. amf_base *enc = (amf_base *)data;
  1043. error("%s: %s: %ls", __FUNCTION__, err.str,
  1044. amf_trace->GetResultText(err.res));
  1045. return false;
  1046. }
  1047. static bool amf_avc_init(void *data, obs_data_t *settings)
  1048. {
  1049. amf_base *enc = (amf_base *)data;
  1050. int64_t bitrate = obs_data_get_int(settings, "bitrate");
  1051. int64_t qp = obs_data_get_int(settings, "cqp");
  1052. const char *preset = obs_data_get_string(settings, "preset");
  1053. const char *profile = obs_data_get_string(settings, "profile");
  1054. const char *rc_str = obs_data_get_string(settings, "rate_control");
  1055. int64_t bf = obs_data_get_int(settings, "bf");
  1056. if (enc->bframes_supported) {
  1057. set_avc_property(enc, MAX_CONSECUTIVE_BPICTURES, 3);
  1058. set_avc_property(enc, B_PIC_PATTERN, bf);
  1059. } else if (bf != 0) {
  1060. warn("B-Frames set to %lld but b-frames are not "
  1061. "supported by this device",
  1062. bf);
  1063. bf = 0;
  1064. }
  1065. int rc = get_avc_rate_control(rc_str);
  1066. set_avc_property(enc, RATE_CONTROL_METHOD, rc);
  1067. set_avc_property(enc, ENABLE_VBAQ, true);
  1068. amf_avc_update_data(enc, rc, bitrate * 1000, qp);
  1069. set_avc_property(enc, ENFORCE_HRD, true);
  1070. set_avc_property(enc, HIGH_MOTION_QUALITY_BOOST_ENABLE, false);
  1071. int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec");
  1072. int gop_size = (keyint_sec) ? keyint_sec * enc->fps_num / enc->fps_den
  1073. : 250;
  1074. set_avc_property(enc, IDR_PERIOD, gop_size);
  1075. bool repeat_headers = obs_data_get_bool(settings, "repeat_headers");
  1076. if (repeat_headers)
  1077. set_avc_property(enc, HEADER_INSERTION_SPACING, gop_size);
  1078. set_avc_property(enc, DE_BLOCKING_FILTER, true);
  1079. check_preset_compatibility(enc, preset);
  1080. const char *ffmpeg_opts = obs_data_get_string(settings, "ffmpeg_opts");
  1081. if (ffmpeg_opts && *ffmpeg_opts) {
  1082. struct obs_options opts = obs_parse_options(ffmpeg_opts);
  1083. for (size_t i = 0; i < opts.count; i++) {
  1084. amf_apply_opt(enc, &opts.options[i]);
  1085. }
  1086. obs_free_options(opts);
  1087. }
  1088. if (!ffmpeg_opts || !*ffmpeg_opts)
  1089. ffmpeg_opts = "(none)";
  1090. info("settings:\n"
  1091. "\trate_control: %s\n"
  1092. "\tbitrate: %d\n"
  1093. "\tcqp: %d\n"
  1094. "\tkeyint: %d\n"
  1095. "\tpreset: %s\n"
  1096. "\tprofile: %s\n"
  1097. "\tb-frames: %d\n"
  1098. "\twidth: %d\n"
  1099. "\theight: %d\n"
  1100. "\tparams: %s",
  1101. rc_str, bitrate, qp, gop_size, preset, profile, bf, enc->cx,
  1102. enc->cy, ffmpeg_opts);
  1103. return true;
  1104. }
  1105. static void amf_avc_create_internal(amf_base *enc, obs_data_t *settings)
  1106. {
  1107. AMF_RESULT res;
  1108. AMFVariant p;
  1109. enc->codec = amf_codec_type::AVC;
  1110. if (!amf_create_encoder(enc))
  1111. throw "Failed to create encoder";
  1112. AMFCapsPtr caps;
  1113. res = enc->amf_encoder->GetCaps(&caps);
  1114. if (res == AMF_OK) {
  1115. caps->GetProperty(AMF_VIDEO_ENCODER_CAP_BFRAMES,
  1116. &enc->bframes_supported);
  1117. caps->GetProperty(AMF_VIDEO_ENCODER_CAP_MAX_THROUGHPUT,
  1118. &enc->max_throughput);
  1119. }
  1120. const char *preset = obs_data_get_string(settings, "preset");
  1121. set_avc_property(enc, FRAMESIZE, AMFConstructSize(enc->cx, enc->cy));
  1122. set_avc_property(enc, USAGE, AMF_VIDEO_ENCODER_USAGE_TRANSCODING);
  1123. set_avc_property(enc, QUALITY_PRESET, get_avc_preset(enc, preset));
  1124. set_avc_property(enc, PROFILE, get_avc_profile(settings));
  1125. set_avc_property(enc, LOWLATENCY_MODE, false);
  1126. set_avc_property(enc, CABAC_ENABLE, AMF_VIDEO_ENCODER_UNDEFINED);
  1127. set_avc_property(enc, PREENCODE_ENABLE, true);
  1128. set_avc_property(enc, OUTPUT_COLOR_PROFILE, enc->amf_color_profile);
  1129. set_avc_property(enc, OUTPUT_TRANSFER_CHARACTERISTIC,
  1130. enc->amf_characteristic);
  1131. set_avc_property(enc, OUTPUT_COLOR_PRIMARIES, enc->amf_primaries);
  1132. set_avc_property(enc, FULL_RANGE_COLOR, enc->full_range);
  1133. amf_avc_init(enc, settings);
  1134. res = enc->amf_encoder->Init(enc->amf_format, enc->cx, enc->cy);
  1135. if (res != AMF_OK)
  1136. throw amf_error("AMFComponent::Init failed", res);
  1137. set_avc_property(enc, FRAMERATE, enc->amf_frame_rate);
  1138. res = enc->amf_encoder->GetProperty(AMF_VIDEO_ENCODER_EXTRADATA, &p);
  1139. if (res == AMF_OK && p.type == AMF_VARIANT_INTERFACE)
  1140. enc->header = AMFBufferPtr(p.pInterface);
  1141. if (enc->bframes_supported) {
  1142. amf_int64 b_frames = 0;
  1143. amf_int64 b_max = 0;
  1144. if (get_avc_property(enc, B_PIC_PATTERN, &b_frames) &&
  1145. get_avc_property(enc, MAX_CONSECUTIVE_BPICTURES, &b_max))
  1146. enc->dts_offset = b_frames + 1;
  1147. else
  1148. enc->dts_offset = 0;
  1149. }
  1150. }
  1151. static void *amf_avc_create_texencode(obs_data_t *settings,
  1152. obs_encoder_t *encoder)
  1153. try {
  1154. check_texture_encode_capability(encoder, amf_codec_type::AVC);
  1155. std::unique_ptr<amf_texencode> enc = std::make_unique<amf_texencode>();
  1156. enc->encoder = encoder;
  1157. enc->encoder_str = "texture-amf-h264";
  1158. if (!amf_init_d3d11(enc.get()))
  1159. throw "Failed to create D3D11";
  1160. amf_avc_create_internal(enc.get(), settings);
  1161. return enc.release();
  1162. } catch (const amf_error &err) {
  1163. blog(LOG_ERROR, "[texture-amf-h264] %s: %s: %ls", __FUNCTION__, err.str,
  1164. amf_trace->GetResultText(err.res));
  1165. return obs_encoder_create_rerouted(encoder, "h264_fallback_amf");
  1166. } catch (const char *err) {
  1167. blog(LOG_ERROR, "[texture-amf-h264] %s: %s", __FUNCTION__, err);
  1168. return obs_encoder_create_rerouted(encoder, "h264_fallback_amf");
  1169. }
  1170. static void *amf_avc_create_fallback(obs_data_t *settings,
  1171. obs_encoder_t *encoder)
  1172. try {
  1173. std::unique_ptr<amf_fallback> enc = std::make_unique<amf_fallback>();
  1174. enc->encoder = encoder;
  1175. enc->encoder_str = "fallback-amf-h264";
  1176. video_t *video = obs_encoder_video(encoder);
  1177. const struct video_output_info *voi = video_output_get_info(video);
  1178. switch (voi->format) {
  1179. case VIDEO_FORMAT_I010:
  1180. case VIDEO_FORMAT_P010: {
  1181. const char *const text =
  1182. obs_module_text("AMF.10bitUnsupportedAvc");
  1183. obs_encoder_set_last_error(encoder, text);
  1184. throw text;
  1185. }
  1186. default:
  1187. switch (voi->colorspace) {
  1188. case VIDEO_CS_2100_PQ:
  1189. case VIDEO_CS_2100_HLG: {
  1190. const char *const text =
  1191. obs_module_text("AMF.8bitUnsupportedHdr");
  1192. obs_encoder_set_last_error(encoder, text);
  1193. throw text;
  1194. }
  1195. }
  1196. }
  1197. amf_avc_create_internal(enc.get(), settings);
  1198. return enc.release();
  1199. } catch (const amf_error &err) {
  1200. blog(LOG_ERROR, "[fallback-amf-h264] %s: %s: %ls", __FUNCTION__,
  1201. err.str, amf_trace->GetResultText(err.res));
  1202. return nullptr;
  1203. } catch (const char *err) {
  1204. blog(LOG_ERROR, "[fallback-amf-h264] %s: %s", __FUNCTION__, err);
  1205. return nullptr;
  1206. }
  1207. static void register_avc()
  1208. {
  1209. struct obs_encoder_info amf_encoder_info = {};
  1210. amf_encoder_info.id = "h264_texture_amf";
  1211. amf_encoder_info.type = OBS_ENCODER_VIDEO;
  1212. amf_encoder_info.codec = "h264";
  1213. amf_encoder_info.get_name = amf_avc_get_name;
  1214. amf_encoder_info.create = amf_avc_create_texencode;
  1215. amf_encoder_info.destroy = amf_destroy;
  1216. amf_encoder_info.update = amf_avc_update;
  1217. amf_encoder_info.encode_texture = amf_encode_tex;
  1218. amf_encoder_info.get_defaults = amf_defaults;
  1219. amf_encoder_info.get_properties = amf_avc_properties;
  1220. amf_encoder_info.get_extra_data = amf_extra_data;
  1221. amf_encoder_info.caps = OBS_ENCODER_CAP_PASS_TEXTURE |
  1222. OBS_ENCODER_CAP_DYN_BITRATE;
  1223. obs_register_encoder(&amf_encoder_info);
  1224. amf_encoder_info.id = "h264_fallback_amf";
  1225. amf_encoder_info.caps = OBS_ENCODER_CAP_INTERNAL |
  1226. OBS_ENCODER_CAP_DYN_BITRATE;
  1227. amf_encoder_info.encode_texture = nullptr;
  1228. amf_encoder_info.create = amf_avc_create_fallback;
  1229. amf_encoder_info.encode = amf_encode_fallback;
  1230. amf_encoder_info.get_video_info = h264_video_info_fallback;
  1231. obs_register_encoder(&amf_encoder_info);
  1232. }
  1233. /* ========================================================================= */
  1234. /* HEVC Implementation */
  1235. #if ENABLE_HEVC
  1236. static const char *amf_hevc_get_name(void *)
  1237. {
  1238. return "AMD HW H.265 (HEVC)";
  1239. }
  1240. static inline int get_hevc_preset(amf_base *enc, const char *preset)
  1241. {
  1242. if (astrcmpi(preset, "balanced") == 0)
  1243. return AMF_VIDEO_ENCODER_HEVC_QUALITY_PRESET_BALANCED;
  1244. else if (astrcmpi(preset, "speed") == 0)
  1245. return AMF_VIDEO_ENCODER_HEVC_QUALITY_PRESET_SPEED;
  1246. return AMF_VIDEO_ENCODER_HEVC_QUALITY_PRESET_QUALITY;
  1247. }
  1248. static inline int get_hevc_rate_control(const char *rc_str)
  1249. {
  1250. if (astrcmpi(rc_str, "cqp") == 0)
  1251. return AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CONSTANT_QP;
  1252. else if (astrcmpi(rc_str, "vbr") == 0)
  1253. return AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR;
  1254. return AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CBR;
  1255. }
  1256. static void amf_hevc_update_data(amf_base *enc, int rc, int64_t bitrate,
  1257. int64_t qp)
  1258. {
  1259. if (rc != AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CONSTANT_QP) {
  1260. set_hevc_property(enc, TARGET_BITRATE, bitrate);
  1261. set_hevc_property(enc, PEAK_BITRATE, bitrate);
  1262. set_hevc_property(enc, VBV_BUFFER_SIZE, bitrate);
  1263. if (rc == AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CBR) {
  1264. set_hevc_property(enc, FILLER_DATA_ENABLE, true);
  1265. }
  1266. } else {
  1267. set_hevc_property(enc, QP_I, qp);
  1268. set_hevc_property(enc, QP_P, qp);
  1269. }
  1270. }
  1271. static bool amf_hevc_update(void *data, obs_data_t *settings)
  1272. try {
  1273. amf_base *enc = (amf_base *)data;
  1274. if (enc->first_update) {
  1275. enc->first_update = false;
  1276. return true;
  1277. }
  1278. int64_t bitrate = obs_data_get_int(settings, "bitrate");
  1279. int64_t qp = obs_data_get_int(settings, "cqp");
  1280. const char *rc_str = obs_data_get_string(settings, "rate_control");
  1281. int rc = get_hevc_rate_control(rc_str);
  1282. AMF_RESULT res;
  1283. amf_hevc_update_data(enc, rc, bitrate * 1000, qp);
  1284. res = enc->amf_encoder->ReInit(enc->cx, enc->cy);
  1285. if (res != AMF_OK)
  1286. throw amf_error("AMFComponent::Init failed", res);
  1287. return true;
  1288. } catch (const amf_error &err) {
  1289. amf_base *enc = (amf_base *)data;
  1290. error("%s: %s: %ls", __FUNCTION__, err.str,
  1291. amf_trace->GetResultText(err.res));
  1292. return false;
  1293. }
  1294. static bool amf_hevc_init(void *data, obs_data_t *settings)
  1295. {
  1296. amf_base *enc = (amf_base *)data;
  1297. int64_t bitrate = obs_data_get_int(settings, "bitrate");
  1298. int64_t qp = obs_data_get_int(settings, "cqp");
  1299. const char *preset = obs_data_get_string(settings, "preset");
  1300. const char *profile = obs_data_get_string(settings, "profile");
  1301. const char *rc_str = obs_data_get_string(settings, "rate_control");
  1302. int rc = get_hevc_rate_control(rc_str);
  1303. set_hevc_property(enc, RATE_CONTROL_METHOD, rc);
  1304. if (rc != AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CONSTANT_QP)
  1305. set_hevc_property(enc, ENABLE_VBAQ, true);
  1306. amf_hevc_update_data(enc, rc, bitrate * 1000, qp);
  1307. set_hevc_property(enc, ENFORCE_HRD, true);
  1308. set_hevc_property(enc, HIGH_MOTION_QUALITY_BOOST_ENABLE, false);
  1309. int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec");
  1310. int gop_size = (keyint_sec) ? keyint_sec * enc->fps_num / enc->fps_den
  1311. : 250;
  1312. set_hevc_property(enc, GOP_SIZE, gop_size);
  1313. check_preset_compatibility(enc, preset);
  1314. const char *ffmpeg_opts = obs_data_get_string(settings, "ffmpeg_opts");
  1315. if (ffmpeg_opts && *ffmpeg_opts) {
  1316. struct obs_options opts = obs_parse_options(ffmpeg_opts);
  1317. for (size_t i = 0; i < opts.count; i++) {
  1318. amf_apply_opt(enc, &opts.options[i]);
  1319. }
  1320. obs_free_options(opts);
  1321. }
  1322. if (!ffmpeg_opts || !*ffmpeg_opts)
  1323. ffmpeg_opts = "(none)";
  1324. info("settings:\n"
  1325. "\trate_control: %s\n"
  1326. "\tbitrate: %d\n"
  1327. "\tcqp: %d\n"
  1328. "\tkeyint: %d\n"
  1329. "\tpreset: %s\n"
  1330. "\tprofile: %s\n"
  1331. "\twidth: %d\n"
  1332. "\theight: %d\n"
  1333. "\tparams: %s",
  1334. rc_str, bitrate, qp, gop_size, preset, profile, enc->cx, enc->cy,
  1335. ffmpeg_opts);
  1336. return true;
  1337. }
  1338. static inline bool is_hlg(amf_base *enc)
  1339. {
  1340. return enc->amf_characteristic ==
  1341. AMF_COLOR_TRANSFER_CHARACTERISTIC_ARIB_STD_B67;
  1342. }
  1343. static inline bool is_pq(amf_base *enc)
  1344. {
  1345. return enc->amf_characteristic ==
  1346. AMF_COLOR_TRANSFER_CHARACTERISTIC_SMPTE2084;
  1347. }
  1348. constexpr amf_uint16 amf_hdr_primary(uint32_t num, uint32_t den)
  1349. {
  1350. return (amf_uint16)(num * 50000 / den);
  1351. }
  1352. constexpr amf_uint32 lum_mul = 10000;
  1353. constexpr amf_uint32 amf_make_lum(amf_uint32 val)
  1354. {
  1355. return val * lum_mul;
  1356. }
  1357. static void amf_hevc_create_internal(amf_base *enc, obs_data_t *settings)
  1358. {
  1359. AMF_RESULT res;
  1360. AMFVariant p;
  1361. enc->codec = amf_codec_type::HEVC;
  1362. if (!amf_create_encoder(enc))
  1363. throw "Failed to create encoder";
  1364. AMFCapsPtr caps;
  1365. res = enc->amf_encoder->GetCaps(&caps);
  1366. if (res == AMF_OK) {
  1367. caps->GetProperty(AMF_VIDEO_ENCODER_HEVC_CAP_MAX_THROUGHPUT,
  1368. &enc->max_throughput);
  1369. }
  1370. const bool is10bit = enc->amf_format == AMF_SURFACE_P010;
  1371. const bool pq = is_pq(enc);
  1372. const bool hlg = is_hlg(enc);
  1373. const bool is_hdr = pq || hlg;
  1374. const char *preset = obs_data_get_string(settings, "preset");
  1375. set_hevc_property(enc, FRAMESIZE, AMFConstructSize(enc->cx, enc->cy));
  1376. set_hevc_property(enc, USAGE, AMF_VIDEO_ENCODER_USAGE_TRANSCODING);
  1377. set_hevc_property(enc, QUALITY_PRESET, get_hevc_preset(enc, preset));
  1378. set_hevc_property(enc, COLOR_BIT_DEPTH,
  1379. is10bit ? AMF_COLOR_BIT_DEPTH_10
  1380. : AMF_COLOR_BIT_DEPTH_8);
  1381. set_hevc_property(enc, PROFILE,
  1382. is10bit ? AMF_VIDEO_ENCODER_HEVC_PROFILE_MAIN_10
  1383. : AMF_VIDEO_ENCODER_HEVC_PROFILE_MAIN);
  1384. set_hevc_property(enc, LOWLATENCY_MODE, false);
  1385. set_hevc_property(enc, OUTPUT_COLOR_PROFILE, enc->amf_color_profile);
  1386. set_hevc_property(enc, OUTPUT_TRANSFER_CHARACTERISTIC,
  1387. enc->amf_characteristic);
  1388. set_hevc_property(enc, OUTPUT_COLOR_PRIMARIES, enc->amf_primaries);
  1389. set_hevc_property(enc, NOMINAL_RANGE, enc->full_range);
  1390. if (is_hdr) {
  1391. const int hdr_nominal_peak_level =
  1392. pq ? (int)obs_get_video_hdr_nominal_peak_level()
  1393. : (hlg ? 1000 : 0);
  1394. AMFBufferPtr buf;
  1395. enc->amf_context->AllocBuffer(AMF_MEMORY_HOST,
  1396. sizeof(AMFHDRMetadata), &buf);
  1397. AMFHDRMetadata *md = (AMFHDRMetadata *)buf->GetNative();
  1398. md->redPrimary[0] = amf_hdr_primary(17, 25);
  1399. md->redPrimary[1] = amf_hdr_primary(8, 25);
  1400. md->greenPrimary[0] = amf_hdr_primary(53, 200);
  1401. md->greenPrimary[1] = amf_hdr_primary(69, 100);
  1402. md->bluePrimary[0] = amf_hdr_primary(3, 20);
  1403. md->bluePrimary[1] = amf_hdr_primary(3, 50);
  1404. md->whitePoint[0] = amf_hdr_primary(3127, 10000);
  1405. md->whitePoint[1] = amf_hdr_primary(329, 1000);
  1406. md->minMasteringLuminance = 0;
  1407. md->maxMasteringLuminance =
  1408. amf_make_lum(hdr_nominal_peak_level);
  1409. md->maxContentLightLevel = hdr_nominal_peak_level;
  1410. md->maxFrameAverageLightLevel = hdr_nominal_peak_level;
  1411. set_hevc_property(enc, INPUT_HDR_METADATA, buf);
  1412. }
  1413. amf_hevc_init(enc, settings);
  1414. res = enc->amf_encoder->Init(enc->amf_format, enc->cx, enc->cy);
  1415. if (res != AMF_OK)
  1416. throw amf_error("AMFComponent::Init failed", res);
  1417. set_hevc_property(enc, FRAMERATE, enc->amf_frame_rate);
  1418. res = enc->amf_encoder->GetProperty(AMF_VIDEO_ENCODER_HEVC_EXTRADATA,
  1419. &p);
  1420. if (res == AMF_OK && p.type == AMF_VARIANT_INTERFACE)
  1421. enc->header = AMFBufferPtr(p.pInterface);
  1422. }
  1423. static void *amf_hevc_create_texencode(obs_data_t *settings,
  1424. obs_encoder_t *encoder)
  1425. try {
  1426. check_texture_encode_capability(encoder, amf_codec_type::HEVC);
  1427. std::unique_ptr<amf_texencode> enc = std::make_unique<amf_texencode>();
  1428. enc->encoder = encoder;
  1429. enc->encoder_str = "texture-amf-h265";
  1430. if (!amf_init_d3d11(enc.get()))
  1431. throw "Failed to create D3D11";
  1432. amf_hevc_create_internal(enc.get(), settings);
  1433. return enc.release();
  1434. } catch (const amf_error &err) {
  1435. blog(LOG_ERROR, "[texture-amf-h265] %s: %s: %ls", __FUNCTION__, err.str,
  1436. amf_trace->GetResultText(err.res));
  1437. return obs_encoder_create_rerouted(encoder, "h265_fallback_amf");
  1438. } catch (const char *err) {
  1439. blog(LOG_ERROR, "[texture-amf-h265] %s: %s", __FUNCTION__, err);
  1440. return obs_encoder_create_rerouted(encoder, "h265_fallback_amf");
  1441. }
  1442. static void *amf_hevc_create_fallback(obs_data_t *settings,
  1443. obs_encoder_t *encoder)
  1444. try {
  1445. std::unique_ptr<amf_fallback> enc = std::make_unique<amf_fallback>();
  1446. enc->encoder = encoder;
  1447. enc->encoder_str = "fallback-amf-h265";
  1448. video_t *video = obs_encoder_video(encoder);
  1449. const struct video_output_info *voi = video_output_get_info(video);
  1450. switch (voi->format) {
  1451. case VIDEO_FORMAT_I010:
  1452. case VIDEO_FORMAT_P010:
  1453. break;
  1454. default:
  1455. switch (voi->colorspace) {
  1456. case VIDEO_CS_2100_PQ:
  1457. case VIDEO_CS_2100_HLG: {
  1458. const char *const text =
  1459. obs_module_text("AMF.8bitUnsupportedHdr");
  1460. obs_encoder_set_last_error(encoder, text);
  1461. throw text;
  1462. }
  1463. }
  1464. }
  1465. amf_hevc_create_internal(enc.get(), settings);
  1466. return enc.release();
  1467. } catch (const amf_error &err) {
  1468. blog(LOG_ERROR, "[fallback-amf-h265] %s: %s: %ls", __FUNCTION__,
  1469. err.str, amf_trace->GetResultText(err.res));
  1470. return nullptr;
  1471. } catch (const char *err) {
  1472. blog(LOG_ERROR, "[fallback-amf-h265] %s: %s", __FUNCTION__, err);
  1473. return nullptr;
  1474. }
  1475. static void register_hevc()
  1476. {
  1477. struct obs_encoder_info amf_encoder_info = {};
  1478. amf_encoder_info.id = "h265_texture_amf";
  1479. amf_encoder_info.type = OBS_ENCODER_VIDEO;
  1480. amf_encoder_info.codec = "hevc";
  1481. amf_encoder_info.get_name = amf_hevc_get_name;
  1482. amf_encoder_info.create = amf_hevc_create_texencode;
  1483. amf_encoder_info.destroy = amf_destroy;
  1484. amf_encoder_info.update = amf_hevc_update;
  1485. amf_encoder_info.encode_texture = amf_encode_tex;
  1486. amf_encoder_info.get_defaults = amf_defaults;
  1487. amf_encoder_info.get_properties = amf_hevc_properties;
  1488. amf_encoder_info.get_extra_data = amf_extra_data;
  1489. amf_encoder_info.caps = OBS_ENCODER_CAP_PASS_TEXTURE |
  1490. OBS_ENCODER_CAP_DYN_BITRATE;
  1491. obs_register_encoder(&amf_encoder_info);
  1492. amf_encoder_info.id = "h265_fallback_amf";
  1493. amf_encoder_info.caps = OBS_ENCODER_CAP_INTERNAL |
  1494. OBS_ENCODER_CAP_DYN_BITRATE;
  1495. amf_encoder_info.encode_texture = nullptr;
  1496. amf_encoder_info.create = amf_hevc_create_fallback;
  1497. amf_encoder_info.encode = amf_encode_fallback;
  1498. amf_encoder_info.get_video_info = h265_video_info_fallback;
  1499. obs_register_encoder(&amf_encoder_info);
  1500. }
  1501. #endif //ENABLE_HEVC
  1502. /* ========================================================================= */
  1503. /* AV1 Implementation */
  1504. static const char *amf_av1_get_name(void *)
  1505. {
  1506. return "AMD HW AV1";
  1507. }
  1508. static inline int get_av1_preset(amf_base *enc, const char *preset)
  1509. {
  1510. if (astrcmpi(preset, "highquality") == 0)
  1511. return AMF_VIDEO_ENCODER_AV1_QUALITY_PRESET_HIGH_QUALITY;
  1512. else if (astrcmpi(preset, "quality") == 0)
  1513. return AMF_VIDEO_ENCODER_AV1_QUALITY_PRESET_QUALITY;
  1514. else if (astrcmpi(preset, "balanced") == 0)
  1515. return AMF_VIDEO_ENCODER_AV1_QUALITY_PRESET_BALANCED;
  1516. else if (astrcmpi(preset, "speed") == 0)
  1517. return AMF_VIDEO_ENCODER_AV1_QUALITY_PRESET_SPEED;
  1518. return AMF_VIDEO_ENCODER_AV1_QUALITY_PRESET_BALANCED;
  1519. }
  1520. static inline int get_av1_rate_control(const char *rc_str)
  1521. {
  1522. if (astrcmpi(rc_str, "cqp") == 0)
  1523. return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_CONSTANT_QP;
  1524. else if (astrcmpi(rc_str, "vbr_lat") == 0)
  1525. return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_LATENCY_CONSTRAINED_VBR;
  1526. else if (astrcmpi(rc_str, "vbr") == 0)
  1527. return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR;
  1528. else if (astrcmpi(rc_str, "cbr") == 0)
  1529. return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_CBR;
  1530. else if (astrcmpi(rc_str, "qvbr") == 0)
  1531. return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_QUALITY_VBR;
  1532. else if (astrcmpi(rc_str, "hqvbr") == 0)
  1533. return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_HIGH_QUALITY_VBR;
  1534. else if (astrcmpi(rc_str, "hqcbr") == 0)
  1535. return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_HIGH_QUALITY_CBR;
  1536. return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_CBR;
  1537. }
  1538. static inline int get_av1_profile(obs_data_t *settings)
  1539. {
  1540. const char *profile = obs_data_get_string(settings, "profile");
  1541. if (astrcmpi(profile, "main") == 0)
  1542. return AMF_VIDEO_ENCODER_AV1_PROFILE_MAIN;
  1543. return AMF_VIDEO_ENCODER_AV1_PROFILE_MAIN;
  1544. }
  1545. static void amf_av1_update_data(amf_base *enc, int rc, int64_t bitrate,
  1546. int64_t cq_value)
  1547. {
  1548. if (rc != AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_CONSTANT_QP) {
  1549. set_av1_property(enc, TARGET_BITRATE, bitrate);
  1550. set_av1_property(enc, PEAK_BITRATE, bitrate);
  1551. set_av1_property(enc, VBV_BUFFER_SIZE, bitrate);
  1552. if (rc == AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CBR) {
  1553. set_av1_property(enc, FILLER_DATA, true);
  1554. } else if (
  1555. rc == AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR ||
  1556. rc == AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_HIGH_QUALITY_VBR) {
  1557. set_av1_property(enc, PEAK_BITRATE, bitrate * 1.5);
  1558. }
  1559. } else {
  1560. int64_t qp = cq_value * 4;
  1561. set_av1_property(enc, Q_INDEX_INTRA, qp);
  1562. set_av1_property(enc, Q_INDEX_INTER, qp);
  1563. }
  1564. }
  1565. static bool amf_av1_update(void *data, obs_data_t *settings)
  1566. try {
  1567. amf_base *enc = (amf_base *)data;
  1568. if (enc->first_update) {
  1569. enc->first_update = false;
  1570. return true;
  1571. }
  1572. int64_t bitrate = obs_data_get_int(settings, "bitrate");
  1573. int64_t cq_level = obs_data_get_int(settings, "cqp");
  1574. const char *rc_str = obs_data_get_string(settings, "rate_control");
  1575. int rc = get_av1_rate_control(rc_str);
  1576. amf_av1_update_data(enc, rc, bitrate * 1000, cq_level);
  1577. AMF_RESULT res = enc->amf_encoder->ReInit(enc->cx, enc->cy);
  1578. if (res != AMF_OK)
  1579. throw amf_error("AMFComponent::Init failed", res);
  1580. return true;
  1581. } catch (const amf_error &err) {
  1582. amf_base *enc = (amf_base *)data;
  1583. error("%s: %s: %ls", __FUNCTION__, err.str,
  1584. amf_trace->GetResultText(err.res));
  1585. return false;
  1586. }
  1587. static bool amf_av1_init(void *data, obs_data_t *settings)
  1588. {
  1589. amf_base *enc = (amf_base *)data;
  1590. int64_t bitrate = obs_data_get_int(settings, "bitrate");
  1591. int64_t qp = obs_data_get_int(settings, "cqp");
  1592. const char *preset = obs_data_get_string(settings, "preset");
  1593. const char *profile = obs_data_get_string(settings, "profile");
  1594. const char *rc_str = obs_data_get_string(settings, "rate_control");
  1595. int rc = get_av1_rate_control(rc_str);
  1596. set_av1_property(enc, RATE_CONTROL_METHOD, rc);
  1597. amf_av1_update_data(enc, rc, bitrate * 1000, qp);
  1598. set_av1_property(enc, ENFORCE_HRD, true);
  1599. int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec");
  1600. int gop_size = (keyint_sec) ? keyint_sec * enc->fps_num / enc->fps_den
  1601. : 250;
  1602. set_av1_property(enc, GOP_SIZE, gop_size);
  1603. const char *ffmpeg_opts = obs_data_get_string(settings, "ffmpeg_opts");
  1604. if (ffmpeg_opts && *ffmpeg_opts) {
  1605. struct obs_options opts = obs_parse_options(ffmpeg_opts);
  1606. for (size_t i = 0; i < opts.count; i++) {
  1607. amf_apply_opt(enc, &opts.options[i]);
  1608. }
  1609. obs_free_options(opts);
  1610. }
  1611. check_preset_compatibility(enc, preset);
  1612. if (!ffmpeg_opts || !*ffmpeg_opts)
  1613. ffmpeg_opts = "(none)";
  1614. info("settings:\n"
  1615. "\trate_control: %s\n"
  1616. "\tbitrate: %d\n"
  1617. "\tcqp: %d\n"
  1618. "\tkeyint: %d\n"
  1619. "\tpreset: %s\n"
  1620. "\tprofile: %s\n"
  1621. "\twidth: %d\n"
  1622. "\theight: %d\n"
  1623. "\tparams: %s",
  1624. rc_str, bitrate, qp, gop_size, preset, profile, enc->cx, enc->cy,
  1625. ffmpeg_opts);
  1626. return true;
  1627. }
  1628. static void amf_av1_create_internal(amf_base *enc, obs_data_t *settings)
  1629. {
  1630. enc->codec = amf_codec_type::AV1;
  1631. if (!amf_create_encoder(enc))
  1632. throw "Failed to create encoder";
  1633. AMFCapsPtr caps;
  1634. AMF_RESULT res = enc->amf_encoder->GetCaps(&caps);
  1635. if (res == AMF_OK) {
  1636. caps->GetProperty(AMF_VIDEO_ENCODER_AV1_CAP_MAX_THROUGHPUT,
  1637. &enc->max_throughput);
  1638. }
  1639. const bool is10bit = enc->amf_format == AMF_SURFACE_P010;
  1640. const char *preset = obs_data_get_string(settings, "preset");
  1641. set_av1_property(enc, FRAMESIZE, AMFConstructSize(enc->cx, enc->cy));
  1642. set_av1_property(enc, USAGE, AMF_VIDEO_ENCODER_USAGE_TRANSCODING);
  1643. set_av1_property(enc, ALIGNMENT_MODE,
  1644. AMF_VIDEO_ENCODER_AV1_ALIGNMENT_MODE_NO_RESTRICTIONS);
  1645. set_av1_property(enc, QUALITY_PRESET, get_av1_preset(enc, preset));
  1646. set_av1_property(enc, COLOR_BIT_DEPTH,
  1647. is10bit ? AMF_COLOR_BIT_DEPTH_10
  1648. : AMF_COLOR_BIT_DEPTH_8);
  1649. set_av1_property(enc, PROFILE, get_av1_profile(settings));
  1650. set_av1_property(enc, ENCODING_LATENCY_MODE,
  1651. AMF_VIDEO_ENCODER_AV1_ENCODING_LATENCY_MODE_NONE);
  1652. // set_av1_property(enc, RATE_CONTROL_PREENCODE, true);
  1653. set_av1_property(enc, OUTPUT_COLOR_PROFILE, enc->amf_color_profile);
  1654. set_av1_property(enc, OUTPUT_TRANSFER_CHARACTERISTIC,
  1655. enc->amf_characteristic);
  1656. set_av1_property(enc, OUTPUT_COLOR_PRIMARIES, enc->amf_primaries);
  1657. amf_av1_init(enc, settings);
  1658. res = enc->amf_encoder->Init(enc->amf_format, enc->cx, enc->cy);
  1659. if (res != AMF_OK)
  1660. throw amf_error("AMFComponent::Init failed", res);
  1661. set_av1_property(enc, FRAMERATE, enc->amf_frame_rate);
  1662. AMFVariant p;
  1663. res = enc->amf_encoder->GetProperty(AMF_VIDEO_ENCODER_AV1_EXTRA_DATA,
  1664. &p);
  1665. if (res == AMF_OK && p.type == AMF_VARIANT_INTERFACE)
  1666. enc->header = AMFBufferPtr(p.pInterface);
  1667. }
  1668. static void *amf_av1_create_texencode(obs_data_t *settings,
  1669. obs_encoder_t *encoder)
  1670. try {
  1671. check_texture_encode_capability(encoder, amf_codec_type::AV1);
  1672. std::unique_ptr<amf_texencode> enc = std::make_unique<amf_texencode>();
  1673. enc->encoder = encoder;
  1674. enc->encoder_str = "texture-amf-av1";
  1675. if (!amf_init_d3d11(enc.get()))
  1676. throw "Failed to create D3D11";
  1677. amf_av1_create_internal(enc.get(), settings);
  1678. return enc.release();
  1679. } catch (const amf_error &err) {
  1680. blog(LOG_ERROR, "[texture-amf-av1] %s: %s: %ls", __FUNCTION__, err.str,
  1681. amf_trace->GetResultText(err.res));
  1682. return obs_encoder_create_rerouted(encoder, "av1_fallback_amf");
  1683. } catch (const char *err) {
  1684. blog(LOG_ERROR, "[texture-amf-av1] %s: %s", __FUNCTION__, err);
  1685. return obs_encoder_create_rerouted(encoder, "av1_fallback_amf");
  1686. }
  1687. static void *amf_av1_create_fallback(obs_data_t *settings,
  1688. obs_encoder_t *encoder)
  1689. try {
  1690. std::unique_ptr<amf_fallback> enc = std::make_unique<amf_fallback>();
  1691. enc->encoder = encoder;
  1692. enc->encoder_str = "fallback-amf-av1";
  1693. video_t *video = obs_encoder_video(encoder);
  1694. const struct video_output_info *voi = video_output_get_info(video);
  1695. switch (voi->format) {
  1696. case VIDEO_FORMAT_I010:
  1697. case VIDEO_FORMAT_P010: {
  1698. break;
  1699. }
  1700. default:
  1701. switch (voi->colorspace) {
  1702. case VIDEO_CS_2100_PQ:
  1703. case VIDEO_CS_2100_HLG: {
  1704. const char *const text =
  1705. obs_module_text("AMF.8bitUnsupportedHdr");
  1706. obs_encoder_set_last_error(encoder, text);
  1707. throw text;
  1708. }
  1709. }
  1710. }
  1711. amf_av1_create_internal(enc.get(), settings);
  1712. return enc.release();
  1713. } catch (const amf_error &err) {
  1714. blog(LOG_ERROR, "[fallback-amf-av1] %s: %s: %ls", __FUNCTION__, err.str,
  1715. amf_trace->GetResultText(err.res));
  1716. return nullptr;
  1717. } catch (const char *err) {
  1718. blog(LOG_ERROR, "[fallback-amf-av1] %s: %s", __FUNCTION__, err);
  1719. return nullptr;
  1720. }
  1721. static void amf_av1_defaults(obs_data_t *settings)
  1722. {
  1723. obs_data_set_default_int(settings, "bitrate", 2500);
  1724. obs_data_set_default_int(settings, "cqp", 7);
  1725. obs_data_set_default_string(settings, "rate_control", "CBR");
  1726. obs_data_set_default_string(settings, "preset", "quality");
  1727. obs_data_set_default_string(settings, "profile", "high");
  1728. }
  1729. static void register_av1()
  1730. {
  1731. struct obs_encoder_info amf_encoder_info = {};
  1732. amf_encoder_info.id = "av1_texture_amf";
  1733. amf_encoder_info.type = OBS_ENCODER_VIDEO;
  1734. amf_encoder_info.codec = "av1";
  1735. amf_encoder_info.get_name = amf_av1_get_name;
  1736. amf_encoder_info.create = amf_av1_create_texencode;
  1737. amf_encoder_info.destroy = amf_destroy;
  1738. amf_encoder_info.update = amf_av1_update;
  1739. amf_encoder_info.encode_texture = amf_encode_tex;
  1740. amf_encoder_info.get_defaults = amf_av1_defaults;
  1741. amf_encoder_info.get_properties = amf_av1_properties;
  1742. amf_encoder_info.get_extra_data = amf_extra_data;
  1743. amf_encoder_info.caps = OBS_ENCODER_CAP_PASS_TEXTURE |
  1744. OBS_ENCODER_CAP_DYN_BITRATE;
  1745. obs_register_encoder(&amf_encoder_info);
  1746. amf_encoder_info.id = "av1_fallback_amf";
  1747. amf_encoder_info.caps = OBS_ENCODER_CAP_INTERNAL |
  1748. OBS_ENCODER_CAP_DYN_BITRATE;
  1749. amf_encoder_info.encode_texture = nullptr;
  1750. amf_encoder_info.create = amf_av1_create_fallback;
  1751. amf_encoder_info.encode = amf_encode_fallback;
  1752. amf_encoder_info.get_video_info = av1_video_info_fallback;
  1753. obs_register_encoder(&amf_encoder_info);
  1754. }
  1755. /* ========================================================================= */
  1756. /* Global Stuff */
  1757. extern "C" void amf_load(void)
  1758. try {
  1759. AMF_RESULT res;
  1760. HMODULE amf_module_test;
  1761. /* Check if the DLL is present before running the more expensive */
  1762. /* obs-amf-test.exe, but load it as data so it can't crash us */
  1763. amf_module_test =
  1764. LoadLibraryExW(AMF_DLL_NAME, nullptr, LOAD_LIBRARY_AS_DATAFILE);
  1765. if (!amf_module_test)
  1766. throw "No AMF library";
  1767. FreeLibrary(amf_module_test);
  1768. /* ----------------------------------- */
  1769. /* Check for supported codecs */
  1770. BPtr<char> test_exe = os_get_executable_path_ptr("obs-amf-test.exe");
  1771. std::string caps_str;
  1772. os_process_pipe_t *pp = os_process_pipe_create(test_exe, "r");
  1773. if (!pp)
  1774. throw "Failed to launch the AMF test process I guess";
  1775. for (;;) {
  1776. char data[2048];
  1777. size_t len =
  1778. os_process_pipe_read(pp, (uint8_t *)data, sizeof(data));
  1779. if (!len)
  1780. break;
  1781. caps_str.append(data, len);
  1782. }
  1783. os_process_pipe_destroy(pp);
  1784. if (caps_str.empty())
  1785. throw "Seems the AMF test subprocess crashed. "
  1786. "Better there than here I guess. "
  1787. "Let's just skip loading AMF then I suppose.";
  1788. ConfigFile config;
  1789. if (config.OpenString(caps_str.c_str()) != 0)
  1790. throw "Failed to open config string";
  1791. const char *error = config_get_string(config, "error", "string");
  1792. if (error)
  1793. throw std::string(error);
  1794. uint32_t adapter_count = (uint32_t)config_num_sections(config);
  1795. bool avc_supported = false;
  1796. bool hevc_supported = false;
  1797. bool av1_supported = false;
  1798. for (uint32_t i = 0; i < adapter_count; i++) {
  1799. std::string section = std::to_string(i);
  1800. adapter_caps &info = caps[i];
  1801. info.is_amd =
  1802. config_get_bool(config, section.c_str(), "is_amd");
  1803. info.supports_avc = config_get_bool(config, section.c_str(),
  1804. "supports_avc");
  1805. info.supports_hevc = config_get_bool(config, section.c_str(),
  1806. "supports_hevc");
  1807. info.supports_av1 = config_get_bool(config, section.c_str(),
  1808. "supports_av1");
  1809. avc_supported |= info.supports_avc;
  1810. hevc_supported |= info.supports_hevc;
  1811. av1_supported |= info.supports_av1;
  1812. }
  1813. if (!avc_supported && !hevc_supported && !av1_supported)
  1814. throw "Neither AVC, HEVC, nor AV1 are supported by any devices";
  1815. /* ----------------------------------- */
  1816. /* Init AMF */
  1817. amf_module = LoadLibraryW(AMF_DLL_NAME);
  1818. if (!amf_module)
  1819. throw "AMF library failed to load";
  1820. AMFInit_Fn init =
  1821. (AMFInit_Fn)GetProcAddress(amf_module, AMF_INIT_FUNCTION_NAME);
  1822. if (!init)
  1823. throw "Failed to get AMFInit address";
  1824. res = init(AMF_FULL_VERSION, &amf_factory);
  1825. if (res != AMF_OK)
  1826. throw amf_error("AMFInit failed", res);
  1827. res = amf_factory->GetTrace(&amf_trace);
  1828. if (res != AMF_OK)
  1829. throw amf_error("GetTrace failed", res);
  1830. AMFQueryVersion_Fn get_ver = (AMFQueryVersion_Fn)GetProcAddress(
  1831. amf_module, AMF_QUERY_VERSION_FUNCTION_NAME);
  1832. if (!get_ver)
  1833. throw "Failed to get AMFQueryVersion address";
  1834. res = get_ver(&amf_version);
  1835. if (res != AMF_OK)
  1836. throw amf_error("AMFQueryVersion failed", res);
  1837. #ifndef DEBUG_AMF_STUFF
  1838. amf_trace->EnableWriter(AMF_TRACE_WRITER_DEBUG_OUTPUT, false);
  1839. amf_trace->EnableWriter(AMF_TRACE_WRITER_CONSOLE, false);
  1840. #endif
  1841. /* ----------------------------------- */
  1842. /* Register encoders */
  1843. if (avc_supported)
  1844. register_avc();
  1845. #if ENABLE_HEVC
  1846. if (hevc_supported)
  1847. register_hevc();
  1848. #endif
  1849. if (av1_supported)
  1850. register_av1();
  1851. } catch (const std::string &str) {
  1852. /* doing debug here because string exceptions indicate the user is
  1853. * probably not using AMD */
  1854. blog(LOG_DEBUG, "%s: %s", __FUNCTION__, str.c_str());
  1855. } catch (const char *str) {
  1856. /* doing debug here because string exceptions indicate the user is
  1857. * probably not using AMD */
  1858. blog(LOG_DEBUG, "%s: %s", __FUNCTION__, str);
  1859. } catch (const amf_error &err) {
  1860. /* doing an error here because it means at least the library has loaded
  1861. * successfully, so they probably have AMD at this point */
  1862. blog(LOG_ERROR, "%s: %s: 0x%lX", __FUNCTION__, err.str,
  1863. (uint32_t)err.res);
  1864. }
  1865. extern "C" void amf_unload(void)
  1866. {
  1867. if (amf_module && amf_trace) {
  1868. amf_trace->TraceFlush();
  1869. amf_trace->UnregisterWriter(L"obs_amf_trace_writer");
  1870. }
  1871. }