screen-relay 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/LICENSE +201 -0
  2. package/Makefile +165 -0
  3. package/README.md +113 -2
  4. package/THIRD-PARTY-NOTICES.md +75 -0
  5. package/dist/cli/client.d.ts +28 -0
  6. package/dist/cli/commands.d.ts +52 -0
  7. package/dist/cli/config.d.ts +32 -0
  8. package/dist/cli/format.d.ts +15 -0
  9. package/dist/cli/help.d.ts +5 -0
  10. package/dist/cli/host/common.d.ts +23 -0
  11. package/dist/cli/host/doctor.d.ts +2 -0
  12. package/dist/cli/host/packages.d.ts +13 -0
  13. package/dist/cli/host/session_commands.d.ts +8 -0
  14. package/dist/cli/host/setup.d.ts +22 -0
  15. package/dist/cli/host/state.d.ts +23 -0
  16. package/dist/cli/host/supervisor.d.ts +91 -0
  17. package/dist/cli/host/watcher.d.ts +4 -0
  18. package/dist/cli/main.d.ts +3 -0
  19. package/dist/cli/mode.d.ts +14 -0
  20. package/dist/cli/output.d.ts +24 -0
  21. package/dist/cli/parser.d.ts +6 -0
  22. package/dist/cli/relay.mjs +12247 -0
  23. package/dist/cli/skills.d.ts +21 -0
  24. package/dist/cli/theme.d.ts +14 -0
  25. package/dist/protocol/errors.d.ts +155 -0
  26. package/dist/protocol/index.d.ts +119 -0
  27. package/dist/protocol/index.js +418 -0
  28. package/dist/sdk/index.d.ts +77 -0
  29. package/dist/sdk/index.js +724 -0
  30. package/dist/viewer/index.html +96 -0
  31. package/dist/viewer/viewer.js +1052 -0
  32. package/package.json +50 -4
  33. package/packages.tsv +38 -0
  34. package/skills/core/SKILL.md +169 -0
  35. package/skills/core/references/cli.md +119 -0
  36. package/skills/core/references/config.md +48 -0
  37. package/skills/core/references/macos.md +50 -0
  38. package/skills/core/references/sdk.md +69 -0
  39. package/skills/core/references/troubleshooting.md +33 -0
  40. package/skills/core/references/wayland.md +47 -0
  41. package/skills/screen-relay/SKILL.md +24 -0
  42. package/skills/vercel-sandbox/SKILL.md +68 -0
  43. package/src/engine/backends/linux/keycodes.hpp +35 -0
  44. package/src/engine/backends/linux/wayland/capture.cpp +298 -0
  45. package/src/engine/backends/linux/wayland/input.cpp +559 -0
  46. package/src/engine/backends/linux/wayland/keymap.cpp +118 -0
  47. package/src/engine/backends/linux/wayland/keymap.hpp +54 -0
  48. package/src/engine/backends/linux/wayland/protocols/virtual-keyboard-unstable-v1.xml +112 -0
  49. package/src/engine/backends/linux/wayland/protocols/wlr-screencopy-unstable-v1.xml +234 -0
  50. package/src/engine/backends/linux/wayland/protocols/wlr-virtual-pointer-unstable-v1.xml +152 -0
  51. package/src/engine/backends/linux/wayland/wayland.cpp +166 -0
  52. package/src/engine/backends/linux/wayland/wayland.hpp +60 -0
  53. package/src/engine/backends/linux/x11/capture.cpp +206 -0
  54. package/src/engine/backends/linux/x11/input.cpp +266 -0
  55. package/src/engine/backends/macos/capture.mm +367 -0
  56. package/src/engine/backends/macos/display.hpp +20 -0
  57. package/src/engine/backends/macos/display.mm +84 -0
  58. package/src/engine/backends/macos/input.mm +287 -0
  59. package/src/engine/backends/macos/keys.hpp +34 -0
  60. package/src/engine/backends/windows/capture.cpp +393 -0
  61. package/src/engine/backends/windows/input.cpp +274 -0
  62. package/src/engine/backends/windows/output.cpp +65 -0
  63. package/src/engine/backends/windows/output.hpp +26 -0
  64. package/src/engine/core/capture-bucket.hpp +40 -0
  65. package/src/engine/core/capture-source.hpp +59 -0
  66. package/src/engine/core/capture.cpp +565 -0
  67. package/src/engine/core/capture.hpp +58 -0
  68. package/src/engine/core/color.cpp +176 -0
  69. package/src/engine/core/color.hpp +16 -0
  70. package/src/engine/core/cpu-budget.hpp +196 -0
  71. package/src/engine/core/flow.hpp +317 -0
  72. package/src/engine/core/input.cpp +98 -0
  73. package/src/engine/core/input.hpp +115 -0
  74. package/src/engine/core/wait.cpp +125 -0
  75. package/src/engine/core/wait.hpp +41 -0
  76. package/src/engine/server/backend.cpp +65 -0
  77. package/src/engine/server/backend.hpp +18 -0
  78. package/src/engine/server/config.cpp +257 -0
  79. package/src/engine/server/config.hpp +24 -0
  80. package/src/engine/server/main.cpp +82 -0
  81. package/src/engine/server/metrics.cpp +47 -0
  82. package/src/engine/server/metrics.hpp +10 -0
  83. package/src/engine/server/screenshot.cpp +108 -0
  84. package/src/engine/server/screenshot.hpp +31 -0
  85. package/src/engine/server/server.cpp +531 -0
  86. package/src/engine/server/server.hpp +88 -0
  87. package/src/engine/server/wire.cpp +65 -0
  88. package/src/engine/server/wire.hpp +27 -0
@@ -0,0 +1,176 @@
1
+ #include "color.hpp"
2
+
3
+ #include <cstddef>
4
+ #include <limits>
5
+
6
+ #if defined(__aarch64__)
7
+ #include <arm_neon.h>
8
+ #endif
9
+
10
+ #if defined(__SSE2__)
11
+ #include <emmintrin.h>
12
+ #endif
13
+
14
+ namespace relay {
15
+ namespace {
16
+ // BT.709 coefficients scaled by 2^14; biases keep all shifts nonnegative.
17
+ uint8_t luma(int b, int g, int r) {
18
+ return static_cast<uint8_t>((2991 * r + 10064 * g + 1016 * b + 8192) / 16384 + 16);
19
+ }
20
+ uint8_t blueChroma(int b, int g, int r) {
21
+ return static_cast<uint8_t>((128 * 16384 + 8192 - 1649 * r - 5547 * g + 7196 * b) / 16384);
22
+ }
23
+ uint8_t redChroma(int b, int g, int r) {
24
+ return static_cast<uint8_t>((128 * 16384 + 8192 + 7196 * r - 6536 * g - 660 * b) / 16384);
25
+ }
26
+
27
+ #if defined(__aarch64__)
28
+ /** BT.709 limited-range luma for 8 pixels with 8-bit coefficients in 16-bit lanes. */
29
+ uint8x8_t luma8(uint8x8_t b, uint8x8_t g, uint8x8_t r) {
30
+ auto sum = vmlal_u8(vmlal_u8(vmull_u8(r, vdup_n_u8(47)), g, vdup_n_u8(157)), b, vdup_n_u8(16));
31
+ return vadd_u8(vshrn_n_u16(vaddq_u16(sum, vdupq_n_u16(128)), 8), vdup_n_u8(16));
32
+ }
33
+ /** Averages vertically adjacent pixel pairs and then horizontal neighbours, rounding to nearest. */
34
+ uint8x8_t box8(uint8x16_t top, uint8x16_t bottom) {
35
+ return vmovn_u16(vrshrq_n_u16(vaddq_u16(vpaddlq_u8(top), vpaddlq_u8(bottom)), 2));
36
+ }
37
+ #endif
38
+
39
+ #if defined(__SSE2__)
40
+ void splitBgra8(const uint8_t* src, __m128i& b, __m128i& g, __m128i& r) {
41
+ const auto mask = _mm_set1_epi32(0xFF);
42
+ const auto lo = _mm_loadu_si128(reinterpret_cast<const __m128i*>(src));
43
+ const auto hi = _mm_loadu_si128(reinterpret_cast<const __m128i*>(src + 16));
44
+ b = _mm_packs_epi32(_mm_and_si128(lo, mask), _mm_and_si128(hi, mask));
45
+ g = _mm_packs_epi32(_mm_and_si128(_mm_srli_epi32(lo, 8), mask),
46
+ _mm_and_si128(_mm_srli_epi32(hi, 8), mask));
47
+ r = _mm_packs_epi32(_mm_and_si128(_mm_srli_epi32(lo, 16), mask),
48
+ _mm_and_si128(_mm_srli_epi32(hi, 16), mask));
49
+ }
50
+ __m128i lumaBlock8(__m128i b, __m128i g, __m128i r) {
51
+ const auto ones = _mm_set1_epi16(1);
52
+ const auto rgCoef = _mm_setr_epi16(2991, 10064, 2991, 10064, 2991, 10064, 2991, 10064);
53
+ const auto bCoef = _mm_setr_epi16(1016, 8192, 1016, 8192, 1016, 8192, 1016, 8192);
54
+ const auto bias = _mm_set1_epi32(16);
55
+ const auto lo = _mm_add_epi32(
56
+ _mm_srai_epi32(_mm_add_epi32(_mm_madd_epi16(_mm_unpacklo_epi16(r, g), rgCoef),
57
+ _mm_madd_epi16(_mm_unpacklo_epi16(b, ones), bCoef)), 14),
58
+ bias);
59
+ const auto hi = _mm_add_epi32(
60
+ _mm_srai_epi32(_mm_add_epi32(_mm_madd_epi16(_mm_unpackhi_epi16(r, g), rgCoef),
61
+ _mm_madd_epi16(_mm_unpackhi_epi16(b, ones), bCoef)), 14),
62
+ bias);
63
+ const auto packed = _mm_packs_epi32(lo, hi);
64
+ return _mm_packus_epi16(packed, packed);
65
+ }
66
+ __m128i boxAverage4(__m128i top, __m128i bottom) {
67
+ const auto pairs = _mm_madd_epi16(_mm_add_epi16(top, bottom), _mm_set1_epi16(1));
68
+ return _mm_srai_epi32(_mm_add_epi32(pairs, _mm_set1_epi32(2)), 2);
69
+ }
70
+ void chromaBlock4(__m128i blue, __m128i green, __m128i red, uint8_t* u, uint8_t* v, int step) {
71
+ const auto zero = _mm_setzero_si128();
72
+ const auto b = _mm_packs_epi32(blue, blue);
73
+ const auto g = _mm_packs_epi32(green, green);
74
+ const auto r = _mm_packs_epi32(red, red);
75
+ const auto bias = _mm_set1_epi32(128 * 16384 + 8192);
76
+ const auto cb = _mm_srai_epi32(
77
+ _mm_add_epi32(bias,
78
+ _mm_add_epi32(_mm_madd_epi16(_mm_unpacklo_epi16(b, g),
79
+ _mm_setr_epi16(7196, -5547, 7196, -5547, 7196, -5547, 7196, -5547)),
80
+ _mm_madd_epi16(_mm_unpacklo_epi16(r, zero),
81
+ _mm_setr_epi16(-1649, 0, -1649, 0, -1649, 0, -1649, 0)))),
82
+ 14);
83
+ const auto cr = _mm_srai_epi32(
84
+ _mm_add_epi32(bias,
85
+ _mm_add_epi32(_mm_madd_epi16(_mm_unpacklo_epi16(r, g),
86
+ _mm_setr_epi16(7196, -6536, 7196, -6536, 7196, -6536, 7196, -6536)),
87
+ _mm_madd_epi16(_mm_unpacklo_epi16(b, zero),
88
+ _mm_setr_epi16(-660, 0, -660, 0, -660, 0, -660, 0)))),
89
+ 14);
90
+ const auto packed = _mm_packs_epi32(cb, cr);
91
+ uint8_t values[16];
92
+ _mm_storeu_si128(reinterpret_cast<__m128i*>(values), _mm_packus_epi16(packed, packed));
93
+ for (int k = 0; k < 4; ++k) {
94
+ u[k * step] = values[k];
95
+ v[k * step] = values[k + 4];
96
+ }
97
+ }
98
+ #endif
99
+ } // namespace
100
+
101
+ template<bool argb>
102
+ bool convertToNv12(const uint8_t* source, int sourceStride,
103
+ uint8_t* y, int yStride, uint8_t* uv, int uvStride,
104
+ int width, int height) {
105
+ if (!source || !y || !uv || width <= 0 || height <= 0 ||
106
+ (width & 1) || (height & 1) || width > std::numeric_limits<int>::max() / 4 ||
107
+ sourceStride < width * 4 || yStride < width ||
108
+ uvStride < width) return false;
109
+ for (int row = 0; row < height; row += 2) {
110
+ const auto* top = source + static_cast<ptrdiff_t>(row) * sourceStride;
111
+ const auto* bottom = top + sourceStride;
112
+ auto* y0 = y + static_cast<ptrdiff_t>(row) * yStride;
113
+ auto* y1 = y0 + yStride;
114
+ auto* uv0 = uv + static_cast<ptrdiff_t>(row / 2) * uvStride;
115
+ int x = 0;
116
+ #if defined(__aarch64__)
117
+ if constexpr (!argb) for (; x <= width - 16; x += 16) {
118
+ const auto a = vld4q_u8(top + x * 4);
119
+ const auto b = vld4q_u8(bottom + x * 4);
120
+ vst1q_u8(y0 + x, vcombine_u8(luma8(vget_low_u8(a.val[0]), vget_low_u8(a.val[1]), vget_low_u8(a.val[2])),
121
+ luma8(vget_high_u8(a.val[0]), vget_high_u8(a.val[1]), vget_high_u8(a.val[2]))));
122
+ vst1q_u8(y1 + x, vcombine_u8(luma8(vget_low_u8(b.val[0]), vget_low_u8(b.val[1]), vget_low_u8(b.val[2])),
123
+ luma8(vget_high_u8(b.val[0]), vget_high_u8(b.val[1]), vget_high_u8(b.val[2]))));
124
+ const auto blue = box8(a.val[0], b.val[0]);
125
+ const auto green = box8(a.val[1], b.val[1]);
126
+ const auto red = box8(a.val[2], b.val[2]);
127
+ const auto bias = vdupq_n_u16(128 * 256 + 128);
128
+ auto cb = vmlal_u8(bias, blue, vdup_n_u8(112));
129
+ cb = vmlsl_u8(vmlsl_u8(cb, red, vdup_n_u8(26)), green, vdup_n_u8(86));
130
+ auto cr = vmlal_u8(bias, red, vdup_n_u8(112));
131
+ cr = vmlsl_u8(vmlsl_u8(cr, green, vdup_n_u8(102)), blue, vdup_n_u8(10));
132
+ const uint8x8x2_t chroma = {{vshrn_n_u16(cb, 8), vshrn_n_u16(cr, 8)}};
133
+ vst2_u8(uv0 + x, chroma);
134
+ }
135
+ #endif
136
+ #if defined(__SSE2__)
137
+ if constexpr (!argb) for (; x <= width - 8; x += 8) {
138
+ __m128i tb, tg, tr, bb, bg, br;
139
+ splitBgra8(top + x * 4, tb, tg, tr);
140
+ splitBgra8(bottom + x * 4, bb, bg, br);
141
+ _mm_storel_epi64(reinterpret_cast<__m128i*>(y0 + x), lumaBlock8(tb, tg, tr));
142
+ _mm_storel_epi64(reinterpret_cast<__m128i*>(y1 + x), lumaBlock8(bb, bg, br));
143
+ chromaBlock4(boxAverage4(tb, bb), boxAverage4(tg, bg), boxAverage4(tr, br),
144
+ uv0 + x, uv0 + x + 1, 2);
145
+ }
146
+ #endif
147
+ for (; x < width; x += 2) {
148
+ const auto* a = top + x * 4;
149
+ const auto* b = bottom + x * 4;
150
+ constexpr int blueOffset = argb ? 3 : 0;
151
+ constexpr int greenOffset = argb ? 2 : 1;
152
+ constexpr int redOffset = argb ? 1 : 2;
153
+ y0[x] = luma(a[blueOffset], a[greenOffset], a[redOffset]);
154
+ y0[x + 1] = luma(a[4 + blueOffset], a[4 + greenOffset], a[4 + redOffset]);
155
+ y1[x] = luma(b[blueOffset], b[greenOffset], b[redOffset]);
156
+ y1[x + 1] = luma(b[4 + blueOffset], b[4 + greenOffset], b[4 + redOffset]);
157
+ const int blue = (a[blueOffset] + a[4 + blueOffset] + b[blueOffset] + b[4 + blueOffset] + 2) / 4;
158
+ const int green = (a[greenOffset] + a[4 + greenOffset] + b[greenOffset] + b[4 + greenOffset] + 2) / 4;
159
+ const int red = (a[redOffset] + a[4 + redOffset] + b[redOffset] + b[4 + redOffset] + 2) / 4;
160
+ uv0[x] = blueChroma(blue, green, red);
161
+ uv0[x + 1] = redChroma(blue, green, red);
162
+ }
163
+ }
164
+ return true;
165
+ }
166
+ bool bgraToNv12(const uint8_t* source, int sourceStride,
167
+ uint8_t* y, int yStride, uint8_t* uv, int uvStride,
168
+ int width, int height) {
169
+ return convertToNv12<false>(source, sourceStride, y, yStride, uv, uvStride, width, height);
170
+ }
171
+ bool argbToNv12(const uint8_t* source, int sourceStride,
172
+ uint8_t* y, int yStride, uint8_t* uv, int uvStride,
173
+ int width, int height) {
174
+ return convertToNv12<true>(source, sourceStride, y, yStride, uv, uvStride, width, height);
175
+ }
176
+ } // namespace relay
@@ -0,0 +1,16 @@
1
+ #pragma once
2
+
3
+ #include <cstdint>
4
+
5
+ namespace relay {
6
+ // Full-range BGRA or ARGB (alpha ignored) to limited-range BT.709 NV12 (interleaved UV).
7
+ // Chroma uses a 2x2 box with channels rounded to nearest before conversion.
8
+ // Requires disjoint buffers covering every row and positive, even dimensions.
9
+ // Invalid pointers, dimensions or strides return false without writing.
10
+ bool bgraToNv12(const uint8_t* source, int sourceStride,
11
+ uint8_t* y, int yStride, uint8_t* uv, int uvStride,
12
+ int width, int height);
13
+ bool argbToNv12(const uint8_t* source, int sourceStride,
14
+ uint8_t* y, int yStride, uint8_t* uv, int uvStride,
15
+ int width, int height);
16
+ } // namespace relay
@@ -0,0 +1,196 @@
1
+ #pragma once
2
+
3
+ #include <algorithm>
4
+ #include <cstdint>
5
+ #include <fstream>
6
+ #include <iterator>
7
+ #include <limits>
8
+ #include <sstream>
9
+ #include <string>
10
+ #include <thread>
11
+ #include <vector>
12
+
13
+ #if defined(__linux__)
14
+ #include <sched.h>
15
+ #endif
16
+
17
+ namespace relay {
18
+ /** Reads a whole file, returning an empty string when it cannot be opened. */
19
+ inline std::string readText(const char* path) {
20
+ std::ifstream file(path);
21
+ return std::string(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
22
+ }
23
+
24
+ /** Reads one signed number from text, returning 0 when there is none. */
25
+ inline int64_t parseCount(const std::string& text) {
26
+ std::istringstream fields(text);
27
+ int64_t value = 0;
28
+ return fields >> value ? value : 0;
29
+ }
30
+
31
+ /** CPUs implied by a quota and its period, or 0 when there is no limit. */
32
+ inline unsigned quotaCpus(uint64_t limit, uint64_t window) {
33
+ if (!limit || !window) return 0;
34
+ const uint64_t cpus = (limit - 1) / window + 1;
35
+ return unsigned(std::min<uint64_t>(cpus, std::numeric_limits<unsigned>::max()));
36
+ }
37
+
38
+ /** Decodes the octal escapes the kernel writes for spaces and control characters in mount fields. */
39
+ inline std::string decodeMountField(const std::string& field) {
40
+ std::string out;
41
+ for (size_t i = 0; i < field.size(); ++i) {
42
+ const auto octal = [&](size_t at) { return field[at] >= '0' && field[at] <= '7'; };
43
+ if (field[i] == '\\' && i + 3 < field.size() && octal(i + 1) && octal(i + 2) && octal(i + 3)) {
44
+ out.push_back(char((field[i + 1] - '0') * 64 + (field[i + 2] - '0') * 8 + (field[i + 3] - '0')));
45
+ i += 3;
46
+ } else {
47
+ out.push_back(field[i]);
48
+ }
49
+ }
50
+ return out;
51
+ }
52
+
53
+ /** Whether a comma-separated cgroup controller list names one controller. */
54
+ inline bool hasController(const std::string& controllers, const std::string& name) {
55
+ std::istringstream list(controllers);
56
+ std::string item;
57
+ while (std::getline(list, item, ',')) if (item == name) return true;
58
+ return false;
59
+ }
60
+
61
+ /** Where one cgroup hierarchy is mounted and which cgroup that mount point is rooted at. */
62
+ struct CgroupMount {
63
+ std::string root, point;
64
+ };
65
+
66
+ /** Finds the mount of the unified hierarchy, or of the v1 hierarchy carrying the cpu controller. */
67
+ inline CgroupMount findCgroupMount(const std::string& mountinfo, bool unified) {
68
+ std::istringstream lines(mountinfo);
69
+ std::string line;
70
+ while (std::getline(lines, line)) {
71
+ std::istringstream fields(line);
72
+ std::string field, root, point;
73
+ int index = 0;
74
+ for (; fields >> field; ++index) {
75
+ if (index == 3) root = field;
76
+ if (index == 4) point = field;
77
+ if (field == "-") break;
78
+ }
79
+ std::string type, source, options;
80
+ if (field != "-" || !(fields >> type >> source)) continue;
81
+ fields >> options;
82
+ if (type != (unified ? "cgroup2" : "cgroup")) continue;
83
+ if (!unified && !hasController(options, "cpu")) continue;
84
+ return {decodeMountField(root), decodeMountField(point)};
85
+ }
86
+ return {};
87
+ }
88
+
89
+ /** Path of the process inside one cgroup hierarchy from /proc/self/cgroup, or an empty string. */
90
+ inline std::string cgroupPath(const std::string& selfCgroup, bool unified) {
91
+ std::istringstream lines(selfCgroup);
92
+ std::string line;
93
+ while (std::getline(lines, line)) {
94
+ const size_t first = line.find(':');
95
+ const size_t second = first == std::string::npos ? first : line.find(':', first + 1);
96
+ if (second == std::string::npos) continue;
97
+ const std::string controllers = line.substr(first + 1, second - first - 1);
98
+ if (unified ? controllers.empty() : hasController(controllers, "cpu")) return line.substr(second + 1);
99
+ }
100
+ return {};
101
+ }
102
+
103
+ /** Cgroup path relative to the root the hierarchy is mounted at; false when it lies outside that mount. */
104
+ inline bool relativeCgroupPath(std::string path, const std::string& root, std::string& relative) {
105
+ if (path.empty()) path = "/";
106
+ if (root != "/") {
107
+ if (path == root) path = "/";
108
+ else if (path.rfind(root + "/", 0) == 0) path.erase(0, root.size());
109
+ else return false;
110
+ }
111
+ while (!path.empty() && path.front() == '/') path.erase(0, 1);
112
+ relative = path;
113
+ return true;
114
+ }
115
+
116
+ /** Joins a directory and a file name with one separator. */
117
+ inline std::string joinPath(const std::string& dir, const char* name) {
118
+ if (dir.empty()) return name;
119
+ return dir.back() == '/' ? dir + name : dir + "/" + name;
120
+ }
121
+
122
+ /** Files with this name in each cgroup from the hierarchy mount point down to the process's own cgroup. */
123
+ inline std::vector<std::string> cgroupFiles(const std::string& mountinfo, const std::string& selfCgroup,
124
+ bool unified, const char* name) {
125
+ std::vector<std::string> files;
126
+ const CgroupMount mount = findCgroupMount(mountinfo, unified);
127
+ if (mount.point.empty()) return files;
128
+ std::string path;
129
+ const std::string own = cgroupPath(selfCgroup, unified);
130
+ if (!own.empty() && !relativeCgroupPath(own, mount.root, path)) return files;
131
+ std::string dir = mount.point;
132
+ files.push_back(joinPath(dir, name));
133
+ while (!path.empty()) {
134
+ const size_t slash = path.find('/');
135
+ if (dir.empty() || dir.back() != '/') dir += '/';
136
+ dir += path.substr(0, slash);
137
+ path.erase(0, slash == std::string::npos ? path.size() : slash + 1);
138
+ files.push_back(joinPath(dir, name));
139
+ }
140
+ return files;
141
+ }
142
+
143
+ /** CPUs implied by a quota and its period written as text, or 0 when there is no limit. */
144
+ inline unsigned quotaCpusText(const std::string& quota, const std::string& period) {
145
+ const int64_t limit = parseCount(quota), window = parseCount(period);
146
+ if (limit <= 0 || window <= 0) return 0;
147
+ return quotaCpus(uint64_t(limit), uint64_t(window));
148
+ }
149
+
150
+ /** CPUs implied by the unified hierarchy quota, or 0 when the hierarchy reports no limit. */
151
+ inline unsigned unifiedQuotaCpus(const std::string& cpuMax) {
152
+ std::istringstream fields(cpuMax);
153
+ std::string quota, period;
154
+ if (!(fields >> quota >> period) || quota == "max") return 0;
155
+ return quotaCpusText(quota, period);
156
+ }
157
+
158
+ /** CPUs implied by the cgroup quota recorded under a /proc/self directory, or 0 when none applies. */
159
+ inline unsigned cgroupQuotaCpus(const std::string& proc = "/proc/self") {
160
+ const std::string mountinfo = readText((proc + "/mountinfo").c_str());
161
+ const std::string self = readText((proc + "/cgroup").c_str());
162
+ unsigned quota = 0;
163
+ const auto add = [&](unsigned cpus) { if (cpus) quota = quota ? std::min(quota, cpus) : cpus; };
164
+ for (const std::string& file : cgroupFiles(mountinfo, self, true, "cpu.max"))
165
+ add(unifiedQuotaCpus(readText(file.c_str())));
166
+ const std::vector<std::string> quotas = cgroupFiles(mountinfo, self, false, "cpu.cfs_quota_us");
167
+ const std::vector<std::string> periods = cgroupFiles(mountinfo, self, false, "cpu.cfs_period_us");
168
+ for (size_t i = 0; i < quotas.size(); ++i)
169
+ add(quotaCpusText(readText(quotas[i].c_str()), readText(periods[i].c_str())));
170
+ return quota;
171
+ }
172
+
173
+ /** CPUs this thread is allowed to run on, which includes cpuset limits, or 0 when unknown. */
174
+ inline unsigned affinityCpus() {
175
+ #if defined(__linux__)
176
+ cpu_set_t mask;
177
+ CPU_ZERO(&mask);
178
+ if (sched_getaffinity(0, sizeof(mask), &mask) == 0 && CPU_COUNT(&mask) > 0) return unsigned(CPU_COUNT(&mask));
179
+ #endif
180
+ return 0;
181
+ }
182
+
183
+ /** CPUs this process may use: the smallest of its cgroup quota, CPU affinity, and online CPUs. */
184
+ inline unsigned availableCpus() {
185
+ unsigned cpus = std::max(1u, std::thread::hardware_concurrency());
186
+ if (const unsigned affinity = affinityCpus()) cpus = std::min(cpus, affinity);
187
+ if (const unsigned quota = cgroupQuotaCpus()) cpus = std::min(cpus, quota);
188
+ return cpus;
189
+ }
190
+
191
+ /** Sliced threads x264 can use for a frame: one slice per four macroblock rows. */
192
+ inline unsigned sliceLimit(int height) { return std::max(1u, unsigned((height + 15) / 16 / 4)); }
193
+
194
+ /** Slice threads that encode one frame in parallel, bounded by the CPU budget and the slice count. */
195
+ inline int encoderThreads(int height) { return int(std::min(availableCpus(), sliceLimit(height))); }
196
+ } // namespace relay