2 * @file src/platform/linux/cuda.cu
3 * @brief CUDA implementation for Linux.
13#include <helper_math.h>
18using namespace std::literals;
20#define HERMES_STRINGVIEW_HELPER(x) x##sv
21#define HERMES_STRINGVIEW(x) HERMES_STRINGVIEW_HELPER(x)
23#define CU_CHECK(x, y) \
24 if (check((x), HERMES_STRINGVIEW(y ": "))) \
27#define CU_CHECK_VOID(x, y) \
28 if (check((x), HERMES_STRINGVIEW(y ": "))) \
31#define CU_CHECK_PTR(x, y) \
32 if (check((x), HERMES_STRINGVIEW(y ": "))) \
35#define CU_CHECK_OPT(x, y) \
36 if (check((x), HERMES_STRINGVIEW(y ": "))) \
39#define CU_CHECK_IGNORE(x, y) \
40 check((x), HERMES_STRINGVIEW(y ": "))
42using namespace std::literals;
44// Special declarations
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.
52 struct img_t: std::enable_shared_from_this<img_t> {
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 {};
60 std::optional<std::chrono::steady_clock::time_point> frame_timestamp;
62 virtual ~img_t() = default;
66// End special declarations
70 struct alignas(16) cuda_color_t {
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");
81 auto constexpr INVALID_TEXTURE = std::numeric_limits<cudaTextureObject_t>::max();
84 inline T div_align(T l, T r) {
85 return (l + r - 1) / r;
88 void pass_error(const std::string_view &sv, const char *name, const char *description);
90 inline static int check(cudaError_t result, const std::string_view &sv) {
92 auto name = cudaGetErrorName(result);
93 auto description = cudaGetErrorString(result);
95 pass_error(sv, name, description);
105 CU_CHECK_PTR(cudaMalloc(&p, sizeof(T)), "Couldn't allocate color matrix");
112 void freeCudaPtr_t::operator()(void *ptr) {
113 CU_CHECK_IGNORE(cudaFree(ptr), "Couldn't free cuda device pointer");
116 void freeCudaStream_t::operator()(cudaStream_t ptr) {
117 CU_CHECK_IGNORE(cudaStreamDestroy(ptr), "Couldn't free cuda stream");
120 stream_t make_stream(int flags) {
124 CU_CHECK_PTR(cudaStreamCreate(&stream), "Couldn't create cuda stream");
126 CU_CHECK_PTR(cudaStreamCreateWithFlags(&stream, flags), "Couldn't create cuda stream with flags");
129 return stream_t {stream};
132 inline __device__ float3 bgra_to_rgb(uchar4 vec) {
133 return make_float3((float) vec.z, (float) vec.y, (float) vec.x);
136 inline __device__ float3 bgra_to_rgb(float4 vec) {
137 return make_float3(vec.z, vec.y, vec.x);
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;
144 float u = dot(pixel, make_float3(vec_u)) + vec_u.w;
145 float v = dot(pixel, make_float3(vec_v)) + vec_v.w;
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;
150 return make_float2(u, v);
153 inline __device__ float calcY(float3 pixel, const cuda_color_t *const color_matrix) {
154 float4 vec_y = color_matrix->color_vec_y;
156 return (dot(pixel, make_float3(vec_y)) + vec_y.w) * color_matrix->range_y.x + color_matrix->range_y.y;
159 __global__ void RGBA_to_NV12(
160 cudaTextureObject_t srcImage,
163 std::uint32_t dstPitchY,
164 std::uint32_t dstPitchUV,
166 const viewport_t viewport,
167 const cuda_color_t *const color_matrix
169 int idX = (threadIdx.x + blockDim.x * blockIdx.x) * 2;
170 int idY = (threadIdx.y + blockDim.y * blockIdx.y) * 2;
172 if (idX >= viewport.width) {
175 if (idY >= viewport.height) {
179 float x = idX * scale;
180 float y = idY * scale;
182 idX += viewport.offsetX;
183 idY += viewport.offsetY;
185 uint8_t *dstY0 = dstY + idX + idY * dstPitchY;
186 uint8_t *dstY1 = dstY + idX + (idY + 1) * dstPitchY;
187 dstUV = dstUV + idX + (idY / 2 * dstPitchUV);
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));
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;
199 float2 uv = (uv_lt + uv_lb + uv_rt + uv_rb) * 0.25f;
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
210 * Sample the input at unnormalized coordinates, as RGB in [0, 1].
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.
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};
224 return pixel::unpack(layout, tex2D<unsigned int>(tex, x, y));
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;
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);
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.
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.
249 template<class sample_t>
250 __global__ void RGB_to_YUV420(
251 cudaTextureObject_t srcImage,
252 pixel::layout_e layout,
256 std::uint32_t dstPitchY,
257 std::uint32_t dstPitchUV,
259 const viewport_t viewport,
260 const pixel::matrix_t *const matrix,
261 std::uint32_t max_code
263 int idX = (threadIdx.x + blockDim.x * blockIdx.x) * 2;
264 int idY = (threadIdx.y + blockDim.y * blockIdx.y) * 2;
266 if (idX >= viewport.width) {
269 if (idY >= viewport.height) {
273 float x = idX * scale;
274 float y = idY * scale;
276 idX += viewport.offsetX;
277 idY += viewport.offsetY;
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);
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;
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));
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));
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");
304 std::optional<tex_t> tex_t::make(int height, int pitch, pixel::layout_e layout) {
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");
314 cudaResourceDesc res {};
315 res.resType = cudaResourceTypeArray;
316 res.res.array.array = tex.array;
318 cudaTextureDesc desc {};
320 desc.readMode = packed ? cudaReadModeElementType : cudaReadModeNormalizedFloat;
321 desc.filterMode = cudaFilterModePoint;
322 desc.normalizedCoords = false;
324 std::fill_n(std::begin(desc.addressMode), 2, cudaAddressModeClamp);
326 CU_CHECK_OPT(cudaCreateTextureObject(&tex.texture.point, &res, &desc, nullptr), "Couldn't create cuda texture that uses point interpolation");
328 // Integer textures cannot be filtered by the hardware: the "linear"
329 // object of a packed texture samples points too, and fetch_rgb() blends.
331 desc.filterMode = cudaFilterModeLinear;
334 CU_CHECK_OPT(cudaCreateTextureObject(&tex.texture.linear, &res, &desc, nullptr), "Couldn't create cuda texture that uses linear interpolation");
341 texture {INVALID_TEXTURE, INVALID_TEXTURE} {
344 tex_t::tex_t(tex_t &&other):
346 layout {other.layout},
347 texture {other.texture} {
349 other.texture.point = INVALID_TEXTURE;
350 other.texture.linear = INVALID_TEXTURE;
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);
362 if (texture.point != INVALID_TEXTURE) {
363 CU_CHECK_IGNORE(cudaDestroyTextureObject(texture.point), "Couldn't deallocate cuda texture that uses point interpolation");
365 texture.point = INVALID_TEXTURE;
368 if (texture.linear != INVALID_TEXTURE) {
369 CU_CHECK_IGNORE(cudaDestroyTextureObject(texture.linear), "Couldn't deallocate cuda texture that uses linear interpolation");
371 texture.linear = INVALID_TEXTURE;
375 CU_CHECK_IGNORE(cudaFreeArray(array), "Couldn't deallocate cuda array");
377 array = cudaArray_t {};
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;
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;
393 viewport.width = out_width_f;
394 viewport.height = out_height_f;
396 viewport.offsetX = offsetX_f;
397 viewport.offsetY = offsetY_f;
399 scale = 1.0f / scalar;
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;
405 CU_CHECK_OPT(cudaGetDevice(&device), "Couldn't get cuda device");
406 CU_CHECK_OPT(cudaGetDeviceProperties(&props, device), "Couldn't get cuda device properties");
408 auto ptr = make_ptr<cuda_color_t>();
413 return std::make_optional<sws_t>(in_width, in_height, out_width, out_height, pitch, props.maxThreadsPerMultiProcessor / props.maxBlocksPerMultiProcessor, std::move(ptr));
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) {
421 auto sws = make(in_width, in_height, out_width, out_height, pitch);
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) {
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);
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;
446 dim3 block(threadsPerBlock);
447 dim3 grid(div_align(threadsX, threadsPerBlock), threadsY);
450 RGBA_to_NV12<<<grid, block, 0, stream>>>(texture, Y, UV, pitchY, pitchUV, scale, viewport, (cuda_color_t *) color_matrix.get());
452 return CU_CHECK_IGNORE(cudaGetLastError(), "RGBA_to_NV12 failed");
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);
459 RGB_to_YUV420<std::uint8_t><<<grid, block, 0, stream>>>(texture, layout, linear, Y, UV, pitchY, pitchUV, scale, viewport, matrix, 255);
462 return CU_CHECK_IGNORE(cudaGetLastError(), "RGB_to_YUV420 failed");
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");
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");
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");