conversion.cpp 21.8 KB
Newer Older
1
#include <libtorio/ffmpeg/stream_reader/conversion.h>
2
3
4
5
6
7
#include <torch/torch.h>

#ifdef USE_CUDA
#include <c10/cuda/CUDAStream.h>
#endif

moto-meta's avatar
moto-meta committed
8
namespace torio::io {
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100

////////////////////////////////////////////////////////////////////////////////
// Audio
////////////////////////////////////////////////////////////////////////////////

template <c10::ScalarType dtype, bool is_planar>
AudioConverter<dtype, is_planar>::AudioConverter(int c) : num_channels(c) {
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(num_channels > 0);
}

template <c10::ScalarType dtype, bool is_planar>
torch::Tensor AudioConverter<dtype, is_planar>::convert(const AVFrame* src) {
  if constexpr (is_planar) {
    torch::Tensor dst = torch::empty({num_channels, src->nb_samples}, dtype);
    convert(src, dst);
    return dst.permute({1, 0});
  } else {
    torch::Tensor dst = torch::empty({src->nb_samples, num_channels}, dtype);
    convert(src, dst);
    return dst;
  }
}

// Converts AVFrame* into pre-allocated Tensor.
// The shape must be [C, T] if is_planar otherwise [T, C]
template <c10::ScalarType dtype, bool is_planar>
void AudioConverter<dtype, is_planar>::convert(
    const AVFrame* src,
    torch::Tensor& dst) {
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(num_channels == src->channels);

  constexpr int bps = []() {
    switch (dtype) {
      case torch::kUInt8:
        return 1;
      case torch::kInt16:
        return 2;
      case torch::kInt32:
      case torch::kFloat32:
        return 4;
      case torch::kInt64:
      case torch::kFloat64:
        return 8;
    }
  }();

  // Note
  // FFMpeg's `nb_samples` represnts the number of samples par channel.
  // whereas, in torchaudio, `num_samples` is used to represent the number of
  // samples across channels. torchaudio uses `num_frames` for per-channel
  // samples.
  if constexpr (is_planar) {
    int plane_size = bps * src->nb_samples;
    uint8_t* p_dst = static_cast<uint8_t*>(dst.data_ptr());
    for (int i = 0; i < num_channels; ++i) {
      memcpy(p_dst, src->extended_data[i], plane_size);
      p_dst += plane_size;
    }
  } else {
    int plane_size = bps * src->nb_samples * num_channels;
    memcpy(dst.data_ptr(), src->extended_data[0], plane_size);
  }
}

// Explicit instantiation
template class AudioConverter<torch::kUInt8, false>;
template class AudioConverter<torch::kUInt8, true>;
template class AudioConverter<torch::kInt16, false>;
template class AudioConverter<torch::kInt16, true>;
template class AudioConverter<torch::kInt32, false>;
template class AudioConverter<torch::kInt32, true>;
template class AudioConverter<torch::kInt64, false>;
template class AudioConverter<torch::kInt64, true>;
template class AudioConverter<torch::kFloat32, false>;
template class AudioConverter<torch::kFloat32, true>;
template class AudioConverter<torch::kFloat64, false>;
template class AudioConverter<torch::kFloat64, true>;

////////////////////////////////////////////////////////////////////////////////
// Image
////////////////////////////////////////////////////////////////////////////////

namespace {

torch::Tensor get_image_buffer(
    at::IntArrayRef shape,
    const torch::Dtype dtype = torch::kUInt8) {
  return torch::empty(
      shape, torch::TensorOptions().dtype(dtype).layout(torch::kStrided));
}

moto-meta's avatar
moto-meta committed
101
#ifdef USE_CUDA
102
103
104
105
106
107
108
109
110
111
112
torch::Tensor get_image_buffer(
    at::IntArrayRef shape,
    torch::Device device,
    const torch::Dtype dtype = torch::kUInt8) {
  return torch::empty(
      shape,
      torch::TensorOptions()
          .dtype(dtype)
          .layout(torch::kStrided)
          .device(device));
}
moto-meta's avatar
moto-meta committed
113
#endif // USE_CUDA
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209

} // namespace

ImageConverterBase::ImageConverterBase(int h, int w, int c)
    : height(h), width(w), num_channels(c) {
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(height > 0);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(width > 0);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(num_channels > 0);
}

////////////////////////////////////////////////////////////////////////////////
// Interlaced Image
////////////////////////////////////////////////////////////////////////////////
void InterlacedImageConverter::convert(const AVFrame* src, torch::Tensor& dst) {
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src->height == height);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(1) == height);
  int stride = width * num_channels;
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(2) * dst.size(3) == stride);
  auto p_dst = dst.data_ptr<uint8_t>();
  uint8_t* p_src = src->data[0];
  for (int i = 0; i < height; ++i) {
    memcpy(p_dst, p_src, stride);
    p_src += src->linesize[0];
    p_dst += stride;
  }
}

torch::Tensor InterlacedImageConverter::convert(const AVFrame* src) {
  torch::Tensor buffer = get_image_buffer({1, height, width, num_channels});
  convert(src, buffer);
  return buffer.permute({0, 3, 1, 2});
}

////////////////////////////////////////////////////////////////////////////////
// Interlaced 16 Bit Image
////////////////////////////////////////////////////////////////////////////////
void Interlaced16BitImageConverter::convert(
    const AVFrame* src,
    torch::Tensor& dst) {
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src->height == height);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(1) == height);
  int stride = width * num_channels;
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(2) * dst.size(3) == stride);
  auto p_dst = dst.data_ptr<int16_t>();
  uint8_t* p_src = src->data[0];
  for (int i = 0; i < height; ++i) {
    memcpy(p_dst, p_src, stride * 2);
    p_src += src->linesize[0];
    p_dst += stride;
  }
  // correct for int16
  dst += 32768;
}

torch::Tensor Interlaced16BitImageConverter::convert(const AVFrame* src) {
  torch::Tensor buffer =
      get_image_buffer({1, height, width, num_channels}, torch::kInt16);
  convert(src, buffer);
  return buffer.permute({0, 3, 1, 2});
}

////////////////////////////////////////////////////////////////////////////////
// Planar Image
////////////////////////////////////////////////////////////////////////////////
void PlanarImageConverter::convert(const AVFrame* src, torch::Tensor& dst) {
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src->height == height);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src->width == width);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(1) == num_channels);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(2) == height);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(3) == width);

  for (int i = 0; i < num_channels; ++i) {
    torch::Tensor plane = dst.index({0, i});
    uint8_t* p_dst = plane.data_ptr<uint8_t>();
    uint8_t* p_src = src->data[i];
    int linesize = src->linesize[i];
    for (int h = 0; h < height; ++h) {
      memcpy(p_dst, p_src, width);
      p_src += linesize;
      p_dst += width;
    }
  }
}

torch::Tensor PlanarImageConverter::convert(const AVFrame* src) {
  torch::Tensor buffer = get_image_buffer({1, num_channels, height, width});
  convert(src, buffer);
  return buffer;
}

////////////////////////////////////////////////////////////////////////////////
// YUV420P
////////////////////////////////////////////////////////////////////////////////
210
YUV420PConverter::YUV420PConverter(int h, int w) : ImageConverterBase(h, w, 3) {
211
212
213
214
215
  TORCH_WARN_ONCE(
      "The output format YUV420P is selected. "
      "This will be implicitly converted to YUV444P, "
      "in which all the color components Y, U, V have the same dimension.");
}
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236

void YUV420PConverter::convert(const AVFrame* src, torch::Tensor& dst) {
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
      (AVPixelFormat)(src->format) == AV_PIX_FMT_YUV420P);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src->height == height);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src->width == width);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(1) == 3);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(2) == height);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(3) == width);

  // Write Y plane directly
  {
    uint8_t* p_dst = dst.data_ptr<uint8_t>();
    uint8_t* p_src = src->data[0];
    for (int h = 0; h < height; ++h) {
      memcpy(p_dst, p_src, width);
      p_dst += width;
      p_src += src->linesize[0];
    }
  }
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
  // Chroma (U and V planes) are subsamapled by 2 in both vertical and
  // holizontal directions.
  // https://en.wikipedia.org/wiki/Chroma_subsampling
  // Since we are returning data in Tensor, which has the same size for all
  // color planes, we need to upsample the UV planes. PyTorch has interpolate
  // function but it does not work for int16 type. So we manually copy them.
  //
  //              block1  block2  block3  block4
  // ab -> aabb = a  b   *  a  b *       *
  // cd    aabb                   a  b      a  b
  //       ccdd   c  d      c  d
  //       ccdd                   c  d      c  d
  //
  auto block00 = dst.slice(2, 0, {}, 2).slice(3, 0, {}, 2);
  auto block01 = dst.slice(2, 0, {}, 2).slice(3, 1, {}, 2);
  auto block10 = dst.slice(2, 1, {}, 2).slice(3, 0, {}, 2);
  auto block11 = dst.slice(2, 1, {}, 2).slice(3, 1, {}, 2);
  for (int i = 1; i < 3; ++i) {
    // borrow data
    auto tmp = torch::from_blob(
        src->data[i],
        {height / 2, width / 2},
        {src->linesize[i], 1},
        [](void*) {},
        torch::TensorOptions().dtype(torch::kUInt8).layout(torch::kStrided));
    // Copy to each block
    block00.slice(1, i, i + 1).copy_(tmp);
    block01.slice(1, i, i + 1).copy_(tmp);
    block10.slice(1, i, i + 1).copy_(tmp);
    block11.slice(1, i, i + 1).copy_(tmp);
267
268
269
270
271
272
273
274
275
  }
}

torch::Tensor YUV420PConverter::convert(const AVFrame* src) {
  torch::Tensor buffer = get_image_buffer({1, num_channels, height, width});
  convert(src, buffer);
  return buffer;
}

276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
////////////////////////////////////////////////////////////////////////////////
// YUV420P10LE
////////////////////////////////////////////////////////////////////////////////
YUV420P10LEConverter::YUV420P10LEConverter(int h, int w)
    : ImageConverterBase(h, w, 3) {
  TORCH_WARN_ONCE(
      "The output format YUV420PLE is selected. "
      "This will be implicitly converted to YUV444P (16-bit), "
      "in which all the color components Y, U, V have the same dimension.");
}

void YUV420P10LEConverter::convert(const AVFrame* src, torch::Tensor& dst) {
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
      (AVPixelFormat)(src->format) == AV_PIX_FMT_YUV420P10LE);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src->height == height);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src->width == width);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(1) == 3);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(2) == height);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(3) == width);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.dtype() == torch::kInt16);

  // Write Y plane directly
  {
    int16_t* p_dst = dst.data_ptr<int16_t>();
    uint8_t* p_src = src->data[0];
    for (int h = 0; h < height; ++h) {
      memcpy(p_dst, p_src, (size_t)width * 2);
      p_dst += width;
      p_src += src->linesize[0];
    }
  }
  // Chroma (U and V planes) are subsamapled by 2 in both vertical and
  // holizontal directions.
  // https://en.wikipedia.org/wiki/Chroma_subsampling
  // Since we are returning data in Tensor, which has the same size for all
  // color planes, we need to upsample the UV planes. PyTorch has interpolate
  // function but it does not work for int16 type. So we manually copy them.
  //
  //              block1  block2  block3  block4
  // ab -> aabb = a  b   *  a  b *       *
  // cd    aabb                   a  b      a  b
  //       ccdd   c  d      c  d
  //       ccdd                   c  d      c  d
  //
  auto block00 = dst.slice(2, 0, {}, 2).slice(3, 0, {}, 2);
  auto block01 = dst.slice(2, 0, {}, 2).slice(3, 1, {}, 2);
  auto block10 = dst.slice(2, 1, {}, 2).slice(3, 0, {}, 2);
  auto block11 = dst.slice(2, 1, {}, 2).slice(3, 1, {}, 2);
  for (int i = 1; i < 3; ++i) {
    // borrow data
    auto tmp = torch::from_blob(
        src->data[i],
        {height / 2, width / 2},
        {src->linesize[i] / 2, 1},
        [](void*) {},
        torch::TensorOptions().dtype(torch::kInt16).layout(torch::kStrided));
    // Copy to each block
    block00.slice(1, i, i + 1).copy_(tmp);
    block01.slice(1, i, i + 1).copy_(tmp);
    block10.slice(1, i, i + 1).copy_(tmp);
    block11.slice(1, i, i + 1).copy_(tmp);
  }
}

torch::Tensor YUV420P10LEConverter::convert(const AVFrame* src) {
  torch::Tensor buffer =
      get_image_buffer({1, num_channels, height, width}, torch::kInt16);
  convert(src, buffer);
  return buffer;
}

348
349
350
////////////////////////////////////////////////////////////////////////////////
// NV12
////////////////////////////////////////////////////////////////////////////////
351
NV12Converter::NV12Converter(int h, int w) : ImageConverterBase(h, w, 3) {
352
353
354
355
356
  TORCH_WARN_ONCE(
      "The output format NV12 is selected. "
      "This will be implicitly converted to YUV444P, "
      "in which all the color components Y, U, V have the same dimension.");
}
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379

void NV12Converter::convert(const AVFrame* src, torch::Tensor& dst) {
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
      (AVPixelFormat)(src->format) == AV_PIX_FMT_NV12);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src->height == height);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src->width == width);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(1) == 3);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(2) == height);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(3) == width);

  // Write Y plane directly
  {
    uint8_t* p_dst = dst.data_ptr<uint8_t>();
    uint8_t* p_src = src->data[0];
    for (int h = 0; h < height; ++h) {
      memcpy(p_dst, p_src, width);
      p_dst += width;
      p_src += src->linesize[0];
    }
  }
  // Write intermediate UV plane
  {
380
381
382
383
384
385
386
387
388
389
390
391
    auto tmp = torch::from_blob(
        src->data[1],
        {height / 2, width},
        {src->linesize[1], 1},
        [](void*) {},
        torch::TensorOptions().dtype(torch::kUInt8).layout(torch::kStrided));
    tmp = tmp.view({1, height / 2, width / 2, 2}).permute({0, 3, 1, 2});
    auto dst_uv = dst.slice(1, 1, 3);
    dst_uv.slice(2, 0, {}, 2).slice(3, 0, {}, 2).copy_(tmp);
    dst_uv.slice(2, 0, {}, 2).slice(3, 1, {}, 2).copy_(tmp);
    dst_uv.slice(2, 1, {}, 2).slice(3, 0, {}, 2).copy_(tmp);
    dst_uv.slice(2, 1, {}, 2).slice(3, 1, {}, 2).copy_(tmp);
392
393
394
395
396
397
398
399
400
401
402
  }
}

torch::Tensor NV12Converter::convert(const AVFrame* src) {
  torch::Tensor buffer = get_image_buffer({1, num_channels, height, width});
  convert(src, buffer);
  return buffer;
}

#ifdef USE_CUDA

403
404
405
CudaImageConverterBase::CudaImageConverterBase(const torch::Device& device)
    : device(device) {}

406
407
408
////////////////////////////////////////////////////////////////////////////////
// NV12 CUDA
////////////////////////////////////////////////////////////////////////////////
409
410
NV12CudaConverter::NV12CudaConverter(const torch::Device& device)
    : CudaImageConverterBase(device) {
411
412
413
414
415
  TORCH_WARN_ONCE(
      "The output format NV12 is selected. "
      "This will be implicitly converted to YUV444P, "
      "in which all the color components Y, U, V have the same dimension.");
}
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432

void NV12CudaConverter::convert(const AVFrame* src, torch::Tensor& dst) {
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src->height == height);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src->width == width);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(1) == 3);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(2) == height);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(3) == width);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.dtype() == torch::kUInt8);

  auto fmt = (AVPixelFormat)(src->format);
  AVHWFramesContext* hwctx = (AVHWFramesContext*)src->hw_frames_ctx->data;
  AVPixelFormat sw_fmt = hwctx->sw_format;

  TORCH_INTERNAL_ASSERT(
      AV_PIX_FMT_CUDA == fmt,
      "Expected CUDA frame. Found: ",
433
      av_get_pix_fmt_name(fmt));
434
435
436
  TORCH_INTERNAL_ASSERT(
      AV_PIX_FMT_NV12 == sw_fmt,
      "Expected NV12 format. Found: ",
437
      av_get_pix_fmt_name(sw_fmt));
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472

  // Write Y plane directly
  auto status = cudaMemcpy2D(
      dst.data_ptr(),
      width,
      src->data[0],
      src->linesize[0],
      width,
      height,
      cudaMemcpyDeviceToDevice);
  TORCH_CHECK(cudaSuccess == status, "Failed to copy Y plane to Cuda tensor.");
  // Preapare intermediate UV planes
  status = cudaMemcpy2D(
      tmp_uv.data_ptr(),
      width,
      src->data[1],
      src->linesize[1],
      width,
      height / 2,
      cudaMemcpyDeviceToDevice);
  TORCH_CHECK(cudaSuccess == status, "Failed to copy UV plane to Cuda tensor.");
  // Upsample width and height
  namespace F = torch::nn::functional;
  torch::Tensor uv = F::interpolate(
      tmp_uv.permute({0, 3, 1, 2}),
      F::InterpolateFuncOptions()
          .mode(torch::kNearest)
          .size(std::vector<int64_t>({height, width})));
  // Write to the UV plane
  // dst[:, 1:] = uv
  using namespace torch::indexing;
  dst.index_put_({Slice(), Slice(1)}, uv);
}

torch::Tensor NV12CudaConverter::convert(const AVFrame* src) {
473
474
475
476
477
478
479
480
481
482
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src);
  if (!init) {
    height = src->height;
    width = src->width;
    tmp_uv =
        get_image_buffer({1, height / 2, width / 2, 2}, device, torch::kUInt8);
    init = true;
  }

  torch::Tensor buffer = get_image_buffer({1, 3, height, width}, device);
483
484
485
486
487
488
489
  convert(src, buffer);
  return buffer;
}

////////////////////////////////////////////////////////////////////////////////
// P010 CUDA
////////////////////////////////////////////////////////////////////////////////
490
491
P010CudaConverter::P010CudaConverter(const torch::Device& device)
    : CudaImageConverterBase{device} {
492
493
494
495
496
  TORCH_WARN_ONCE(
      "The output format P010 is selected. "
      "This will be implicitly converted to YUV444P, "
      "in which all the color components Y, U, V have the same dimension.");
}
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513

void P010CudaConverter::convert(const AVFrame* src, torch::Tensor& dst) {
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src->height == height);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src->width == width);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(1) == 3);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(2) == height);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(3) == width);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.dtype() == torch::kInt16);

  auto fmt = (AVPixelFormat)(src->format);
  AVHWFramesContext* hwctx = (AVHWFramesContext*)src->hw_frames_ctx->data;
  AVPixelFormat sw_fmt = hwctx->sw_format;

  TORCH_INTERNAL_ASSERT(
      AV_PIX_FMT_CUDA == fmt,
      "Expected CUDA frame. Found: ",
514
      av_get_pix_fmt_name(fmt));
515
516
517
  TORCH_INTERNAL_ASSERT(
      AV_PIX_FMT_P010 == sw_fmt,
      "Expected P010 format. Found: ",
518
      av_get_pix_fmt_name(sw_fmt));
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557

  // Write Y plane directly
  auto status = cudaMemcpy2D(
      dst.data_ptr(),
      width * 2,
      src->data[0],
      src->linesize[0],
      width * 2,
      height,
      cudaMemcpyDeviceToDevice);
  TORCH_CHECK(cudaSuccess == status, "Failed to copy Y plane to CUDA tensor.");
  // Prepare intermediate UV planes
  status = cudaMemcpy2D(
      tmp_uv.data_ptr(),
      width * 2,
      src->data[1],
      src->linesize[1],
      width * 2,
      height / 2,
      cudaMemcpyDeviceToDevice);
  TORCH_CHECK(cudaSuccess == status, "Failed to copy UV plane to CUDA tensor.");
  // Write to the UV plane
  torch::Tensor uv = tmp_uv.permute({0, 3, 1, 2});
  using namespace torch::indexing;
  // very simplistic upscale using indexing since interpolate doesn't support
  // shorts
  dst.index_put_(
      {Slice(), Slice(1, 3), Slice(None, None, 2), Slice(None, None, 2)}, uv);
  dst.index_put_(
      {Slice(), Slice(1, 3), Slice(1, None, 2), Slice(None, None, 2)}, uv);
  dst.index_put_(
      {Slice(), Slice(1, 3), Slice(None, None, 2), Slice(1, None, 2)}, uv);
  dst.index_put_(
      {Slice(), Slice(1, 3), Slice(1, None, 2), Slice(1, None, 2)}, uv);
  // correct for int16
  dst += 32768;
}

torch::Tensor P010CudaConverter::convert(const AVFrame* src) {
558
559
560
561
562
563
564
565
566
567
568
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src);
  if (!init) {
    height = src->height;
    width = src->width;
    tmp_uv =
        get_image_buffer({1, height / 2, width / 2, 2}, device, torch::kInt16);
    init = true;
  }

  torch::Tensor buffer =
      get_image_buffer({1, 3, height, width}, device, torch::kInt16);
569
570
571
572
  convert(src, buffer);
  return buffer;
}

moto's avatar
moto committed
573
574
575
////////////////////////////////////////////////////////////////////////////////
// YUV444P CUDA
////////////////////////////////////////////////////////////////////////////////
576
577
YUV444PCudaConverter::YUV444PCudaConverter(const torch::Device& device)
    : CudaImageConverterBase(device) {}
moto's avatar
moto committed
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594

void YUV444PCudaConverter::convert(const AVFrame* src, torch::Tensor& dst) {
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src->height == height);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src->width == width);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(1) == 3);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(2) == height);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.size(3) == width);
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(dst.dtype() == torch::kUInt8);

  auto fmt = (AVPixelFormat)(src->format);
  AVHWFramesContext* hwctx = (AVHWFramesContext*)src->hw_frames_ctx->data;
  AVPixelFormat sw_fmt = hwctx->sw_format;

  TORCH_INTERNAL_ASSERT(
      AV_PIX_FMT_CUDA == fmt,
      "Expected CUDA frame. Found: ",
595
      av_get_pix_fmt_name(fmt));
moto's avatar
moto committed
596
597
598
  TORCH_INTERNAL_ASSERT(
      AV_PIX_FMT_YUV444P == sw_fmt,
      "Expected YUV444P format. Found: ",
599
      av_get_pix_fmt_name(sw_fmt));
moto's avatar
moto committed
600
601

  // Write Y plane directly
602
  for (int i = 0; i < 3; ++i) {
moto's avatar
moto committed
603
604
605
606
607
608
609
610
611
612
613
614
615
616
    auto status = cudaMemcpy2D(
        dst.index({0, i}).data_ptr(),
        width,
        src->data[i],
        src->linesize[i],
        width,
        height,
        cudaMemcpyDeviceToDevice);
    TORCH_CHECK(
        cudaSuccess == status, "Failed to copy plane ", i, " to CUDA tensor.");
  }
}

torch::Tensor YUV444PCudaConverter::convert(const AVFrame* src) {
617
618
619
620
621
622
623
  TORCH_INTERNAL_ASSERT_DEBUG_ONLY(src);
  if (!init) {
    height = src->height;
    width = src->width;
    init = true;
  }
  torch::Tensor buffer = get_image_buffer({1, 3, height, width}, device);
moto's avatar
moto committed
624
625
626
627
  convert(src, buffer);
  return buffer;
}

628
629
#endif

moto-meta's avatar
moto-meta committed
630
} // namespace torio::io