-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathconversion.cpp
More file actions
769 lines (709 loc) · 23.8 KB
/
Copy pathconversion.cpp
File metadata and controls
769 lines (709 loc) · 23.8 KB
1
2
3
4
5
6
7
8
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
101
102
103
104
105
106
107
108
109
110
111
112
113
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
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
267
268
269
270
271
272
273
274
275
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <libspdl/core/conversion.h>
#include "libspdl/common/logging.h"
#include "libspdl/common/tracing.h"
#include "libspdl/core/detail/ffmpeg/compat.h"
#include "libspdl/core/detail/ffmpeg/logging.h"
#include "libspdl/core/detail/ffmpeg/wrappers.h"
#include <fmt/format.h>
#include <glog/logging.h>
#include <cassert>
extern "C" {
#include <libavutil/frame.h>
#include <libavutil/imgutils.h>
#include <libavutil/pixdesc.h>
}
namespace spdl::core {
////////////////////////////////////////////////////////////////////////////////
// Frame to buffer - Audio
////////////////////////////////////////////////////////////////////////////////
namespace {
template <size_t depth, ElemClass type, bool is_planar>
CPUBufferPtr convert_frames(
const std::vector<const AudioFrames*>& batch,
std::shared_ptr<CPUStorage> storage) {
size_t num_frames = batch.at(0)->get_num_frames();
size_t num_channels = GET_NUM_CHANNELS(batch.at(0)->get_frames().at(0));
if constexpr (is_planar) {
auto buf = cpu_buffer(
{batch.size(), num_channels, num_frames},
type,
depth,
std::move(storage));
uint8_t* dst = static_cast<uint8_t*>(buf->data());
for (auto frames_ptr : batch) {
for (int i = 0; i < (int)num_channels; ++i) {
for (const auto frame : frames_ptr->get_frames()) {
int plane_size = depth * frame->nb_samples;
memcpy(dst, frame->extended_data[i], plane_size);
dst += plane_size;
}
}
}
return buf;
} else {
auto buf = cpu_buffer(
{batch.size(), num_frames, num_channels},
type,
depth,
std::move(storage));
uint8_t* dst = static_cast<uint8_t*>(buf->data());
for (auto frames_ptr : batch) {
for (const auto frame : frames_ptr->get_frames()) {
int plane_size = (int)(depth * frame->nb_samples * num_channels);
memcpy(dst, frame->extended_data[0], plane_size);
dst += plane_size;
}
}
return buf;
}
}
} // namespace
template <>
CPUBufferPtr convert_frames(
const std::vector<const AudioFrames*>& batch,
std::shared_ptr<CPUStorage> storage) {
if (batch.empty()) {
SPDL_FAIL("No frame to convert to buffer.");
}
auto frames_ptr0 = batch.at(0);
auto num_frames0 = frames_ptr0->get_num_frames();
if (num_frames0 == 0) {
SPDL_FAIL("No frame to convert to buffer.");
}
auto frames0 = frames_ptr0->get_frames();
auto num_channels0 = GET_NUM_CHANNELS(frames0.at(0));
auto sample_fmt0 = static_cast<AVSampleFormat>(frames0.at(0)->format);
for (auto& frames_ptr : batch) {
auto num_frames = frames_ptr->get_num_frames();
if (num_frames == 0) {
SPDL_FAIL("No frame to convert to buffer.");
}
auto frames = frames_ptr->get_frames();
auto sample_fmt = static_cast<AVSampleFormat>(frames.at(0)->format);
auto num_channels = GET_NUM_CHANNELS(frames.at(0));
if (num_frames == 0) {
SPDL_FAIL("No frame to convert to buffer.");
}
if (num_frames != num_frames0) {
SPDL_FAIL(
fmt::format(
"Inconsistent number of frames: {} vs {}",
num_frames0,
num_frames));
}
if (sample_fmt0 != sample_fmt) {
SPDL_FAIL(
fmt::format(
"Inconsistent sample format: {} vs {}",
av_get_sample_fmt_name(sample_fmt0),
av_get_sample_fmt_name(sample_fmt)));
}
if (num_channels0 != num_channels) {
SPDL_FAIL(
fmt::format(
"Inconsistent number of channels: {} vs {}",
num_channels0,
num_channels));
}
}
switch (sample_fmt0) {
case AV_SAMPLE_FMT_U8:
return convert_frames<1, ElemClass::UInt, false>(
batch, std::move(storage));
case AV_SAMPLE_FMT_U8P:
return convert_frames<1, ElemClass::UInt, true>(
batch, std::move(storage));
case AV_SAMPLE_FMT_S16:
return convert_frames<2, ElemClass::Int, false>(
batch, std::move(storage));
case AV_SAMPLE_FMT_S16P:
return convert_frames<2, ElemClass::Int, true>(batch, std::move(storage));
case AV_SAMPLE_FMT_S32:
return convert_frames<4, ElemClass::Int, false>(
batch, std::move(storage));
case AV_SAMPLE_FMT_S32P:
return convert_frames<4, ElemClass::Int, true>(batch, std::move(storage));
case AV_SAMPLE_FMT_FLT:
return convert_frames<4, ElemClass::Float, false>(
batch, std::move(storage));
case AV_SAMPLE_FMT_FLTP:
return convert_frames<4, ElemClass::Float, true>(
batch, std::move(storage));
case AV_SAMPLE_FMT_S64:
return convert_frames<8, ElemClass::Int, false>(
batch, std::move(storage));
case AV_SAMPLE_FMT_S64P:
return convert_frames<8, ElemClass::Int, true>(batch, std::move(storage));
case AV_SAMPLE_FMT_DBL:
return convert_frames<8, ElemClass::Float, false>(
batch, std::move(storage));
case AV_SAMPLE_FMT_DBLP:
return convert_frames<8, ElemClass::Float, true>(
batch, std::move(storage));
default:
SPDL_FAIL_INTERNAL(
fmt::format(
"Unexpected sample format: {}",
av_get_sample_fmt_name(sample_fmt0)));
}
}
////////////////////////////////////////////////////////////////////////////////
// Frame to buffer - Image / Video
////////////////////////////////////////////////////////////////////////////////
namespace {
template <MediaType media>
void copy(
AVPixelFormat pix_fmt,
const std::vector<const Frames<media>*>& batch,
CPUBuffer* buf) {
auto dst = (uint8_t*)buf->data();
auto dst_size = buf->shape[2] * buf->shape[3] * buf->shape[4] * buf->depth;
for (auto& frames : batch) {
for (const auto& f : frames->get_frames()) {
CHECK_AVERROR(
av_image_copy_to_buffer(
dst,
(int)dst_size,
f->data,
f->linesize,
pix_fmt,
f->width,
f->height,
(int)buf->depth),
"Failed to copy image data.")
dst += dst_size;
}
}
}
template <MediaType media>
CPUBufferPtr convert_interleaved(
enum AVPixelFormat pix_fmt,
const std::vector<const Frames<media>*>& batch,
std::shared_ptr<CPUStorage> storage,
int depth = 1) {
auto& ref_frames = batch.at(0)->get_frames();
size_t w = ref_frames.at(0)->width, h = ref_frames.at(0)->height;
auto num_frames = ref_frames.size();
int num_channels = av_pix_fmt_desc_get(pix_fmt)->nb_components;
assert(num_channels > 0);
auto buf = cpu_buffer(
{batch.size(), num_frames, h, w, (unsigned int)num_channels},
ElemClass::UInt,
depth,
std::move(storage));
copy(pix_fmt, batch, buf.get());
return buf;
}
template <MediaType media>
CPUBufferPtr convert_planer(
enum AVPixelFormat pix_fmt,
const std::vector<const Frames<media>*>& batch,
std::shared_ptr<CPUStorage> storage,
int depth = 1) {
auto& ref_frames = batch.at(0)->get_frames();
size_t w = ref_frames.at(0)->width, h = ref_frames.at(0)->height;
auto num_frames = ref_frames.size();
int num_planes = av_pix_fmt_count_planes(pix_fmt);
if (num_planes <= 0) {
SPDL_FAIL("Failed to fetch the number of planes.");
}
auto buf = cpu_buffer(
{batch.size(), num_frames, (unsigned int)num_planes, h, w},
ElemClass::UInt,
depth,
std::move(storage));
copy(pix_fmt, batch, buf.get());
return buf;
}
template <MediaType media>
CPUBufferPtr convert_yuv420p(
enum AVPixelFormat pix_fmt,
const std::vector<const Frames<media>*>& batch,
std::shared_ptr<CPUStorage> storage,
int depth = 1) {
auto& ref_frames = batch.at(0)->get_frames();
size_t w = ref_frames.at(0)->width, h = ref_frames.at(0)->height;
auto num_frames = ref_frames.size();
assert(h % 2 == 0 && w % 2 == 0);
size_t h2 = h / 2;
auto buf = cpu_buffer(
{batch.size(), num_frames, 1, h + h2, w},
ElemClass::UInt,
depth,
std::move(storage));
copy(pix_fmt, batch, buf.get());
return buf;
}
template <MediaType media>
CPUBufferPtr convert_yuv422p(
enum AVPixelFormat pix_fmt,
const std::vector<const Frames<media>*>& batch,
std::shared_ptr<CPUStorage> storage,
int depth = 1) {
auto& ref_frames = batch.at(0)->get_frames();
size_t w = ref_frames.at(0)->width, h = ref_frames.at(0)->height;
auto num_frames = ref_frames.size();
auto buf = cpu_buffer(
{batch.size(), num_frames, 1, h + h, w},
ElemClass::UInt,
depth,
std::move(storage));
copy(pix_fmt, batch, buf.get());
return buf;
}
template <MediaType media>
CPUBufferPtr convert_nv12(
enum AVPixelFormat pix_fmt,
const std::vector<const Frames<media>*>& batch,
std::shared_ptr<CPUStorage> storage,
int depth = 1) {
auto& ref_frames = batch.at(0)->get_frames();
size_t w = ref_frames.at(0)->width, h = ref_frames.at(0)->height;
auto num_frames = ref_frames.size();
assert(h % 2 == 0 && w % 2 == 0);
size_t h2 = h / 2;
auto buf = cpu_buffer(
{batch.size(), num_frames, 1, h + h2, w},
ElemClass::UInt,
depth,
std::move(storage));
copy(pix_fmt, batch, buf.get());
return buf;
}
} // namespace
namespace {
template <MediaType media>
void check_frame_consistency(const Frames<media>* frames_ptr)
requires(media != MediaType::Audio)
{
auto numel = frames_ptr->get_num_frames();
if (numel == 0) {
SPDL_FAIL("No frame to convert to buffer.");
}
if constexpr (media == MediaType::Image) {
if (numel != 1) {
SPDL_FAIL_INTERNAL(
fmt::format(
"There must be exactly one frame to convert to buffer. Found: {}",
numel));
}
}
auto frames = frames_ptr->get_frames();
auto pix_fmt = static_cast<AVPixelFormat>(frames[0]->format);
if (pix_fmt == AV_PIX_FMT_CUDA) {
SPDL_FAIL_INTERNAL("FFmpeg-native CUDA frames are not supported.");
}
int height = frames[0]->height, width = frames[0]->width;
for (auto* f : frames) {
if (f->height != height || f->width != width) {
SPDL_FAIL(
fmt::format(
"Cannot convert the frames as the frames do not have the same size. "
"Reference WxH = {}x{}, found {}x{}.",
height,
width,
f->height,
f->width));
}
if (static_cast<AVPixelFormat>(f->format) != pix_fmt) {
SPDL_FAIL(
fmt::format(
"Cannot convert the frames as the frames do not have the same pixel format."));
}
}
}
template <MediaType media>
void check_batch_frame_consistency(
const std::vector<const Frames<media>*>& batch) {
if (batch.empty()) {
SPDL_FAIL("No frame to convert to buffer.");
}
auto& frames0 = batch.at(0)->get_frames();
auto w = frames0.at(0)->width, h = frames0.at(0)->height;
auto num_frames = frames0.size();
auto pix_fmt0 = static_cast<AVPixelFormat>(frames0.at(0)->format);
for (auto& frames_ptr : batch) {
check_frame_consistency(frames_ptr);
auto frames = frames_ptr->get_frames();
auto pix_fmt = static_cast<AVPixelFormat>(frames.at(0)->format);
if (pix_fmt != pix_fmt0) {
SPDL_FAIL(
fmt::format(
"The input video frames must have the same pixel format. Expected {}, but found {}",
av_get_pix_fmt_name(pix_fmt0),
av_get_pix_fmt_name(pix_fmt)));
}
if (frames.size() != num_frames) {
SPDL_FAIL(
fmt::format(
"The number of frames must be the same. Expected {}, but found {}",
num_frames,
frames.size()));
}
for (auto& frame : frames) {
if (frame->width != w || frame->height != h) {
SPDL_FAIL(
fmt::format(
"The input video frames must be the same size. Expected {}x{}, but found {}x{}",
w,
h,
frame->width,
frame->height));
}
}
}
}
} // namespace
// Note:
//
// YUV is a limited range (16 - 235), while YUVJ is a full range. (0-255).
//
// YUVJ == YUV + AVCOL_RANGE_JPEG
//
// AVCOL_RANGE_JPEG has slight different value range for Chroma.
// (1 - 255 instead of 0 - 255)
// https://ffmpeg.org/doxygen/5.1/pixfmt_8h.html#a3da0bf691418bc22c4bcbe6583ad589a
//
// FFmpeg emits a warning like
// `deprecated pixel format used, make sure you did set range correctly`
//
// See also: https://superuser.com/a/1273941
//
// It might be more appropriate to convert the limited range to the full range
// for YUV, but for now, it copies data as-is for both YUV and YUVJ.
template <MediaType media>
CPUBufferPtr convert_frames(
const std::vector<const Frames<media>*>& batch,
std::shared_ptr<CPUStorage> storage) {
TRACE_EVENT("decoding", "core::convert_frames");
check_batch_frame_consistency(batch);
auto ret = [&]() {
auto& ref_frames = batch.at(0)->get_frames();
auto pix_fmt = static_cast<AVPixelFormat>(ref_frames.at(0)->format);
switch (pix_fmt) {
case AV_PIX_FMT_GRAY8:
case AV_PIX_FMT_RGBA:
case AV_PIX_FMT_RGB24:
return convert_interleaved(pix_fmt, batch, std::move(storage));
case AV_PIX_FMT_GRAY16BE:
case AV_PIX_FMT_GRAY16LE:
return convert_planer(pix_fmt, batch, std::move(storage), 2);
case AV_PIX_FMT_YUVJ444P:
case AV_PIX_FMT_YUV444P:
return convert_planer(pix_fmt, batch, std::move(storage));
case AV_PIX_FMT_YUVJ420P:
case AV_PIX_FMT_YUV420P:
return convert_yuv420p(pix_fmt, batch, std::move(storage));
case AV_PIX_FMT_YUVJ422P:
case AV_PIX_FMT_YUV422P:
return convert_yuv422p(pix_fmt, batch, std::move(storage));
case AV_PIX_FMT_NV12: {
return convert_nv12(pix_fmt, batch, std::move(storage));
}
default:
SPDL_FAIL(
fmt::format(
"Unsupported pixel format: {}", av_get_pix_fmt_name(pix_fmt)));
}
}();
if constexpr (media == MediaType::Image) {
// Remove the 2nd num_frame dimension (which is 1).
// BNCHW -> BCHW.
ret->shape.erase(std::next(ret->shape.begin()));
}
return ret;
}
template CPUBufferPtr convert_frames(
const std::vector<const ImageFrames*>& batch,
std::shared_ptr<CPUStorage> storage);
template CPUBufferPtr convert_frames(
const std::vector<const VideoFrames*>& batch,
std::shared_ptr<CPUStorage> storage);
namespace detail {
////////////////////////////////////////////////////////////////////////////////
// Buffer to frame
////////////////////////////////////////////////////////////////////////////////
namespace {
AVFramePtr
get_video_frame(AVPixelFormat fmt, size_t width, size_t height, int64_t pts) {
AVFramePtr ret{CHECK_AVALLOCATE(av_frame_alloc())};
ret->format = fmt;
ret->width = (int)width;
ret->height = (int)height;
ret->pts = pts;
return ret;
}
void no_free(void*, uint8_t* data) {
VLOG(15) << fmt::format("Not free-ing data @ {}", (void*)data);
}
// Create an AVBufferRef object that points to an existing buffer,
// but not owning it.
AVBufferRef* create_reference_buffer(uint8_t* data, int size) {
return av_buffer_create(
data, size, no_free, nullptr, AV_BUFFER_FLAG_READONLY);
}
} // namespace
} // namespace detail
////////////////////////////////////////////////////////////////////////////////
// Buffer to frame - Audio
////////////////////////////////////////////////////////////////////////////////
AudioFramesPtr create_reference_audio_frame(
const std::string& sample_fmt,
const void* data,
int bits,
const std::array<size_t, 2>& shape,
const std::array<int64_t, 2>& stride,
int sample_rate,
int64_t pts) {
auto fmt = av_get_sample_fmt(sample_fmt.c_str());
if (fmt == AV_SAMPLE_FMT_NONE) {
SPDL_FAIL(fmt::format("Unexpected sample_fmt: {}", sample_fmt));
}
if (auto bps = av_get_bytes_per_sample(fmt); bps != 0 && bps != bits / 8) {
SPDL_FAIL(
fmt::format(
"The input dtype must be {} bytes par element. Found {}",
bps,
bits / 8));
}
detail::AVFramePtr f{CHECK_AVALLOCATE(av_frame_alloc())};
f->format = fmt;
f->sample_rate = sample_rate;
f->pts = pts;
if (av_sample_fmt_is_planar(fmt)) {
// Planar == channel_first
// NOTE: nanobind's stride is element count. Not bytes
if (stride[1] != 1) {
SPDL_FAIL(
fmt::format(
"The planar audio frame is requested, but the input data is "
"not contiguous along channel planes. (stride[1] must be 1) "
"Found: Stride: ({})",
fmt::join(stride, ", ")));
}
auto c = (int)shape[0];
f->nb_samples = (int)shape[1];
SET_CHANNELS(f, c);
if (c <= AV_NUM_DATA_POINTERS) {
// This is handled in AVFrame initialization, but just in case.
f->extended_data = f->data;
} else {
f->extended_data = (uint8_t**)av_malloc(c * sizeof(uint8_t*));
f->extended_buf = (AVBufferRef**)av_malloc(
(c - AV_NUM_DATA_POINTERS) * sizeof(AVBufferRef*));
f->nb_extended_buf = (c - AV_NUM_DATA_POINTERS);
}
int bps = av_get_bytes_per_sample(fmt);
auto pitch = stride[0] * bps;
auto buffer_size = f->nb_samples * bps;
auto* src = (uint8_t*)data;
for (int i = 0; i < c; ++i) {
if (i < AV_NUM_DATA_POINTERS) {
f->data[i] = src;
f->buf[i] = detail::create_reference_buffer(src, buffer_size);
f->linesize[i] = buffer_size;
} else {
int j = i - AV_NUM_DATA_POINTERS;
f->extended_buf[j] = detail::create_reference_buffer(src, buffer_size);
}
f->extended_data[i] = src;
src += pitch;
}
} else {
// interleaved == channel_last
// NOTE: nanobind's stride is element count. Not bytes
if (stride[0] != (int)shape[1]) {
SPDL_FAIL(
fmt::format(
"The interleaved audio frame is requested, but the input data is "
"not contiguous. (stride[0] must match shape[1]) "
"Found: Shape: ({}), Stride: ({})",
fmt::join(shape, ", "),
fmt::join(stride, ", ")));
}
auto c = (int)shape[1];
f->nb_samples = (int)shape[0];
SET_CHANNELS(f, c);
auto* src = (uint8_t*)data;
auto size =
av_samples_get_buffer_size(f->linesize, c, f->nb_samples, fmt, 0);
f->data[0] = src;
f->buf[0] = detail::create_reference_buffer(src, size);
}
auto ret = std::make_unique<AudioFrames>(
reinterpret_cast<uintptr_t>(data), Rational{1, sample_rate});
ret->push_back(f.release());
return ret;
}
////////////////////////////////////////////////////////////////////////////////
// Buffer to frame - Video (v2)
////////////////////////////////////////////////////////////////////////////////
namespace {
void validate_nhwc(
int c,
const std::vector<size_t>& shape,
const std::vector<int64_t>& stride) {
if (!(shape.size() == 4 && stride.size() == 4)) {
SPDL_FAIL("The input array must be 4D.");
}
// Note: nanobind's stride is element count, not byte.
if ((int)shape[3] != c) {
SPDL_FAIL(
fmt::format(
"The shape must be (N, H, W, C=={}). Found: ({})",
c,
fmt::join(shape, ", ")));
}
if (!(stride[3] == 1 && stride[2] == c)) {
SPDL_FAIL(
fmt::format(
"Each row must be contiguous. (stride == [..., {}, 1]) "
"Found: Stride ({})",
c,
fmt::join(stride, ", ")));
}
}
void validate_nchw(
int c,
const std::vector<size_t>& shape,
const std::vector<int64_t>& stride) {
if (!(shape.size() == 4 && stride.size() == 4)) {
SPDL_FAIL("The input array must be 4D.");
}
// Note: nanobind's stride is element count, not byte.
if ((int)shape[1] != c) {
SPDL_FAIL(
fmt::format(
"The shape must be (N, C=={}, H, W). Found: ({})",
c,
fmt::join(shape, ", ")));
}
if (!(stride[3] == 1)) {
SPDL_FAIL(
fmt::format(
"Each row must be contiguous. (stride == [..., 1]) "
"Found: Stride ({})",
fmt::join(stride, ", ")));
}
}
void validate_nhw(
const std::vector<size_t>& shape,
const std::vector<int64_t>& stride) {
if (!(shape.size() == 3 && stride.size() == 3)) {
SPDL_FAIL("The input array must be 3D.");
}
// Note: nanobind's stride is element count, not byte.
if (!(stride[2] == 1)) {
SPDL_FAIL(
fmt::format(
"Each row must be contiguous. (stride == [..., 1]) "
"Found: Stride ({})",
fmt::join(stride, ", ")));
}
}
VideoFramesPtr create_reference_video_frame(
enum AVPixelFormat fmt,
const void* data,
const std::vector<size_t>& shape,
const std::vector<int64_t>& stride,
Rational time_base,
int64_t pts,
int bps = 1) {
auto ret = std::make_unique<VideoFrames>((uintptr_t)data, time_base);
auto n = shape[0], h = shape[1], w = shape[2];
auto* src = (uint8_t*)data;
// Note: nanobind's stride is element count, not byte.
auto plane_size = stride[0] * bps;
auto linesize = stride[1] * bps;
for (size_t i = 0; i < n; ++i) {
auto f = detail::get_video_frame(fmt, w, h, pts + i);
f->data[0] = src;
f->linesize[0] = (int)linesize;
f->buf[0] = detail::create_reference_buffer(src, (int)plane_size);
src += plane_size;
ret->push_back(f.release());
}
return ret;
}
VideoFramesPtr convert_planar_video_array(
enum AVPixelFormat fmt,
const void* data,
const std::vector<size_t>& shape,
const std::vector<int64_t>& stride,
Rational time_base,
int64_t pts,
int num_color = 3,
int bps = 1) {
auto ret = std::make_unique<VideoFrames>((uintptr_t)data, time_base);
auto n = shape[0], h = shape[2], w = shape[3];
auto frame_size = stride[0] * bps;
auto plane_size = stride[1] * bps;
auto linesize = stride[2] * bps;
for (size_t i = 0; i < n; ++i) {
auto f = detail::get_video_frame(fmt, w, h, pts + i);
auto* src = ((uint8_t*)data) + i * frame_size;
for (int c = 0; c < num_color; ++c) {
f->data[c] = src;
f->linesize[c] = (int)linesize;
f->buf[c] = detail::create_reference_buffer(src, (int)plane_size);
src += plane_size;
}
ret->push_back(f.release());
}
return ret;
}
} // namespace
VideoFramesPtr create_reference_video_frame(
const std::string& pix_fmt,
const void* data,
int bits,
const std::vector<size_t>& shape,
const std::vector<int64_t>& stride,
Rational time_base,
int64_t pts) {
auto fmt = av_get_pix_fmt(pix_fmt.c_str());
if (fmt == AV_PIX_FMT_NONE) {
SPDL_FAIL(fmt::format("Unexpected pix_fmt: {}", pix_fmt));
}
#define CHECK_BITS(x, y) \
if (x != y) { \
SPDL_FAIL( \
fmt::format( \
"The input dtype must be {} bit par element. Found {}", y, x)); \
}
switch (fmt) {
case AV_PIX_FMT_RGB24:
case AV_PIX_FMT_BGR24:
CHECK_BITS(bits, 8)
validate_nhwc(3, shape, stride);
return create_reference_video_frame(
fmt, data, shape, stride, time_base, pts);
case AV_PIX_FMT_GRAY8:
CHECK_BITS(bits, 8)
validate_nhw(shape, stride);
return create_reference_video_frame(
fmt, data, shape, stride, time_base, pts, 1);
case AV_PIX_FMT_GRAY16BE:
case AV_PIX_FMT_GRAY16LE:
validate_nhw(shape, stride);
CHECK_BITS(bits, 16)
return create_reference_video_frame(
fmt, data, shape, stride, time_base, pts, 2);
case AV_PIX_FMT_YUV444P:
CHECK_BITS(bits, 8)
validate_nchw(3, shape, stride);
return convert_planar_video_array(
fmt, data, shape, stride, time_base, pts);
default:;
}
#undef CHECK_BITS
SPDL_FAIL(fmt::format("Unsupported pix_fmt: {}", pix_fmt));
}
} // namespace spdl::core