Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
cuda.cu
1/**
2 * @file src/platform/linux/cuda.cu
3 * @brief CUDA implementation for Linux.
4 */
5// standard includes
6#include <chrono>
7#include <limits>
8#include <memory>
9#include <optional>
10#include <string_view>
11
12// platform includes
13#include <helper_math.h>
14
15// local includes
16#include "cuda.h"
17
18using namespace std::literals;
19
20#define HERMES_STRINGVIEW_HELPER(x) x##sv
21#define HERMES_STRINGVIEW(x) HERMES_STRINGVIEW_HELPER(x)
22
23#define CU_CHECK(x, y) \
24 if (check((x), HERMES_STRINGVIEW(y ": "))) \
25 return -1
26
27#define CU_CHECK_VOID(x, y) \
28 if (check((x), HERMES_STRINGVIEW(y ": "))) \
29 return;
30
31#define CU_CHECK_PTR(x, y) \
32 if (check((x), HERMES_STRINGVIEW(y ": "))) \
33 return nullptr;
34
35#define CU_CHECK_OPT(x, y) \
36 if (check((x), HERMES_STRINGVIEW(y ": "))) \
37 return std::nullopt;
38
39#define CU_CHECK_IGNORE(x, y) \
40 check((x), HERMES_STRINGVIEW(y ": "))
41
42using namespace std::literals;
43
44// Special declarations
45/**
46 * NVCC tends to have problems with standard headers.
47 * Don't include common.h, instead use bare minimum
48 * of standard headers and duplicate declarations of necessary classes.
49 * Not pretty and extremely error-prone, fix at earliest convenience.
50 */
51namespace platf {
52 struct img_t: std::enable_shared_from_this<img_t> {
53 public:
54 std::uint8_t *data {};
55 std::int32_t width {};
56 std::int32_t height {};
57 std::int32_t pixel_pitch {};
58 std::int32_t row_pitch {};
59
60 std::optional<std::chrono::steady_clock::time_point> frame_timestamp;
61
62 virtual ~img_t() = default;
63 };
64} // namespace platf
65
66// End special declarations
67
68namespace cuda {
69
70 struct alignas(16) cuda_color_t {
71 float4 color_vec_y;
72 float4 color_vec_u;
73 float4 color_vec_v;
74 float2 range_y;
75 float2 range_uv;
76 };
77
78 static_assert(sizeof(video::color_t) == sizeof(cuda::cuda_color_t), "color matrix struct mismatch");
79 static_assert(sizeof(video::color_t) == sizeof(pixel::matrix_t), "code matrix struct mismatch");
80
81 auto constexpr INVALID_TEXTURE = std::numeric_limits<cudaTextureObject_t>::max();
82
83 template<class T>
84 inline T div_align(T l, T r) {
85 return (l + r - 1) / r;
86 }
87
88 void pass_error(const std::string_view &sv, const char *name, const char *description);
89
90 inline static int check(cudaError_t result, const std::string_view &sv) {
91 if (result) {
92 auto name = cudaGetErrorName(result);
93 auto description = cudaGetErrorString(result);
94
95 pass_error(sv, name, description);
96 return -1;
97 }
98
99 return 0;
100 }
101
102 template<class T>
103 ptr_t make_ptr() {
104 void *p;
105 CU_CHECK_PTR(cudaMalloc(&p, sizeof(T)), "Couldn't allocate color matrix");
106
107 ptr_t ptr {p};
108
109 return ptr;
110 }
111
112 void freeCudaPtr_t::operator()(void *ptr) {
113 CU_CHECK_IGNORE(cudaFree(ptr), "Couldn't free cuda device pointer");
114 }
115
116 void freeCudaStream_t::operator()(cudaStream_t ptr) {
117 CU_CHECK_IGNORE(cudaStreamDestroy(ptr), "Couldn't free cuda stream");
118 }
119
120 stream_t make_stream(int flags) {
121 cudaStream_t stream;
122
123 if (!flags) {
124 CU_CHECK_PTR(cudaStreamCreate(&stream), "Couldn't create cuda stream");
125 } else {
126 CU_CHECK_PTR(cudaStreamCreateWithFlags(&stream, flags), "Couldn't create cuda stream with flags");
127 }
128
129 return stream_t {stream};
130 }
131
132 inline __device__ float3 bgra_to_rgb(uchar4 vec) {
133 return make_float3((float) vec.z, (float) vec.y, (float) vec.x);
134 }
135
136 inline __device__ float3 bgra_to_rgb(float4 vec) {
137 return make_float3(vec.z, vec.y, vec.x);
138 }
139
140 inline __device__ float2 calcUV(float3 pixel, const cuda_color_t *const color_matrix) {
141 float4 vec_u = color_matrix->color_vec_u;
142 float4 vec_v = color_matrix->color_vec_v;
143
144 float u = dot(pixel, make_float3(vec_u)) + vec_u.w;
145 float v = dot(pixel, make_float3(vec_v)) + vec_v.w;
146
147 u = u * color_matrix->range_uv.x + color_matrix->range_uv.y;
148 v = v * color_matrix->range_uv.x + color_matrix->range_uv.y;
149
150 return make_float2(u, v);
151 }
152
153 inline __device__ float calcY(float3 pixel, const cuda_color_t *const color_matrix) {
154 float4 vec_y = color_matrix->color_vec_y;
155
156 return (dot(pixel, make_float3(vec_y)) + vec_y.w) * color_matrix->range_y.x + color_matrix->range_y.y;
157 }
158
159 __global__ void RGBA_to_NV12(
160 cudaTextureObject_t srcImage,
161 std::uint8_t *dstY,
162 std::uint8_t *dstUV,
163 std::uint32_t dstPitchY,
164 std::uint32_t dstPitchUV,
165 float scale,
166 const viewport_t viewport,
167 const cuda_color_t *const color_matrix
168 ) {
169 int idX = (threadIdx.x + blockDim.x * blockIdx.x) * 2;
170 int idY = (threadIdx.y + blockDim.y * blockIdx.y) * 2;
171
172 if (idX >= viewport.width) {
173 return;
174 }
175 if (idY >= viewport.height) {
176 return;
177 }
178
179 float x = idX * scale;
180 float y = idY * scale;
181
182 idX += viewport.offsetX;
183 idY += viewport.offsetY;
184
185 uint8_t *dstY0 = dstY + idX + idY * dstPitchY;
186 uint8_t *dstY1 = dstY + idX + (idY + 1) * dstPitchY;
187 dstUV = dstUV + idX + (idY / 2 * dstPitchUV);
188
189 float3 rgb_lt = bgra_to_rgb(tex2D<float4>(srcImage, x, y));
190 float3 rgb_rt = bgra_to_rgb(tex2D<float4>(srcImage, x + scale, y));
191 float3 rgb_lb = bgra_to_rgb(tex2D<float4>(srcImage, x, y + scale));
192 float3 rgb_rb = bgra_to_rgb(tex2D<float4>(srcImage, x + scale, y + scale));
193
194 float2 uv_lt = calcUV(rgb_lt, color_matrix) * 256.0f;
195 float2 uv_rt = calcUV(rgb_rt, color_matrix) * 256.0f;
196 float2 uv_lb = calcUV(rgb_lb, color_matrix) * 256.0f;
197 float2 uv_rb = calcUV(rgb_rb, color_matrix) * 256.0f;
198
199 float2 uv = (uv_lt + uv_lb + uv_rt + uv_rb) * 0.25f;
200
201 dstUV[0] = uv.x;
202 dstUV[1] = uv.y;
203 dstY0[0] = calcY(rgb_lt, color_matrix) * 245.0f; // 245.0f is a magic number to ensure slight changes in luminosity are more visible
204 dstY0[1] = calcY(rgb_rt, color_matrix) * 245.0f; // 245.0f is a magic number to ensure slight changes in luminosity are more visible
205 dstY1[0] = calcY(rgb_lb, color_matrix) * 245.0f; // 245.0f is a magic number to ensure slight changes in luminosity are more visible
206 dstY1[1] = calcY(rgb_rb, color_matrix) * 245.0f; // 245.0f is a magic number to ensure slight changes in luminosity are more visible
207 }
208
209 /**
210 * Sample the input at unnormalized coordinates, as RGB in [0, 1].
211 *
212 * 8-bit BGRA comes from a normalized-float texture that the hardware
213 * filters, point or linear depending on the texture object passed. Packed
214 * 10-bit words come from an unsigned-integer texture, which cannot be
215 * filtered, so when scaling the four texels around the sample are decoded
216 * and blended here, around texel centres the way the hardware would.
217 */
218 __device__ pixel::rgb_t fetch_rgb(cudaTextureObject_t tex, pixel::layout_e layout, bool linear, float x, float y) {
219 if (layout == pixel::layout_e::bgra8) {
220 const float4 bgra = tex2D<float4>(tex, x, y);
221 return {bgra.z, bgra.y, bgra.x};
222 }
223 if (!linear) {
224 return pixel::unpack(layout, tex2D<unsigned int>(tex, x, y));
225 }
226
227 const float fx = x - 0.5f;
228 const float fy = y - 0.5f;
229 const float x0 = floorf(fx);
230 const float y0 = floorf(fy);
231 const float ax = fx - x0;
232 const float ay = fy - y0;
233
234 const auto t00 = pixel::unpack(layout, tex2D<unsigned int>(tex, x0 + 0.5f, y0 + 0.5f));
235 const auto t10 = pixel::unpack(layout, tex2D<unsigned int>(tex, x0 + 1.5f, y0 + 0.5f));
236 const auto t01 = pixel::unpack(layout, tex2D<unsigned int>(tex, x0 + 0.5f, y0 + 1.5f));
237 const auto t11 = pixel::unpack(layout, tex2D<unsigned int>(tex, x0 + 1.5f, y0 + 1.5f));
238 return pixel::mix(pixel::mix(t00, t10, ax), pixel::mix(t01, t11, ax), ay);
239 }
240
241 /**
242 * RGB to 4:2:0 YUV in integer code values, for 8-bit (NV12) or 10-bit
243 * (P010) samples, from any input layout.
244 *
245 * Uses the matrices of video::new_color_vectors_from_colorspace(), which
246 * produce code values for the target bit depth and range directly. The
247 * original 8-bit BGRA to NV12 path keeps RGBA_to_NV12 and its constants.
248 */
249 template<class sample_t>
250 __global__ void RGB_to_YUV420(
251 cudaTextureObject_t srcImage,
252 pixel::layout_e layout,
253 bool linear,
254 std::uint8_t *dstY,
255 std::uint8_t *dstUV,
256 std::uint32_t dstPitchY,
257 std::uint32_t dstPitchUV,
258 float scale,
259 const viewport_t viewport,
260 const pixel::matrix_t *const matrix,
261 std::uint32_t max_code
262 ) {
263 int idX = (threadIdx.x + blockDim.x * blockIdx.x) * 2;
264 int idY = (threadIdx.y + blockDim.y * blockIdx.y) * 2;
265
266 if (idX >= viewport.width) {
267 return;
268 }
269 if (idY >= viewport.height) {
270 return;
271 }
272
273 float x = idX * scale;
274 float y = idY * scale;
275
276 idX += viewport.offsetX;
277 idY += viewport.offsetY;
278
279 const auto lt = fetch_rgb(srcImage, layout, linear, x, y);
280 const auto rt = fetch_rgb(srcImage, layout, linear, x + scale, y);
281 const auto lb = fetch_rgb(srcImage, layout, linear, x, y + scale);
282 const auto rb = fetch_rgb(srcImage, layout, linear, x + scale, y + scale);
283
284 auto *dstY0 = reinterpret_cast<sample_t *>(dstY + idY * dstPitchY) + idX;
285 auto *dstY1 = reinterpret_cast<sample_t *>(dstY + (idY + 1) * dstPitchY) + idX;
286 auto *uv = reinterpret_cast<sample_t *>(dstUV + (idY / 2) * dstPitchUV) + idX;
287
288 dstY0[0] = pixel::store<sample_t>(pixel::quantize(pixel::encode(matrix->y, lt), max_code));
289 dstY0[1] = pixel::store<sample_t>(pixel::quantize(pixel::encode(matrix->y, rt), max_code));
290 dstY1[0] = pixel::store<sample_t>(pixel::quantize(pixel::encode(matrix->y, lb), max_code));
291 dstY1[1] = pixel::store<sample_t>(pixel::quantize(pixel::encode(matrix->y, rb), max_code));
292
293 const auto chroma = pixel::average(lt, rt, lb, rb);
294 uv[0] = pixel::store<sample_t>(pixel::quantize(pixel::encode(matrix->u, chroma), max_code));
295 uv[1] = pixel::store<sample_t>(pixel::quantize(pixel::encode(matrix->v, chroma), max_code));
296 }
297
298 int tex_t::copy(std::uint8_t *src, int height, int pitch) {
299 CU_CHECK(cudaMemcpy2DToArray(array, 0, 0, src, pitch, pitch, height, cudaMemcpyDeviceToDevice), "Couldn't copy to cuda array from deviceptr");
300
301 return 0;
302 }
303
304 std::optional<tex_t> tex_t::make(int height, int pitch, pixel::layout_e layout) {
305 tex_t tex;
306 tex.layout = layout;
307
308 const bool packed = layout != pixel::layout_e::bgra8;
309 auto format = packed ? cudaCreateChannelDesc<unsigned int>() : cudaCreateChannelDesc<uchar4>();
310 // The BGRA array has always been allocated `pitch` elements wide; a packed
311 // array is exactly one element per pixel.
312 CU_CHECK_OPT(cudaMallocArray(&tex.array, &format, packed ? pitch / 4 : pitch, height, cudaArrayDefault), "Couldn't allocate cuda array");
313
314 cudaResourceDesc res {};
315 res.resType = cudaResourceTypeArray;
316 res.res.array.array = tex.array;
317
318 cudaTextureDesc desc {};
319
320 desc.readMode = packed ? cudaReadModeElementType : cudaReadModeNormalizedFloat;
321 desc.filterMode = cudaFilterModePoint;
322 desc.normalizedCoords = false;
323
324 std::fill_n(std::begin(desc.addressMode), 2, cudaAddressModeClamp);
325
326 CU_CHECK_OPT(cudaCreateTextureObject(&tex.texture.point, &res, &desc, nullptr), "Couldn't create cuda texture that uses point interpolation");
327
328 // Integer textures cannot be filtered by the hardware: the "linear"
329 // object of a packed texture samples points too, and fetch_rgb() blends.
330 if (!packed) {
331 desc.filterMode = cudaFilterModeLinear;
332 }
333
334 CU_CHECK_OPT(cudaCreateTextureObject(&tex.texture.linear, &res, &desc, nullptr), "Couldn't create cuda texture that uses linear interpolation");
335
336 return tex;
337 }
338
339 tex_t::tex_t():
340 array {},
341 texture {INVALID_TEXTURE, INVALID_TEXTURE} {
342 }
343
344 tex_t::tex_t(tex_t &&other):
345 array {other.array},
346 layout {other.layout},
347 texture {other.texture} {
348 other.array = 0;
349 other.texture.point = INVALID_TEXTURE;
350 other.texture.linear = INVALID_TEXTURE;
351 }
352
353 tex_t &tex_t::operator=(tex_t &&other) {
354 std::swap(array, other.array);
355 std::swap(layout, other.layout);
356 std::swap(texture, other.texture);
357
358 return *this;
359 }
360
361 tex_t::~tex_t() {
362 if (texture.point != INVALID_TEXTURE) {
363 CU_CHECK_IGNORE(cudaDestroyTextureObject(texture.point), "Couldn't deallocate cuda texture that uses point interpolation");
364
365 texture.point = INVALID_TEXTURE;
366 }
367
368 if (texture.linear != INVALID_TEXTURE) {
369 CU_CHECK_IGNORE(cudaDestroyTextureObject(texture.linear), "Couldn't deallocate cuda texture that uses linear interpolation");
370
371 texture.linear = INVALID_TEXTURE;
372 }
373
374 if (array) {
375 CU_CHECK_IGNORE(cudaFreeArray(array), "Couldn't deallocate cuda array");
376
377 array = cudaArray_t {};
378 }
379 }
380
381 sws_t::sws_t(int in_width, int in_height, int out_width, int out_height, int pitch, int threadsPerBlock, ptr_t &&color_matrix):
382 threadsPerBlock {threadsPerBlock},
383 color_matrix {std::move(color_matrix)} {
384 // Ensure aspect ratio is maintained
385 auto scalar = std::fminf(out_width / (float) in_width, out_height / (float) in_height);
386 auto out_width_f = in_width * scalar;
387 auto out_height_f = in_height * scalar;
388
389 // result is always positive
390 auto offsetX_f = (out_width - out_width_f) / 2;
391 auto offsetY_f = (out_height - out_height_f) / 2;
392
393 viewport.width = out_width_f;
394 viewport.height = out_height_f;
395
396 viewport.offsetX = offsetX_f;
397 viewport.offsetY = offsetY_f;
398
399 scale = 1.0f / scalar;
400 }
401
402 std::optional<sws_t> sws_t::make(int in_width, int in_height, int out_width, int out_height, int pitch) {
403 cudaDeviceProp props;
404 int device;
405 CU_CHECK_OPT(cudaGetDevice(&device), "Couldn't get cuda device");
406 CU_CHECK_OPT(cudaGetDeviceProperties(&props, device), "Couldn't get cuda device properties");
407
408 auto ptr = make_ptr<cuda_color_t>();
409 if (!ptr) {
410 return std::nullopt;
411 }
412
413 return std::make_optional<sws_t>(in_width, in_height, out_width, out_height, pitch, props.maxThreadsPerMultiProcessor / props.maxBlocksPerMultiProcessor, std::move(ptr));
414 }
415
416 std::optional<sws_t> sws_t::make(int in_width, int in_height, int out_width, int out_height, int pitch, pixel::layout_e layout, int output_bits) {
417 if (output_bits != 8 && output_bits != 10) {
418 return std::nullopt;
419 }
420
421 auto sws = make(in_width, in_height, out_width, out_height, pitch);
422 if (!sws) {
423 return std::nullopt;
424 }
425
426 sws->layout = layout;
427 sws->output_bits = output_bits;
428 if (layout != pixel::layout_e::bgra8 || output_bits != 8) {
429 sws->code_matrix = make_ptr<pixel::matrix_t>();
430 if (!sws->code_matrix) {
431 return std::nullopt;
432 }
433 }
434
435 return sws;
436 }
437
438 int sws_t::convert(std::uint8_t *Y, std::uint8_t *UV, std::uint32_t pitchY, std::uint32_t pitchUV, cudaTextureObject_t texture, stream_t::pointer stream) {
439 return convert(Y, UV, pitchY, pitchUV, texture, stream, viewport);
440 }
441
442 int sws_t::convert(std::uint8_t *Y, std::uint8_t *UV, std::uint32_t pitchY, std::uint32_t pitchUV, cudaTextureObject_t texture, stream_t::pointer stream, const viewport_t &viewport) {
443 int threadsX = viewport.width / 2;
444 int threadsY = viewport.height / 2;
445
446 dim3 block(threadsPerBlock);
447 dim3 grid(div_align(threadsX, threadsPerBlock), threadsY);
448
449 if (!code_matrix) {
450 RGBA_to_NV12<<<grid, block, 0, stream>>>(texture, Y, UV, pitchY, pitchUV, scale, viewport, (cuda_color_t *) color_matrix.get());
451
452 return CU_CHECK_IGNORE(cudaGetLastError(), "RGBA_to_NV12 failed");
453 }
454
455 auto matrix = (const pixel::matrix_t *) code_matrix.get();
456 if (output_bits == 10) {
457 RGB_to_YUV420<std::uint16_t><<<grid, block, 0, stream>>>(texture, layout, linear, Y, UV, pitchY, pitchUV, scale, viewport, matrix, 1023);
458 } else {
459 RGB_to_YUV420<std::uint8_t><<<grid, block, 0, stream>>>(texture, layout, linear, Y, UV, pitchY, pitchUV, scale, viewport, matrix, 255);
460 }
461
462 return CU_CHECK_IGNORE(cudaGetLastError(), "RGB_to_YUV420 failed");
463 }
464
465 void sws_t::apply_colorspace(const video::sunshine_colorspace_t &colorspace) {
466 auto color_p = video::color_vectors_from_colorspace(colorspace);
467 CU_CHECK_IGNORE(cudaMemcpy(color_matrix.get(), color_p, sizeof(video::color_t), cudaMemcpyHostToDevice), "Couldn't copy color matrix to cuda");
468
469 if (code_matrix) {
470 // Code values for the samples actually written, whatever depth the
471 // client's colorspace names.
472 auto target = colorspace;
473 target.bit_depth = output_bits;
474 auto codes = video::new_color_vectors_from_colorspace(target);
475 CU_CHECK_IGNORE(cudaMemcpy(code_matrix.get(), codes, sizeof(video::color_t), cudaMemcpyHostToDevice), "Couldn't copy code matrix to cuda");
476 }
477 }
478
479 int sws_t::load_ram(platf::img_t &img, cudaArray_t array) {
480 return CU_CHECK_IGNORE(cudaMemcpy2DToArray(array, 0, 0, img.data, img.row_pitch, img.width * img.pixel_pitch, img.height, cudaMemcpyHostToDevice), "Couldn't copy to cuda array");
481 }
482
483} // namespace cuda