1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 // 5 // The bulk of this file is support code; sorry about that. Here's an overview 6 // to hopefully help readers of this code: 7 // - RenderingHelper is charged with interacting with X11/{EGL/GLES2,GLX/GL} or 8 // Win/EGL. 9 // - ClientState is an enum for the state of the decode client used by the test. 10 // - ClientStateNotification is a barrier abstraction that allows the test code 11 // to be written sequentially and wait for the decode client to see certain 12 // state transitions. 13 // - GLRenderingVDAClient is a VideoDecodeAccelerator::Client implementation 14 // - Finally actual TEST cases are at the bottom of this file, using the above 15 // infrastructure. 16 17 #include <fcntl.h> 18 #include <sys/stat.h> 19 #include <sys/types.h> 20 #include <algorithm> 21 #include <deque> 22 #include <map> 23 24 // Include gtest.h out of order because <X11/X.h> #define's Bool & None, which 25 // gtest uses as struct names (inside a namespace). This means that 26 // #include'ing gtest after anything that pulls in X.h fails to compile. 27 // This is http://code.google.com/p/googletest/issues/detail?id=371 28 #include "testing/gtest/include/gtest/gtest.h" 29 30 #include "base/at_exit.h" 31 #include "base/bind.h" 32 #include "base/command_line.h" 33 #include "base/file_util.h" 34 #include "base/format_macros.h" 35 #include "base/md5.h" 36 #include "base/message_loop/message_loop_proxy.h" 37 #include "base/platform_file.h" 38 #include "base/process/process.h" 39 #include "base/stl_util.h" 40 #include "base/strings/string_number_conversions.h" 41 #include "base/strings/string_split.h" 42 #include "base/strings/stringize_macros.h" 43 #include "base/strings/stringprintf.h" 44 #include "base/strings/utf_string_conversions.h" 45 #include "base/synchronization/condition_variable.h" 46 #include "base/synchronization/lock.h" 47 #include "base/synchronization/waitable_event.h" 48 #include "base/threading/thread.h" 49 #include "content/common/gpu/media/h264_parser.h" 50 #include "content/common/gpu/media/rendering_helper.h" 51 #include "content/common/gpu/media/video_accelerator_unittest_helpers.h" 52 #include "content/public/common/content_switches.h" 53 #include "ui/gfx/codec/png_codec.h" 54 55 #if defined(OS_WIN) 56 #include "content/common/gpu/media/dxva_video_decode_accelerator.h" 57 #elif defined(OS_CHROMEOS) 58 #if defined(ARCH_CPU_ARMEL) 59 #include "content/common/gpu/media/exynos_video_decode_accelerator.h" 60 #elif defined(ARCH_CPU_X86_FAMILY) 61 #include "content/common/gpu/media/vaapi_video_decode_accelerator.h" 62 #include "content/common/gpu/media/vaapi_wrapper.h" 63 #endif // ARCH_CPU_ARMEL 64 #else 65 #error The VideoAccelerator tests are not supported on this platform. 66 #endif // OS_WIN 67 68 using media::VideoDecodeAccelerator; 69 70 namespace content { 71 namespace { 72 73 // Values optionally filled in from flags; see main() below. 74 // The syntax of multiple test videos is: 75 // test-video1;test-video2;test-video3 76 // where only the first video is required and other optional videos would be 77 // decoded by concurrent decoders. 78 // The syntax of each test-video is: 79 // filename:width:height:numframes:numfragments:minFPSwithRender:minFPSnoRender 80 // where only the first field is required. Value details: 81 // - |filename| must be an h264 Annex B (NAL) stream or an IVF VP8 stream. 82 // - |width| and |height| are in pixels. 83 // - |numframes| is the number of picture frames in the file. 84 // - |numfragments| NALU (h264) or frame (VP8) count in the stream. 85 // - |minFPSwithRender| and |minFPSnoRender| are minimum frames/second speeds 86 // expected to be achieved with and without rendering to the screen, resp. 87 // (the latter tests just decode speed). 88 // - |profile| is the media::VideoCodecProfile set during Initialization. 89 // An empty value for a numeric field means "ignore". 90 const base::FilePath::CharType* g_test_video_data = 91 // FILE_PATH_LITERAL("test-25fps.vp8:320:240:250:250:50:175:11"); 92 FILE_PATH_LITERAL("test-25fps.h264:320:240:250:258:50:175:1"); 93 94 // The file path of the test output log. This is used to communicate the test 95 // results to CrOS autotests. We can enable the log and specify the filename by 96 // the "--output_log" switch. 97 const base::FilePath::CharType* g_output_log = NULL; 98 99 // The value is set by the switch "--rendering_fps". 100 double g_rendering_fps = 0; 101 102 // Disable rendering, the value is set by the switch "--disable_rendering". 103 bool g_disable_rendering = false; 104 105 // Magic constants for differentiating the reasons for NotifyResetDone being 106 // called. 107 enum ResetPoint { 108 // Reset() just after calling Decode() with a fragment containing config info. 109 RESET_AFTER_FIRST_CONFIG_INFO = -4, 110 START_OF_STREAM_RESET = -3, 111 MID_STREAM_RESET = -2, 112 END_OF_STREAM_RESET = -1 113 }; 114 115 const int kMaxResetAfterFrameNum = 100; 116 const int kMaxFramesToDelayReuse = 64; 117 const base::TimeDelta kReuseDelay = base::TimeDelta::FromSeconds(1); 118 // Simulate WebRTC and call VDA::Decode 30 times per second. 119 const int kWebRtcDecodeCallsPerSecond = 30; 120 121 struct TestVideoFile { 122 explicit TestVideoFile(base::FilePath::StringType file_name) 123 : file_name(file_name), 124 width(-1), 125 height(-1), 126 num_frames(-1), 127 num_fragments(-1), 128 min_fps_render(-1), 129 min_fps_no_render(-1), 130 profile(media::VIDEO_CODEC_PROFILE_UNKNOWN), 131 reset_after_frame_num(END_OF_STREAM_RESET) { 132 } 133 134 base::FilePath::StringType file_name; 135 int width; 136 int height; 137 int num_frames; 138 int num_fragments; 139 int min_fps_render; 140 int min_fps_no_render; 141 media::VideoCodecProfile profile; 142 int reset_after_frame_num; 143 std::string data_str; 144 }; 145 146 // Presumed minimal display size. 147 // We subtract one pixel from the width because some ARM chromebooks do not 148 // support two fullscreen app running at the same time. See crbug.com/270064. 149 const gfx::Size kThumbnailsDisplaySize(1366 - 1, 768); 150 const gfx::Size kThumbnailsPageSize(1600, 1200); 151 const gfx::Size kThumbnailSize(160, 120); 152 const int kMD5StringLength = 32; 153 154 // Read in golden MD5s for the thumbnailed rendering of this video 155 void ReadGoldenThumbnailMD5s(const TestVideoFile* video_file, 156 std::vector<std::string>* md5_strings) { 157 base::FilePath filepath(video_file->file_name); 158 filepath = filepath.AddExtension(FILE_PATH_LITERAL(".md5")); 159 std::string all_md5s; 160 base::ReadFileToString(filepath, &all_md5s); 161 base::SplitString(all_md5s, '\n', md5_strings); 162 // Check these are legitimate MD5s. 163 for (std::vector<std::string>::iterator md5_string = md5_strings->begin(); 164 md5_string != md5_strings->end(); ++md5_string) { 165 // Ignore the empty string added by SplitString 166 if (!md5_string->length()) 167 continue; 168 // Ignore comments 169 if (md5_string->at(0) == '#') 170 continue; 171 172 CHECK_EQ(static_cast<int>(md5_string->length()), 173 kMD5StringLength) << *md5_string; 174 bool hex_only = std::count_if(md5_string->begin(), 175 md5_string->end(), isxdigit) == 176 kMD5StringLength; 177 CHECK(hex_only) << *md5_string; 178 } 179 CHECK_GE(md5_strings->size(), 1U) << all_md5s; 180 } 181 182 // State of the GLRenderingVDAClient below. Order matters here as the test 183 // makes assumptions about it. 184 enum ClientState { 185 CS_CREATED = 0, 186 CS_DECODER_SET = 1, 187 CS_INITIALIZED = 2, 188 CS_FLUSHING = 3, 189 CS_FLUSHED = 4, 190 CS_RESETTING = 5, 191 CS_RESET = 6, 192 CS_ERROR = 7, 193 CS_DESTROYED = 8, 194 CS_MAX, // Must be last entry. 195 }; 196 197 // A wrapper client that throttles the PictureReady callbacks to a given rate. 198 // It may drops or queues frame to deliver them on time. 199 class ThrottlingVDAClient : public VideoDecodeAccelerator::Client, 200 public base::SupportsWeakPtr<ThrottlingVDAClient> { 201 public: 202 // Callback invoked whan the picture is dropped and should be reused for 203 // the decoder again. 204 typedef base::Callback<void(int32 picture_buffer_id)> ReusePictureCB; 205 206 ThrottlingVDAClient(VideoDecodeAccelerator::Client* client, 207 double fps, 208 ReusePictureCB reuse_picture_cb); 209 virtual ~ThrottlingVDAClient(); 210 211 // VideoDecodeAccelerator::Client implementation 212 virtual void ProvidePictureBuffers(uint32 requested_num_of_buffers, 213 const gfx::Size& dimensions, 214 uint32 texture_target) OVERRIDE; 215 virtual void DismissPictureBuffer(int32 picture_buffer_id) OVERRIDE; 216 virtual void PictureReady(const media::Picture& picture) OVERRIDE; 217 virtual void NotifyInitializeDone() OVERRIDE; 218 virtual void NotifyEndOfBitstreamBuffer(int32 bitstream_buffer_id) OVERRIDE; 219 virtual void NotifyFlushDone() OVERRIDE; 220 virtual void NotifyResetDone() OVERRIDE; 221 virtual void NotifyError(VideoDecodeAccelerator::Error error) OVERRIDE; 222 223 int num_decoded_frames() { return num_decoded_frames_; } 224 225 private: 226 227 void CallClientPictureReady(int version); 228 229 VideoDecodeAccelerator::Client* client_; 230 ReusePictureCB reuse_picture_cb_; 231 base::TimeTicks next_frame_delivered_time_; 232 base::TimeDelta frame_duration_; 233 234 int num_decoded_frames_; 235 int stream_version_; 236 std::deque<media::Picture> pending_pictures_; 237 238 DISALLOW_IMPLICIT_CONSTRUCTORS(ThrottlingVDAClient); 239 }; 240 241 ThrottlingVDAClient::ThrottlingVDAClient(VideoDecodeAccelerator::Client* client, 242 double fps, 243 ReusePictureCB reuse_picture_cb) 244 : client_(client), 245 reuse_picture_cb_(reuse_picture_cb), 246 num_decoded_frames_(0), 247 stream_version_(0) { 248 CHECK(client_); 249 CHECK_GT(fps, 0); 250 frame_duration_ = base::TimeDelta::FromSeconds(1) / fps; 251 } 252 253 ThrottlingVDAClient::~ThrottlingVDAClient() {} 254 255 void ThrottlingVDAClient::ProvidePictureBuffers(uint32 requested_num_of_buffers, 256 const gfx::Size& dimensions, 257 uint32 texture_target) { 258 client_->ProvidePictureBuffers( 259 requested_num_of_buffers, dimensions, texture_target); 260 } 261 262 void ThrottlingVDAClient::DismissPictureBuffer(int32 picture_buffer_id) { 263 client_->DismissPictureBuffer(picture_buffer_id); 264 } 265 266 void ThrottlingVDAClient::PictureReady(const media::Picture& picture) { 267 ++num_decoded_frames_; 268 269 if (pending_pictures_.empty()) { 270 base::TimeDelta delay = 271 next_frame_delivered_time_.is_null() 272 ? base::TimeDelta() 273 : next_frame_delivered_time_ - base::TimeTicks::Now(); 274 base::MessageLoop::current()->PostDelayedTask( 275 FROM_HERE, 276 base::Bind(&ThrottlingVDAClient::CallClientPictureReady, 277 AsWeakPtr(), 278 stream_version_), 279 delay); 280 } 281 pending_pictures_.push_back(picture); 282 } 283 284 void ThrottlingVDAClient::CallClientPictureReady(int version) { 285 // Just return if we have reset the decoder 286 if (version != stream_version_) 287 return; 288 289 base::TimeTicks now = base::TimeTicks::Now(); 290 291 if (next_frame_delivered_time_.is_null()) 292 next_frame_delivered_time_ = now; 293 294 if (next_frame_delivered_time_ + frame_duration_ < now) { 295 // Too late, drop the frame 296 reuse_picture_cb_.Run(pending_pictures_.front().picture_buffer_id()); 297 } else { 298 client_->PictureReady(pending_pictures_.front()); 299 } 300 301 pending_pictures_.pop_front(); 302 next_frame_delivered_time_ += frame_duration_; 303 if (!pending_pictures_.empty()) { 304 base::MessageLoop::current()->PostDelayedTask( 305 FROM_HERE, 306 base::Bind(&ThrottlingVDAClient::CallClientPictureReady, 307 AsWeakPtr(), 308 stream_version_), 309 next_frame_delivered_time_ - base::TimeTicks::Now()); 310 } 311 } 312 313 void ThrottlingVDAClient::NotifyInitializeDone() { 314 client_->NotifyInitializeDone(); 315 } 316 317 void ThrottlingVDAClient::NotifyEndOfBitstreamBuffer( 318 int32 bitstream_buffer_id) { 319 client_->NotifyEndOfBitstreamBuffer(bitstream_buffer_id); 320 } 321 322 void ThrottlingVDAClient::NotifyFlushDone() { 323 if (!pending_pictures_.empty()) { 324 base::MessageLoop::current()->PostDelayedTask( 325 FROM_HERE, 326 base::Bind(&ThrottlingVDAClient::NotifyFlushDone, 327 base::Unretained(this)), 328 next_frame_delivered_time_ - base::TimeTicks::Now()); 329 return; 330 } 331 client_->NotifyFlushDone(); 332 } 333 334 void ThrottlingVDAClient::NotifyResetDone() { 335 ++stream_version_; 336 while (!pending_pictures_.empty()) { 337 reuse_picture_cb_.Run(pending_pictures_.front().picture_buffer_id()); 338 pending_pictures_.pop_front(); 339 } 340 next_frame_delivered_time_ = base::TimeTicks(); 341 client_->NotifyResetDone(); 342 } 343 344 void ThrottlingVDAClient::NotifyError(VideoDecodeAccelerator::Error error) { 345 client_->NotifyError(error); 346 } 347 348 // Client that can accept callbacks from a VideoDecodeAccelerator and is used by 349 // the TESTs below. 350 class GLRenderingVDAClient 351 : public VideoDecodeAccelerator::Client, 352 public base::SupportsWeakPtr<GLRenderingVDAClient> { 353 public: 354 // Doesn't take ownership of |rendering_helper| or |note|, which must outlive 355 // |*this|. 356 // |num_play_throughs| indicates how many times to play through the video. 357 // |reset_after_frame_num| can be a frame number >=0 indicating a mid-stream 358 // Reset() should be done after that frame number is delivered, or 359 // END_OF_STREAM_RESET to indicate no mid-stream Reset(). 360 // |delete_decoder_state| indicates when the underlying decoder should be 361 // Destroy()'d and deleted and can take values: N<0: delete after -N Decode() 362 // calls have been made, N>=0 means interpret as ClientState. 363 // Both |reset_after_frame_num| & |delete_decoder_state| apply only to the 364 // last play-through (governed by |num_play_throughs|). 365 // |rendering_fps| indicates the target rendering fps. 0 means no target fps 366 // and it would render as fast as possible. 367 // |suppress_rendering| indicates GL rendering is suppressed or not. 368 // After |delay_reuse_after_frame_num| frame has been delivered, the client 369 // will start delaying the call to ReusePictureBuffer() for kReuseDelay. 370 // |decode_calls_per_second| is the number of VDA::Decode calls per second. 371 // If |decode_calls_per_second| > 0, |num_in_flight_decodes| must be 1. 372 GLRenderingVDAClient(RenderingHelper* rendering_helper, 373 int rendering_window_id, 374 ClientStateNotification<ClientState>* note, 375 const std::string& encoded_data, 376 int num_in_flight_decodes, 377 int num_play_throughs, 378 int reset_after_frame_num, 379 int delete_decoder_state, 380 int frame_width, 381 int frame_height, 382 media::VideoCodecProfile profile, 383 double rendering_fps, 384 bool suppress_rendering, 385 int delay_reuse_after_frame_num, 386 int decode_calls_per_second); 387 virtual ~GLRenderingVDAClient(); 388 void CreateAndStartDecoder(); 389 390 // VideoDecodeAccelerator::Client implementation. 391 // The heart of the Client. 392 virtual void ProvidePictureBuffers(uint32 requested_num_of_buffers, 393 const gfx::Size& dimensions, 394 uint32 texture_target) OVERRIDE; 395 virtual void DismissPictureBuffer(int32 picture_buffer_id) OVERRIDE; 396 virtual void PictureReady(const media::Picture& picture) OVERRIDE; 397 // Simple state changes. 398 virtual void NotifyInitializeDone() OVERRIDE; 399 virtual void NotifyEndOfBitstreamBuffer(int32 bitstream_buffer_id) OVERRIDE; 400 virtual void NotifyFlushDone() OVERRIDE; 401 virtual void NotifyResetDone() OVERRIDE; 402 virtual void NotifyError(VideoDecodeAccelerator::Error error) OVERRIDE; 403 404 void OutputFrameDeliveryTimes(base::PlatformFile output); 405 406 void NotifyFrameDropped(int32 picture_buffer_id); 407 408 // Simple getters for inspecting the state of the Client. 409 int num_done_bitstream_buffers() { return num_done_bitstream_buffers_; } 410 int num_skipped_fragments() { return num_skipped_fragments_; } 411 int num_queued_fragments() { return num_queued_fragments_; } 412 int num_decoded_frames(); 413 double frames_per_second(); 414 // Return the median of the decode time in milliseconds. 415 int decode_time_median(); 416 bool decoder_deleted() { return !decoder_.get(); } 417 418 private: 419 typedef std::map<int, media::PictureBuffer*> PictureBufferById; 420 421 void SetState(ClientState new_state); 422 423 // Delete the associated decoder helper. 424 void DeleteDecoder(); 425 426 // Compute & return the first encoded bytes (including a start frame) to send 427 // to the decoder, starting at |start_pos| and returning one fragment. Skips 428 // to the first decodable position. 429 std::string GetBytesForFirstFragment(size_t start_pos, size_t* end_pos); 430 // Compute & return the encoded bytes of next fragment to send to the decoder 431 // (based on |start_pos|). 432 std::string GetBytesForNextFragment(size_t start_pos, size_t* end_pos); 433 // Helpers for GetBytesForNextFragment above. 434 void GetBytesForNextNALU(size_t start_pos, size_t* end_pos); // For h.264. 435 std::string GetBytesForNextFrame( 436 size_t start_pos, size_t* end_pos); // For VP8. 437 438 // Request decode of the next fragment in the encoded data. 439 void DecodeNextFragment(); 440 441 RenderingHelper* rendering_helper_; 442 int rendering_window_id_; 443 std::string encoded_data_; 444 const int num_in_flight_decodes_; 445 int outstanding_decodes_; 446 size_t encoded_data_next_pos_to_decode_; 447 int next_bitstream_buffer_id_; 448 ClientStateNotification<ClientState>* note_; 449 scoped_ptr<VideoDecodeAccelerator> decoder_; 450 std::set<int> outstanding_texture_ids_; 451 int remaining_play_throughs_; 452 int reset_after_frame_num_; 453 int delete_decoder_state_; 454 ClientState state_; 455 int num_skipped_fragments_; 456 int num_queued_fragments_; 457 int num_decoded_frames_; 458 int num_done_bitstream_buffers_; 459 PictureBufferById picture_buffers_by_id_; 460 base::TimeTicks initialize_done_ticks_; 461 media::VideoCodecProfile profile_; 462 GLenum texture_target_; 463 bool suppress_rendering_; 464 std::vector<base::TimeTicks> frame_delivery_times_; 465 int delay_reuse_after_frame_num_; 466 scoped_ptr<ThrottlingVDAClient> throttling_client_; 467 // A map from bitstream buffer id to the decode start time of the buffer. 468 std::map<int, base::TimeTicks> decode_start_time_; 469 // The decode time of all decoded frames. 470 std::vector<base::TimeDelta> decode_time_; 471 // The number of VDA::Decode calls per second. This is to simulate webrtc. 472 int decode_calls_per_second_; 473 474 DISALLOW_IMPLICIT_CONSTRUCTORS(GLRenderingVDAClient); 475 }; 476 477 GLRenderingVDAClient::GLRenderingVDAClient( 478 RenderingHelper* rendering_helper, 479 int rendering_window_id, 480 ClientStateNotification<ClientState>* note, 481 const std::string& encoded_data, 482 int num_in_flight_decodes, 483 int num_play_throughs, 484 int reset_after_frame_num, 485 int delete_decoder_state, 486 int frame_width, 487 int frame_height, 488 media::VideoCodecProfile profile, 489 double rendering_fps, 490 bool suppress_rendering, 491 int delay_reuse_after_frame_num, 492 int decode_calls_per_second) 493 : rendering_helper_(rendering_helper), 494 rendering_window_id_(rendering_window_id), 495 encoded_data_(encoded_data), 496 num_in_flight_decodes_(num_in_flight_decodes), 497 outstanding_decodes_(0), 498 encoded_data_next_pos_to_decode_(0), 499 next_bitstream_buffer_id_(0), 500 note_(note), 501 remaining_play_throughs_(num_play_throughs), 502 reset_after_frame_num_(reset_after_frame_num), 503 delete_decoder_state_(delete_decoder_state), 504 state_(CS_CREATED), 505 num_skipped_fragments_(0), 506 num_queued_fragments_(0), 507 num_decoded_frames_(0), 508 num_done_bitstream_buffers_(0), 509 profile_(profile), 510 texture_target_(0), 511 suppress_rendering_(suppress_rendering), 512 delay_reuse_after_frame_num_(delay_reuse_after_frame_num), 513 decode_calls_per_second_(decode_calls_per_second) { 514 CHECK_GT(num_in_flight_decodes, 0); 515 CHECK_GT(num_play_throughs, 0); 516 CHECK_GE(rendering_fps, 0); 517 // |num_in_flight_decodes_| is unsupported if |decode_calls_per_second_| > 0. 518 if (decode_calls_per_second_ > 0) 519 CHECK_EQ(1, num_in_flight_decodes_); 520 if (rendering_fps > 0) 521 throttling_client_.reset(new ThrottlingVDAClient( 522 this, 523 rendering_fps, 524 base::Bind(&GLRenderingVDAClient::NotifyFrameDropped, 525 base::Unretained(this)))); 526 } 527 528 GLRenderingVDAClient::~GLRenderingVDAClient() { 529 DeleteDecoder(); // Clean up in case of expected error. 530 CHECK(decoder_deleted()); 531 STLDeleteValues(&picture_buffers_by_id_); 532 SetState(CS_DESTROYED); 533 } 534 535 static bool DoNothingReturnTrue() { return true; } 536 537 void GLRenderingVDAClient::CreateAndStartDecoder() { 538 CHECK(decoder_deleted()); 539 CHECK(!decoder_.get()); 540 541 VideoDecodeAccelerator::Client* client = this; 542 base::WeakPtr<VideoDecodeAccelerator::Client> weak_client = AsWeakPtr(); 543 if (throttling_client_) { 544 client = throttling_client_.get(); 545 weak_client = throttling_client_->AsWeakPtr(); 546 } 547 #if defined(OS_WIN) 548 decoder_.reset( 549 new DXVAVideoDecodeAccelerator(client, base::Bind(&DoNothingReturnTrue))); 550 #elif defined(OS_CHROMEOS) 551 #if defined(ARCH_CPU_ARMEL) 552 decoder_.reset(new ExynosVideoDecodeAccelerator( 553 static_cast<EGLDisplay>(rendering_helper_->GetGLDisplay()), 554 static_cast<EGLContext>(rendering_helper_->GetGLContext()), 555 client, 556 weak_client, 557 base::Bind(&DoNothingReturnTrue), 558 base::MessageLoopProxy::current())); 559 #elif defined(ARCH_CPU_X86_FAMILY) 560 decoder_.reset(new VaapiVideoDecodeAccelerator( 561 static_cast<Display*>(rendering_helper_->GetGLDisplay()), 562 static_cast<GLXContext>(rendering_helper_->GetGLContext()), 563 client, 564 base::Bind(&DoNothingReturnTrue))); 565 #endif // ARCH_CPU_ARMEL 566 #endif // OS_WIN 567 CHECK(decoder_.get()); 568 SetState(CS_DECODER_SET); 569 if (decoder_deleted()) 570 return; 571 572 // Configure the decoder. 573 profile_ = (profile_ != media::VIDEO_CODEC_PROFILE_UNKNOWN ? 574 profile_ : media::H264PROFILE_BASELINE); 575 CHECK(decoder_->Initialize(profile_)); 576 } 577 578 void GLRenderingVDAClient::ProvidePictureBuffers( 579 uint32 requested_num_of_buffers, 580 const gfx::Size& dimensions, 581 uint32 texture_target) { 582 if (decoder_deleted()) 583 return; 584 std::vector<media::PictureBuffer> buffers; 585 586 texture_target_ = texture_target; 587 for (uint32 i = 0; i < requested_num_of_buffers; ++i) { 588 uint32 id = picture_buffers_by_id_.size(); 589 uint32 texture_id; 590 base::WaitableEvent done(false, false); 591 rendering_helper_->CreateTexture( 592 rendering_window_id_, texture_target_, &texture_id, &done); 593 done.Wait(); 594 CHECK(outstanding_texture_ids_.insert(texture_id).second); 595 media::PictureBuffer* buffer = 596 new media::PictureBuffer(id, dimensions, texture_id); 597 CHECK(picture_buffers_by_id_.insert(std::make_pair(id, buffer)).second); 598 buffers.push_back(*buffer); 599 } 600 decoder_->AssignPictureBuffers(buffers); 601 } 602 603 void GLRenderingVDAClient::DismissPictureBuffer(int32 picture_buffer_id) { 604 PictureBufferById::iterator it = 605 picture_buffers_by_id_.find(picture_buffer_id); 606 CHECK(it != picture_buffers_by_id_.end()); 607 CHECK_EQ(outstanding_texture_ids_.erase(it->second->texture_id()), 1U); 608 rendering_helper_->DeleteTexture(it->second->texture_id()); 609 delete it->second; 610 picture_buffers_by_id_.erase(it); 611 } 612 613 void GLRenderingVDAClient::PictureReady(const media::Picture& picture) { 614 // We shouldn't be getting pictures delivered after Reset has completed. 615 CHECK_LT(state_, CS_RESET); 616 617 if (decoder_deleted()) 618 return; 619 620 base::TimeTicks now = base::TimeTicks::Now(); 621 frame_delivery_times_.push_back(now); 622 // Save the decode time of this picture. 623 std::map<int, base::TimeTicks>::iterator it = 624 decode_start_time_.find(picture.bitstream_buffer_id()); 625 ASSERT_NE(decode_start_time_.end(), it); 626 decode_time_.push_back(now - it->second); 627 decode_start_time_.erase(it); 628 629 CHECK_LE(picture.bitstream_buffer_id(), next_bitstream_buffer_id_); 630 ++num_decoded_frames_; 631 632 // Mid-stream reset applies only to the last play-through per constructor 633 // comment. 634 if (remaining_play_throughs_ == 1 && 635 reset_after_frame_num_ == num_decoded_frames()) { 636 reset_after_frame_num_ = MID_STREAM_RESET; 637 decoder_->Reset(); 638 // Re-start decoding from the beginning of the stream to avoid needing to 639 // know how to find I-frames and so on in this test. 640 encoded_data_next_pos_to_decode_ = 0; 641 } 642 643 media::PictureBuffer* picture_buffer = 644 picture_buffers_by_id_[picture.picture_buffer_id()]; 645 CHECK(picture_buffer); 646 if (!suppress_rendering_) { 647 rendering_helper_->RenderTexture(texture_target_, 648 picture_buffer->texture_id()); 649 } 650 651 if (num_decoded_frames() > delay_reuse_after_frame_num_) { 652 base::MessageLoop::current()->PostDelayedTask( 653 FROM_HERE, 654 base::Bind(&VideoDecodeAccelerator::ReusePictureBuffer, 655 decoder_->AsWeakPtr(), 656 picture.picture_buffer_id()), 657 kReuseDelay); 658 } else { 659 decoder_->ReusePictureBuffer(picture.picture_buffer_id()); 660 } 661 } 662 663 void GLRenderingVDAClient::NotifyInitializeDone() { 664 SetState(CS_INITIALIZED); 665 initialize_done_ticks_ = base::TimeTicks::Now(); 666 667 if (reset_after_frame_num_ == START_OF_STREAM_RESET) { 668 reset_after_frame_num_ = MID_STREAM_RESET; 669 decoder_->Reset(); 670 return; 671 } 672 673 for (int i = 0; i < num_in_flight_decodes_; ++i) 674 DecodeNextFragment(); 675 DCHECK_EQ(outstanding_decodes_, num_in_flight_decodes_); 676 } 677 678 void GLRenderingVDAClient::NotifyEndOfBitstreamBuffer( 679 int32 bitstream_buffer_id) { 680 // TODO(fischman): this test currently relies on this notification to make 681 // forward progress during a Reset(). But the VDA::Reset() API doesn't 682 // guarantee this, so stop relying on it (and remove the notifications from 683 // VaapiVideoDecodeAccelerator::FinishReset()). 684 ++num_done_bitstream_buffers_; 685 --outstanding_decodes_; 686 if (decode_calls_per_second_ == 0) 687 DecodeNextFragment(); 688 } 689 690 void GLRenderingVDAClient::NotifyFlushDone() { 691 if (decoder_deleted()) 692 return; 693 SetState(CS_FLUSHED); 694 --remaining_play_throughs_; 695 DCHECK_GE(remaining_play_throughs_, 0); 696 if (decoder_deleted()) 697 return; 698 decoder_->Reset(); 699 SetState(CS_RESETTING); 700 } 701 702 void GLRenderingVDAClient::NotifyResetDone() { 703 if (decoder_deleted()) 704 return; 705 706 if (reset_after_frame_num_ == MID_STREAM_RESET) { 707 reset_after_frame_num_ = END_OF_STREAM_RESET; 708 DecodeNextFragment(); 709 return; 710 } else if (reset_after_frame_num_ == START_OF_STREAM_RESET) { 711 reset_after_frame_num_ = END_OF_STREAM_RESET; 712 for (int i = 0; i < num_in_flight_decodes_; ++i) 713 DecodeNextFragment(); 714 return; 715 } 716 717 if (remaining_play_throughs_) { 718 encoded_data_next_pos_to_decode_ = 0; 719 NotifyInitializeDone(); 720 return; 721 } 722 723 SetState(CS_RESET); 724 if (!decoder_deleted()) 725 DeleteDecoder(); 726 } 727 728 void GLRenderingVDAClient::NotifyError(VideoDecodeAccelerator::Error error) { 729 SetState(CS_ERROR); 730 } 731 732 void GLRenderingVDAClient::OutputFrameDeliveryTimes(base::PlatformFile output) { 733 std::string s = base::StringPrintf("frame count: %" PRIuS "\n", 734 frame_delivery_times_.size()); 735 base::WritePlatformFileAtCurrentPos(output, s.data(), s.length()); 736 base::TimeTicks t0 = initialize_done_ticks_; 737 for (size_t i = 0; i < frame_delivery_times_.size(); ++i) { 738 s = base::StringPrintf("frame %04" PRIuS ": %" PRId64 " us\n", 739 i, 740 (frame_delivery_times_[i] - t0).InMicroseconds()); 741 t0 = frame_delivery_times_[i]; 742 base::WritePlatformFileAtCurrentPos(output, s.data(), s.length()); 743 } 744 } 745 746 void GLRenderingVDAClient::NotifyFrameDropped(int32 picture_buffer_id) { 747 decoder_->ReusePictureBuffer(picture_buffer_id); 748 } 749 750 static bool LookingAtNAL(const std::string& encoded, size_t pos) { 751 return encoded[pos] == 0 && encoded[pos + 1] == 0 && 752 encoded[pos + 2] == 0 && encoded[pos + 3] == 1; 753 } 754 755 void GLRenderingVDAClient::SetState(ClientState new_state) { 756 note_->Notify(new_state); 757 state_ = new_state; 758 if (!remaining_play_throughs_ && new_state == delete_decoder_state_) { 759 CHECK(!decoder_deleted()); 760 DeleteDecoder(); 761 } 762 } 763 764 void GLRenderingVDAClient::DeleteDecoder() { 765 if (decoder_deleted()) 766 return; 767 decoder_.release()->Destroy(); 768 STLClearObject(&encoded_data_); 769 for (std::set<int>::iterator it = outstanding_texture_ids_.begin(); 770 it != outstanding_texture_ids_.end(); ++it) { 771 rendering_helper_->DeleteTexture(*it); 772 } 773 outstanding_texture_ids_.clear(); 774 // Cascade through the rest of the states to simplify test code below. 775 for (int i = state_ + 1; i < CS_MAX; ++i) 776 SetState(static_cast<ClientState>(i)); 777 } 778 779 std::string GLRenderingVDAClient::GetBytesForFirstFragment( 780 size_t start_pos, size_t* end_pos) { 781 if (profile_ < media::H264PROFILE_MAX) { 782 *end_pos = start_pos; 783 while (*end_pos + 4 < encoded_data_.size()) { 784 if ((encoded_data_[*end_pos + 4] & 0x1f) == 0x7) // SPS start frame 785 return GetBytesForNextFragment(*end_pos, end_pos); 786 GetBytesForNextNALU(*end_pos, end_pos); 787 num_skipped_fragments_++; 788 } 789 *end_pos = start_pos; 790 return std::string(); 791 } 792 DCHECK_LE(profile_, media::VP8PROFILE_MAX); 793 return GetBytesForNextFragment(start_pos, end_pos); 794 } 795 796 std::string GLRenderingVDAClient::GetBytesForNextFragment( 797 size_t start_pos, size_t* end_pos) { 798 if (profile_ < media::H264PROFILE_MAX) { 799 *end_pos = start_pos; 800 GetBytesForNextNALU(*end_pos, end_pos); 801 if (start_pos != *end_pos) { 802 num_queued_fragments_++; 803 } 804 return encoded_data_.substr(start_pos, *end_pos - start_pos); 805 } 806 DCHECK_LE(profile_, media::VP8PROFILE_MAX); 807 return GetBytesForNextFrame(start_pos, end_pos); 808 } 809 810 void GLRenderingVDAClient::GetBytesForNextNALU( 811 size_t start_pos, size_t* end_pos) { 812 *end_pos = start_pos; 813 if (*end_pos + 4 > encoded_data_.size()) 814 return; 815 CHECK(LookingAtNAL(encoded_data_, start_pos)); 816 *end_pos += 4; 817 while (*end_pos + 4 <= encoded_data_.size() && 818 !LookingAtNAL(encoded_data_, *end_pos)) { 819 ++*end_pos; 820 } 821 if (*end_pos + 3 >= encoded_data_.size()) 822 *end_pos = encoded_data_.size(); 823 } 824 825 std::string GLRenderingVDAClient::GetBytesForNextFrame( 826 size_t start_pos, size_t* end_pos) { 827 // Helpful description: http://wiki.multimedia.cx/index.php?title=IVF 828 std::string bytes; 829 if (start_pos == 0) 830 start_pos = 32; // Skip IVF header. 831 *end_pos = start_pos; 832 uint32 frame_size = *reinterpret_cast<uint32*>(&encoded_data_[*end_pos]); 833 *end_pos += 12; // Skip frame header. 834 bytes.append(encoded_data_.substr(*end_pos, frame_size)); 835 *end_pos += frame_size; 836 num_queued_fragments_++; 837 return bytes; 838 } 839 840 static bool FragmentHasConfigInfo(const uint8* data, size_t size, 841 media::VideoCodecProfile profile) { 842 if (profile >= media::H264PROFILE_MIN && 843 profile <= media::H264PROFILE_MAX) { 844 content::H264Parser parser; 845 parser.SetStream(data, size); 846 content::H264NALU nalu; 847 content::H264Parser::Result result = parser.AdvanceToNextNALU(&nalu); 848 if (result != content::H264Parser::kOk) { 849 // Let the VDA figure out there's something wrong with the stream. 850 return false; 851 } 852 853 return nalu.nal_unit_type == content::H264NALU::kSPS; 854 } else if (profile >= media::VP8PROFILE_MIN && 855 profile <= media::VP8PROFILE_MAX) { 856 return (size > 0 && !(data[0] & 0x01)); 857 } 858 859 CHECK(false) << "Invalid profile"; // Shouldn't happen at this point. 860 return false; 861 } 862 863 void GLRenderingVDAClient::DecodeNextFragment() { 864 if (decoder_deleted()) 865 return; 866 if (encoded_data_next_pos_to_decode_ == encoded_data_.size()) { 867 if (outstanding_decodes_ == 0) { 868 decoder_->Flush(); 869 SetState(CS_FLUSHING); 870 } 871 return; 872 } 873 size_t end_pos; 874 std::string next_fragment_bytes; 875 if (encoded_data_next_pos_to_decode_ == 0) { 876 next_fragment_bytes = GetBytesForFirstFragment(0, &end_pos); 877 } else { 878 next_fragment_bytes = 879 GetBytesForNextFragment(encoded_data_next_pos_to_decode_, &end_pos); 880 } 881 size_t next_fragment_size = next_fragment_bytes.size(); 882 883 // Call Reset() just after Decode() if the fragment contains config info. 884 // This tests how the VDA behaves when it gets a reset request before it has 885 // a chance to ProvidePictureBuffers(). 886 bool reset_here = false; 887 if (reset_after_frame_num_ == RESET_AFTER_FIRST_CONFIG_INFO) { 888 reset_here = FragmentHasConfigInfo( 889 reinterpret_cast<const uint8*>(next_fragment_bytes.data()), 890 next_fragment_size, 891 profile_); 892 if (reset_here) 893 reset_after_frame_num_ = END_OF_STREAM_RESET; 894 } 895 896 // Populate the shared memory buffer w/ the fragment, duplicate its handle, 897 // and hand it off to the decoder. 898 base::SharedMemory shm; 899 CHECK(shm.CreateAndMapAnonymous(next_fragment_size)); 900 memcpy(shm.memory(), next_fragment_bytes.data(), next_fragment_size); 901 base::SharedMemoryHandle dup_handle; 902 CHECK(shm.ShareToProcess(base::Process::Current().handle(), &dup_handle)); 903 media::BitstreamBuffer bitstream_buffer( 904 next_bitstream_buffer_id_, dup_handle, next_fragment_size); 905 decode_start_time_[next_bitstream_buffer_id_] = base::TimeTicks::Now(); 906 // Mask against 30 bits, to avoid (undefined) wraparound on signed integer. 907 next_bitstream_buffer_id_ = (next_bitstream_buffer_id_ + 1) & 0x3FFFFFFF; 908 decoder_->Decode(bitstream_buffer); 909 ++outstanding_decodes_; 910 if (!remaining_play_throughs_ && 911 -delete_decoder_state_ == next_bitstream_buffer_id_) { 912 DeleteDecoder(); 913 } 914 915 if (reset_here) { 916 reset_after_frame_num_ = MID_STREAM_RESET; 917 decoder_->Reset(); 918 // Restart from the beginning to re-Decode() the SPS we just sent. 919 encoded_data_next_pos_to_decode_ = 0; 920 } else { 921 encoded_data_next_pos_to_decode_ = end_pos; 922 } 923 924 if (decode_calls_per_second_ > 0) { 925 base::MessageLoop::current()->PostDelayedTask( 926 FROM_HERE, 927 base::Bind(&GLRenderingVDAClient::DecodeNextFragment, AsWeakPtr()), 928 base::TimeDelta::FromSeconds(1) / decode_calls_per_second_); 929 } 930 } 931 932 int GLRenderingVDAClient::num_decoded_frames() { 933 return throttling_client_ ? throttling_client_->num_decoded_frames() 934 : num_decoded_frames_; 935 } 936 937 double GLRenderingVDAClient::frames_per_second() { 938 base::TimeDelta delta = frame_delivery_times_.back() - initialize_done_ticks_; 939 if (delta.InSecondsF() == 0) 940 return 0; 941 return num_decoded_frames() / delta.InSecondsF(); 942 } 943 944 int GLRenderingVDAClient::decode_time_median() { 945 if (decode_time_.size() == 0) 946 return 0; 947 std::sort(decode_time_.begin(), decode_time_.end()); 948 int index = decode_time_.size() / 2; 949 if (decode_time_.size() % 2 != 0) 950 return decode_time_[index].InMilliseconds(); 951 952 return (decode_time_[index] + decode_time_[index - 1]).InMilliseconds() / 2; 953 } 954 955 class VideoDecodeAcceleratorTest : public ::testing::Test { 956 protected: 957 VideoDecodeAcceleratorTest(); 958 virtual void SetUp(); 959 virtual void TearDown(); 960 961 // Parse |data| into its constituent parts, set the various output fields 962 // accordingly, and read in video stream. CHECK-fails on unexpected or 963 // missing required data. Unspecified optional fields are set to -1. 964 void ParseAndReadTestVideoData(base::FilePath::StringType data, 965 std::vector<TestVideoFile*>* test_video_files); 966 967 // Update the parameters of |test_video_files| according to 968 // |num_concurrent_decoders| and |reset_point|. Ex: the expected number of 969 // frames should be adjusted if decoder is reset in the middle of the stream. 970 void UpdateTestVideoFileParams( 971 size_t num_concurrent_decoders, 972 int reset_point, 973 std::vector<TestVideoFile*>* test_video_files); 974 975 void InitializeRenderingHelper(const RenderingHelperParams& helper_params); 976 void CreateAndStartDecoder(GLRenderingVDAClient* client, 977 ClientStateNotification<ClientState>* note); 978 void WaitUntilDecodeFinish(ClientStateNotification<ClientState>* note); 979 void WaitUntilIdle(); 980 void OutputLogFile(const base::FilePath::CharType* log_path, 981 const std::string& content); 982 983 std::vector<TestVideoFile*> test_video_files_; 984 RenderingHelper rendering_helper_; 985 scoped_refptr<base::MessageLoopProxy> rendering_loop_proxy_; 986 987 private: 988 base::Thread rendering_thread_; 989 // Required for Thread to work. Not used otherwise. 990 base::ShadowingAtExitManager at_exit_manager_; 991 992 DISALLOW_COPY_AND_ASSIGN(VideoDecodeAcceleratorTest); 993 }; 994 995 VideoDecodeAcceleratorTest::VideoDecodeAcceleratorTest() 996 : rendering_thread_("GLRenderingVDAClientThread") {} 997 998 void VideoDecodeAcceleratorTest::SetUp() { 999 ParseAndReadTestVideoData(g_test_video_data, &test_video_files_); 1000 1001 // Initialize the rendering thread. 1002 base::Thread::Options options; 1003 options.message_loop_type = base::MessageLoop::TYPE_DEFAULT; 1004 #if defined(OS_WIN) 1005 // For windows the decoding thread initializes the media foundation decoder 1006 // which uses COM. We need the thread to be a UI thread. 1007 options.message_loop_type = base::MessageLoop::TYPE_UI; 1008 #endif // OS_WIN 1009 1010 rendering_thread_.StartWithOptions(options); 1011 rendering_loop_proxy_ = rendering_thread_.message_loop_proxy(); 1012 } 1013 1014 void VideoDecodeAcceleratorTest::TearDown() { 1015 rendering_loop_proxy_->PostTask( 1016 FROM_HERE, 1017 base::Bind(&STLDeleteElements<std::vector<TestVideoFile*> >, 1018 &test_video_files_)); 1019 1020 base::WaitableEvent done(false, false); 1021 rendering_loop_proxy_->PostTask( 1022 FROM_HERE, 1023 base::Bind(&RenderingHelper::UnInitialize, 1024 base::Unretained(&rendering_helper_), 1025 &done)); 1026 done.Wait(); 1027 1028 rendering_thread_.Stop(); 1029 } 1030 1031 void VideoDecodeAcceleratorTest::ParseAndReadTestVideoData( 1032 base::FilePath::StringType data, 1033 std::vector<TestVideoFile*>* test_video_files) { 1034 std::vector<base::FilePath::StringType> entries; 1035 base::SplitString(data, ';', &entries); 1036 CHECK_GE(entries.size(), 1U) << data; 1037 for (size_t index = 0; index < entries.size(); ++index) { 1038 std::vector<base::FilePath::StringType> fields; 1039 base::SplitString(entries[index], ':', &fields); 1040 CHECK_GE(fields.size(), 1U) << entries[index]; 1041 CHECK_LE(fields.size(), 8U) << entries[index]; 1042 TestVideoFile* video_file = new TestVideoFile(fields[0]); 1043 if (!fields[1].empty()) 1044 CHECK(base::StringToInt(fields[1], &video_file->width)); 1045 if (!fields[2].empty()) 1046 CHECK(base::StringToInt(fields[2], &video_file->height)); 1047 if (!fields[3].empty()) 1048 CHECK(base::StringToInt(fields[3], &video_file->num_frames)); 1049 if (!fields[4].empty()) 1050 CHECK(base::StringToInt(fields[4], &video_file->num_fragments)); 1051 if (!fields[5].empty()) 1052 CHECK(base::StringToInt(fields[5], &video_file->min_fps_render)); 1053 if (!fields[6].empty()) 1054 CHECK(base::StringToInt(fields[6], &video_file->min_fps_no_render)); 1055 int profile = -1; 1056 if (!fields[7].empty()) 1057 CHECK(base::StringToInt(fields[7], &profile)); 1058 video_file->profile = static_cast<media::VideoCodecProfile>(profile); 1059 1060 // Read in the video data. 1061 base::FilePath filepath(video_file->file_name); 1062 CHECK(base::ReadFileToString(filepath, &video_file->data_str)) 1063 << "test_video_file: " << filepath.MaybeAsASCII(); 1064 1065 test_video_files->push_back(video_file); 1066 } 1067 } 1068 1069 void VideoDecodeAcceleratorTest::UpdateTestVideoFileParams( 1070 size_t num_concurrent_decoders, 1071 int reset_point, 1072 std::vector<TestVideoFile*>* test_video_files) { 1073 for (size_t i = 0; i < test_video_files->size(); i++) { 1074 TestVideoFile* video_file = (*test_video_files)[i]; 1075 if (reset_point == MID_STREAM_RESET) { 1076 // Reset should not go beyond the last frame; 1077 // reset in the middle of the stream for short videos. 1078 video_file->reset_after_frame_num = kMaxResetAfterFrameNum; 1079 if (video_file->num_frames <= video_file->reset_after_frame_num) 1080 video_file->reset_after_frame_num = video_file->num_frames / 2; 1081 1082 video_file->num_frames += video_file->reset_after_frame_num; 1083 } else { 1084 video_file->reset_after_frame_num = reset_point; 1085 } 1086 1087 if (video_file->min_fps_render != -1) 1088 video_file->min_fps_render /= num_concurrent_decoders; 1089 if (video_file->min_fps_no_render != -1) 1090 video_file->min_fps_no_render /= num_concurrent_decoders; 1091 } 1092 } 1093 1094 void VideoDecodeAcceleratorTest::InitializeRenderingHelper( 1095 const RenderingHelperParams& helper_params) { 1096 base::WaitableEvent done(false, false); 1097 rendering_loop_proxy_->PostTask( 1098 FROM_HERE, 1099 base::Bind(&RenderingHelper::Initialize, 1100 base::Unretained(&rendering_helper_), 1101 helper_params, 1102 &done)); 1103 done.Wait(); 1104 } 1105 1106 void VideoDecodeAcceleratorTest::CreateAndStartDecoder( 1107 GLRenderingVDAClient* client, 1108 ClientStateNotification<ClientState>* note) { 1109 rendering_loop_proxy_->PostTask( 1110 FROM_HERE, 1111 base::Bind(&GLRenderingVDAClient::CreateAndStartDecoder, 1112 base::Unretained(client))); 1113 ASSERT_EQ(note->Wait(), CS_DECODER_SET); 1114 } 1115 1116 void VideoDecodeAcceleratorTest::WaitUntilDecodeFinish( 1117 ClientStateNotification<ClientState>* note) { 1118 for (int i = 0; i < CS_MAX; i++) { 1119 if (note->Wait() == CS_DESTROYED) 1120 break; 1121 } 1122 } 1123 1124 void VideoDecodeAcceleratorTest::WaitUntilIdle() { 1125 base::WaitableEvent done(false, false); 1126 rendering_loop_proxy_->PostTask( 1127 FROM_HERE, 1128 base::Bind(&base::WaitableEvent::Signal, base::Unretained(&done))); 1129 done.Wait(); 1130 } 1131 1132 void VideoDecodeAcceleratorTest::OutputLogFile( 1133 const base::FilePath::CharType* log_path, 1134 const std::string& content) { 1135 base::PlatformFile file = base::CreatePlatformFile( 1136 base::FilePath(log_path), 1137 base::PLATFORM_FILE_CREATE_ALWAYS | base::PLATFORM_FILE_WRITE, 1138 NULL, 1139 NULL); 1140 base::WritePlatformFileAtCurrentPos(file, content.data(), content.length()); 1141 base::ClosePlatformFile(file); 1142 } 1143 1144 // Test parameters: 1145 // - Number of concurrent decoders. 1146 // - Number of concurrent in-flight Decode() calls per decoder. 1147 // - Number of play-throughs. 1148 // - reset_after_frame_num: see GLRenderingVDAClient ctor. 1149 // - delete_decoder_phase: see GLRenderingVDAClient ctor. 1150 // - whether to test slow rendering by delaying ReusePictureBuffer(). 1151 // - whether the video frames are rendered as thumbnails. 1152 class VideoDecodeAcceleratorParamTest 1153 : public VideoDecodeAcceleratorTest, 1154 public ::testing::WithParamInterface< 1155 Tuple7<int, int, int, ResetPoint, ClientState, bool, bool> > { 1156 }; 1157 1158 // Helper so that gtest failures emit a more readable version of the tuple than 1159 // its byte representation. 1160 ::std::ostream& operator<<( 1161 ::std::ostream& os, 1162 const Tuple7<int, int, int, ResetPoint, ClientState, bool, bool>& t) { 1163 return os << t.a << ", " << t.b << ", " << t.c << ", " << t.d << ", " << t.e 1164 << ", " << t.f << ", " << t.g; 1165 } 1166 1167 // Wait for |note| to report a state and if it's not |expected_state| then 1168 // assert |client| has deleted its decoder. 1169 static void AssertWaitForStateOrDeleted( 1170 ClientStateNotification<ClientState>* note, 1171 GLRenderingVDAClient* client, 1172 ClientState expected_state) { 1173 ClientState state = note->Wait(); 1174 if (state == expected_state) return; 1175 ASSERT_TRUE(client->decoder_deleted()) 1176 << "Decoder not deleted but Wait() returned " << state 1177 << ", instead of " << expected_state; 1178 } 1179 1180 // We assert a minimal number of concurrent decoders we expect to succeed. 1181 // Different platforms can support more concurrent decoders, so we don't assert 1182 // failure above this. 1183 enum { kMinSupportedNumConcurrentDecoders = 3 }; 1184 1185 // Test the most straightforward case possible: data is decoded from a single 1186 // chunk and rendered to the screen. 1187 TEST_P(VideoDecodeAcceleratorParamTest, TestSimpleDecode) { 1188 const size_t num_concurrent_decoders = GetParam().a; 1189 const size_t num_in_flight_decodes = GetParam().b; 1190 const int num_play_throughs = GetParam().c; 1191 const int reset_point = GetParam().d; 1192 const int delete_decoder_state = GetParam().e; 1193 bool test_reuse_delay = GetParam().f; 1194 const bool render_as_thumbnails = GetParam().g; 1195 1196 UpdateTestVideoFileParams( 1197 num_concurrent_decoders, reset_point, &test_video_files_); 1198 1199 // Suppress GL rendering for all tests when the "--disable_rendering" is set. 1200 const bool suppress_rendering = g_disable_rendering; 1201 1202 std::vector<ClientStateNotification<ClientState>*> 1203 notes(num_concurrent_decoders, NULL); 1204 std::vector<GLRenderingVDAClient*> clients(num_concurrent_decoders, NULL); 1205 1206 RenderingHelperParams helper_params; 1207 helper_params.num_windows = num_concurrent_decoders; 1208 helper_params.render_as_thumbnails = render_as_thumbnails; 1209 if (render_as_thumbnails) { 1210 // Only one decoder is supported with thumbnail rendering 1211 CHECK_EQ(num_concurrent_decoders, 1U); 1212 gfx::Size frame_size(test_video_files_[0]->width, 1213 test_video_files_[0]->height); 1214 helper_params.frame_dimensions.push_back(frame_size); 1215 helper_params.window_dimensions.push_back(kThumbnailsDisplaySize); 1216 helper_params.thumbnails_page_size = kThumbnailsPageSize; 1217 helper_params.thumbnail_size = kThumbnailSize; 1218 } else { 1219 for (size_t index = 0; index < test_video_files_.size(); ++index) { 1220 gfx::Size frame_size(test_video_files_[index]->width, 1221 test_video_files_[index]->height); 1222 helper_params.frame_dimensions.push_back(frame_size); 1223 helper_params.window_dimensions.push_back(frame_size); 1224 } 1225 } 1226 InitializeRenderingHelper(helper_params); 1227 1228 // First kick off all the decoders. 1229 for (size_t index = 0; index < num_concurrent_decoders; ++index) { 1230 TestVideoFile* video_file = 1231 test_video_files_[index % test_video_files_.size()]; 1232 ClientStateNotification<ClientState>* note = 1233 new ClientStateNotification<ClientState>(); 1234 notes[index] = note; 1235 1236 int delay_after_frame_num = std::numeric_limits<int>::max(); 1237 if (test_reuse_delay && 1238 kMaxFramesToDelayReuse * 2 < video_file->num_frames) { 1239 delay_after_frame_num = video_file->num_frames - kMaxFramesToDelayReuse; 1240 } 1241 1242 GLRenderingVDAClient* client = 1243 new GLRenderingVDAClient(&rendering_helper_, 1244 index, 1245 note, 1246 video_file->data_str, 1247 num_in_flight_decodes, 1248 num_play_throughs, 1249 video_file->reset_after_frame_num, 1250 delete_decoder_state, 1251 video_file->width, 1252 video_file->height, 1253 video_file->profile, 1254 g_rendering_fps, 1255 suppress_rendering, 1256 delay_after_frame_num, 1257 0); 1258 clients[index] = client; 1259 1260 CreateAndStartDecoder(client, note); 1261 } 1262 // Then wait for all the decodes to finish. 1263 // Only check performance & correctness later if we play through only once. 1264 bool skip_performance_and_correctness_checks = num_play_throughs > 1; 1265 for (size_t i = 0; i < num_concurrent_decoders; ++i) { 1266 ClientStateNotification<ClientState>* note = notes[i]; 1267 ClientState state = note->Wait(); 1268 if (state != CS_INITIALIZED) { 1269 skip_performance_and_correctness_checks = true; 1270 // We expect initialization to fail only when more than the supported 1271 // number of decoders is instantiated. Assert here that something else 1272 // didn't trigger failure. 1273 ASSERT_GT(num_concurrent_decoders, 1274 static_cast<size_t>(kMinSupportedNumConcurrentDecoders)); 1275 continue; 1276 } 1277 ASSERT_EQ(state, CS_INITIALIZED); 1278 for (int n = 0; n < num_play_throughs; ++n) { 1279 // For play-throughs other than the first, we expect initialization to 1280 // succeed unconditionally. 1281 if (n > 0) { 1282 ASSERT_NO_FATAL_FAILURE( 1283 AssertWaitForStateOrDeleted(note, clients[i], CS_INITIALIZED)); 1284 } 1285 // InitializeDone kicks off decoding inside the client, so we just need to 1286 // wait for Flush. 1287 ASSERT_NO_FATAL_FAILURE( 1288 AssertWaitForStateOrDeleted(note, clients[i], CS_FLUSHING)); 1289 ASSERT_NO_FATAL_FAILURE( 1290 AssertWaitForStateOrDeleted(note, clients[i], CS_FLUSHED)); 1291 // FlushDone requests Reset(). 1292 ASSERT_NO_FATAL_FAILURE( 1293 AssertWaitForStateOrDeleted(note, clients[i], CS_RESETTING)); 1294 } 1295 ASSERT_NO_FATAL_FAILURE( 1296 AssertWaitForStateOrDeleted(note, clients[i], CS_RESET)); 1297 // ResetDone requests Destroy(). 1298 ASSERT_NO_FATAL_FAILURE( 1299 AssertWaitForStateOrDeleted(note, clients[i], CS_DESTROYED)); 1300 } 1301 // Finally assert that decoding went as expected. 1302 for (size_t i = 0; i < num_concurrent_decoders && 1303 !skip_performance_and_correctness_checks; ++i) { 1304 // We can only make performance/correctness assertions if the decoder was 1305 // allowed to finish. 1306 if (delete_decoder_state < CS_FLUSHED) 1307 continue; 1308 GLRenderingVDAClient* client = clients[i]; 1309 TestVideoFile* video_file = test_video_files_[i % test_video_files_.size()]; 1310 if (video_file->num_frames > 0) { 1311 // Expect the decoded frames may be more than the video frames as frames 1312 // could still be returned until resetting done. 1313 if (video_file->reset_after_frame_num > 0) 1314 EXPECT_GE(client->num_decoded_frames(), video_file->num_frames); 1315 else 1316 EXPECT_EQ(client->num_decoded_frames(), video_file->num_frames); 1317 } 1318 if (reset_point == END_OF_STREAM_RESET) { 1319 EXPECT_EQ(video_file->num_fragments, client->num_skipped_fragments() + 1320 client->num_queued_fragments()); 1321 EXPECT_EQ(client->num_done_bitstream_buffers(), 1322 client->num_queued_fragments()); 1323 } 1324 VLOG(0) << "Decoder " << i << " fps: " << client->frames_per_second(); 1325 if (!render_as_thumbnails) { 1326 int min_fps = suppress_rendering ? 1327 video_file->min_fps_no_render : video_file->min_fps_render; 1328 if (min_fps > 0 && !test_reuse_delay) 1329 EXPECT_GT(client->frames_per_second(), min_fps); 1330 } 1331 } 1332 1333 if (render_as_thumbnails) { 1334 std::vector<unsigned char> rgb; 1335 bool alpha_solid; 1336 base::WaitableEvent done(false, false); 1337 rendering_loop_proxy_->PostTask( 1338 FROM_HERE, 1339 base::Bind(&RenderingHelper::GetThumbnailsAsRGB, 1340 base::Unretained(&rendering_helper_), 1341 &rgb, &alpha_solid, &done)); 1342 done.Wait(); 1343 1344 std::vector<std::string> golden_md5s; 1345 std::string md5_string = base::MD5String( 1346 base::StringPiece(reinterpret_cast<char*>(&rgb[0]), rgb.size())); 1347 ReadGoldenThumbnailMD5s(test_video_files_[0], &golden_md5s); 1348 std::vector<std::string>::iterator match = 1349 find(golden_md5s.begin(), golden_md5s.end(), md5_string); 1350 if (match == golden_md5s.end()) { 1351 // Convert raw RGB into PNG for export. 1352 std::vector<unsigned char> png; 1353 gfx::PNGCodec::Encode(&rgb[0], 1354 gfx::PNGCodec::FORMAT_RGB, 1355 kThumbnailsPageSize, 1356 kThumbnailsPageSize.width() * 3, 1357 true, 1358 std::vector<gfx::PNGCodec::Comment>(), 1359 &png); 1360 1361 LOG(ERROR) << "Unknown thumbnails MD5: " << md5_string; 1362 1363 base::FilePath filepath(test_video_files_[0]->file_name); 1364 filepath = filepath.AddExtension(FILE_PATH_LITERAL(".bad_thumbnails")); 1365 filepath = filepath.AddExtension(FILE_PATH_LITERAL(".png")); 1366 int num_bytes = file_util::WriteFile(filepath, 1367 reinterpret_cast<char*>(&png[0]), 1368 png.size()); 1369 ASSERT_EQ(num_bytes, static_cast<int>(png.size())); 1370 } 1371 ASSERT_NE(match, golden_md5s.end()); 1372 EXPECT_EQ(alpha_solid, true) << "RGBA frame had incorrect alpha"; 1373 } 1374 1375 // Output the frame delivery time to file 1376 // We can only make performance/correctness assertions if the decoder was 1377 // allowed to finish. 1378 if (g_output_log != NULL && delete_decoder_state >= CS_FLUSHED) { 1379 base::PlatformFile output_file = base::CreatePlatformFile( 1380 base::FilePath(g_output_log), 1381 base::PLATFORM_FILE_CREATE_ALWAYS | base::PLATFORM_FILE_WRITE, 1382 NULL, 1383 NULL); 1384 for (size_t i = 0; i < num_concurrent_decoders; ++i) { 1385 clients[i]->OutputFrameDeliveryTimes(output_file); 1386 } 1387 base::ClosePlatformFile(output_file); 1388 } 1389 1390 rendering_loop_proxy_->PostTask( 1391 FROM_HERE, 1392 base::Bind(&STLDeleteElements<std::vector<GLRenderingVDAClient*> >, 1393 &clients)); 1394 rendering_loop_proxy_->PostTask( 1395 FROM_HERE, 1396 base::Bind(&STLDeleteElements< 1397 std::vector<ClientStateNotification<ClientState>*> >, 1398 ¬es)); 1399 WaitUntilIdle(); 1400 }; 1401 1402 // Test that replay after EOS works fine. 1403 INSTANTIATE_TEST_CASE_P( 1404 ReplayAfterEOS, VideoDecodeAcceleratorParamTest, 1405 ::testing::Values( 1406 MakeTuple(1, 1, 4, END_OF_STREAM_RESET, CS_RESET, false, false))); 1407 1408 // Test that Reset() before the first Decode() works fine. 1409 INSTANTIATE_TEST_CASE_P( 1410 ResetBeforeDecode, VideoDecodeAcceleratorParamTest, 1411 ::testing::Values( 1412 MakeTuple(1, 1, 1, START_OF_STREAM_RESET, CS_RESET, false, false))); 1413 1414 // Test Reset() immediately after Decode() containing config info. 1415 INSTANTIATE_TEST_CASE_P( 1416 ResetAfterFirstConfigInfo, VideoDecodeAcceleratorParamTest, 1417 ::testing::Values( 1418 MakeTuple( 1419 1, 1, 1, RESET_AFTER_FIRST_CONFIG_INFO, CS_RESET, false, false))); 1420 1421 // Test that Reset() mid-stream works fine and doesn't affect decoding even when 1422 // Decode() calls are made during the reset. 1423 INSTANTIATE_TEST_CASE_P( 1424 MidStreamReset, VideoDecodeAcceleratorParamTest, 1425 ::testing::Values( 1426 MakeTuple(1, 1, 1, MID_STREAM_RESET, CS_RESET, false, false))); 1427 1428 INSTANTIATE_TEST_CASE_P( 1429 SlowRendering, VideoDecodeAcceleratorParamTest, 1430 ::testing::Values( 1431 MakeTuple(1, 1, 1, END_OF_STREAM_RESET, CS_RESET, true, false))); 1432 1433 // Test that Destroy() mid-stream works fine (primarily this is testing that no 1434 // crashes occur). 1435 INSTANTIATE_TEST_CASE_P( 1436 TearDownTiming, VideoDecodeAcceleratorParamTest, 1437 ::testing::Values( 1438 MakeTuple(1, 1, 1, END_OF_STREAM_RESET, CS_DECODER_SET, false, false), 1439 MakeTuple(1, 1, 1, END_OF_STREAM_RESET, CS_INITIALIZED, false, false), 1440 MakeTuple(1, 1, 1, END_OF_STREAM_RESET, CS_FLUSHING, false, false), 1441 MakeTuple(1, 1, 1, END_OF_STREAM_RESET, CS_FLUSHED, false, false), 1442 MakeTuple(1, 1, 1, END_OF_STREAM_RESET, CS_RESETTING, false, false), 1443 MakeTuple(1, 1, 1, END_OF_STREAM_RESET, CS_RESET, false, false), 1444 MakeTuple(1, 1, 1, END_OF_STREAM_RESET, 1445 static_cast<ClientState>(-1), false, false), 1446 MakeTuple(1, 1, 1, END_OF_STREAM_RESET, 1447 static_cast<ClientState>(-10), false, false), 1448 MakeTuple(1, 1, 1, END_OF_STREAM_RESET, 1449 static_cast<ClientState>(-100), false, false))); 1450 1451 // Test that decoding various variation works with multiple in-flight decodes. 1452 INSTANTIATE_TEST_CASE_P( 1453 DecodeVariations, VideoDecodeAcceleratorParamTest, 1454 ::testing::Values( 1455 MakeTuple(1, 1, 1, END_OF_STREAM_RESET, CS_RESET, false, false), 1456 MakeTuple(1, 10, 1, END_OF_STREAM_RESET, CS_RESET, false, false), 1457 // Tests queuing. 1458 MakeTuple(1, 15, 1, END_OF_STREAM_RESET, CS_RESET, false, false))); 1459 1460 // Find out how many concurrent decoders can go before we exhaust system 1461 // resources. 1462 INSTANTIATE_TEST_CASE_P( 1463 ResourceExhaustion, VideoDecodeAcceleratorParamTest, 1464 ::testing::Values( 1465 // +0 hack below to promote enum to int. 1466 MakeTuple(kMinSupportedNumConcurrentDecoders + 0, 1, 1, 1467 END_OF_STREAM_RESET, CS_RESET, false, false), 1468 MakeTuple(kMinSupportedNumConcurrentDecoders + 1, 1, 1, 1469 END_OF_STREAM_RESET, CS_RESET, false, false))); 1470 1471 // Thumbnailing test 1472 INSTANTIATE_TEST_CASE_P( 1473 Thumbnail, VideoDecodeAcceleratorParamTest, 1474 ::testing::Values( 1475 MakeTuple(1, 1, 1, END_OF_STREAM_RESET, CS_RESET, false, true))); 1476 1477 // Measure the median of the decode time when VDA::Decode is called 30 times per 1478 // second. 1479 TEST_F(VideoDecodeAcceleratorTest, TestDecodeTimeMedian) { 1480 RenderingHelperParams helper_params; 1481 helper_params.num_windows = 1; 1482 helper_params.render_as_thumbnails = false; 1483 gfx::Size frame_size(test_video_files_[0]->width, 1484 test_video_files_[0]->height); 1485 helper_params.frame_dimensions.push_back(frame_size); 1486 helper_params.window_dimensions.push_back(frame_size); 1487 InitializeRenderingHelper(helper_params); 1488 1489 ClientStateNotification<ClientState>* note = 1490 new ClientStateNotification<ClientState>(); 1491 GLRenderingVDAClient* client = 1492 new GLRenderingVDAClient(&rendering_helper_, 1493 0, 1494 note, 1495 test_video_files_[0]->data_str, 1496 1, 1497 1, 1498 test_video_files_[0]->reset_after_frame_num, 1499 CS_RESET, 1500 test_video_files_[0]->width, 1501 test_video_files_[0]->height, 1502 test_video_files_[0]->profile, 1503 g_rendering_fps, 1504 true, 1505 std::numeric_limits<int>::max(), 1506 kWebRtcDecodeCallsPerSecond); 1507 CreateAndStartDecoder(client, note); 1508 WaitUntilDecodeFinish(note); 1509 1510 int decode_time_median = client->decode_time_median(); 1511 std::string output_string = 1512 base::StringPrintf("Decode time median: %d ms", decode_time_median); 1513 VLOG(0) << output_string; 1514 ASSERT_GT(decode_time_median, 0); 1515 1516 if (g_output_log != NULL) 1517 OutputLogFile(g_output_log, output_string); 1518 1519 rendering_loop_proxy_->DeleteSoon(FROM_HERE, client); 1520 rendering_loop_proxy_->DeleteSoon(FROM_HERE, note); 1521 WaitUntilIdle(); 1522 }; 1523 1524 // TODO(fischman, vrk): add more tests! In particular: 1525 // - Test life-cycle: Seek/Stop/Pause/Play for a single decoder. 1526 // - Test alternate configurations 1527 // - Test failure conditions. 1528 // - Test frame size changes mid-stream 1529 1530 } // namespace 1531 } // namespace content 1532 1533 int main(int argc, char **argv) { 1534 testing::InitGoogleTest(&argc, argv); // Removes gtest-specific args. 1535 CommandLine::Init(argc, argv); 1536 1537 // Needed to enable DVLOG through --vmodule. 1538 logging::LoggingSettings settings; 1539 settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG; 1540 settings.dcheck_state = 1541 logging::ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS; 1542 CHECK(logging::InitLogging(settings)); 1543 1544 CommandLine* cmd_line = CommandLine::ForCurrentProcess(); 1545 DCHECK(cmd_line); 1546 1547 CommandLine::SwitchMap switches = cmd_line->GetSwitches(); 1548 for (CommandLine::SwitchMap::const_iterator it = switches.begin(); 1549 it != switches.end(); ++it) { 1550 if (it->first == "test_video_data") { 1551 content::g_test_video_data = it->second.c_str(); 1552 continue; 1553 } 1554 // TODO(wuchengli): remove frame_deliver_log after CrOS test get updated. 1555 // See http://crosreview.com/175426. 1556 if (it->first == "frame_delivery_log" || it->first == "output_log") { 1557 content::g_output_log = it->second.c_str(); 1558 continue; 1559 } 1560 if (it->first == "rendering_fps") { 1561 // On Windows, CommandLine::StringType is wstring. We need to convert 1562 // it to std::string first 1563 std::string input(it->second.begin(), it->second.end()); 1564 CHECK(base::StringToDouble(input, &content::g_rendering_fps)); 1565 continue; 1566 } 1567 if (it->first == "disable_rendering") { 1568 content::g_disable_rendering = true; 1569 continue; 1570 } 1571 if (it->first == "v" || it->first == "vmodule") 1572 continue; 1573 LOG(FATAL) << "Unexpected switch: " << it->first << ":" << it->second; 1574 } 1575 1576 base::ShadowingAtExitManager at_exit_manager; 1577 1578 return RUN_ALL_TESTS(); 1579 } 1580