texture-amf.cpp 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276
  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. obs_property_list_add_string(p, "VBR_LAT", "VBR_LAT");
  907. obs_property_list_add_string(p, "QVBR", "QVBR");
  908. obs_property_list_add_string(p, "HQVBR", "HQVBR");
  909. obs_property_list_add_string(p, "HQCBR", "HQCBR");
  910. obs_property_set_modified_callback(p, rate_control_modified);
  911. p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"),
  912. 50, 100000, 50);
  913. obs_property_int_set_suffix(p, " Kbps");
  914. obs_properties_add_int(props, "cqp", obs_module_text("NVENC.CQLevel"),
  915. 0, codec == amf_codec_type::AV1 ? 63 : 51, 1);
  916. p = obs_properties_add_int(props, "keyint_sec",
  917. obs_module_text("KeyframeIntervalSec"), 0,
  918. 10, 1);
  919. obs_property_int_set_suffix(p, " s");
  920. p = obs_properties_add_list(props, "preset", obs_module_text("Preset"),
  921. OBS_COMBO_TYPE_LIST,
  922. OBS_COMBO_FORMAT_STRING);
  923. #define add_preset(val) \
  924. obs_property_list_add_string(p, obs_module_text("AMF.Preset." val), val)
  925. if (amf_codec_type::AV1 == codec) {
  926. add_preset("highQuality");
  927. }
  928. add_preset("quality");
  929. add_preset("balanced");
  930. add_preset("speed");
  931. #undef add_preset
  932. if (amf_codec_type::AVC == codec || amf_codec_type::AV1 == codec) {
  933. p = obs_properties_add_list(props, "profile",
  934. obs_module_text("Profile"),
  935. OBS_COMBO_TYPE_LIST,
  936. OBS_COMBO_FORMAT_STRING);
  937. #define add_profile(val) obs_property_list_add_string(p, val, val)
  938. if (amf_codec_type::AVC == codec)
  939. add_profile("high");
  940. add_profile("main");
  941. if (amf_codec_type::AVC == codec)
  942. add_profile("baseline");
  943. #undef add_profile
  944. }
  945. if (amf_codec_type::AVC == codec) {
  946. obs_properties_add_int(props, "bf", obs_module_text("BFrames"),
  947. 0, 5, 1);
  948. }
  949. p = obs_properties_add_text(props, "ffmpeg_opts",
  950. obs_module_text("AMFOpts"),
  951. OBS_TEXT_DEFAULT);
  952. obs_property_set_long_description(p,
  953. obs_module_text("AMFOpts.ToolTip"));
  954. return props;
  955. }
  956. static obs_properties_t *amf_avc_properties(void *unused)
  957. {
  958. UNUSED_PARAMETER(unused);
  959. return amf_properties_internal(amf_codec_type::AVC);
  960. }
  961. static obs_properties_t *amf_hevc_properties(void *unused)
  962. {
  963. UNUSED_PARAMETER(unused);
  964. return amf_properties_internal(amf_codec_type::HEVC);
  965. }
  966. static obs_properties_t *amf_av1_properties(void *unused)
  967. {
  968. UNUSED_PARAMETER(unused);
  969. return amf_properties_internal(amf_codec_type::AV1);
  970. }
  971. /* ========================================================================= */
  972. /* AVC Implementation */
  973. static const char *amf_avc_get_name(void *)
  974. {
  975. return "AMD HW H.264 (AVC)";
  976. }
  977. static inline int get_avc_preset(amf_base *enc, const char *preset)
  978. {
  979. if (astrcmpi(preset, "quality") == 0)
  980. return AMF_VIDEO_ENCODER_QUALITY_PRESET_QUALITY;
  981. else if (astrcmpi(preset, "speed") == 0)
  982. return AMF_VIDEO_ENCODER_QUALITY_PRESET_SPEED;
  983. return AMF_VIDEO_ENCODER_QUALITY_PRESET_BALANCED;
  984. }
  985. static inline int get_avc_rate_control(const char *rc_str)
  986. {
  987. if (astrcmpi(rc_str, "cqp") == 0)
  988. return AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CONSTANT_QP;
  989. else if (astrcmpi(rc_str, "vbr") == 0)
  990. return AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR;
  991. return AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CBR;
  992. }
  993. static inline int get_avc_profile(obs_data_t *settings)
  994. {
  995. const char *profile = obs_data_get_string(settings, "profile");
  996. if (astrcmpi(profile, "baseline") == 0)
  997. return AMF_VIDEO_ENCODER_PROFILE_BASELINE;
  998. else if (astrcmpi(profile, "main") == 0)
  999. return AMF_VIDEO_ENCODER_PROFILE_MAIN;
  1000. else if (astrcmpi(profile, "constrained_baseline") == 0)
  1001. return AMF_VIDEO_ENCODER_PROFILE_CONSTRAINED_BASELINE;
  1002. else if (astrcmpi(profile, "constrained_high") == 0)
  1003. return AMF_VIDEO_ENCODER_PROFILE_CONSTRAINED_HIGH;
  1004. return AMF_VIDEO_ENCODER_PROFILE_HIGH;
  1005. }
  1006. static void amf_avc_update_data(amf_base *enc, int rc, int64_t bitrate,
  1007. int64_t qp)
  1008. {
  1009. if (rc != AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CONSTANT_QP) {
  1010. set_avc_property(enc, TARGET_BITRATE, bitrate);
  1011. set_avc_property(enc, PEAK_BITRATE, bitrate);
  1012. set_avc_property(enc, VBV_BUFFER_SIZE, bitrate);
  1013. if (rc == AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CBR) {
  1014. set_avc_property(enc, FILLER_DATA_ENABLE, true);
  1015. }
  1016. } else {
  1017. set_avc_property(enc, QP_I, qp);
  1018. set_avc_property(enc, QP_P, qp);
  1019. set_avc_property(enc, QP_B, qp);
  1020. }
  1021. }
  1022. static bool amf_avc_update(void *data, obs_data_t *settings)
  1023. try {
  1024. amf_base *enc = (amf_base *)data;
  1025. if (enc->first_update) {
  1026. enc->first_update = false;
  1027. return true;
  1028. }
  1029. int64_t bitrate = obs_data_get_int(settings, "bitrate");
  1030. int64_t qp = obs_data_get_int(settings, "cqp");
  1031. const char *rc_str = obs_data_get_string(settings, "rate_control");
  1032. int rc = get_avc_rate_control(rc_str);
  1033. AMF_RESULT res;
  1034. amf_avc_update_data(enc, rc, bitrate * 1000, qp);
  1035. res = enc->amf_encoder->ReInit(enc->cx, enc->cy);
  1036. if (res != AMF_OK)
  1037. throw amf_error("AMFComponent::Init failed", res);
  1038. return true;
  1039. } catch (const amf_error &err) {
  1040. amf_base *enc = (amf_base *)data;
  1041. error("%s: %s: %ls", __FUNCTION__, err.str,
  1042. amf_trace->GetResultText(err.res));
  1043. return false;
  1044. }
  1045. static bool amf_avc_init(void *data, obs_data_t *settings)
  1046. {
  1047. amf_base *enc = (amf_base *)data;
  1048. int64_t bitrate = obs_data_get_int(settings, "bitrate");
  1049. int64_t qp = obs_data_get_int(settings, "cqp");
  1050. const char *preset = obs_data_get_string(settings, "preset");
  1051. const char *profile = obs_data_get_string(settings, "profile");
  1052. const char *rc_str = obs_data_get_string(settings, "rate_control");
  1053. int64_t bf = obs_data_get_int(settings, "bf");
  1054. if (enc->bframes_supported) {
  1055. set_avc_property(enc, MAX_CONSECUTIVE_BPICTURES, 3);
  1056. set_avc_property(enc, B_PIC_PATTERN, bf);
  1057. } else if (bf != 0) {
  1058. warn("B-Frames set to %lld but b-frames are not "
  1059. "supported by this device",
  1060. bf);
  1061. bf = 0;
  1062. }
  1063. int rc = get_avc_rate_control(rc_str);
  1064. set_avc_property(enc, RATE_CONTROL_METHOD, rc);
  1065. if (rc != AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CONSTANT_QP)
  1066. set_avc_property(enc, ENABLE_VBAQ, true);
  1067. amf_avc_update_data(enc, rc, bitrate * 1000, qp);
  1068. set_avc_property(enc, ENFORCE_HRD, true);
  1069. set_avc_property(enc, HIGH_MOTION_QUALITY_BOOST_ENABLE, false);
  1070. int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec");
  1071. int gop_size = (keyint_sec) ? keyint_sec * enc->fps_num / enc->fps_den
  1072. : 250;
  1073. set_avc_property(enc, IDR_PERIOD, gop_size);
  1074. bool repeat_headers = obs_data_get_bool(settings, "repeat_headers");
  1075. if (repeat_headers)
  1076. set_avc_property(enc, HEADER_INSERTION_SPACING, gop_size);
  1077. set_avc_property(enc, DE_BLOCKING_FILTER, true);
  1078. check_preset_compatibility(enc, preset);
  1079. const char *ffmpeg_opts = obs_data_get_string(settings, "ffmpeg_opts");
  1080. if (ffmpeg_opts && *ffmpeg_opts) {
  1081. struct obs_options opts = obs_parse_options(ffmpeg_opts);
  1082. for (size_t i = 0; i < opts.count; i++) {
  1083. amf_apply_opt(enc, &opts.options[i]);
  1084. }
  1085. obs_free_options(opts);
  1086. }
  1087. if (!ffmpeg_opts || !*ffmpeg_opts)
  1088. ffmpeg_opts = "(none)";
  1089. info("settings:\n"
  1090. "\trate_control: %s\n"
  1091. "\tbitrate: %d\n"
  1092. "\tcqp: %d\n"
  1093. "\tkeyint: %d\n"
  1094. "\tpreset: %s\n"
  1095. "\tprofile: %s\n"
  1096. "\tb-frames: %d\n"
  1097. "\twidth: %d\n"
  1098. "\theight: %d\n"
  1099. "\tparams: %s",
  1100. rc_str, bitrate, qp, gop_size, preset, profile, bf, enc->cx,
  1101. enc->cy, ffmpeg_opts);
  1102. return true;
  1103. }
  1104. static void amf_avc_create_internal(amf_base *enc, obs_data_t *settings)
  1105. {
  1106. AMF_RESULT res;
  1107. AMFVariant p;
  1108. enc->codec = amf_codec_type::AVC;
  1109. if (!amf_create_encoder(enc))
  1110. throw "Failed to create encoder";
  1111. AMFCapsPtr caps;
  1112. res = enc->amf_encoder->GetCaps(&caps);
  1113. if (res == AMF_OK) {
  1114. caps->GetProperty(AMF_VIDEO_ENCODER_CAP_BFRAMES,
  1115. &enc->bframes_supported);
  1116. caps->GetProperty(AMF_VIDEO_ENCODER_CAP_MAX_THROUGHPUT,
  1117. &enc->max_throughput);
  1118. }
  1119. const char *preset = obs_data_get_string(settings, "preset");
  1120. set_avc_property(enc, FRAMESIZE, AMFConstructSize(enc->cx, enc->cy));
  1121. set_avc_property(enc, USAGE, AMF_VIDEO_ENCODER_USAGE_TRANSCODING);
  1122. set_avc_property(enc, QUALITY_PRESET, get_avc_preset(enc, preset));
  1123. set_avc_property(enc, PROFILE, get_avc_profile(settings));
  1124. set_avc_property(enc, LOWLATENCY_MODE, false);
  1125. set_avc_property(enc, CABAC_ENABLE, AMF_VIDEO_ENCODER_UNDEFINED);
  1126. set_avc_property(enc, PREENCODE_ENABLE, true);
  1127. set_avc_property(enc, OUTPUT_COLOR_PROFILE, enc->amf_color_profile);
  1128. set_avc_property(enc, OUTPUT_TRANSFER_CHARACTERISTIC,
  1129. enc->amf_characteristic);
  1130. set_avc_property(enc, OUTPUT_COLOR_PRIMARIES, enc->amf_primaries);
  1131. set_avc_property(enc, FULL_RANGE_COLOR, enc->full_range);
  1132. amf_avc_init(enc, settings);
  1133. res = enc->amf_encoder->Init(enc->amf_format, enc->cx, enc->cy);
  1134. if (res != AMF_OK)
  1135. throw amf_error("AMFComponent::Init failed", res);
  1136. set_avc_property(enc, FRAMERATE, enc->amf_frame_rate);
  1137. res = enc->amf_encoder->GetProperty(AMF_VIDEO_ENCODER_EXTRADATA, &p);
  1138. if (res == AMF_OK && p.type == AMF_VARIANT_INTERFACE)
  1139. enc->header = AMFBufferPtr(p.pInterface);
  1140. if (enc->bframes_supported) {
  1141. amf_int64 b_frames = 0;
  1142. amf_int64 b_max = 0;
  1143. if (get_avc_property(enc, B_PIC_PATTERN, &b_frames) &&
  1144. get_avc_property(enc, MAX_CONSECUTIVE_BPICTURES, &b_max))
  1145. enc->dts_offset = b_frames + 1;
  1146. else
  1147. enc->dts_offset = 0;
  1148. }
  1149. }
  1150. static void *amf_avc_create_texencode(obs_data_t *settings,
  1151. obs_encoder_t *encoder)
  1152. try {
  1153. check_texture_encode_capability(encoder, amf_codec_type::AVC);
  1154. std::unique_ptr<amf_texencode> enc = std::make_unique<amf_texencode>();
  1155. enc->encoder = encoder;
  1156. enc->encoder_str = "texture-amf-h264";
  1157. if (!amf_init_d3d11(enc.get()))
  1158. throw "Failed to create D3D11";
  1159. amf_avc_create_internal(enc.get(), settings);
  1160. return enc.release();
  1161. } catch (const amf_error &err) {
  1162. blog(LOG_ERROR, "[texture-amf-h264] %s: %s: %ls", __FUNCTION__, err.str,
  1163. amf_trace->GetResultText(err.res));
  1164. return obs_encoder_create_rerouted(encoder, "h264_fallback_amf");
  1165. } catch (const char *err) {
  1166. blog(LOG_ERROR, "[texture-amf-h264] %s: %s", __FUNCTION__, err);
  1167. return obs_encoder_create_rerouted(encoder, "h264_fallback_amf");
  1168. }
  1169. static void *amf_avc_create_fallback(obs_data_t *settings,
  1170. obs_encoder_t *encoder)
  1171. try {
  1172. std::unique_ptr<amf_fallback> enc = std::make_unique<amf_fallback>();
  1173. enc->encoder = encoder;
  1174. enc->encoder_str = "fallback-amf-h264";
  1175. video_t *video = obs_encoder_video(encoder);
  1176. const struct video_output_info *voi = video_output_get_info(video);
  1177. switch (voi->format) {
  1178. case VIDEO_FORMAT_I010:
  1179. case VIDEO_FORMAT_P010: {
  1180. const char *const text =
  1181. obs_module_text("AMF.10bitUnsupportedAvc");
  1182. obs_encoder_set_last_error(encoder, text);
  1183. throw text;
  1184. }
  1185. default:
  1186. switch (voi->colorspace) {
  1187. case VIDEO_CS_2100_PQ:
  1188. case VIDEO_CS_2100_HLG: {
  1189. const char *const text =
  1190. obs_module_text("AMF.8bitUnsupportedHdr");
  1191. obs_encoder_set_last_error(encoder, text);
  1192. throw text;
  1193. }
  1194. }
  1195. }
  1196. amf_avc_create_internal(enc.get(), settings);
  1197. return enc.release();
  1198. } catch (const amf_error &err) {
  1199. blog(LOG_ERROR, "[fallback-amf-h264] %s: %s: %ls", __FUNCTION__,
  1200. err.str, amf_trace->GetResultText(err.res));
  1201. return nullptr;
  1202. } catch (const char *err) {
  1203. blog(LOG_ERROR, "[fallback-amf-h264] %s: %s", __FUNCTION__, err);
  1204. return nullptr;
  1205. }
  1206. static void register_avc()
  1207. {
  1208. struct obs_encoder_info amf_encoder_info = {};
  1209. amf_encoder_info.id = "h264_texture_amf";
  1210. amf_encoder_info.type = OBS_ENCODER_VIDEO;
  1211. amf_encoder_info.codec = "h264";
  1212. amf_encoder_info.get_name = amf_avc_get_name;
  1213. amf_encoder_info.create = amf_avc_create_texencode;
  1214. amf_encoder_info.destroy = amf_destroy;
  1215. amf_encoder_info.update = amf_avc_update;
  1216. amf_encoder_info.encode_texture = amf_encode_tex;
  1217. amf_encoder_info.get_defaults = amf_defaults;
  1218. amf_encoder_info.get_properties = amf_avc_properties;
  1219. amf_encoder_info.get_extra_data = amf_extra_data;
  1220. amf_encoder_info.caps = OBS_ENCODER_CAP_PASS_TEXTURE |
  1221. OBS_ENCODER_CAP_DYN_BITRATE;
  1222. obs_register_encoder(&amf_encoder_info);
  1223. amf_encoder_info.id = "h264_fallback_amf";
  1224. amf_encoder_info.caps = OBS_ENCODER_CAP_INTERNAL |
  1225. OBS_ENCODER_CAP_DYN_BITRATE;
  1226. amf_encoder_info.encode_texture = nullptr;
  1227. amf_encoder_info.create = amf_avc_create_fallback;
  1228. amf_encoder_info.encode = amf_encode_fallback;
  1229. amf_encoder_info.get_video_info = h264_video_info_fallback;
  1230. obs_register_encoder(&amf_encoder_info);
  1231. }
  1232. /* ========================================================================= */
  1233. /* HEVC Implementation */
  1234. #if ENABLE_HEVC
  1235. static const char *amf_hevc_get_name(void *)
  1236. {
  1237. return "AMD HW H.265 (HEVC)";
  1238. }
  1239. static inline int get_hevc_preset(amf_base *enc, const char *preset)
  1240. {
  1241. if (astrcmpi(preset, "balanced") == 0)
  1242. return AMF_VIDEO_ENCODER_HEVC_QUALITY_PRESET_BALANCED;
  1243. else if (astrcmpi(preset, "speed") == 0)
  1244. return AMF_VIDEO_ENCODER_HEVC_QUALITY_PRESET_SPEED;
  1245. return AMF_VIDEO_ENCODER_HEVC_QUALITY_PRESET_QUALITY;
  1246. }
  1247. static inline int get_hevc_rate_control(const char *rc_str)
  1248. {
  1249. if (astrcmpi(rc_str, "cqp") == 0)
  1250. return AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CONSTANT_QP;
  1251. else if (astrcmpi(rc_str, "vbr") == 0)
  1252. return AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR;
  1253. return AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CBR;
  1254. }
  1255. static void amf_hevc_update_data(amf_base *enc, int rc, int64_t bitrate,
  1256. int64_t qp)
  1257. {
  1258. if (rc != AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CONSTANT_QP) {
  1259. set_hevc_property(enc, TARGET_BITRATE, bitrate);
  1260. set_hevc_property(enc, PEAK_BITRATE, bitrate);
  1261. set_hevc_property(enc, VBV_BUFFER_SIZE, bitrate);
  1262. if (rc == AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CBR) {
  1263. set_hevc_property(enc, FILLER_DATA_ENABLE, true);
  1264. }
  1265. } else {
  1266. set_hevc_property(enc, QP_I, qp);
  1267. set_hevc_property(enc, QP_P, qp);
  1268. }
  1269. }
  1270. static bool amf_hevc_update(void *data, obs_data_t *settings)
  1271. try {
  1272. amf_base *enc = (amf_base *)data;
  1273. if (enc->first_update) {
  1274. enc->first_update = false;
  1275. return true;
  1276. }
  1277. int64_t bitrate = obs_data_get_int(settings, "bitrate");
  1278. int64_t qp = obs_data_get_int(settings, "cqp");
  1279. const char *rc_str = obs_data_get_string(settings, "rate_control");
  1280. int rc = get_hevc_rate_control(rc_str);
  1281. AMF_RESULT res;
  1282. amf_hevc_update_data(enc, rc, bitrate * 1000, qp);
  1283. res = enc->amf_encoder->ReInit(enc->cx, enc->cy);
  1284. if (res != AMF_OK)
  1285. throw amf_error("AMFComponent::Init failed", res);
  1286. return true;
  1287. } catch (const amf_error &err) {
  1288. amf_base *enc = (amf_base *)data;
  1289. error("%s: %s: %ls", __FUNCTION__, err.str,
  1290. amf_trace->GetResultText(err.res));
  1291. return false;
  1292. }
  1293. static bool amf_hevc_init(void *data, obs_data_t *settings)
  1294. {
  1295. amf_base *enc = (amf_base *)data;
  1296. int64_t bitrate = obs_data_get_int(settings, "bitrate");
  1297. int64_t qp = obs_data_get_int(settings, "cqp");
  1298. const char *preset = obs_data_get_string(settings, "preset");
  1299. const char *profile = obs_data_get_string(settings, "profile");
  1300. const char *rc_str = obs_data_get_string(settings, "rate_control");
  1301. int rc = get_hevc_rate_control(rc_str);
  1302. set_hevc_property(enc, RATE_CONTROL_METHOD, rc);
  1303. if (rc != AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CONSTANT_QP)
  1304. set_hevc_property(enc, ENABLE_VBAQ, true);
  1305. amf_hevc_update_data(enc, rc, bitrate * 1000, qp);
  1306. set_hevc_property(enc, ENFORCE_HRD, true);
  1307. set_hevc_property(enc, HIGH_MOTION_QUALITY_BOOST_ENABLE, false);
  1308. int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec");
  1309. int gop_size = (keyint_sec) ? keyint_sec * enc->fps_num / enc->fps_den
  1310. : 250;
  1311. set_hevc_property(enc, GOP_SIZE, gop_size);
  1312. check_preset_compatibility(enc, preset);
  1313. const char *ffmpeg_opts = obs_data_get_string(settings, "ffmpeg_opts");
  1314. if (ffmpeg_opts && *ffmpeg_opts) {
  1315. struct obs_options opts = obs_parse_options(ffmpeg_opts);
  1316. for (size_t i = 0; i < opts.count; i++) {
  1317. amf_apply_opt(enc, &opts.options[i]);
  1318. }
  1319. obs_free_options(opts);
  1320. }
  1321. if (!ffmpeg_opts || !*ffmpeg_opts)
  1322. ffmpeg_opts = "(none)";
  1323. info("settings:\n"
  1324. "\trate_control: %s\n"
  1325. "\tbitrate: %d\n"
  1326. "\tcqp: %d\n"
  1327. "\tkeyint: %d\n"
  1328. "\tpreset: %s\n"
  1329. "\tprofile: %s\n"
  1330. "\twidth: %d\n"
  1331. "\theight: %d\n"
  1332. "\tparams: %s",
  1333. rc_str, bitrate, qp, gop_size, preset, profile, enc->cx, enc->cy,
  1334. ffmpeg_opts);
  1335. return true;
  1336. }
  1337. static inline bool is_hlg(amf_base *enc)
  1338. {
  1339. return enc->amf_characteristic ==
  1340. AMF_COLOR_TRANSFER_CHARACTERISTIC_ARIB_STD_B67;
  1341. }
  1342. static inline bool is_pq(amf_base *enc)
  1343. {
  1344. return enc->amf_characteristic ==
  1345. AMF_COLOR_TRANSFER_CHARACTERISTIC_SMPTE2084;
  1346. }
  1347. constexpr amf_uint16 amf_hdr_primary(uint32_t num, uint32_t den)
  1348. {
  1349. return (amf_uint16)(num * 50000 / den);
  1350. }
  1351. constexpr amf_uint32 lum_mul = 10000;
  1352. constexpr amf_uint32 amf_make_lum(amf_uint32 val)
  1353. {
  1354. return val * lum_mul;
  1355. }
  1356. static void amf_hevc_create_internal(amf_base *enc, obs_data_t *settings)
  1357. {
  1358. AMF_RESULT res;
  1359. AMFVariant p;
  1360. enc->codec = amf_codec_type::HEVC;
  1361. if (!amf_create_encoder(enc))
  1362. throw "Failed to create encoder";
  1363. AMFCapsPtr caps;
  1364. res = enc->amf_encoder->GetCaps(&caps);
  1365. if (res == AMF_OK) {
  1366. caps->GetProperty(AMF_VIDEO_ENCODER_HEVC_CAP_MAX_THROUGHPUT,
  1367. &enc->max_throughput);
  1368. }
  1369. const bool is10bit = enc->amf_format == AMF_SURFACE_P010;
  1370. const bool pq = is_pq(enc);
  1371. const bool hlg = is_hlg(enc);
  1372. const bool is_hdr = pq || hlg;
  1373. const char *preset = obs_data_get_string(settings, "preset");
  1374. set_hevc_property(enc, FRAMESIZE, AMFConstructSize(enc->cx, enc->cy));
  1375. set_hevc_property(enc, USAGE, AMF_VIDEO_ENCODER_USAGE_TRANSCODING);
  1376. set_hevc_property(enc, QUALITY_PRESET, get_hevc_preset(enc, preset));
  1377. set_hevc_property(enc, COLOR_BIT_DEPTH,
  1378. is10bit ? AMF_COLOR_BIT_DEPTH_10
  1379. : AMF_COLOR_BIT_DEPTH_8);
  1380. set_hevc_property(enc, PROFILE,
  1381. is10bit ? AMF_VIDEO_ENCODER_HEVC_PROFILE_MAIN_10
  1382. : AMF_VIDEO_ENCODER_HEVC_PROFILE_MAIN);
  1383. set_hevc_property(enc, LOWLATENCY_MODE, false);
  1384. set_hevc_property(enc, OUTPUT_COLOR_PROFILE, enc->amf_color_profile);
  1385. set_hevc_property(enc, OUTPUT_TRANSFER_CHARACTERISTIC,
  1386. enc->amf_characteristic);
  1387. set_hevc_property(enc, OUTPUT_COLOR_PRIMARIES, enc->amf_primaries);
  1388. set_hevc_property(enc, NOMINAL_RANGE, enc->full_range);
  1389. if (is_hdr) {
  1390. const int hdr_nominal_peak_level =
  1391. pq ? (int)obs_get_video_hdr_nominal_peak_level()
  1392. : (hlg ? 1000 : 0);
  1393. AMFBufferPtr buf;
  1394. enc->amf_context->AllocBuffer(AMF_MEMORY_HOST,
  1395. sizeof(AMFHDRMetadata), &buf);
  1396. AMFHDRMetadata *md = (AMFHDRMetadata *)buf->GetNative();
  1397. md->redPrimary[0] = amf_hdr_primary(17, 25);
  1398. md->redPrimary[1] = amf_hdr_primary(8, 25);
  1399. md->greenPrimary[0] = amf_hdr_primary(53, 200);
  1400. md->greenPrimary[1] = amf_hdr_primary(69, 100);
  1401. md->bluePrimary[0] = amf_hdr_primary(3, 20);
  1402. md->bluePrimary[1] = amf_hdr_primary(3, 50);
  1403. md->whitePoint[0] = amf_hdr_primary(3127, 10000);
  1404. md->whitePoint[1] = amf_hdr_primary(329, 1000);
  1405. md->minMasteringLuminance = 0;
  1406. md->maxMasteringLuminance =
  1407. amf_make_lum(hdr_nominal_peak_level);
  1408. md->maxContentLightLevel = hdr_nominal_peak_level;
  1409. md->maxFrameAverageLightLevel = hdr_nominal_peak_level;
  1410. set_hevc_property(enc, INPUT_HDR_METADATA, buf);
  1411. }
  1412. amf_hevc_init(enc, settings);
  1413. res = enc->amf_encoder->Init(enc->amf_format, enc->cx, enc->cy);
  1414. if (res != AMF_OK)
  1415. throw amf_error("AMFComponent::Init failed", res);
  1416. set_hevc_property(enc, FRAMERATE, enc->amf_frame_rate);
  1417. res = enc->amf_encoder->GetProperty(AMF_VIDEO_ENCODER_HEVC_EXTRADATA,
  1418. &p);
  1419. if (res == AMF_OK && p.type == AMF_VARIANT_INTERFACE)
  1420. enc->header = AMFBufferPtr(p.pInterface);
  1421. }
  1422. static void *amf_hevc_create_texencode(obs_data_t *settings,
  1423. obs_encoder_t *encoder)
  1424. try {
  1425. check_texture_encode_capability(encoder, amf_codec_type::HEVC);
  1426. std::unique_ptr<amf_texencode> enc = std::make_unique<amf_texencode>();
  1427. enc->encoder = encoder;
  1428. enc->encoder_str = "texture-amf-h265";
  1429. if (!amf_init_d3d11(enc.get()))
  1430. throw "Failed to create D3D11";
  1431. amf_hevc_create_internal(enc.get(), settings);
  1432. return enc.release();
  1433. } catch (const amf_error &err) {
  1434. blog(LOG_ERROR, "[texture-amf-h265] %s: %s: %ls", __FUNCTION__, err.str,
  1435. amf_trace->GetResultText(err.res));
  1436. return obs_encoder_create_rerouted(encoder, "h265_fallback_amf");
  1437. } catch (const char *err) {
  1438. blog(LOG_ERROR, "[texture-amf-h265] %s: %s", __FUNCTION__, err);
  1439. return obs_encoder_create_rerouted(encoder, "h265_fallback_amf");
  1440. }
  1441. static void *amf_hevc_create_fallback(obs_data_t *settings,
  1442. obs_encoder_t *encoder)
  1443. try {
  1444. std::unique_ptr<amf_fallback> enc = std::make_unique<amf_fallback>();
  1445. enc->encoder = encoder;
  1446. enc->encoder_str = "fallback-amf-h265";
  1447. video_t *video = obs_encoder_video(encoder);
  1448. const struct video_output_info *voi = video_output_get_info(video);
  1449. switch (voi->format) {
  1450. case VIDEO_FORMAT_I010:
  1451. case VIDEO_FORMAT_P010:
  1452. break;
  1453. default:
  1454. switch (voi->colorspace) {
  1455. case VIDEO_CS_2100_PQ:
  1456. case VIDEO_CS_2100_HLG: {
  1457. const char *const text =
  1458. obs_module_text("AMF.8bitUnsupportedHdr");
  1459. obs_encoder_set_last_error(encoder, text);
  1460. throw text;
  1461. }
  1462. }
  1463. }
  1464. amf_hevc_create_internal(enc.get(), settings);
  1465. return enc.release();
  1466. } catch (const amf_error &err) {
  1467. blog(LOG_ERROR, "[fallback-amf-h265] %s: %s: %ls", __FUNCTION__,
  1468. err.str, amf_trace->GetResultText(err.res));
  1469. return nullptr;
  1470. } catch (const char *err) {
  1471. blog(LOG_ERROR, "[fallback-amf-h265] %s: %s", __FUNCTION__, err);
  1472. return nullptr;
  1473. }
  1474. static void register_hevc()
  1475. {
  1476. struct obs_encoder_info amf_encoder_info = {};
  1477. amf_encoder_info.id = "h265_texture_amf";
  1478. amf_encoder_info.type = OBS_ENCODER_VIDEO;
  1479. amf_encoder_info.codec = "hevc";
  1480. amf_encoder_info.get_name = amf_hevc_get_name;
  1481. amf_encoder_info.create = amf_hevc_create_texencode;
  1482. amf_encoder_info.destroy = amf_destroy;
  1483. amf_encoder_info.update = amf_hevc_update;
  1484. amf_encoder_info.encode_texture = amf_encode_tex;
  1485. amf_encoder_info.get_defaults = amf_defaults;
  1486. amf_encoder_info.get_properties = amf_hevc_properties;
  1487. amf_encoder_info.get_extra_data = amf_extra_data;
  1488. amf_encoder_info.caps = OBS_ENCODER_CAP_PASS_TEXTURE |
  1489. OBS_ENCODER_CAP_DYN_BITRATE;
  1490. obs_register_encoder(&amf_encoder_info);
  1491. amf_encoder_info.id = "h265_fallback_amf";
  1492. amf_encoder_info.caps = OBS_ENCODER_CAP_INTERNAL |
  1493. OBS_ENCODER_CAP_DYN_BITRATE;
  1494. amf_encoder_info.encode_texture = nullptr;
  1495. amf_encoder_info.create = amf_hevc_create_fallback;
  1496. amf_encoder_info.encode = amf_encode_fallback;
  1497. amf_encoder_info.get_video_info = h265_video_info_fallback;
  1498. obs_register_encoder(&amf_encoder_info);
  1499. }
  1500. #endif //ENABLE_HEVC
  1501. /* ========================================================================= */
  1502. /* AV1 Implementation */
  1503. static const char *amf_av1_get_name(void *)
  1504. {
  1505. return "AMD HW AV1";
  1506. }
  1507. static inline int get_av1_preset(amf_base *enc, const char *preset)
  1508. {
  1509. if (astrcmpi(preset, "highquality") == 0)
  1510. return AMF_VIDEO_ENCODER_AV1_QUALITY_PRESET_HIGH_QUALITY;
  1511. else if (astrcmpi(preset, "quality") == 0)
  1512. return AMF_VIDEO_ENCODER_AV1_QUALITY_PRESET_QUALITY;
  1513. else if (astrcmpi(preset, "balanced") == 0)
  1514. return AMF_VIDEO_ENCODER_AV1_QUALITY_PRESET_BALANCED;
  1515. else if (astrcmpi(preset, "speed") == 0)
  1516. return AMF_VIDEO_ENCODER_AV1_QUALITY_PRESET_SPEED;
  1517. return AMF_VIDEO_ENCODER_AV1_QUALITY_PRESET_BALANCED;
  1518. }
  1519. static inline int get_av1_rate_control(const char *rc_str)
  1520. {
  1521. if (astrcmpi(rc_str, "cqp") == 0)
  1522. return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_CONSTANT_QP;
  1523. else if (astrcmpi(rc_str, "vbr_lat") == 0)
  1524. return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_LATENCY_CONSTRAINED_VBR;
  1525. else if (astrcmpi(rc_str, "vbr") == 0)
  1526. return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR;
  1527. else if (astrcmpi(rc_str, "cbr") == 0)
  1528. return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_CBR;
  1529. else if (astrcmpi(rc_str, "qvbr") == 0)
  1530. return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_QUALITY_VBR;
  1531. else if (astrcmpi(rc_str, "hqvbr") == 0)
  1532. return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_HIGH_QUALITY_VBR;
  1533. else if (astrcmpi(rc_str, "hqcbr") == 0)
  1534. return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_HIGH_QUALITY_CBR;
  1535. return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_CBR;
  1536. }
  1537. static inline int get_av1_profile(obs_data_t *settings)
  1538. {
  1539. const char *profile = obs_data_get_string(settings, "profile");
  1540. if (astrcmpi(profile, "main") == 0)
  1541. return AMF_VIDEO_ENCODER_AV1_PROFILE_MAIN;
  1542. return AMF_VIDEO_ENCODER_AV1_PROFILE_MAIN;
  1543. }
  1544. static void amf_av1_update_data(amf_base *enc, int rc, int64_t bitrate,
  1545. int64_t cq_value)
  1546. {
  1547. if (rc != AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_CONSTANT_QP) {
  1548. set_av1_property(enc, TARGET_BITRATE, bitrate);
  1549. set_av1_property(enc, PEAK_BITRATE, bitrate);
  1550. set_av1_property(enc, VBV_BUFFER_SIZE, bitrate);
  1551. if (rc == AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CBR) {
  1552. set_av1_property(enc, FILLER_DATA, true);
  1553. } else if (
  1554. rc == AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR ||
  1555. rc == AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_HIGH_QUALITY_VBR) {
  1556. set_av1_property(enc, PEAK_BITRATE, bitrate * 1.5);
  1557. }
  1558. } else {
  1559. int64_t qp = cq_value * 4;
  1560. set_av1_property(enc, Q_INDEX_INTRA, qp);
  1561. set_av1_property(enc, Q_INDEX_INTER, qp);
  1562. }
  1563. }
  1564. static bool amf_av1_update(void *data, obs_data_t *settings)
  1565. try {
  1566. amf_base *enc = (amf_base *)data;
  1567. if (enc->first_update) {
  1568. enc->first_update = false;
  1569. return true;
  1570. }
  1571. int64_t bitrate = obs_data_get_int(settings, "bitrate");
  1572. int64_t cq_level = obs_data_get_int(settings, "cqp");
  1573. const char *rc_str = obs_data_get_string(settings, "rate_control");
  1574. int rc = get_av1_rate_control(rc_str);
  1575. amf_av1_update_data(enc, rc, bitrate * 1000, cq_level);
  1576. AMF_RESULT res = enc->amf_encoder->ReInit(enc->cx, enc->cy);
  1577. if (res != AMF_OK)
  1578. throw amf_error("AMFComponent::Init failed", res);
  1579. return true;
  1580. } catch (const amf_error &err) {
  1581. amf_base *enc = (amf_base *)data;
  1582. error("%s: %s: %ls", __FUNCTION__, err.str,
  1583. amf_trace->GetResultText(err.res));
  1584. return false;
  1585. }
  1586. static bool amf_av1_init(void *data, obs_data_t *settings)
  1587. {
  1588. amf_base *enc = (amf_base *)data;
  1589. int64_t bitrate = obs_data_get_int(settings, "bitrate");
  1590. int64_t qp = obs_data_get_int(settings, "cqp");
  1591. const char *preset = obs_data_get_string(settings, "preset");
  1592. const char *profile = obs_data_get_string(settings, "profile");
  1593. const char *rc_str = obs_data_get_string(settings, "rate_control");
  1594. int rc = get_av1_rate_control(rc_str);
  1595. set_av1_property(enc, RATE_CONTROL_METHOD, rc);
  1596. amf_av1_update_data(enc, rc, bitrate * 1000, qp);
  1597. set_av1_property(enc, ENFORCE_HRD, true);
  1598. int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec");
  1599. int gop_size = (keyint_sec) ? keyint_sec * enc->fps_num / enc->fps_den
  1600. : 250;
  1601. set_av1_property(enc, GOP_SIZE, gop_size);
  1602. const char *ffmpeg_opts = obs_data_get_string(settings, "ffmpeg_opts");
  1603. if (ffmpeg_opts && *ffmpeg_opts) {
  1604. struct obs_options opts = obs_parse_options(ffmpeg_opts);
  1605. for (size_t i = 0; i < opts.count; i++) {
  1606. amf_apply_opt(enc, &opts.options[i]);
  1607. }
  1608. obs_free_options(opts);
  1609. }
  1610. check_preset_compatibility(enc, preset);
  1611. if (!ffmpeg_opts || !*ffmpeg_opts)
  1612. ffmpeg_opts = "(none)";
  1613. info("settings:\n"
  1614. "\trate_control: %s\n"
  1615. "\tbitrate: %d\n"
  1616. "\tcqp: %d\n"
  1617. "\tkeyint: %d\n"
  1618. "\tpreset: %s\n"
  1619. "\tprofile: %s\n"
  1620. "\twidth: %d\n"
  1621. "\theight: %d\n"
  1622. "\tparams: %s",
  1623. rc_str, bitrate, qp, gop_size, preset, profile, enc->cx, enc->cy,
  1624. ffmpeg_opts);
  1625. return true;
  1626. }
  1627. static void amf_av1_create_internal(amf_base *enc, obs_data_t *settings)
  1628. {
  1629. enc->codec = amf_codec_type::AV1;
  1630. if (!amf_create_encoder(enc))
  1631. throw "Failed to create encoder";
  1632. AMFCapsPtr caps;
  1633. AMF_RESULT res = enc->amf_encoder->GetCaps(&caps);
  1634. if (res == AMF_OK) {
  1635. caps->GetProperty(AMF_VIDEO_ENCODER_AV1_CAP_MAX_THROUGHPUT,
  1636. &enc->max_throughput);
  1637. }
  1638. const bool is10bit = enc->amf_format == AMF_SURFACE_P010;
  1639. const char *preset = obs_data_get_string(settings, "preset");
  1640. set_av1_property(enc, FRAMESIZE, AMFConstructSize(enc->cx, enc->cy));
  1641. set_av1_property(enc, USAGE, AMF_VIDEO_ENCODER_USAGE_TRANSCODING);
  1642. set_av1_property(enc, ALIGNMENT_MODE,
  1643. AMF_VIDEO_ENCODER_AV1_ALIGNMENT_MODE_NO_RESTRICTIONS);
  1644. set_av1_property(enc, QUALITY_PRESET, get_av1_preset(enc, preset));
  1645. set_av1_property(enc, COLOR_BIT_DEPTH,
  1646. is10bit ? AMF_COLOR_BIT_DEPTH_10
  1647. : AMF_COLOR_BIT_DEPTH_8);
  1648. set_av1_property(enc, PROFILE, get_av1_profile(settings));
  1649. set_av1_property(enc, ENCODING_LATENCY_MODE,
  1650. AMF_VIDEO_ENCODER_AV1_ENCODING_LATENCY_MODE_NONE);
  1651. // set_av1_property(enc, RATE_CONTROL_PREENCODE, true);
  1652. set_av1_property(enc, OUTPUT_COLOR_PROFILE, enc->amf_color_profile);
  1653. set_av1_property(enc, OUTPUT_TRANSFER_CHARACTERISTIC,
  1654. enc->amf_characteristic);
  1655. set_av1_property(enc, OUTPUT_COLOR_PRIMARIES, enc->amf_primaries);
  1656. amf_av1_init(enc, settings);
  1657. res = enc->amf_encoder->Init(enc->amf_format, enc->cx, enc->cy);
  1658. if (res != AMF_OK)
  1659. throw amf_error("AMFComponent::Init failed", res);
  1660. set_av1_property(enc, FRAMERATE, enc->amf_frame_rate);
  1661. AMFVariant p;
  1662. res = enc->amf_encoder->GetProperty(AMF_VIDEO_ENCODER_AV1_EXTRA_DATA,
  1663. &p);
  1664. if (res == AMF_OK && p.type == AMF_VARIANT_INTERFACE)
  1665. enc->header = AMFBufferPtr(p.pInterface);
  1666. }
  1667. static void *amf_av1_create_texencode(obs_data_t *settings,
  1668. obs_encoder_t *encoder)
  1669. try {
  1670. check_texture_encode_capability(encoder, amf_codec_type::AV1);
  1671. std::unique_ptr<amf_texencode> enc = std::make_unique<amf_texencode>();
  1672. enc->encoder = encoder;
  1673. enc->encoder_str = "texture-amf-av1";
  1674. if (!amf_init_d3d11(enc.get()))
  1675. throw "Failed to create D3D11";
  1676. amf_av1_create_internal(enc.get(), settings);
  1677. return enc.release();
  1678. } catch (const amf_error &err) {
  1679. blog(LOG_ERROR, "[texture-amf-av1] %s: %s: %ls", __FUNCTION__, err.str,
  1680. amf_trace->GetResultText(err.res));
  1681. return obs_encoder_create_rerouted(encoder, "av1_fallback_amf");
  1682. } catch (const char *err) {
  1683. blog(LOG_ERROR, "[texture-amf-av1] %s: %s", __FUNCTION__, err);
  1684. return obs_encoder_create_rerouted(encoder, "av1_fallback_amf");
  1685. }
  1686. static void *amf_av1_create_fallback(obs_data_t *settings,
  1687. obs_encoder_t *encoder)
  1688. try {
  1689. std::unique_ptr<amf_fallback> enc = std::make_unique<amf_fallback>();
  1690. enc->encoder = encoder;
  1691. enc->encoder_str = "fallback-amf-av1";
  1692. video_t *video = obs_encoder_video(encoder);
  1693. const struct video_output_info *voi = video_output_get_info(video);
  1694. switch (voi->format) {
  1695. case VIDEO_FORMAT_I010:
  1696. case VIDEO_FORMAT_P010: {
  1697. break;
  1698. }
  1699. default:
  1700. switch (voi->colorspace) {
  1701. case VIDEO_CS_2100_PQ:
  1702. case VIDEO_CS_2100_HLG: {
  1703. const char *const text =
  1704. obs_module_text("AMF.8bitUnsupportedHdr");
  1705. obs_encoder_set_last_error(encoder, text);
  1706. throw text;
  1707. }
  1708. }
  1709. }
  1710. amf_av1_create_internal(enc.get(), settings);
  1711. return enc.release();
  1712. } catch (const amf_error &err) {
  1713. blog(LOG_ERROR, "[fallback-amf-av1] %s: %s: %ls", __FUNCTION__, err.str,
  1714. amf_trace->GetResultText(err.res));
  1715. return nullptr;
  1716. } catch (const char *err) {
  1717. blog(LOG_ERROR, "[fallback-amf-av1] %s: %s", __FUNCTION__, err);
  1718. return nullptr;
  1719. }
  1720. static void amf_av1_defaults(obs_data_t *settings)
  1721. {
  1722. obs_data_set_default_int(settings, "bitrate", 2500);
  1723. obs_data_set_default_int(settings, "cqp", 7);
  1724. obs_data_set_default_string(settings, "rate_control", "CBR");
  1725. obs_data_set_default_string(settings, "preset", "quality");
  1726. obs_data_set_default_string(settings, "profile", "high");
  1727. }
  1728. static void register_av1()
  1729. {
  1730. struct obs_encoder_info amf_encoder_info = {};
  1731. amf_encoder_info.id = "av1_texture_amf";
  1732. amf_encoder_info.type = OBS_ENCODER_VIDEO;
  1733. amf_encoder_info.codec = "av1";
  1734. amf_encoder_info.get_name = amf_av1_get_name;
  1735. amf_encoder_info.create = amf_av1_create_texencode;
  1736. amf_encoder_info.destroy = amf_destroy;
  1737. amf_encoder_info.update = amf_av1_update;
  1738. amf_encoder_info.encode_texture = amf_encode_tex;
  1739. amf_encoder_info.get_defaults = amf_av1_defaults;
  1740. amf_encoder_info.get_properties = amf_av1_properties;
  1741. amf_encoder_info.get_extra_data = amf_extra_data;
  1742. amf_encoder_info.caps = OBS_ENCODER_CAP_PASS_TEXTURE |
  1743. OBS_ENCODER_CAP_DYN_BITRATE;
  1744. obs_register_encoder(&amf_encoder_info);
  1745. amf_encoder_info.id = "av1_fallback_amf";
  1746. amf_encoder_info.caps = OBS_ENCODER_CAP_INTERNAL |
  1747. OBS_ENCODER_CAP_DYN_BITRATE;
  1748. amf_encoder_info.encode_texture = nullptr;
  1749. amf_encoder_info.create = amf_av1_create_fallback;
  1750. amf_encoder_info.encode = amf_encode_fallback;
  1751. amf_encoder_info.get_video_info = av1_video_info_fallback;
  1752. obs_register_encoder(&amf_encoder_info);
  1753. }
  1754. /* ========================================================================= */
  1755. /* Global Stuff */
  1756. extern "C" void amf_load(void)
  1757. try {
  1758. AMF_RESULT res;
  1759. HMODULE amf_module_test;
  1760. /* Check if the DLL is present before running the more expensive */
  1761. /* obs-amf-test.exe, but load it as data so it can't crash us */
  1762. amf_module_test =
  1763. LoadLibraryExW(AMF_DLL_NAME, nullptr, LOAD_LIBRARY_AS_DATAFILE);
  1764. if (!amf_module_test)
  1765. throw "No AMF library";
  1766. FreeLibrary(amf_module_test);
  1767. /* ----------------------------------- */
  1768. /* Check for supported codecs */
  1769. BPtr<char> test_exe = os_get_executable_path_ptr("obs-amf-test.exe");
  1770. std::string caps_str;
  1771. os_process_pipe_t *pp = os_process_pipe_create(test_exe, "r");
  1772. if (!pp)
  1773. throw "Failed to launch the AMF test process I guess";
  1774. for (;;) {
  1775. char data[2048];
  1776. size_t len =
  1777. os_process_pipe_read(pp, (uint8_t *)data, sizeof(data));
  1778. if (!len)
  1779. break;
  1780. caps_str.append(data, len);
  1781. }
  1782. os_process_pipe_destroy(pp);
  1783. if (caps_str.empty())
  1784. throw "Seems the AMF test subprocess crashed. "
  1785. "Better there than here I guess. "
  1786. "Let's just skip loading AMF then I suppose.";
  1787. ConfigFile config;
  1788. if (config.OpenString(caps_str.c_str()) != 0)
  1789. throw "Failed to open config string";
  1790. const char *error = config_get_string(config, "error", "string");
  1791. if (error)
  1792. throw std::string(error);
  1793. uint32_t adapter_count = (uint32_t)config_num_sections(config);
  1794. bool avc_supported = false;
  1795. bool hevc_supported = false;
  1796. bool av1_supported = false;
  1797. for (uint32_t i = 0; i < adapter_count; i++) {
  1798. std::string section = std::to_string(i);
  1799. adapter_caps &info = caps[i];
  1800. info.is_amd =
  1801. config_get_bool(config, section.c_str(), "is_amd");
  1802. info.supports_avc = config_get_bool(config, section.c_str(),
  1803. "supports_avc");
  1804. info.supports_hevc = config_get_bool(config, section.c_str(),
  1805. "supports_hevc");
  1806. info.supports_av1 = config_get_bool(config, section.c_str(),
  1807. "supports_av1");
  1808. avc_supported |= info.supports_avc;
  1809. hevc_supported |= info.supports_hevc;
  1810. av1_supported |= info.supports_av1;
  1811. }
  1812. if (!avc_supported && !hevc_supported && !av1_supported)
  1813. throw "Neither AVC, HEVC, nor AV1 are supported by any devices";
  1814. /* ----------------------------------- */
  1815. /* Init AMF */
  1816. amf_module = LoadLibraryW(AMF_DLL_NAME);
  1817. if (!amf_module)
  1818. throw "AMF library failed to load";
  1819. AMFInit_Fn init =
  1820. (AMFInit_Fn)GetProcAddress(amf_module, AMF_INIT_FUNCTION_NAME);
  1821. if (!init)
  1822. throw "Failed to get AMFInit address";
  1823. res = init(AMF_FULL_VERSION, &amf_factory);
  1824. if (res != AMF_OK)
  1825. throw amf_error("AMFInit failed", res);
  1826. res = amf_factory->GetTrace(&amf_trace);
  1827. if (res != AMF_OK)
  1828. throw amf_error("GetTrace failed", res);
  1829. AMFQueryVersion_Fn get_ver = (AMFQueryVersion_Fn)GetProcAddress(
  1830. amf_module, AMF_QUERY_VERSION_FUNCTION_NAME);
  1831. if (!get_ver)
  1832. throw "Failed to get AMFQueryVersion address";
  1833. res = get_ver(&amf_version);
  1834. if (res != AMF_OK)
  1835. throw amf_error("AMFQueryVersion failed", res);
  1836. #ifndef DEBUG_AMF_STUFF
  1837. amf_trace->EnableWriter(AMF_TRACE_WRITER_DEBUG_OUTPUT, false);
  1838. amf_trace->EnableWriter(AMF_TRACE_WRITER_CONSOLE, false);
  1839. #endif
  1840. /* ----------------------------------- */
  1841. /* Register encoders */
  1842. if (avc_supported)
  1843. register_avc();
  1844. #if ENABLE_HEVC
  1845. if (hevc_supported)
  1846. register_hevc();
  1847. #endif
  1848. if (av1_supported)
  1849. register_av1();
  1850. } catch (const std::string &str) {
  1851. /* doing debug here because string exceptions indicate the user is
  1852. * probably not using AMD */
  1853. blog(LOG_DEBUG, "%s: %s", __FUNCTION__, str.c_str());
  1854. } catch (const char *str) {
  1855. /* doing debug here because string exceptions indicate the user is
  1856. * probably not using AMD */
  1857. blog(LOG_DEBUG, "%s: %s", __FUNCTION__, str);
  1858. } catch (const amf_error &err) {
  1859. /* doing an error here because it means at least the library has loaded
  1860. * successfully, so they probably have AMD at this point */
  1861. blog(LOG_ERROR, "%s: %s: 0x%lX", __FUNCTION__, err.str,
  1862. (uint32_t)err.res);
  1863. }
  1864. extern "C" void amf_unload(void)
  1865. {
  1866. if (amf_module && amf_trace) {
  1867. amf_trace->TraceFlush();
  1868. amf_trace->UnregisterWriter(L"obs_amf_trace_writer");
  1869. }
  1870. }