codec.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. // SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <algorithm>
  4. #include <fstream>
  5. #include <vector>
  6. #include "common/assert.h"
  7. #include "common/scope_exit.h"
  8. #include "common/settings.h"
  9. #include "video_core/host1x/codecs/codec.h"
  10. #include "video_core/host1x/codecs/h264.h"
  11. #include "video_core/host1x/codecs/vp8.h"
  12. #include "video_core/host1x/codecs/vp9.h"
  13. #include "video_core/host1x/host1x.h"
  14. #include "video_core/memory_manager.h"
  15. extern "C" {
  16. #include <libavfilter/buffersink.h>
  17. #include <libavfilter/buffersrc.h>
  18. #include <libavutil/opt.h>
  19. #ifdef LIBVA_FOUND
  20. // for querying VAAPI driver information
  21. #include <libavutil/hwcontext_vaapi.h>
  22. #endif
  23. }
  24. namespace Tegra {
  25. namespace {
  26. constexpr AVPixelFormat PREFERRED_GPU_FMT = AV_PIX_FMT_NV12;
  27. constexpr AVPixelFormat PREFERRED_CPU_FMT = AV_PIX_FMT_YUV420P;
  28. constexpr std::array PREFERRED_GPU_DECODERS = {
  29. AV_HWDEVICE_TYPE_CUDA,
  30. #ifdef _WIN32
  31. AV_HWDEVICE_TYPE_D3D11VA,
  32. AV_HWDEVICE_TYPE_DXVA2,
  33. #elif defined(__unix__)
  34. AV_HWDEVICE_TYPE_VAAPI,
  35. AV_HWDEVICE_TYPE_VDPAU,
  36. #endif
  37. // last resort for Linux Flatpak (w/ NVIDIA)
  38. AV_HWDEVICE_TYPE_VULKAN,
  39. };
  40. void AVPacketDeleter(AVPacket* ptr) {
  41. av_packet_free(&ptr);
  42. }
  43. using AVPacketPtr = std::unique_ptr<AVPacket, decltype(&AVPacketDeleter)>;
  44. AVPixelFormat GetGpuFormat(AVCodecContext* av_codec_ctx, const AVPixelFormat* pix_fmts) {
  45. for (const AVPixelFormat* p = pix_fmts; *p != AV_PIX_FMT_NONE; ++p) {
  46. if (*p == av_codec_ctx->pix_fmt) {
  47. return av_codec_ctx->pix_fmt;
  48. }
  49. }
  50. LOG_INFO(Service_NVDRV, "Could not find compatible GPU AV format, falling back to CPU");
  51. av_buffer_unref(&av_codec_ctx->hw_device_ctx);
  52. av_codec_ctx->pix_fmt = PREFERRED_CPU_FMT;
  53. return PREFERRED_CPU_FMT;
  54. }
  55. // List all the currently available hwcontext in ffmpeg
  56. std::vector<AVHWDeviceType> ListSupportedContexts() {
  57. std::vector<AVHWDeviceType> contexts{};
  58. AVHWDeviceType current_device_type = AV_HWDEVICE_TYPE_NONE;
  59. do {
  60. current_device_type = av_hwdevice_iterate_types(current_device_type);
  61. contexts.push_back(current_device_type);
  62. } while (current_device_type != AV_HWDEVICE_TYPE_NONE);
  63. return contexts;
  64. }
  65. } // namespace
  66. void AVFrameDeleter(AVFrame* ptr) {
  67. av_frame_free(&ptr);
  68. }
  69. Codec::Codec(Host1x::Host1x& host1x_, const Host1x::NvdecCommon::NvdecRegisters& regs)
  70. : host1x(host1x_), state{regs}, h264_decoder(std::make_unique<Decoder::H264>(host1x)),
  71. vp8_decoder(std::make_unique<Decoder::VP8>(host1x)),
  72. vp9_decoder(std::make_unique<Decoder::VP9>(host1x)) {}
  73. Codec::~Codec() {
  74. if (!initialized) {
  75. return;
  76. }
  77. // Free libav memory
  78. avcodec_free_context(&av_codec_ctx);
  79. av_buffer_unref(&av_gpu_decoder);
  80. if (filters_initialized) {
  81. avfilter_graph_free(&av_filter_graph);
  82. }
  83. }
  84. bool Codec::CreateGpuAvDevice() {
  85. static constexpr auto HW_CONFIG_METHOD = AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX;
  86. static const auto supported_contexts = ListSupportedContexts();
  87. for (const auto& type : PREFERRED_GPU_DECODERS) {
  88. if (std::none_of(supported_contexts.begin(), supported_contexts.end(),
  89. [&type](const auto& context) { return context == type; })) {
  90. LOG_DEBUG(Service_NVDRV, "{} explicitly unsupported", av_hwdevice_get_type_name(type));
  91. continue;
  92. }
  93. // Avoid memory leak from not cleaning up after av_hwdevice_ctx_create
  94. av_buffer_unref(&av_gpu_decoder);
  95. const int hwdevice_res = av_hwdevice_ctx_create(&av_gpu_decoder, type, nullptr, nullptr, 0);
  96. if (hwdevice_res < 0) {
  97. LOG_DEBUG(Service_NVDRV, "{} av_hwdevice_ctx_create failed {}",
  98. av_hwdevice_get_type_name(type), hwdevice_res);
  99. continue;
  100. }
  101. #ifdef LIBVA_FOUND
  102. if (type == AV_HWDEVICE_TYPE_VAAPI) {
  103. // we need to determine if this is an impersonated VAAPI driver
  104. AVHWDeviceContext* hwctx =
  105. static_cast<AVHWDeviceContext*>(static_cast<void*>(av_gpu_decoder->data));
  106. AVVAAPIDeviceContext* vactx = static_cast<AVVAAPIDeviceContext*>(hwctx->hwctx);
  107. const char* vendor_name = vaQueryVendorString(vactx->display);
  108. if (strstr(vendor_name, "VDPAU backend")) {
  109. // VDPAU impersonated VAAPI impl's are super buggy, we need to skip them
  110. LOG_DEBUG(Service_NVDRV, "Skipping vdapu impersonated VAAPI driver");
  111. continue;
  112. } else {
  113. // according to some user testing, certain vaapi driver (Intel?) could be buggy
  114. // so let's log the driver name which may help the developers/supporters
  115. LOG_DEBUG(Service_NVDRV, "Using VAAPI driver: {}", vendor_name);
  116. }
  117. }
  118. #endif
  119. for (int i = 0;; i++) {
  120. const AVCodecHWConfig* config = avcodec_get_hw_config(av_codec, i);
  121. if (!config) {
  122. LOG_DEBUG(Service_NVDRV, "{} decoder does not support device type {}.",
  123. av_codec->name, av_hwdevice_get_type_name(type));
  124. break;
  125. }
  126. if ((config->methods & HW_CONFIG_METHOD) != 0 && config->device_type == type) {
  127. #if defined(__unix__)
  128. // Some linux decoding backends are reported to crash with this config method
  129. // TODO(ameerj): Properly support this method
  130. if ((config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX) != 0) {
  131. // skip zero-copy decoders, we don't currently support them
  132. LOG_DEBUG(Service_NVDRV, "Skipping decoder {} with unsupported capability {}.",
  133. av_hwdevice_get_type_name(type), config->methods);
  134. continue;
  135. }
  136. #endif
  137. LOG_INFO(Service_NVDRV, "Using {} GPU decoder", av_hwdevice_get_type_name(type));
  138. av_codec_ctx->pix_fmt = config->pix_fmt;
  139. return true;
  140. }
  141. }
  142. }
  143. return false;
  144. }
  145. void Codec::InitializeAvCodecContext() {
  146. av_codec_ctx = avcodec_alloc_context3(av_codec);
  147. av_opt_set(av_codec_ctx->priv_data, "tune", "zerolatency", 0);
  148. av_codec_ctx->thread_count = 0;
  149. av_codec_ctx->thread_type &= ~FF_THREAD_FRAME;
  150. }
  151. void Codec::InitializeGpuDecoder() {
  152. if (!CreateGpuAvDevice()) {
  153. av_buffer_unref(&av_gpu_decoder);
  154. return;
  155. }
  156. auto* hw_device_ctx = av_buffer_ref(av_gpu_decoder);
  157. ASSERT_MSG(hw_device_ctx, "av_buffer_ref failed");
  158. av_codec_ctx->hw_device_ctx = hw_device_ctx;
  159. av_codec_ctx->get_format = GetGpuFormat;
  160. }
  161. void Codec::InitializeAvFilters(AVFrame* frame) {
  162. const AVFilter* buffer_src = avfilter_get_by_name("buffer");
  163. const AVFilter* buffer_sink = avfilter_get_by_name("buffersink");
  164. AVFilterInOut* inputs = avfilter_inout_alloc();
  165. AVFilterInOut* outputs = avfilter_inout_alloc();
  166. SCOPE_EXIT({
  167. avfilter_inout_free(&inputs);
  168. avfilter_inout_free(&outputs);
  169. });
  170. // Don't know how to get the accurate time_base but it doesn't matter for yadif filter
  171. // so just use 1/1 to make buffer filter happy
  172. std::string args = fmt::format("video_size={}x{}:pix_fmt={}:time_base=1/1", frame->width,
  173. frame->height, frame->format);
  174. av_filter_graph = avfilter_graph_alloc();
  175. int ret = avfilter_graph_create_filter(&av_filter_src_ctx, buffer_src, "in", args.c_str(),
  176. nullptr, av_filter_graph);
  177. if (ret < 0) {
  178. LOG_ERROR(Service_NVDRV, "avfilter_graph_create_filter source error: {}", ret);
  179. return;
  180. }
  181. ret = avfilter_graph_create_filter(&av_filter_sink_ctx, buffer_sink, "out", nullptr, nullptr,
  182. av_filter_graph);
  183. if (ret < 0) {
  184. LOG_ERROR(Service_NVDRV, "avfilter_graph_create_filter sink error: {}", ret);
  185. return;
  186. }
  187. inputs->name = av_strdup("out");
  188. inputs->filter_ctx = av_filter_sink_ctx;
  189. inputs->pad_idx = 0;
  190. inputs->next = nullptr;
  191. outputs->name = av_strdup("in");
  192. outputs->filter_ctx = av_filter_src_ctx;
  193. outputs->pad_idx = 0;
  194. outputs->next = nullptr;
  195. const char* description = "yadif=1:-1:0";
  196. ret = avfilter_graph_parse_ptr(av_filter_graph, description, &inputs, &outputs, nullptr);
  197. if (ret < 0) {
  198. LOG_ERROR(Service_NVDRV, "avfilter_graph_parse_ptr error: {}", ret);
  199. return;
  200. }
  201. ret = avfilter_graph_config(av_filter_graph, nullptr);
  202. if (ret < 0) {
  203. LOG_ERROR(Service_NVDRV, "avfilter_graph_config error: {}", ret);
  204. return;
  205. }
  206. filters_initialized = true;
  207. }
  208. void Codec::Initialize() {
  209. const AVCodecID codec = [&] {
  210. switch (current_codec) {
  211. case Host1x::NvdecCommon::VideoCodec::H264:
  212. return AV_CODEC_ID_H264;
  213. case Host1x::NvdecCommon::VideoCodec::VP8:
  214. return AV_CODEC_ID_VP8;
  215. case Host1x::NvdecCommon::VideoCodec::VP9:
  216. return AV_CODEC_ID_VP9;
  217. default:
  218. UNIMPLEMENTED_MSG("Unknown codec {}", current_codec);
  219. return AV_CODEC_ID_NONE;
  220. }
  221. }();
  222. av_codec = avcodec_find_decoder(codec);
  223. InitializeAvCodecContext();
  224. if (Settings::values.nvdec_emulation.GetValue() == Settings::NvdecEmulation::GPU) {
  225. InitializeGpuDecoder();
  226. }
  227. if (const int res = avcodec_open2(av_codec_ctx, av_codec, nullptr); res < 0) {
  228. LOG_ERROR(Service_NVDRV, "avcodec_open2() Failed with result {}", res);
  229. avcodec_free_context(&av_codec_ctx);
  230. av_buffer_unref(&av_gpu_decoder);
  231. return;
  232. }
  233. if (!av_codec_ctx->hw_device_ctx) {
  234. LOG_INFO(Service_NVDRV, "Using FFmpeg software decoding");
  235. }
  236. initialized = true;
  237. }
  238. void Codec::SetTargetCodec(Host1x::NvdecCommon::VideoCodec codec) {
  239. if (current_codec != codec) {
  240. current_codec = codec;
  241. LOG_INFO(Service_NVDRV, "NVDEC video codec initialized to {}", GetCurrentCodecName());
  242. }
  243. }
  244. void Codec::Decode() {
  245. const bool is_first_frame = !initialized;
  246. if (is_first_frame) {
  247. Initialize();
  248. }
  249. if (!initialized) {
  250. return;
  251. }
  252. bool vp9_hidden_frame = false;
  253. const auto& frame_data = [&]() {
  254. switch (current_codec) {
  255. case Tegra::Host1x::NvdecCommon::VideoCodec::H264:
  256. return h264_decoder->ComposeFrame(state, is_first_frame);
  257. case Tegra::Host1x::NvdecCommon::VideoCodec::VP8:
  258. return vp8_decoder->ComposeFrame(state);
  259. case Tegra::Host1x::NvdecCommon::VideoCodec::VP9:
  260. vp9_decoder->ComposeFrame(state);
  261. vp9_hidden_frame = vp9_decoder->WasFrameHidden();
  262. return vp9_decoder->GetFrameBytes();
  263. default:
  264. ASSERT(false);
  265. return std::span<const u8>{};
  266. }
  267. }();
  268. AVPacketPtr packet{av_packet_alloc(), AVPacketDeleter};
  269. if (!packet) {
  270. LOG_ERROR(Service_NVDRV, "av_packet_alloc failed");
  271. return;
  272. }
  273. packet->data = const_cast<u8*>(frame_data.data());
  274. packet->size = static_cast<s32>(frame_data.size());
  275. if (const int res = avcodec_send_packet(av_codec_ctx, packet.get()); res != 0) {
  276. LOG_DEBUG(Service_NVDRV, "avcodec_send_packet error {}", res);
  277. return;
  278. }
  279. // Only receive/store visible frames
  280. if (vp9_hidden_frame) {
  281. return;
  282. }
  283. AVFramePtr initial_frame{av_frame_alloc(), AVFrameDeleter};
  284. AVFramePtr final_frame{nullptr, AVFrameDeleter};
  285. ASSERT_MSG(initial_frame, "av_frame_alloc initial_frame failed");
  286. if (const int ret = avcodec_receive_frame(av_codec_ctx, initial_frame.get()); ret) {
  287. LOG_DEBUG(Service_NVDRV, "avcodec_receive_frame error {}", ret);
  288. return;
  289. }
  290. if (initial_frame->width == 0 || initial_frame->height == 0) {
  291. LOG_WARNING(Service_NVDRV, "Zero width or height in frame");
  292. return;
  293. }
  294. if (av_codec_ctx->hw_device_ctx) {
  295. final_frame = AVFramePtr{av_frame_alloc(), AVFrameDeleter};
  296. ASSERT_MSG(final_frame, "av_frame_alloc final_frame failed");
  297. // Can't use AV_PIX_FMT_YUV420P and share code with software decoding in vic.cpp
  298. // because Intel drivers crash unless using AV_PIX_FMT_NV12
  299. final_frame->format = PREFERRED_GPU_FMT;
  300. const int ret = av_hwframe_transfer_data(final_frame.get(), initial_frame.get(), 0);
  301. ASSERT_MSG(!ret, "av_hwframe_transfer_data error {}", ret);
  302. } else {
  303. final_frame = std::move(initial_frame);
  304. }
  305. if (final_frame->format != PREFERRED_CPU_FMT && final_frame->format != PREFERRED_GPU_FMT) {
  306. UNIMPLEMENTED_MSG("Unexpected video format: {}", final_frame->format);
  307. return;
  308. }
  309. if (!final_frame->interlaced_frame) {
  310. av_frames.push(std::move(final_frame));
  311. } else {
  312. if (!filters_initialized) {
  313. InitializeAvFilters(final_frame.get());
  314. }
  315. if (const int ret = av_buffersrc_add_frame_flags(av_filter_src_ctx, final_frame.get(),
  316. AV_BUFFERSRC_FLAG_KEEP_REF);
  317. ret) {
  318. LOG_DEBUG(Service_NVDRV, "av_buffersrc_add_frame_flags error {}", ret);
  319. return;
  320. }
  321. while (true) {
  322. auto filter_frame = AVFramePtr{av_frame_alloc(), AVFrameDeleter};
  323. int ret = av_buffersink_get_frame(av_filter_sink_ctx, filter_frame.get());
  324. if (ret == AVERROR(EAGAIN) || ret == AVERROR(AVERROR_EOF))
  325. break;
  326. if (ret < 0) {
  327. LOG_DEBUG(Service_NVDRV, "av_buffersink_get_frame error {}", ret);
  328. return;
  329. }
  330. av_frames.push(std::move(filter_frame));
  331. }
  332. }
  333. while (av_frames.size() > 10) {
  334. LOG_TRACE(Service_NVDRV, "av_frames.push overflow dropped frame");
  335. av_frames.pop();
  336. }
  337. }
  338. AVFramePtr Codec::GetCurrentFrame() {
  339. // Sometimes VIC will request more frames than have been decoded.
  340. // in this case, return a nullptr and don't overwrite previous frame data
  341. if (av_frames.empty()) {
  342. return AVFramePtr{nullptr, AVFrameDeleter};
  343. }
  344. AVFramePtr frame = std::move(av_frames.front());
  345. av_frames.pop();
  346. return frame;
  347. }
  348. Host1x::NvdecCommon::VideoCodec Codec::GetCurrentCodec() const {
  349. return current_codec;
  350. }
  351. std::string_view Codec::GetCurrentCodecName() const {
  352. switch (current_codec) {
  353. case Host1x::NvdecCommon::VideoCodec::None:
  354. return "None";
  355. case Host1x::NvdecCommon::VideoCodec::H264:
  356. return "H264";
  357. case Host1x::NvdecCommon::VideoCodec::VP8:
  358. return "VP8";
  359. case Host1x::NvdecCommon::VideoCodec::H265:
  360. return "H265";
  361. case Host1x::NvdecCommon::VideoCodec::VP9:
  362. return "VP9";
  363. default:
  364. return "Unknown";
  365. }
  366. }
  367. } // namespace Tegra