Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
encode_gpu.cpp
Go to the documentation of this file.
1
5// standard includes
6#include <algorithm>
7#include <cctype>
8#include <array>
9#include <cerrno>
10#include <cstdint>
11#include <cstring>
12#include <filesystem>
13#include <format>
14#include <fstream>
15#include <mutex>
16#include <string>
17#include <string_view>
18
19// platform includes
20#include <fcntl.h>
21#include <sys/stat.h>
22#include <sys/sysmacros.h>
23#include <unistd.h>
24#include <xf86drm.h>
25
26// local includes
27#include "misc.h"
28#include "src/config.h"
29#include "src/logging.h"
30#include "src/utility.h"
31#include "vaapi.h"
32
33using namespace std::literals;
34
35namespace platf {
36 namespace {
37 using version_t = util::safe_ptr<drmVersion, drmFreeVersion>;
38
39 std::string driver_name(int fd) {
40 version_t version {drmGetVersion(fd)};
41 if (!version || !version->name) {
42 return {};
43 }
44 return {version->name, static_cast<std::size_t>(version->name_len)};
45 }
46
52 std::uint64_t video_memory(int fd) {
53 struct stat node {};
54
55 if (::fstat(fd, &node) != 0 || !S_ISCHR(node.st_mode)) {
56 return 0;
57 }
58 std::ifstream file {std::format("/sys/dev/char/{}:{}/device/mem_info_vram_total", major(node.st_rdev), minor(node.st_rdev))};
59 std::uint64_t bytes = 0;
60 file >> bytes;
61 return file ? bytes : 0;
62 }
63
64 std::string capability_names(int capability) {
65 std::string names;
66 for (const auto &[bit, name] : std::array<std::pair<int, std::string_view>, 4> {{
67 {8, "AV1"sv},
68 {4, "HEVC Main10"sv},
69 {2, "HEVC"sv},
70 {1, "H.264"sv},
71 }}) {
72 if (capability & bit) {
73 names += (names.empty() ? ""s : ", "s) + std::string {name};
74 }
75 }
76 return names.empty() ? "no VAAPI encoding"s : names;
77 }
78 } // namespace
79
81 if (!config::video.adapter_name.empty()) {
82 const auto &node = config::video.adapter_name;
83 const int fd = ::open(node.c_str(), O_RDWR | O_CLOEXEC);
84 if (fd < 0) {
85 BOOST_LOG(error) << "Could not open the configured adapter "sv << node << ": "sv << std::strerror(errno);
86 return -1;
87 }
88 if (driver_name(fd) == "hermes-kms"sv) {
89 BOOST_LOG(error) << "The configured adapter "sv << node
90 << " is the capture-only Hermes-KMS render node, not a GPU that can encode."sv;
91 ::close(fd);
92 return -1;
93 }
94 return fd;
95 }
96
97 std::array<drmDevicePtr, DRM_MAX_MINOR> devices {};
98 const int n = drmGetDevices2(0, devices.data(), static_cast<int>(devices.size()));
99 if (n <= 0) {
100 return -1;
101 }
102 const int device_count = std::min(n, static_cast<int>(devices.size()));
103 auto free_devices = util::fail_guard([&]() {
104 drmFreeDevices(devices.data(), device_count);
105 });
106
107 struct choice_t {
108 int fd = -1;
109 std::string node;
110 std::string driver;
111 bool nvidia = false;
112 int capability = 0;
113 std::uint64_t memory = 0;
114 } best;
115
116 // Better is: the vendor NVENC needs, then more codecs, then more memory.
117 const auto better = [nvenc](const choice_t &a, const choice_t &b) {
118 if (nvenc && a.nvidia != b.nvidia) {
119 return a.nvidia;
120 }
121 if (a.capability != b.capability) {
122 return a.capability > b.capability;
123 }
124 return a.memory > b.memory;
125 };
126
127 for (int i = 0; i < device_count; ++i) {
128 if (!devices[i] || !(devices[i]->available_nodes & (1U << DRM_NODE_RENDER)) ||
129 !devices[i]->nodes[DRM_NODE_RENDER]) {
130 continue;
131 }
132 choice_t candidate;
133 candidate.node = devices[i]->nodes[DRM_NODE_RENDER];
134 candidate.fd = ::open(candidate.node.c_str(), O_RDWR | O_CLOEXEC);
135 if (candidate.fd < 0) {
136 continue;
137 }
138 candidate.driver = driver_name(candidate.fd);
139 if (candidate.driver.empty() || candidate.driver == "hermes-kms"sv) {
140 ::close(candidate.fd);
141 continue;
142 }
143 candidate.nvidia = candidate.driver == "nvidia-drm"sv;
144#ifdef HERMES_BUILD_VAAPI
145 candidate.capability = va::encode_capability(candidate.fd);
146#endif
147 candidate.memory = video_memory(candidate.fd);
148 BOOST_LOG(debug) << "Encoding GPU candidate "sv << candidate.node << " ("sv << candidate.driver
149 << "): "sv << capability_names(candidate.capability) << ", "sv
150 << candidate.memory / (1024 * 1024) << " MiB video memory"sv;
151
152 if (best.fd < 0 || better(candidate, best)) {
153 if (best.fd >= 0) {
154 ::close(best.fd);
155 }
156 best = std::move(candidate);
157 } else {
158 ::close(candidate.fd);
159 }
160 }
161
162 if (best.fd >= 0) {
163 // Every encoder check opens a device, so the choice is reported when it
164 // changes rather than each time it is made.
165 static std::mutex reported_mutex;
166 static std::string reported;
167 std::lock_guard lock {reported_mutex};
168 if (reported != best.node) {
169 reported = best.node;
170 BOOST_LOG(info) << "Encoding on "sv << best.node << " ("sv << best.driver << "): "sv
171 << capability_names(best.capability);
172 }
173 }
174 return best.fd;
175 }
176
177 namespace {
183 std::string gpu_marketing_name(const std::string &sysfs, const std::string &vendor, const std::string &device, const std::string &revision) {
184 const auto upper = [](std::string text) {
185 std::ranges::transform(text, text.begin(), [](unsigned char c) {
186 return static_cast<char>(std::toupper(c));
187 });
188 return text;
189 };
190 if (vendor == "1002") {
191 // "7550,\tC0,\tAMD Radeon RX 9070 XT": one line per device and revision.
192 for (const auto *path : {"/usr/share/libdrm/amdgpu.ids", "/usr/local/share/libdrm/amdgpu.ids"}) {
193 std::ifstream ids {path};
194 for (std::string line; std::getline(ids, line);) {
195 if (line.empty() || line.front() == '#') {
196 continue;
197 }
198 const auto first = line.find(',');
199 const auto second = first == std::string::npos ? first : line.find(',', first + 1);
200 if (second == std::string::npos) {
201 continue;
202 }
203 const auto trim = [](std::string text) {
204 const auto begin = text.find_first_not_of(" \t");
205 const auto end = text.find_last_not_of(" \t\r");
206 return begin == std::string::npos ? std::string {} : text.substr(begin, end - begin + 1);
207 };
208 if (upper(trim(line.substr(0, first))) == upper(device) &&
209 upper(trim(line.substr(first + 1, second - first - 1))) == upper(revision)) {
210 return trim(line.substr(second + 1));
211 }
212 }
213 }
214 } else if (vendor == "10de") {
215 // /proc/driver/nvidia/gpus/<PCI address>/information: "Model: \t NVIDIA ...".
216 std::error_code ec;
217 const auto address = std::filesystem::canonical(sysfs, ec).filename().string();
218 std::ifstream information {"/proc/driver/nvidia/gpus/" + address + "/information"};
219 for (std::string line; std::getline(information, line);) {
220 if (line.starts_with("Model:")) {
221 const auto begin = line.find_first_not_of(" \t", 6);
222 return begin == std::string::npos ? std::string {} : line.substr(begin);
223 }
224 }
225 }
226 return {};
227 }
228 } // namespace
229
230 namespace {
231 std::string describe_render_node(int fd) {
232 struct stat st {};
233 if (::fstat(fd, &st) || !S_ISCHR(st.st_mode)) {
234 return {};
235 }
236 const auto sysfs = std::format("/sys/dev/char/{}:{}/device/", major(st.st_rdev), minor(st.st_rdev));
237 const auto read_id = [&](const char *file) {
238 std::string value;
239 std::ifstream {sysfs + file} >> value;
240 return value.starts_with("0x") ? value.substr(2) : value;
241 };
242 std::error_code ec;
243 const auto node = std::filesystem::read_symlink(std::format("/proc/self/fd/{}", fd), ec).string();
244 const auto driver = driver_name(fd);
245 if (driver == "hermes-kms"sv) {
246 // A virtual device: no PCI id, but the driver's own version.
247 version_t version {drmGetVersion(fd)};
248 return version ? std::format("{} (hermes-kms {}.{}.{})", node, version->version_major, version->version_minor, version->version_patchlevel) :
249 std::format("{} (hermes-kms)", node);
250 }
251 const auto vendor = read_id("vendor");
252 const auto device = read_id("device");
253 auto name = gpu_marketing_name(sysfs, vendor, device, read_id("revision"));
254 if (name.empty()) {
255 const auto vendor_name = vendor == "1002" ? "AMD"s : vendor == "10de" ? "NVIDIA"s : vendor == "8086" ? "Intel"s : "PCI"s;
256 name = std::format("{} {}:{}", vendor_name, vendor, device);
257 }
258 // A GPU in the CPU has a small carve-out of memory, a card gigabytes.
259 if (const auto memory = video_memory(fd); memory > 0 && memory < 1024ull * 1024 * 1024) {
260 name += ", integrated";
261 }
262 return std::format("{} ({}, {})", node, driver, name);
263 }
264 } // namespace
265
266 std::string encode_gpu_description(bool nvenc) {
267 const int fd = open_encode_render_node(nvenc);
268 if (fd < 0) {
269 return {};
270 }
271 auto close_fd = util::fail_guard([fd]() {
272 ::close(fd);
273 });
274 return describe_render_node(fd);
275 }
276
277 namespace {
278 std::mutex last_vaapi_node_mutex;
279 std::string last_vaapi_node;
280 } // namespace
281
283 // Only the path: describing reads sysfs and amdgpu.ids, and this runs
284 // for every VAAPI device an encoder probe or a stream opens.
285 std::string node;
286 if (fd >= 0) {
287 std::error_code ec;
288 node = std::filesystem::read_symlink(std::format("/proc/self/fd/{}", fd), ec).string();
289 }
290 std::lock_guard lock {last_vaapi_node_mutex};
291 last_vaapi_node = std::move(node);
292 }
293
294 std::string last_vaapi_encode_gpu() {
295 std::string node;
296 {
297 std::lock_guard lock {last_vaapi_node_mutex};
298 node = last_vaapi_node;
299 }
300 if (node.empty()) {
301 return {};
302 }
303 const int fd = ::open(node.c_str(), O_RDWR | O_CLOEXEC);
304 if (fd < 0) {
305 return {};
306 }
307 auto close_fd = util::fail_guard([fd]() {
308 ::close(fd);
309 });
310 return describe_render_node(fd);
311 }
312
313 std::vector<std::string> render_node_descriptions() {
314 std::vector<std::string> descriptions;
315 std::error_code ec;
316 std::vector<std::filesystem::path> nodes;
317 for (const auto &entry : std::filesystem::directory_iterator {"/dev/dri", ec}) {
318 if (entry.path().filename().string().starts_with("renderD")) {
319 nodes.push_back(entry.path());
320 }
321 }
322 std::ranges::sort(nodes);
323 for (const auto &node : nodes) {
324 const int fd = ::open(node.c_str(), O_RDWR | O_CLOEXEC);
325 if (fd < 0) {
326 descriptions.push_back(node.string() + " (cannot open: " + std::strerror(errno) + ")");
327 continue;
328 }
329 auto description = describe_render_node(fd);
330 if (driver_name(fd) == "hermes-kms"sv) {
331 description += " - capture node, not used for encoding";
332 }
333 ::close(fd);
334 descriptions.push_back(std::move(description));
335 }
336 return descriptions;
337 }
338} // namespace platf
Declarations for the configuration of Sunshine.
int open_encode_render_node(bool nvenc)
Open the render node of the best GPU to encode a stream on.
std::vector< std::string > render_node_descriptions()
Describe every GPU render node, as encode_gpu_description() does, the capture-only Hermes-KMS node in...
void note_vaapi_encode_gpu(int fd)
Record the GPU a VAAPI encoder actually opened, from its DRM fd.
std::string encode_gpu_description(bool nvenc)
Describe the GPU a stream encodes on, for logs and diagnostics: its render node, driver and the name ...
std::string last_vaapi_encode_gpu()
The GPU the last VAAPI encoder opened, described as encode_gpu_description() does,...
Declarations for logging related functions.
Miscellaneous declarations for Linux.
int version()
Print the version to stdout, then exit.
Standalone NVENC encoder.
Declarations for utility functions.
int encode_capability(int fd)
Rank what the GPU behind fd can encode, for choosing between GPUs.
Definition vaapi.cpp:634
Declarations for VA-API hardware accelerated capture.