-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvideo_encode_accelerator_unittest.cc
2664 lines (2277 loc) · 96.5 KB
/
video_encode_accelerator_unittest.cc
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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <inttypes.h>
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include "base/at_exit.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/bits.h"
#include "base/cancelable_callback.h"
#include "base/command_line.h"
#include "base/containers/queue.h"
#include "base/files/file_util.h"
#include "base/macros.h"
#include "base/memory/aligned_memory.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/numerics/safe_conversions.h"
#include "base/process/process_handle.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/launcher/unit_test_launcher.h"
#include "base/test/scoped_task_environment.h"
#include "base/test/test_suite.h"
#include "base/threading/thread.h"
#include "base/threading/thread_checker.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "build/build_config.h"
#include "media/base/bind_to_current_loop.h"
#include "media/base/bitstream_buffer.h"
#include "media/base/cdm_context.h"
#include "media/base/decoder_buffer.h"
#include "media/base/media_log.h"
#include "media/base/media_util.h"
#include "media/base/test_data_util.h"
#include "media/base/video_decoder.h"
#include "media/base/video_frame.h"
#include "media/filters/ffmpeg_video_decoder.h"
#include "media/filters/ivf_parser.h"
#include "media/filters/vp8_parser.h"
#include "media/gpu/buildflags.h"
#include "media/gpu/gpu_video_encode_accelerator_factory.h"
#include "media/gpu/h264_decoder.h"
#include "media/gpu/h264_dpb.h"
#include "media/gpu/test/video_accelerator_unittest_helpers.h"
#include "media/video/fake_video_encode_accelerator.h"
#include "media/video/h264_parser.h"
#include "media/video/video_encode_accelerator.h"
#include "mojo/core/embedder/embedder.h"
#include "testing/gtest/include/gtest/gtest.h"
#if BUILDFLAG(USE_VAAPI)
#include "media/gpu/vaapi/vaapi_wrapper.h"
#elif defined(OS_WIN)
#include "media/gpu/windows/media_foundation_video_encode_accelerator_win.h"
#endif
namespace media {
namespace {
// The absolute differences between original frame and decoded frame usually
// ranges aroud 1 ~ 7. So we pick 10 as an extreme value to detect abnormal
// decoded frames.
const double kDecodeSimilarityThreshold = 10.0;
// Arbitrarily chosen to add some depth to the pipeline.
const unsigned int kNumOutputBuffers = 4;
const unsigned int kNumExtraInputFrames = 4;
// Maximum delay between requesting a keyframe and receiving one, in frames.
// Arbitrarily chosen as a reasonable requirement.
const unsigned int kMaxKeyframeDelay = 4;
// Default initial bitrate.
const uint32_t kDefaultBitrate = 2000000;
// Default ratio of requested_subsequent_bitrate to initial_bitrate
// (see test parameters below) if one is not provided.
const double kDefaultSubsequentBitrateRatio = 2.0;
// Default initial framerate.
const uint32_t kDefaultFramerate = 30;
// Default ratio of requested_subsequent_framerate to initial_framerate
// (see test parameters below) if one is not provided.
const double kDefaultSubsequentFramerateRatio = 0.1;
// Tolerance factor for how encoded bitrate can differ from requested bitrate.
const double kBitrateTolerance = 0.1;
// Minimum required FPS throughput for the basic performance test.
const uint32_t kMinPerfFPS = 30;
// Minimum (arbitrary) number of frames required to enforce bitrate requirements
// over. Streams shorter than this may be too short to realistically require
// an encoder to be able to converge to the requested bitrate over.
// The input stream will be looped as many times as needed in bitrate tests
// to reach at least this number of frames before calculating final bitrate.
const unsigned int kMinFramesForBitrateTests = 300;
// The percentiles to measure for encode latency.
const unsigned int kLoggedLatencyPercentiles[] = {50, 75, 95};
// Timeout for the flush is completed. In the multiple encoder test case, the
// FPS might be lower than expected. Let us assume that the lowest FPS is 5,
// then the period per frame is 200 milliseconds. Here we set the timeout 10x
// periods considering that there might be some pending frames.
const unsigned int kFlushTimeoutMs = 2000;
// The syntax of multiple test streams is:
// test-stream1;test-stream2;test-stream3
// The syntax of each test stream is:
// "in_filename:width:height:profile:out_filename:requested_bitrate
// :requested_framerate:requested_subsequent_bitrate
// :requested_subsequent_framerate:pixel_format"
// Instead of ":", "," can be used as a seperator as well. Note that ":" does
// not work on Windows as it interferes with file paths.
// - |in_filename| is YUV raw stream. Its format must be |pixel_format|
// (see http://www.fourcc.org/yuv.php#IYUV).
// - |width| and |height| are in pixels.
// - |profile| to encode into (values of VideoCodecProfile).
// - |out_filename| filename to save the encoded stream to (optional). The
// format for H264 is Annex-B byte stream. The format for VP8 is IVF. Output
// stream is saved for the simple encode test only. H264 raw stream and IVF
// can be used as input of VDA unittest. H264 raw stream can be played by
// "mplayer -fps 25 out.h264" and IVF can be played by mplayer directly.
// Helpful description: http://wiki.multimedia.cx/index.php?title=IVF
// Further parameters are optional (need to provide preceding positional
// parameters if a specific subsequent parameter is required):
// - |requested_bitrate| requested bitrate in bits per second.
// Bitrate is only forced for tests that test bitrate.
// - |requested_framerate| requested initial framerate.
// - |requested_subsequent_bitrate| bitrate to switch to in the middle of the
// stream.
// - |requested_subsequent_framerate| framerate to switch to in the middle
// of the stream.
// - |pixel_format| is the VideoPixelFormat of |in_filename|. Users needs to
// set the value corresponding to the desired format. If it is not specified,
// this would be PIXEL_FORMAT_I420.
#if defined(OS_CHROMEOS) || defined(OS_LINUX)
const char* g_default_in_filename = "bear_320x192_40frames.yuv";
const base::FilePath::CharType* g_default_in_parameters =
FILE_PATH_LITERAL(":320:192:1:out.h264:200000");
#elif defined(OS_MACOSX)
// VideoToolbox falls back to SW encoder with resolutions lower than this.
const char* g_default_in_filename = "bear_640x384_40frames.yuv";
const base::FilePath::CharType* g_default_in_parameters =
FILE_PATH_LITERAL(":640:384:1:out.h264:200000");
#elif defined(OS_WIN)
const char* g_default_in_filename = "bear_320x192_40frames.yuv";
const base::FilePath::CharType* g_default_in_parameters =
FILE_PATH_LITERAL(",320,192,0,out.h264,200000");
#endif // defined(OS_CHROMEOS) || defined(OS_LINUX)
// Default params that can be overriden via command line.
std::unique_ptr<base::FilePath::StringType> g_test_stream_data(
new base::FilePath::StringType(
media::GetTestDataFilePath(media::g_default_in_filename).value() +
media::g_default_in_parameters));
base::FilePath g_log_path;
base::FilePath g_frame_stats_path;
bool g_run_at_fps = false;
bool g_needs_encode_latency = false;
bool g_verify_all_output = false;
bool g_fake_encoder = false;
// Environment to store test stream data for all test cases.
class VideoEncodeAcceleratorTestEnvironment;
VideoEncodeAcceleratorTestEnvironment* g_env;
// The number of frames to be encoded. This variable is set by the switch
// "--num_frames_to_encode". Ignored if 0.
int g_num_frames_to_encode = 0;
#ifdef ARCH_CPU_ARMEL
// ARM performs CPU cache management with CPU cache line granularity. We thus
// need to ensure our buffers are CPU cache line-aligned (64 byte-aligned).
// Otherwise newer kernels will refuse to accept them, and on older kernels
// we'll be treating ourselves to random corruption.
// Moreover, some hardware codecs require 128-byte alignment for physical
// buffers.
const size_t kPlatformBufferAlignment = 128;
#else
const size_t kPlatformBufferAlignment = 8;
#endif
inline static size_t AlignToPlatformRequirements(size_t value) {
return base::bits::Align(value, kPlatformBufferAlignment);
}
// An aligned STL allocator.
template <typename T, size_t ByteAlignment>
class AlignedAllocator : public std::allocator<T> {
public:
typedef size_t size_type;
typedef T* pointer;
template <class T1>
struct rebind {
typedef AlignedAllocator<T1, ByteAlignment> other;
};
AlignedAllocator() {}
explicit AlignedAllocator(const AlignedAllocator&) {}
template <class T1>
explicit AlignedAllocator(const AlignedAllocator<T1, ByteAlignment>&) {}
~AlignedAllocator() {}
pointer allocate(size_type n, const void* = 0) {
return static_cast<pointer>(base::AlignedAlloc(n, ByteAlignment));
}
void deallocate(pointer p, size_type n) {
base::AlignedFree(static_cast<void*>(p));
}
size_type max_size() const {
return std::numeric_limits<size_t>::max() / sizeof(T);
}
};
struct TestStream {
TestStream()
: num_frames(0),
aligned_buffer_size(0),
requested_bitrate(0),
requested_framerate(0),
requested_subsequent_bitrate(0),
requested_subsequent_framerate(0) {}
~TestStream() {}
VideoPixelFormat pixel_format;
gfx::Size visible_size;
gfx::Size coded_size;
unsigned int num_frames;
// Original unaligned YUV input file name provided as an argument to the test.
std::string in_filename;
// A vector used to prepare aligned input buffers of |in_filename|. This
// makes sure starting addresses of YUV planes are aligned to
// kPlatformBufferAlignment bytes.
std::vector<char, AlignedAllocator<char, kPlatformBufferAlignment>>
aligned_in_file_data;
// Byte size of a frame of |aligned_in_file_data|.
size_t aligned_buffer_size;
// Byte size for each aligned plane of a frame.
std::vector<size_t> aligned_plane_size;
std::string out_filename;
VideoCodecProfile requested_profile;
unsigned int requested_bitrate;
unsigned int requested_framerate;
unsigned int requested_subsequent_bitrate;
unsigned int requested_subsequent_framerate;
};
// Return the |percentile| from a sorted vector.
static base::TimeDelta Percentile(
const std::vector<base::TimeDelta>& sorted_values,
unsigned int percentile) {
size_t size = sorted_values.size();
LOG_ASSERT(size > 0UL);
LOG_ASSERT(percentile <= 100UL);
// Use Nearest Rank method in http://en.wikipedia.org/wiki/Percentile.
int index =
std::max(static_cast<int>(ceil(0.01f * percentile * size)) - 1, 0);
return sorted_values[index];
}
static bool IsH264(VideoCodecProfile profile) {
return profile >= H264PROFILE_MIN && profile <= H264PROFILE_MAX;
}
static bool IsVP8(VideoCodecProfile profile) {
return profile >= VP8PROFILE_MIN && profile <= VP8PROFILE_MAX;
}
// Helper functions to do string conversions.
static base::FilePath::StringType StringToFilePathStringType(
const std::string& str) {
#if defined(OS_WIN)
return base::UTF8ToWide(str);
#else
return str;
#endif // defined(OS_WIN)
}
static std::string FilePathStringTypeToString(
const base::FilePath::StringType& str) {
#if defined(OS_WIN)
return base::WideToUTF8(str);
#else
return str;
#endif // defined(OS_WIN)
}
// Some platforms may have requirements on physical memory buffer alignment.
// Since we are just mapping and passing chunks of the input file directly to
// the VEA as input frames, to avoid copying large chunks of raw data on each
// frame, and thus affecting performance measurements, we have to prepare a
// temporary file with all planes aligned to the required alignment beforehand.
static void CreateAlignedInputStreamFile(const gfx::Size& coded_size,
TestStream* test_stream) {
// Test case may have many encoders and memory should be prepared once.
if (test_stream->coded_size == coded_size &&
!test_stream->aligned_in_file_data.empty())
return;
// All encoders in multiple encoder test reuse the same test_stream, make
// sure they requested the same coded_size
ASSERT_TRUE(test_stream->aligned_in_file_data.empty() ||
coded_size == test_stream->coded_size);
test_stream->coded_size = coded_size;
ASSERT_NE(test_stream->pixel_format, PIXEL_FORMAT_UNKNOWN);
const VideoPixelFormat pixel_format = test_stream->pixel_format;
size_t num_planes = VideoFrame::NumPlanes(pixel_format);
std::vector<size_t> padding_sizes(num_planes);
std::vector<size_t> coded_bpl(num_planes);
std::vector<size_t> visible_bpl(num_planes);
std::vector<size_t> visible_plane_rows(num_planes);
// Calculate padding in bytes to be added after each plane required to keep
// starting addresses of all planes at a byte boundary required by the
// platform. This padding will be added after each plane when copying to the
// temporary file.
// At the same time we also need to take into account coded_size requested by
// the VEA; each row of visible_bpl bytes in the original file needs to be
// copied into a row of coded_bpl bytes in the aligned file.
for (size_t i = 0; i < num_planes; i++) {
const size_t size =
VideoFrame::PlaneSize(pixel_format, i, coded_size).GetArea();
test_stream->aligned_plane_size.push_back(
AlignToPlatformRequirements(size));
test_stream->aligned_buffer_size += test_stream->aligned_plane_size.back();
coded_bpl[i] = VideoFrame::RowBytes(i, pixel_format, coded_size.width());
visible_bpl[i] = VideoFrame::RowBytes(i, pixel_format,
test_stream->visible_size.width());
visible_plane_rows[i] =
VideoFrame::Rows(i, pixel_format, test_stream->visible_size.height());
const size_t padding_rows =
VideoFrame::Rows(i, pixel_format, coded_size.height()) -
visible_plane_rows[i];
padding_sizes[i] =
padding_rows * coded_bpl[i] + AlignToPlatformRequirements(size) - size;
}
base::FilePath src_file(StringToFilePathStringType(test_stream->in_filename));
int64_t src_file_size = 0;
LOG_ASSERT(base::GetFileSize(src_file, &src_file_size));
size_t visible_buffer_size =
VideoFrame::AllocationSize(pixel_format, test_stream->visible_size);
LOG_ASSERT(src_file_size % visible_buffer_size == 0U)
<< "Stream byte size is not a product of calculated frame byte size";
test_stream->num_frames =
static_cast<unsigned int>(src_file_size / visible_buffer_size);
LOG_ASSERT(test_stream->aligned_buffer_size > 0UL);
test_stream->aligned_in_file_data.resize(test_stream->aligned_buffer_size *
test_stream->num_frames);
base::File src(src_file, base::File::FLAG_OPEN | base::File::FLAG_READ);
std::vector<char> src_data(visible_buffer_size);
off_t src_offset = 0, dest_offset = 0;
for (size_t frame = 0; frame < test_stream->num_frames; frame++) {
LOG_ASSERT(src.Read(src_offset, &src_data[0],
static_cast<int>(visible_buffer_size)) ==
static_cast<int>(visible_buffer_size));
const char* src_ptr = &src_data[0];
for (size_t i = 0; i < num_planes; i++) {
// Assert that each plane of frame starts at required byte boundary.
ASSERT_EQ(0u, dest_offset & (kPlatformBufferAlignment - 1))
<< "Planes of frame should be mapped per platform requirements";
for (size_t j = 0; j < visible_plane_rows[i]; j++) {
memcpy(&test_stream->aligned_in_file_data[dest_offset], src_ptr,
visible_bpl[i]);
src_ptr += visible_bpl[i];
dest_offset += static_cast<off_t>(coded_bpl[i]);
}
dest_offset += static_cast<off_t>(padding_sizes[i]);
}
src_offset += static_cast<off_t>(visible_buffer_size);
}
src.Close();
LOG_ASSERT(test_stream->num_frames > 0UL);
}
// Parse |data| into its constituent parts, set the various output fields
// accordingly, read in video stream, and store them to |test_streams|.
static void ParseAndReadTestStreamData(
const base::FilePath::StringType& data,
std::vector<std::unique_ptr<TestStream>>* test_streams) {
// Split the string to individual test stream data.
std::vector<base::FilePath::StringType> test_streams_data =
base::SplitString(data, base::FilePath::StringType(1, ';'),
base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
LOG_ASSERT(test_streams_data.size() >= 1U) << data;
// Parse each test stream data and read the input file.
for (size_t index = 0; index < test_streams_data.size(); ++index) {
std::vector<base::FilePath::StringType> fields = base::SplitString(
test_streams_data[index], base::FilePath::StringType(1, ','),
base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
// Try using ":" as the seperator if "," isn't used.
if (fields.size() == 1U) {
fields = base::SplitString(test_streams_data[index],
base::FilePath::StringType(1, ':'),
base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
}
LOG_ASSERT(fields.size() >= 4U) << data;
LOG_ASSERT(fields.size() <= 10U) << data;
auto test_stream = std::make_unique<TestStream>();
test_stream->in_filename = FilePathStringTypeToString(fields[0]);
int width, height;
bool result = base::StringToInt(fields[1], &width);
LOG_ASSERT(result);
result = base::StringToInt(fields[2], &height);
LOG_ASSERT(result);
test_stream->visible_size = gfx::Size(width, height);
LOG_ASSERT(!test_stream->visible_size.IsEmpty());
int profile;
result = base::StringToInt(fields[3], &profile);
LOG_ASSERT(result);
LOG_ASSERT(profile > VIDEO_CODEC_PROFILE_UNKNOWN);
LOG_ASSERT(profile <= VIDEO_CODEC_PROFILE_MAX);
test_stream->requested_profile = static_cast<VideoCodecProfile>(profile);
test_stream->pixel_format = PIXEL_FORMAT_I420;
if (fields.size() >= 5 && !fields[4].empty())
test_stream->out_filename = FilePathStringTypeToString(fields[4]);
if (fields.size() >= 6 && !fields[5].empty())
LOG_ASSERT(
base::StringToUint(fields[5], &test_stream->requested_bitrate));
if (fields.size() >= 7 && !fields[6].empty())
LOG_ASSERT(
base::StringToUint(fields[6], &test_stream->requested_framerate));
if (fields.size() >= 8 && !fields[7].empty()) {
LOG_ASSERT(base::StringToUint(
fields[7], &test_stream->requested_subsequent_bitrate));
}
if (fields.size() >= 9 && !fields[8].empty()) {
LOG_ASSERT(base::StringToUint(
fields[8], &test_stream->requested_subsequent_framerate));
}
if (fields.size() >= 10 && !fields[9].empty()) {
unsigned int format = 0;
LOG_ASSERT(base::StringToUint(fields[9], &format));
test_stream->pixel_format = static_cast<VideoPixelFormat>(format);
}
test_streams->push_back(std::move(test_stream));
}
}
// Basic test environment shared across multiple test cases. We only need to
// setup it once for all test cases.
// It helps
// - maintain test stream data and other test settings.
// - clean up temporary aligned files.
// - output log to file.
class VideoEncodeAcceleratorTestEnvironment : public ::testing::Environment {
public:
VideoEncodeAcceleratorTestEnvironment(
std::unique_ptr<base::FilePath::StringType> data,
const base::FilePath& log_path,
const base::FilePath& frame_stats_path,
bool run_at_fps,
bool needs_encode_latency,
bool verify_all_output)
: test_stream_data_(std::move(data)),
log_path_(log_path),
frame_stats_path_(frame_stats_path),
run_at_fps_(run_at_fps),
needs_encode_latency_(needs_encode_latency),
verify_all_output_(verify_all_output) {}
virtual void SetUp() {
if (!log_path_.empty()) {
log_file_.reset(new base::File(
log_path_, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE));
LOG_ASSERT(log_file_->IsValid());
}
ParseAndReadTestStreamData(*test_stream_data_, &test_streams_);
}
virtual void TearDown() {
log_file_.reset();
}
// Log one entry of machine-readable data to file and LOG(INFO).
// The log has one data entry per line in the format of "<key>: <value>".
// Note that Chrome OS video_VEAPerf autotest parses the output key and value
// pairs. Be sure to keep the autotest in sync.
void LogToFile(const std::string& key, const std::string& value) {
std::string s = base::StringPrintf("%s: %s\n", key.c_str(), value.c_str());
LOG(INFO) << s;
if (log_file_) {
log_file_->WriteAtCurrentPos(s.data(), static_cast<int>(s.length()));
}
}
// Feed the encoder with the input buffers at the requested framerate. If
// false, feed as fast as possible. This is set by the command line switch
// "--run_at_fps".
bool run_at_fps() const { return run_at_fps_; }
// Whether to measure encode latency. This is set by the command line switch
// "--measure_latency".
bool needs_encode_latency() const { return needs_encode_latency_; }
// Verify the encoder output of all testcases. This is set by the command line
// switch "--verify_all_output".
bool verify_all_output() const { return verify_all_output_; }
const base::FilePath& frame_stats_path() const { return frame_stats_path_; }
std::vector<std::unique_ptr<TestStream>> test_streams_;
private:
std::unique_ptr<base::FilePath::StringType> test_stream_data_;
base::FilePath log_path_;
base::FilePath frame_stats_path_;
std::unique_ptr<base::File> log_file_;
bool run_at_fps_;
bool needs_encode_latency_;
bool verify_all_output_;
};
enum ClientState {
CS_CREATED, // Encoder is created.
CS_INITIALIZED, // Encoder initialization is finished.
CS_ENCODING, // Encoder is encoding.
CS_FLUSHING, // Ask encoder to flush.
CS_FINISHED, // Encoding has finished, all frames are encoded.
CS_FLUSHED, // Encoder notifies the flush is finished.
CS_VALIDATED, // Encoded frame quality has been validated.
CS_ERROR, // Any error occurs.
};
// Performs basic, codec-specific sanity checks on the stream buffers passed
// to ProcessStreamBuffer(): whether we've seen keyframes before non-keyframes,
// correct sequences of H.264 NALUs (SPS before PPS and before slices), etc.
// Calls given FrameFoundCallback when a complete frame is found while
// processing.
class StreamValidator {
public:
// To be called when a complete frame is found while processing a stream
// buffer, passing true if the frame is a keyframe and the visible size.
// Returns false if we are not interested in more frames and further
// processing should be aborted.
typedef base::Callback<bool(bool, const gfx::Size&)> FrameFoundCallback;
virtual ~StreamValidator() {}
// Provide a StreamValidator instance for the given |profile|.
static std::unique_ptr<StreamValidator> Create(
VideoCodecProfile profile,
const FrameFoundCallback& frame_cb);
// Process and verify contents of a bitstream buffer.
virtual void ProcessStreamBuffer(const uint8_t* stream, size_t size) = 0;
protected:
explicit StreamValidator(const FrameFoundCallback& frame_cb)
: frame_cb_(frame_cb) {}
FrameFoundCallback frame_cb_;
gfx::Size visible_size_;
};
class H264Validator : public StreamValidator {
public:
explicit H264Validator(const FrameFoundCallback& frame_cb)
: StreamValidator(frame_cb),
seen_sps_(false),
seen_pps_(false),
seen_idr_(false),
curr_pic_(new H264Picture) {}
void ProcessStreamBuffer(const uint8_t* stream, size_t size) override;
private:
bool IsNewPicture(const H264SliceHeader& slice_hdr);
bool UpdateCurrentPicture(const H264SliceHeader& slice_hdr);
// Set to true when encoder provides us with the corresponding NALU type.
bool seen_sps_;
bool seen_pps_;
bool seen_idr_;
scoped_refptr<H264Picture> curr_pic_;
int curr_sps_id_ = -1;
int curr_pps_id_ = -1;
H264Parser h264_parser_;
};
void H264Validator::ProcessStreamBuffer(const uint8_t* stream, size_t size) {
h264_parser_.SetStream(stream, static_cast<off_t>(size));
while (1) {
H264NALU nalu;
H264Parser::Result result;
result = h264_parser_.AdvanceToNextNALU(&nalu);
if (result == H264Parser::kEOStream)
break;
ASSERT_EQ(H264Parser::kOk, result);
bool keyframe = false;
switch (nalu.nal_unit_type) {
case H264NALU::kIDRSlice:
ASSERT_TRUE(seen_sps_);
ASSERT_TRUE(seen_pps_);
seen_idr_ = true;
keyframe = true;
FALLTHROUGH;
case H264NALU::kNonIDRSlice: {
ASSERT_TRUE(seen_idr_);
H264SliceHeader slice_hdr;
ASSERT_EQ(H264Parser::kOk,
h264_parser_.ParseSliceHeader(nalu, &slice_hdr));
if (IsNewPicture(slice_hdr)) {
if (!frame_cb_.Run(keyframe, visible_size_))
return;
ASSERT_TRUE(UpdateCurrentPicture(slice_hdr));
}
break;
}
case H264NALU::kSPS: {
int sps_id;
ASSERT_EQ(H264Parser::kOk, h264_parser_.ParseSPS(&sps_id));
// Check the visible size.
gfx::Rect visible_size =
h264_parser_.GetSPS(sps_id)->GetVisibleRect().value_or(gfx::Rect());
ASSERT_FALSE(visible_size.IsEmpty());
visible_size_ = visible_size.size();
seen_sps_ = true;
break;
}
case H264NALU::kPPS: {
ASSERT_TRUE(seen_sps_);
int pps_id;
ASSERT_EQ(H264Parser::kOk, h264_parser_.ParsePPS(&pps_id));
seen_pps_ = true;
break;
}
default:
break;
}
}
}
bool H264Validator::IsNewPicture(const H264SliceHeader& slice_hdr) {
if (!curr_pic_)
return true;
return H264Decoder::IsNewPrimaryCodedPicture(
curr_pic_.get(), curr_pps_id_, h264_parser_.GetSPS(curr_sps_id_),
slice_hdr);
}
bool H264Validator::UpdateCurrentPicture(const H264SliceHeader& slice_hdr) {
curr_pps_id_ = slice_hdr.pic_parameter_set_id;
const H264PPS* pps = h264_parser_.GetPPS(curr_pps_id_);
if (!pps) {
LOG(ERROR) << "Cannot parse pps.";
return false;
}
curr_sps_id_ = pps->seq_parameter_set_id;
const H264SPS* sps = h264_parser_.GetSPS(curr_sps_id_);
if (!sps) {
LOG(ERROR) << "Cannot parse sps.";
return false;
}
if (!H264Decoder::FillH264PictureFromSliceHeader(sps, slice_hdr,
curr_pic_.get())) {
LOG(FATAL) << "Cannot initialize current frame.";
return false;
}
return true;
}
class VP8Validator : public StreamValidator {
public:
explicit VP8Validator(const FrameFoundCallback& frame_cb)
: StreamValidator(frame_cb), seen_keyframe_(false) {}
void ProcessStreamBuffer(const uint8_t* stream, size_t size) override;
private:
// Have we already got a keyframe in the stream?
bool seen_keyframe_;
};
void VP8Validator::ProcessStreamBuffer(const uint8_t* stream, size_t size) {
// TODO(posciak): We could be getting more frames in the buffer, but there is
// no simple way to detect this. We'd need to parse the frames and go through
// partition numbers/sizes. For now assume one frame per buffer.
Vp8Parser parser;
Vp8FrameHeader header;
EXPECT_TRUE(parser.ParseFrame(stream, size, &header));
if (header.IsKeyframe()) {
seen_keyframe_ = true;
visible_size_.SetSize(header.width, header.height);
}
EXPECT_TRUE(seen_keyframe_);
ASSERT_FALSE(visible_size_.IsEmpty());
frame_cb_.Run(header.IsKeyframe(), visible_size_);
}
// static
std::unique_ptr<StreamValidator> StreamValidator::Create(
VideoCodecProfile profile,
const FrameFoundCallback& frame_cb) {
std::unique_ptr<StreamValidator> validator;
if (IsH264(profile)) {
validator.reset(new H264Validator(frame_cb));
} else if (IsVP8(profile)) {
validator.reset(new VP8Validator(frame_cb));
} else {
LOG(FATAL) << "Unsupported profile: " << GetProfileName(profile);
}
return validator;
}
class VideoFrameQualityValidator
: public base::SupportsWeakPtr<VideoFrameQualityValidator> {
public:
VideoFrameQualityValidator(const VideoCodecProfile profile,
const VideoPixelFormat pixel_format,
bool verify_quality,
const base::Closure& flush_complete_cb,
const base::Closure& decode_error_cb);
void Initialize(const gfx::Size& coded_size, const gfx::Rect& visible_size);
// Save original YUV frame to compare it with the decoded frame later.
void AddOriginalFrame(scoped_refptr<VideoFrame> frame);
void AddDecodeBuffer(scoped_refptr<DecoderBuffer> buffer);
// Flush the decoder.
void Flush();
private:
void InitializeCB(bool success);
void DecodeDone(DecodeStatus status);
void FlushDone(DecodeStatus status);
void VerifyOutputFrame(const scoped_refptr<VideoFrame>& output_frame);
void Decode();
void WriteFrameStats();
enum State { UNINITIALIZED, INITIALIZED, DECODING, DECODER_ERROR };
struct FrameStats {
int width;
int height;
double ssim[VideoFrame::kMaxPlanes];
uint64_t mse[VideoFrame::kMaxPlanes];
};
FrameStats CompareFrames(const VideoFrame& original_frame,
const VideoFrame& output_frame);
MediaLog media_log_;
const VideoCodecProfile profile_;
const VideoPixelFormat pixel_format_;
const bool verify_quality_;
std::unique_ptr<FFmpegVideoDecoder> decoder_;
VideoDecoder::DecodeCB decode_cb_;
// Decode callback of an EOS buffer.
VideoDecoder::DecodeCB eos_decode_cb_;
// Callback of Flush(). Called after all frames are decoded.
const base::Closure flush_complete_cb_;
const base::Closure decode_error_cb_;
State decoder_state_;
base::queue<scoped_refptr<VideoFrame>> original_frames_;
base::queue<scoped_refptr<DecoderBuffer>> decode_buffers_;
std::vector<FrameStats> frame_stats_;
base::ThreadChecker thread_checker_;
};
VideoFrameQualityValidator::VideoFrameQualityValidator(
const VideoCodecProfile profile,
const VideoPixelFormat pixel_format,
const bool verify_quality,
const base::Closure& flush_complete_cb,
const base::Closure& decode_error_cb)
: profile_(profile),
pixel_format_(pixel_format),
verify_quality_(verify_quality),
decoder_(new FFmpegVideoDecoder(&media_log_)),
decode_cb_(base::BindRepeating(&VideoFrameQualityValidator::DecodeDone,
AsWeakPtr())),
eos_decode_cb_(base::BindRepeating(&VideoFrameQualityValidator::FlushDone,
AsWeakPtr())),
flush_complete_cb_(flush_complete_cb),
decode_error_cb_(decode_error_cb),
decoder_state_(UNINITIALIZED) {
// Allow decoding of individual NALU. Entire frames are required by default.
decoder_->set_decode_nalus(true);
}
void VideoFrameQualityValidator::Initialize(const gfx::Size& coded_size,
const gfx::Rect& visible_size) {
DCHECK(thread_checker_.CalledOnValidThread());
gfx::Size natural_size(visible_size.size());
// The default output format of ffmpeg video decoder is YV12.
VideoDecoderConfig config;
if (IsVP8(profile_))
config.Initialize(kCodecVP8, VP8PROFILE_ANY, pixel_format_,
COLOR_SPACE_UNSPECIFIED, VIDEO_ROTATION_0, coded_size,
visible_size, natural_size, EmptyExtraData(),
Unencrypted());
else if (IsH264(profile_))
config.Initialize(kCodecH264, H264PROFILE_MAIN, pixel_format_,
COLOR_SPACE_UNSPECIFIED, VIDEO_ROTATION_0, coded_size,
visible_size, natural_size, EmptyExtraData(),
Unencrypted());
else
LOG_ASSERT(0) << "Invalid profile " << GetProfileName(profile_);
decoder_->Initialize(
config, false, nullptr,
base::BindRepeating(&VideoFrameQualityValidator::InitializeCB,
base::Unretained(this)),
base::BindRepeating(&VideoFrameQualityValidator::VerifyOutputFrame,
base::Unretained(this)),
base::NullCallback());
}
void VideoFrameQualityValidator::InitializeCB(bool success) {
DCHECK(thread_checker_.CalledOnValidThread());
if (success) {
decoder_state_ = INITIALIZED;
Decode();
} else {
decoder_state_ = DECODER_ERROR;
if (IsH264(profile_))
LOG(ERROR) << "Chromium does not support H264 decode. Try Chrome.";
decode_error_cb_.Run();
FAIL() << "Decoder initialization error";
}
}
void VideoFrameQualityValidator::AddOriginalFrame(
scoped_refptr<VideoFrame> frame) {
DCHECK(thread_checker_.CalledOnValidThread());
original_frames_.push(frame);
}
void VideoFrameQualityValidator::DecodeDone(DecodeStatus status) {
DCHECK(thread_checker_.CalledOnValidThread());
if (status == DecodeStatus::OK) {
decoder_state_ = INITIALIZED;
Decode();
} else {
decoder_state_ = DECODER_ERROR;
decode_error_cb_.Run();
FAIL() << "Unexpected decode status = " << status << ". Stop decoding.";
}
}
void VideoFrameQualityValidator::FlushDone(DecodeStatus status) {
DCHECK(thread_checker_.CalledOnValidThread());
WriteFrameStats();
flush_complete_cb_.Run();
}
void VideoFrameQualityValidator::Flush() {
DCHECK(thread_checker_.CalledOnValidThread());
if (decoder_state_ != DECODER_ERROR) {
decode_buffers_.push(DecoderBuffer::CreateEOSBuffer());
Decode();
}
}
void VideoFrameQualityValidator::WriteFrameStats() {
if (g_env->frame_stats_path().empty())
return;
base::File frame_stats_file(
g_env->frame_stats_path(),
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
LOG_ASSERT(frame_stats_file.IsValid());
// TODO(pbos): Consider adding encoded bytes per frame + key/delta frame.
std::string csv =
"frame,width,height,ssim-y,ssim-u,ssim-v,mse-y,mse-u,mse-v\n";
frame_stats_file.WriteAtCurrentPos(csv.data(), static_cast<int>(csv.size()));
for (size_t frame_idx = 0; frame_idx < frame_stats_.size(); ++frame_idx) {
const FrameStats& frame_stats = frame_stats_[frame_idx];
csv = base::StringPrintf(
"%d,%d,%d,%f,%f,%f,%" PRIu64 ",%" PRIu64 ",%" PRIu64 "\n",
static_cast<int>(frame_idx), frame_stats.width, frame_stats.height,
frame_stats.ssim[VideoFrame::kYPlane],
frame_stats.ssim[VideoFrame::kUPlane],
frame_stats.ssim[VideoFrame::kVPlane],
frame_stats.mse[VideoFrame::kYPlane],
frame_stats.mse[VideoFrame::kUPlane],
frame_stats.mse[VideoFrame::kVPlane]);
frame_stats_file.WriteAtCurrentPos(csv.data(),
static_cast<int>(csv.size()));
}
}
void VideoFrameQualityValidator::AddDecodeBuffer(
scoped_refptr<DecoderBuffer> buffer) {
DCHECK(thread_checker_.CalledOnValidThread());
if (decoder_state_ != DECODER_ERROR) {
decode_buffers_.push(buffer);
Decode();
}
}
void VideoFrameQualityValidator::Decode() {
DCHECK(thread_checker_.CalledOnValidThread());
if (decoder_state_ == INITIALIZED && !decode_buffers_.empty()) {
scoped_refptr<DecoderBuffer> next_buffer = decode_buffers_.front();
decode_buffers_.pop();
decoder_state_ = DECODING;
if (next_buffer->end_of_stream())
decoder_->Decode(next_buffer, eos_decode_cb_);
else
decoder_->Decode(next_buffer, decode_cb_);
}
}
namespace {
// Gets SSIM (see below) parameters for a 8x8 block.
void GetSsimParams8x8(const uint8_t* orig,
size_t orig_stride,
const uint8_t* recon,
size_t recon_stride,
int* sum_orig,
int* sum_recon,
int* sum_sq_orig,
int* sum_sq_recon,
int* sum_orig_x_recon) {
for (size_t i = 0; i < 8; ++i, orig += orig_stride, recon += recon_stride) {
for (size_t j = 0; j < 8; ++j) {
*sum_orig += orig[j];
*sum_recon += recon[j];
*sum_sq_orig += orig[j] * orig[j];
*sum_sq_recon += recon[j] * recon[j];
*sum_orig_x_recon += orig[j] * recon[j];
}
}
}
// Generates SSIM (see below) for a 8x8 block from input parameters.
// https://en.wikipedia.org/wiki/Structural_similarity
double GenerateSimilarity(int sum_orig,
int sum_recon,
int sum_sq_orig,
int sum_sq_recon,
int sum_orig_x_recon,
int count) {
// Same constants as used inside libvpx.
static const int64_t kC1 = 26634; // (64^2*(.01*255)^2
static const int64_t kC2 = 239708; // (64^2*(.03*255)^2
// scale the constants by number of pixels
int64_t c1 = (kC1 * count * count) >> 12;
int64_t c2 = (kC2 * count * count) >> 12;
int64_t ssim_n = (2 * sum_orig * sum_recon + c1) *