texture-amf.cpp 67 KB

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