DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (c68fe15a81fc)

VCS Links

Line Code
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
/*
/*
 *  Copyright 2016 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */
 */


#include "video/receive_statistics_proxy.h"

#include <limits>
#include <limits>
#include <memory>
#include <utility>

#include "api/video/i420_buffer.h"
#include "api/video/video_frame.h"
#include "api/video/video_frame.h"
#include "api/video/video_rotation.h"
#include "modules/video_coding/include/video_codec_interface.h"
#include "system_wrappers/include/metrics.h"
#include "system_wrappers/include/metrics_default.h"
#include "test/gtest.h"
#include "test/gtest.h"

namespace webrtc {
namespace {
const int64_t kFreqOffsetProcessIntervalInMs = 40000;
const int64_t kFreqOffsetProcessIntervalInMs = 40000;
const uint32_t kLocalSsrc = 123;
const uint32_t kRemoteSsrc = 456;
const int kMinRequiredSamples = 200;
}  // namespace


// TODO(sakal): ReceiveStatisticsProxy is lacking unittesting.
class ReceiveStatisticsProxyTest
    : public ::testing::TestWithParam<webrtc::VideoContentType> {
 public:
  ReceiveStatisticsProxyTest() : fake_clock_(1234), config_(GetTestConfig()) {}
  ReceiveStatisticsProxyTest() : fake_clock_(1234), config_(GetTestConfig()) {}
  virtual ~ReceiveStatisticsProxyTest() {}

 protected:
  virtual void SetUp() {
    metrics::Reset();
    metrics::Reset();
    statistics_proxy_.reset(new ReceiveStatisticsProxy(&config_, &fake_clock_));
  }

  VideoReceiveStream::Config GetTestConfig() {
    VideoReceiveStream::Config config(nullptr);
    VideoReceiveStream::Config config(nullptr);
    config.rtp.local_ssrc = kLocalSsrc;
    config.rtp.remote_ssrc = kRemoteSsrc;
    return config;
  }


  void InsertFirstRtpPacket(uint32_t ssrc) {
    StreamDataCounters counters;
    counters.first_packet_time_ms = fake_clock_.TimeInMilliseconds();
    statistics_proxy_->DataCountersUpdated(counters, ssrc);
  }
  }

  VideoFrame CreateFrame(int width, int height) {
    VideoFrame frame(I420Buffer::Create(width, height), 0, 0, kVideoRotation_0);
    frame.set_ntp_time_ms(fake_clock_.CurrentNtpInMilliseconds());
    frame.set_ntp_time_ms(fake_clock_.CurrentNtpInMilliseconds());
    return frame;
  }

  SimulatedClock fake_clock_;
  const VideoReceiveStream::Config config_;
  const VideoReceiveStream::Config config_;
  std::unique_ptr<ReceiveStatisticsProxy> statistics_proxy_;
};

TEST_F(ReceiveStatisticsProxyTest, OnDecodedFrameIncreasesFramesDecoded) {
  EXPECT_EQ(0u, statistics_proxy_->GetStats().frames_decoded);
  for (uint32_t i = 1; i <= 3; ++i) {
    statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(),
    statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(),
                                      VideoContentType::UNSPECIFIED);
    EXPECT_EQ(i, statistics_proxy_->GetStats().frames_decoded);
  }
}


TEST_F(ReceiveStatisticsProxyTest, OnDecodedFrameWithQpResetsFramesDecoded) {
  EXPECT_EQ(0u, statistics_proxy_->GetStats().frames_decoded);
  for (uint32_t i = 1; i <= 3; ++i) {
    statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(),
                                      VideoContentType::UNSPECIFIED);
                                      VideoContentType::UNSPECIFIED);
    EXPECT_EQ(i, statistics_proxy_->GetStats().frames_decoded);
  }
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(1u),
                                    VideoContentType::UNSPECIFIED);
  EXPECT_EQ(1u, statistics_proxy_->GetStats().frames_decoded);
  EXPECT_EQ(1u, statistics_proxy_->GetStats().frames_decoded);
}

TEST_F(ReceiveStatisticsProxyTest, OnDecodedFrameIncreasesQpSum) {
  EXPECT_EQ(rtc::Optional<uint64_t>(), statistics_proxy_->GetStats().qp_sum);
  EXPECT_EQ(rtc::Optional<uint64_t>(), statistics_proxy_->GetStats().qp_sum);
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(3u),
                                    VideoContentType::UNSPECIFIED);
  EXPECT_EQ(rtc::Optional<uint64_t>(3u), statistics_proxy_->GetStats().qp_sum);
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(127u),
                                    VideoContentType::UNSPECIFIED);
                                    VideoContentType::UNSPECIFIED);
  EXPECT_EQ(rtc::Optional<uint64_t>(130u),
            statistics_proxy_->GetStats().qp_sum);
}


TEST_F(ReceiveStatisticsProxyTest, ReportsContentType) {
  const std::string kRealtimeString("realtime");
  const std::string kScreenshareString("screen");
  EXPECT_EQ(kRealtimeString, videocontenttypehelpers::ToString(
                            statistics_proxy_->GetStats().content_type));
                            statistics_proxy_->GetStats().content_type));
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(3u),
                                    VideoContentType::SCREENSHARE);
  EXPECT_EQ(kScreenshareString, videocontenttypehelpers::ToString(
                          statistics_proxy_->GetStats().content_type));
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(3u),
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(3u),
                                    VideoContentType::UNSPECIFIED);
  EXPECT_EQ(kRealtimeString, videocontenttypehelpers::ToString(
                            statistics_proxy_->GetStats().content_type));
}


TEST_F(ReceiveStatisticsProxyTest, ReportsMaxInterframeDelay) {
  const int64_t kInterframeDelayMs1 = 100;
  const int64_t kInterframeDelayMs2 = 200;
  const int64_t kInterframeDelayMs3 = 100;
  EXPECT_EQ(-1, statistics_proxy_->GetStats().interframe_delay_max_ms);
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(3u),
                                    VideoContentType::UNSPECIFIED);
  EXPECT_EQ(-1, statistics_proxy_->GetStats().interframe_delay_max_ms);
  EXPECT_EQ(-1, statistics_proxy_->GetStats().interframe_delay_max_ms);

  fake_clock_.AdvanceTimeMilliseconds(kInterframeDelayMs1);
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(127u),
                                    VideoContentType::UNSPECIFIED);
  EXPECT_EQ(kInterframeDelayMs1,
  EXPECT_EQ(kInterframeDelayMs1,
            statistics_proxy_->GetStats().interframe_delay_max_ms);

  fake_clock_.AdvanceTimeMilliseconds(kInterframeDelayMs2);
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(127u),
                                    VideoContentType::UNSPECIFIED);
                                    VideoContentType::UNSPECIFIED);
  EXPECT_EQ(kInterframeDelayMs2,
            statistics_proxy_->GetStats().interframe_delay_max_ms);

  fake_clock_.AdvanceTimeMilliseconds(kInterframeDelayMs3);
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(127u),
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(127u),
                                    VideoContentType::UNSPECIFIED);
  // kInterframeDelayMs3 is smaller than kInterframeDelayMs2.
  EXPECT_EQ(kInterframeDelayMs2,
            statistics_proxy_->GetStats().interframe_delay_max_ms);
}
}

TEST_F(ReceiveStatisticsProxyTest, ReportInterframeDelayInWindow) {
  const int64_t kInterframeDelayMs1 = 900;
  const int64_t kInterframeDelayMs2 = 750;
  const int64_t kInterframeDelayMs3 = 700;
  const int64_t kInterframeDelayMs3 = 700;
  EXPECT_EQ(-1, statistics_proxy_->GetStats().interframe_delay_max_ms);
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(3u),
                                    VideoContentType::UNSPECIFIED);
  EXPECT_EQ(-1, statistics_proxy_->GetStats().interframe_delay_max_ms);


  fake_clock_.AdvanceTimeMilliseconds(kInterframeDelayMs1);
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(127u),
                                    VideoContentType::UNSPECIFIED);
  EXPECT_EQ(kInterframeDelayMs1,
            statistics_proxy_->GetStats().interframe_delay_max_ms);
            statistics_proxy_->GetStats().interframe_delay_max_ms);

  fake_clock_.AdvanceTimeMilliseconds(kInterframeDelayMs2);
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(127u),
                                    VideoContentType::UNSPECIFIED);
                                    VideoContentType::UNSPECIFIED);
  // Still first delay is the maximum
  EXPECT_EQ(kInterframeDelayMs1,
            statistics_proxy_->GetStats().interframe_delay_max_ms);

  fake_clock_.AdvanceTimeMilliseconds(kInterframeDelayMs3);
  fake_clock_.AdvanceTimeMilliseconds(kInterframeDelayMs3);
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(127u),
                                    VideoContentType::UNSPECIFIED);
  // Now the first sample is out of the window, so the second is the maximum.
  EXPECT_EQ(kInterframeDelayMs2,
            statistics_proxy_->GetStats().interframe_delay_max_ms);
            statistics_proxy_->GetStats().interframe_delay_max_ms);
}

TEST_F(ReceiveStatisticsProxyTest, OnDecodedFrameWithoutQpQpSumWontExist) {
  EXPECT_EQ(rtc::Optional<uint64_t>(), statistics_proxy_->GetStats().qp_sum);
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(),
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(),
                                    VideoContentType::UNSPECIFIED);
  EXPECT_EQ(rtc::Optional<uint64_t>(), statistics_proxy_->GetStats().qp_sum);
}

TEST_F(ReceiveStatisticsProxyTest, OnDecodedFrameWithoutQpResetsQpSum) {
TEST_F(ReceiveStatisticsProxyTest, OnDecodedFrameWithoutQpResetsQpSum) {
  EXPECT_EQ(rtc::Optional<uint64_t>(), statistics_proxy_->GetStats().qp_sum);
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(3u),
                                    VideoContentType::UNSPECIFIED);
  EXPECT_EQ(rtc::Optional<uint64_t>(3u), statistics_proxy_->GetStats().qp_sum);
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(),
                                    VideoContentType::UNSPECIFIED);
                                    VideoContentType::UNSPECIFIED);
  EXPECT_EQ(rtc::Optional<uint64_t>(), statistics_proxy_->GetStats().qp_sum);
}

TEST_F(ReceiveStatisticsProxyTest, OnRenderedFrameIncreasesFramesRendered) {
  EXPECT_EQ(0u, statistics_proxy_->GetStats().frames_rendered);
  webrtc::VideoFrame frame(webrtc::I420Buffer::Create(1, 1), 0, 0,
                           webrtc::kVideoRotation_0);
                           webrtc::kVideoRotation_0);
  for (uint32_t i = 1; i <= 3; ++i) {
    statistics_proxy_->OnRenderedFrame(frame);
    EXPECT_EQ(i, statistics_proxy_->GetStats().frames_rendered);
  }
}
}

TEST_F(ReceiveStatisticsProxyTest, GetStatsReportsSsrc) {
  EXPECT_EQ(kRemoteSsrc, statistics_proxy_->GetStats().ssrc);
}


TEST_F(ReceiveStatisticsProxyTest, GetStatsReportsIncomingPayloadType) {
  const int kPayloadType = 111;
  statistics_proxy_->OnIncomingPayloadType(kPayloadType);
  EXPECT_EQ(kPayloadType, statistics_proxy_->GetStats().current_payload_type);
}
}

TEST_F(ReceiveStatisticsProxyTest, GetStatsReportsDecoderImplementationName) {
  const char* kName = "decoderName";
  statistics_proxy_->OnDecoderImplementationName(kName);
  EXPECT_STREQ(
  EXPECT_STREQ(
      kName, statistics_proxy_->GetStats().decoder_implementation_name.c_str());
      kName, statistics_proxy_->GetStats().decoder_implementation_name.c_str());
}

TEST_F(ReceiveStatisticsProxyTest, GetStatsReportsOnCompleteFrame) {
  const int kFrameSizeBytes = 1000;
  statistics_proxy_->OnCompleteFrame(true, kFrameSizeBytes,
  statistics_proxy_->OnCompleteFrame(true, kFrameSizeBytes,
                                     VideoContentType::UNSPECIFIED);
  VideoReceiveStream::Stats stats = statistics_proxy_->GetStats();
  EXPECT_EQ(1, stats.network_frame_rate);
  EXPECT_EQ(1, stats.frame_counts.key_frames);
  EXPECT_EQ(0, stats.frame_counts.delta_frames);
  EXPECT_EQ(0, stats.frame_counts.delta_frames);
}

TEST_F(ReceiveStatisticsProxyTest, GetStatsReportsDecodeTimingStats) {
  const int kDecodeMs = 1;
  const int kMaxDecodeMs = 2;
  const int kMaxDecodeMs = 2;
  const int kCurrentDelayMs = 3;
  const int kTargetDelayMs = 4;
  const int kJitterBufferMs = 5;
  const int kMinPlayoutDelayMs = 6;
  const int kMinPlayoutDelayMs = 6;
  const int kRenderDelayMs = 7;
  const int64_t kRttMs = 8;
  statistics_proxy_->OnRttUpdate(kRttMs, 0);
  statistics_proxy_->OnFrameBufferTimingsUpdated(
      kDecodeMs, kMaxDecodeMs, kCurrentDelayMs, kTargetDelayMs, kJitterBufferMs,
      kDecodeMs, kMaxDecodeMs, kCurrentDelayMs, kTargetDelayMs, kJitterBufferMs,
      kMinPlayoutDelayMs, kRenderDelayMs);
  VideoReceiveStream::Stats stats = statistics_proxy_->GetStats();
  EXPECT_EQ(kDecodeMs, stats.decode_ms);
  EXPECT_EQ(kMaxDecodeMs, stats.max_decode_ms);
  EXPECT_EQ(kCurrentDelayMs, stats.current_delay_ms);
  EXPECT_EQ(kCurrentDelayMs, stats.current_delay_ms);
  EXPECT_EQ(kTargetDelayMs, stats.target_delay_ms);
  EXPECT_EQ(kJitterBufferMs, stats.jitter_buffer_ms);
  EXPECT_EQ(kMinPlayoutDelayMs, stats.min_playout_delay_ms);
  EXPECT_EQ(kRenderDelayMs, stats.render_delay_ms);
}


TEST_F(ReceiveStatisticsProxyTest, GetStatsReportsRtcpPacketTypeCounts) {
  const uint32_t kFirPackets = 33;
  const uint32_t kPliPackets = 44;
  const uint32_t kNackPackets = 55;
  RtcpPacketTypeCounter counter;
  RtcpPacketTypeCounter counter;
  counter.fir_packets = kFirPackets;
  counter.pli_packets = kPliPackets;
  counter.nack_packets = kNackPackets;
  statistics_proxy_->RtcpPacketTypesCounterUpdated(kRemoteSsrc, counter);
  VideoReceiveStream::Stats stats = statistics_proxy_->GetStats();
  VideoReceiveStream::Stats stats = statistics_proxy_->GetStats();
  EXPECT_EQ(kFirPackets, stats.rtcp_packet_type_counts.fir_packets);
  EXPECT_EQ(kPliPackets, stats.rtcp_packet_type_counts.pli_packets);
  EXPECT_EQ(kNackPackets, stats.rtcp_packet_type_counts.nack_packets);
}


TEST_F(ReceiveStatisticsProxyTest,
       GetStatsReportsNoRtcpPacketTypeCountsForUnknownSsrc) {
  RtcpPacketTypeCounter counter;
  counter.fir_packets = 33;
  statistics_proxy_->RtcpPacketTypesCounterUpdated(kRemoteSsrc + 1, counter);
  statistics_proxy_->RtcpPacketTypesCounterUpdated(kRemoteSsrc + 1, counter);
  EXPECT_EQ(0u,
            statistics_proxy_->GetStats().rtcp_packet_type_counts.fir_packets);
}

TEST_F(ReceiveStatisticsProxyTest, GetStatsReportsFrameCounts) {
TEST_F(ReceiveStatisticsProxyTest, GetStatsReportsFrameCounts) {
  const int kKeyFrames = 3;
  const int kDeltaFrames = 22;
  FrameCounts frame_counts;
  frame_counts.key_frames = kKeyFrames;
  frame_counts.delta_frames = kDeltaFrames;
  statistics_proxy_->OnFrameCountsUpdated(frame_counts);
  VideoReceiveStream::Stats stats = statistics_proxy_->GetStats();
  VideoReceiveStream::Stats stats = statistics_proxy_->GetStats();
  EXPECT_EQ(kKeyFrames, stats.frame_counts.key_frames);
  EXPECT_EQ(kDeltaFrames, stats.frame_counts.delta_frames);
}

TEST_F(ReceiveStatisticsProxyTest, GetStatsReportsDiscardedPackets) {
TEST_F(ReceiveStatisticsProxyTest, GetStatsReportsDiscardedPackets) {
  const int kDiscardedPackets = 12;
  statistics_proxy_->OnDiscardedPacketsUpdated(kDiscardedPackets);
  EXPECT_EQ(kDiscardedPackets, statistics_proxy_->GetStats().discarded_packets);
}

TEST_F(ReceiveStatisticsProxyTest, GetStatsReportsRtcpStats) {
  const uint8_t kFracLost = 0;
  const uint8_t kFracLost = 0;
  const uint32_t kCumLost = 1;
  const uint32_t kExtSeqNum = 10;
  const uint32_t kJitter = 4;

  RtcpStatistics rtcp_stats;
  RtcpStatistics rtcp_stats;
  rtcp_stats.fraction_lost = kFracLost;
  rtcp_stats.packets_lost = kCumLost;
  rtcp_stats.extended_highest_sequence_number = kExtSeqNum;
  rtcp_stats.jitter = kJitter;
  statistics_proxy_->StatisticsUpdated(rtcp_stats, kRemoteSsrc);
  statistics_proxy_->StatisticsUpdated(rtcp_stats, kRemoteSsrc);

  VideoReceiveStream::Stats stats = statistics_proxy_->GetStats();
  EXPECT_EQ(kFracLost, stats.rtcp_stats.fraction_lost);
  EXPECT_EQ(kCumLost, stats.rtcp_stats.packets_lost);
  EXPECT_EQ(kExtSeqNum, stats.rtcp_stats.extended_highest_sequence_number);
  EXPECT_EQ(kExtSeqNum, stats.rtcp_stats.extended_highest_sequence_number);
  EXPECT_EQ(kJitter, stats.rtcp_stats.jitter);
}

TEST_F(ReceiveStatisticsProxyTest, GetStatsReportsCName) {
  const char* kName = "cName";
  statistics_proxy_->CNameChanged(kName, kRemoteSsrc);
  EXPECT_STREQ(kName, statistics_proxy_->GetStats().c_name.c_str());
  EXPECT_STREQ(kName, statistics_proxy_->GetStats().c_name.c_str());
}

TEST_F(ReceiveStatisticsProxyTest, GetStatsReportsNoCNameForUnknownSsrc) {
  const char* kName = "cName";
  statistics_proxy_->CNameChanged(kName, kRemoteSsrc + 1);
  statistics_proxy_->CNameChanged(kName, kRemoteSsrc + 1);
  EXPECT_STREQ("", statistics_proxy_->GetStats().c_name.c_str());
}

TEST_F(ReceiveStatisticsProxyTest,
       ReportsLongestTimingFrameInfo) {
       ReportsLongestTimingFrameInfo) {
  const int64_t kShortEndToEndDelay = 10;
  const int64_t kMedEndToEndDelay = 20;
  const int64_t kLongEndToEndDelay = 100;
  const uint32_t kExpectedRtpTimestamp = 2;
  TimingFrameInfo info;
  TimingFrameInfo info;
  rtc::Optional<TimingFrameInfo> result;
  info.rtp_timestamp = kExpectedRtpTimestamp - 1;
  info.capture_time_ms = 0;
  info.decode_finish_ms = kShortEndToEndDelay;
  statistics_proxy_->OnTimingFrameInfoUpdated(info);
  statistics_proxy_->OnTimingFrameInfoUpdated(info);
  info.rtp_timestamp =
      kExpectedRtpTimestamp;  // this frame should be reported in the end.
  info.capture_time_ms = 0;
  info.decode_finish_ms = kLongEndToEndDelay;
  statistics_proxy_->OnTimingFrameInfoUpdated(info);
  info.rtp_timestamp = kExpectedRtpTimestamp + 1;
  info.capture_time_ms = 0;
  info.decode_finish_ms = kMedEndToEndDelay;
  info.decode_finish_ms = kMedEndToEndDelay;
  statistics_proxy_->OnTimingFrameInfoUpdated(info);
  result = statistics_proxy_->GetStats().timing_frame_info;
  EXPECT_TRUE(result);
  EXPECT_EQ(kExpectedRtpTimestamp, result->rtp_timestamp);
}
}

TEST_F(ReceiveStatisticsProxyTest, RespectsReportingIntervalForTimingFrames) {
  TimingFrameInfo info;
  TimingFrameInfo info;
  const int64_t kShortEndToEndDelay = 10;
  const int64_t kShortEndToEndDelay = 10;
  const uint32_t kExpectedRtpTimestamp = 2;
  const int64_t kShortDelayMs = 1000;
  const int64_t kLongDelayMs = 10000;
  const int64_t kLongDelayMs = 10000;
  rtc::Optional<TimingFrameInfo> result;
  info.rtp_timestamp = kExpectedRtpTimestamp;
  info.capture_time_ms = 0;
  info.decode_finish_ms = kShortEndToEndDelay;
  statistics_proxy_->OnTimingFrameInfoUpdated(info);
  statistics_proxy_->OnTimingFrameInfoUpdated(info);
  fake_clock_.AdvanceTimeMilliseconds(kShortDelayMs);
  result = statistics_proxy_->GetStats().timing_frame_info;
  EXPECT_TRUE(result);
  EXPECT_EQ(kExpectedRtpTimestamp, result->rtp_timestamp);
  fake_clock_.AdvanceTimeMilliseconds(kLongDelayMs);
  fake_clock_.AdvanceTimeMilliseconds(kLongDelayMs);
  result = statistics_proxy_->GetStats().timing_frame_info;
  EXPECT_FALSE(result);
}

TEST_F(ReceiveStatisticsProxyTest, LifetimeHistogramIsUpdated) {
TEST_F(ReceiveStatisticsProxyTest, LifetimeHistogramIsUpdated) {
  const int64_t kTimeSec = 3;
  fake_clock_.AdvanceTimeMilliseconds(kTimeSec * 1000);
  // Need at least one frame to report stream lifetime.
  statistics_proxy_->OnCompleteFrame(true, 1000, VideoContentType::UNSPECIFIED);
  // Histograms are updated when the statistics_proxy_ is deleted.
  statistics_proxy_.reset();
  EXPECT_EQ(1,
            metrics::NumSamples("WebRTC.Video.ReceiveStreamLifetimeInSeconds"));
            metrics::NumSamples("WebRTC.Video.ReceiveStreamLifetimeInSeconds"));
  EXPECT_EQ(1, metrics::NumEvents("WebRTC.Video.ReceiveStreamLifetimeInSeconds",
                                  kTimeSec));
}

TEST_F(ReceiveStatisticsProxyTest,
TEST_F(ReceiveStatisticsProxyTest,
       LifetimeHistogramNotReportedForEmptyStreams) {
  const int64_t kTimeSec = 3;
  fake_clock_.AdvanceTimeMilliseconds(kTimeSec * 1000);
  // No frames received.
  // No frames received.
  // Histograms are updated when the statistics_proxy_ is deleted.
  statistics_proxy_.reset();
  EXPECT_EQ(0,
            metrics::NumSamples("WebRTC.Video.ReceiveStreamLifetimeInSeconds"));
}
}

TEST_F(ReceiveStatisticsProxyTest, BadCallHistogramsAreUpdated) {
  // Based on the tuning parameters this will produce 7 uncertain states,
  // then 10 certainly bad states. There has to be 10 certain states before
  // any histograms are recorded.
  // any histograms are recorded.
  const int kNumBadSamples = 17;

  StreamDataCounters counters;
  counters.first_packet_time_ms = fake_clock_.TimeInMilliseconds();
  statistics_proxy_->DataCountersUpdated(counters, config_.rtp.remote_ssrc);
  statistics_proxy_->DataCountersUpdated(counters, config_.rtp.remote_ssrc);

  for (int i = 0; i < kNumBadSamples; ++i) {
    // Since OnRenderedFrame is never called the fps in each sample will be 0,
    // i.e. bad
    // i.e. bad
    fake_clock_.AdvanceTimeMilliseconds(1000);
    statistics_proxy_->OnIncomingRate(0, 0);
  }
  // Histograms are updated when the statistics_proxy_ is deleted.
  statistics_proxy_.reset();
  statistics_proxy_.reset();
  EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.BadCall.Any"));
  EXPECT_EQ(1, metrics::NumEvents("WebRTC.Video.BadCall.Any", 100));

  EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.BadCall.FrameRate"));
  EXPECT_EQ(1, metrics::NumEvents("WebRTC.Video.BadCall.FrameRate", 100));
  EXPECT_EQ(1, metrics::NumEvents("WebRTC.Video.BadCall.FrameRate", 100));

  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.BadCall.FrameRateVariance"));

  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.BadCall.Qp"));
  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.BadCall.Qp"));
}

TEST_F(ReceiveStatisticsProxyTest, PacketLossHistogramIsUpdated) {
  const uint32_t kCumLost1 = 1;
  const uint32_t kExtSeqNum1 = 10;
  const uint32_t kExtSeqNum1 = 10;
  const uint32_t kCumLost2 = 2;
  const uint32_t kExtSeqNum2 = 20;

  // One report block received.
  RtcpStatistics rtcp_stats1;
  RtcpStatistics rtcp_stats1;
  rtcp_stats1.packets_lost = kCumLost1;
  rtcp_stats1.extended_highest_sequence_number = kExtSeqNum1;
  statistics_proxy_->StatisticsUpdated(rtcp_stats1, kRemoteSsrc);

  // Two report blocks received.
  // Two report blocks received.
  RtcpStatistics rtcp_stats2;
  RtcpStatistics rtcp_stats2;
  rtcp_stats2.packets_lost = kCumLost2;
  rtcp_stats2.extended_highest_sequence_number = kExtSeqNum2;
  statistics_proxy_->StatisticsUpdated(rtcp_stats2, kRemoteSsrc);


  // Two received report blocks but min run time has not passed.
  fake_clock_.AdvanceTimeMilliseconds(metrics::kMinRunTimeInSeconds * 1000 - 1);
  SetUp();  // Reset stat proxy causes histograms to be updated.
  EXPECT_EQ(0,
            metrics::NumSamples("WebRTC.Video.ReceivedPacketsLostInPercent"));
            metrics::NumSamples("WebRTC.Video.ReceivedPacketsLostInPercent"));

  // Two report blocks received.
  statistics_proxy_->StatisticsUpdated(rtcp_stats1, kRemoteSsrc);
  statistics_proxy_->StatisticsUpdated(rtcp_stats2, kRemoteSsrc);


  // Two received report blocks and min run time has passed.
  fake_clock_.AdvanceTimeMilliseconds(metrics::kMinRunTimeInSeconds * 1000);
  SetUp();
  EXPECT_EQ(1,
            metrics::NumSamples("WebRTC.Video.ReceivedPacketsLostInPercent"));
            metrics::NumSamples("WebRTC.Video.ReceivedPacketsLostInPercent"));
  EXPECT_EQ(1, metrics::NumEvents("WebRTC.Video.ReceivedPacketsLostInPercent",
                                  (kCumLost2 - kCumLost1) * 100 /
                                      (kExtSeqNum2 - kExtSeqNum1)));
}


TEST_F(ReceiveStatisticsProxyTest,
       PacketLossHistogramIsNotUpdatedIfLessThanTwoReportBlocksAreReceived) {
  RtcpStatistics rtcp_stats1;
  rtcp_stats1.packets_lost = 1;
  rtcp_stats1.extended_highest_sequence_number = 10;
  rtcp_stats1.extended_highest_sequence_number = 10;

  // Min run time has passed but no received report block.
  fake_clock_.AdvanceTimeMilliseconds(metrics::kMinRunTimeInSeconds * 1000);
  fake_clock_.AdvanceTimeMilliseconds(metrics::kMinRunTimeInSeconds * 1000);
  SetUp();  // Reset stat proxy causes histograms to be updated.
  EXPECT_EQ(0,
            metrics::NumSamples("WebRTC.Video.ReceivedPacketsLostInPercent"));

  // Min run time has passed but only one received report block.
  // Min run time has passed but only one received report block.
  statistics_proxy_->StatisticsUpdated(rtcp_stats1, kRemoteSsrc);
  fake_clock_.AdvanceTimeMilliseconds(metrics::kMinRunTimeInSeconds * 1000);
  SetUp();
  EXPECT_EQ(0,
            metrics::NumSamples("WebRTC.Video.ReceivedPacketsLostInPercent"));
            metrics::NumSamples("WebRTC.Video.ReceivedPacketsLostInPercent"));
}

TEST_F(ReceiveStatisticsProxyTest, GetStatsReportsAvSyncOffset) {
TEST_F(ReceiveStatisticsProxyTest, GetStatsReportsAvSyncOffset) {
  const int64_t kSyncOffsetMs = 22;
  const int64_t kSyncOffsetMs = 22;
  const double kFreqKhz = 90.0;
  EXPECT_EQ(std::numeric_limits<int>::max(),
            statistics_proxy_->GetStats().sync_offset_ms);
            statistics_proxy_->GetStats().sync_offset_ms);
  statistics_proxy_->OnSyncOffsetUpdated(kSyncOffsetMs, kFreqKhz);
  EXPECT_EQ(kSyncOffsetMs, statistics_proxy_->GetStats().sync_offset_ms);
}

TEST_F(ReceiveStatisticsProxyTest, AvSyncOffsetHistogramIsUpdated) {
TEST_F(ReceiveStatisticsProxyTest, AvSyncOffsetHistogramIsUpdated) {
  const int64_t kSyncOffsetMs = 22;
  const double kFreqKhz = 90.0;
  for (int i = 0; i < kMinRequiredSamples; ++i)
    statistics_proxy_->OnSyncOffsetUpdated(kSyncOffsetMs, kFreqKhz);
  // Histograms are updated when the statistics_proxy_ is deleted.
  // Histograms are updated when the statistics_proxy_ is deleted.
  statistics_proxy_.reset();
  EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.AVSyncOffsetInMs"));
  EXPECT_EQ(1,
            metrics::NumEvents("WebRTC.Video.AVSyncOffsetInMs", kSyncOffsetMs));
}
}

TEST_F(ReceiveStatisticsProxyTest, RtpToNtpFrequencyOffsetHistogramIsUpdated) {
  const int64_t kSyncOffsetMs = 22;
  const double kFreqKhz = 90.0;
  statistics_proxy_->OnSyncOffsetUpdated(kSyncOffsetMs, kFreqKhz);
  statistics_proxy_->OnSyncOffsetUpdated(kSyncOffsetMs, kFreqKhz);
  statistics_proxy_->OnSyncOffsetUpdated(kSyncOffsetMs, kFreqKhz + 2.2);
  fake_clock_.AdvanceTimeMilliseconds(kFreqOffsetProcessIntervalInMs);
  // Process interval passed, max diff: 2.
  statistics_proxy_->OnSyncOffsetUpdated(kSyncOffsetMs, kFreqKhz + 1.1);
  statistics_proxy_->OnSyncOffsetUpdated(kSyncOffsetMs, kFreqKhz - 4.2);
  statistics_proxy_->OnSyncOffsetUpdated(kSyncOffsetMs, kFreqKhz - 4.2);
  statistics_proxy_->OnSyncOffsetUpdated(kSyncOffsetMs, kFreqKhz - 0.9);
  fake_clock_.AdvanceTimeMilliseconds(kFreqOffsetProcessIntervalInMs);
  // Process interval passed, max diff: 4.
  statistics_proxy_->OnSyncOffsetUpdated(kSyncOffsetMs, kFreqKhz);
  statistics_proxy_.reset();
  statistics_proxy_.reset();
  // Average reported: (2 + 4) / 2 = 3.
  EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.RtpToNtpFreqOffsetInKhz"));
  EXPECT_EQ(1, metrics::NumEvents("WebRTC.Video.RtpToNtpFreqOffsetInKhz", 3));
}
}

TEST_F(ReceiveStatisticsProxyTest, Vp8QpHistogramIsUpdated) {
  const int kQp = 22;
  EncodedImage encoded_image;
  encoded_image.qp_ = kQp;
  encoded_image.qp_ = kQp;
  CodecSpecificInfo codec_info;
  codec_info.codecType = kVideoCodecVP8;

  for (int i = 0; i < kMinRequiredSamples; ++i)
    statistics_proxy_->OnPreDecode(encoded_image, &codec_info);


  statistics_proxy_.reset();
  EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.Decoded.Vp8.Qp"));
  EXPECT_EQ(1, metrics::NumEvents("WebRTC.Video.Decoded.Vp8.Qp", kQp));
}


TEST_F(ReceiveStatisticsProxyTest, Vp8QpHistogramIsNotUpdatedForTooFewSamples) {
  EncodedImage encoded_image;
  encoded_image.qp_ = 22;
  CodecSpecificInfo codec_info;
  codec_info.codecType = kVideoCodecVP8;
  codec_info.codecType = kVideoCodecVP8;

  for (int i = 0; i < kMinRequiredSamples - 1; ++i)
    statistics_proxy_->OnPreDecode(encoded_image, &codec_info);

  statistics_proxy_.reset();
  statistics_proxy_.reset();
  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.Decoded.Vp8.Qp"));
}

TEST_F(ReceiveStatisticsProxyTest, Vp8QpHistogramIsNotUpdatedIfNoQpValue) {
  EncodedImage encoded_image;
  EncodedImage encoded_image;
  CodecSpecificInfo codec_info;
  codec_info.codecType = kVideoCodecVP8;

  for (int i = 0; i < kMinRequiredSamples; ++i)
    statistics_proxy_->OnPreDecode(encoded_image, &codec_info);
    statistics_proxy_->OnPreDecode(encoded_image, &codec_info);

  statistics_proxy_.reset();
  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.Decoded.Vp8.Qp"));
}


TEST_F(ReceiveStatisticsProxyTest,
       KeyFrameHistogramNotUpdatedForTooFewSamples) {
  const bool kIsKeyFrame = false;
  const int kFrameSizeBytes = 1000;


  for (int i = 0; i < kMinRequiredSamples - 1; ++i)
    statistics_proxy_->OnCompleteFrame(kIsKeyFrame, kFrameSizeBytes,
                                       VideoContentType::UNSPECIFIED);

  EXPECT_EQ(0, statistics_proxy_->GetStats().frame_counts.key_frames);
  EXPECT_EQ(0, statistics_proxy_->GetStats().frame_counts.key_frames);
  EXPECT_EQ(kMinRequiredSamples - 1,
            statistics_proxy_->GetStats().frame_counts.delta_frames);

  statistics_proxy_.reset();
  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.KeyFramesReceivedInPermille"));
  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.KeyFramesReceivedInPermille"));
}

TEST_F(ReceiveStatisticsProxyTest,
       KeyFrameHistogramUpdatedForMinRequiredSamples) {
  const bool kIsKeyFrame = false;
  const int kFrameSizeBytes = 1000;


  for (int i = 0; i < kMinRequiredSamples; ++i)
    statistics_proxy_->OnCompleteFrame(kIsKeyFrame, kFrameSizeBytes,
                                       VideoContentType::UNSPECIFIED);

  EXPECT_EQ(0, statistics_proxy_->GetStats().frame_counts.key_frames);
  EXPECT_EQ(0, statistics_proxy_->GetStats().frame_counts.key_frames);
  EXPECT_EQ(kMinRequiredSamples,
            statistics_proxy_->GetStats().frame_counts.delta_frames);

  statistics_proxy_.reset();
  EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.KeyFramesReceivedInPermille"));
  EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.KeyFramesReceivedInPermille"));
  EXPECT_EQ(1,
            metrics::NumEvents("WebRTC.Video.KeyFramesReceivedInPermille", 0));
}

TEST_F(ReceiveStatisticsProxyTest, KeyFrameHistogramIsUpdated) {
  const int kFrameSizeBytes = 1000;
  const int kFrameSizeBytes = 1000;

  for (int i = 0; i < kMinRequiredSamples; ++i)
    statistics_proxy_->OnCompleteFrame(true, kFrameSizeBytes,
                                       VideoContentType::UNSPECIFIED);


  for (int i = 0; i < kMinRequiredSamples; ++i)
    statistics_proxy_->OnCompleteFrame(false, kFrameSizeBytes,
                                       VideoContentType::UNSPECIFIED);

  EXPECT_EQ(kMinRequiredSamples,
            statistics_proxy_->GetStats().frame_counts.key_frames);
  EXPECT_EQ(kMinRequiredSamples,
  EXPECT_EQ(kMinRequiredSamples,
            statistics_proxy_->GetStats().frame_counts.delta_frames);

  statistics_proxy_.reset();
  EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.KeyFramesReceivedInPermille"));
  EXPECT_EQ(
  EXPECT_EQ(
      1, metrics::NumEvents("WebRTC.Video.KeyFramesReceivedInPermille", 500));
}

TEST_F(ReceiveStatisticsProxyTest, TimingHistogramsNotUpdatedForTooFewSamples) {
  const int kDecodeMs = 1;
  const int kDecodeMs = 1;
  const int kMaxDecodeMs = 2;
  const int kCurrentDelayMs = 3;
  const int kTargetDelayMs = 4;
  const int kJitterBufferMs = 5;
  const int kMinPlayoutDelayMs = 6;
  const int kRenderDelayMs = 7;
  const int kRenderDelayMs = 7;

  for (int i = 0; i < kMinRequiredSamples - 1; ++i) {
    statistics_proxy_->OnFrameBufferTimingsUpdated(
        kDecodeMs, kMaxDecodeMs, kCurrentDelayMs, kTargetDelayMs,
        kJitterBufferMs, kMinPlayoutDelayMs, kRenderDelayMs);
        kJitterBufferMs, kMinPlayoutDelayMs, kRenderDelayMs);
  }

  statistics_proxy_.reset();
  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.DecodeTimeInMs"));
  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.JitterBufferDelayInMs"));
  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.JitterBufferDelayInMs"));
  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.TargetDelayInMs"));
  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.CurrentDelayInMs"));
  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.OnewayDelayInMs"));
}


TEST_F(ReceiveStatisticsProxyTest, TimingHistogramsAreUpdated) {
  const int kDecodeMs = 1;
  const int kMaxDecodeMs = 2;
  const int kCurrentDelayMs = 3;
  const int kTargetDelayMs = 4;
  const int kTargetDelayMs = 4;
  const int kJitterBufferMs = 5;
  const int kMinPlayoutDelayMs = 6;
  const int kRenderDelayMs = 7;


  for (int i = 0; i < kMinRequiredSamples; ++i) {
    statistics_proxy_->OnFrameBufferTimingsUpdated(
        kDecodeMs, kMaxDecodeMs, kCurrentDelayMs, kTargetDelayMs,
        kJitterBufferMs, kMinPlayoutDelayMs, kRenderDelayMs);
        kJitterBufferMs, kMinPlayoutDelayMs, kRenderDelayMs);
  }

  statistics_proxy_.reset();
  EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.DecodeTimeInMs"));
  EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.JitterBufferDelayInMs"));
  EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.JitterBufferDelayInMs"));
  EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.TargetDelayInMs"));
  EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.CurrentDelayInMs"));
  EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.OnewayDelayInMs"));

  EXPECT_EQ(1, metrics::NumEvents("WebRTC.Video.DecodeTimeInMs", kDecodeMs));
  EXPECT_EQ(1, metrics::NumEvents("WebRTC.Video.DecodeTimeInMs", kDecodeMs));
  EXPECT_EQ(1, metrics::NumEvents("WebRTC.Video.JitterBufferDelayInMs",
                                  kJitterBufferMs));
  EXPECT_EQ(1,
            metrics::NumEvents("WebRTC.Video.TargetDelayInMs", kTargetDelayMs));
  EXPECT_EQ(
  EXPECT_EQ(
      1, metrics::NumEvents("WebRTC.Video.CurrentDelayInMs", kCurrentDelayMs));
  EXPECT_EQ(1,
            metrics::NumEvents("WebRTC.Video.OnewayDelayInMs", kTargetDelayMs));
}


TEST_F(ReceiveStatisticsProxyTest, DoesNotReportStaleFramerates) {
  const int kDefaultFps = 30;
  const int kWidth = 320;
  const int kHeight = 240;


  rtc::scoped_refptr<VideoFrameBuffer> video_frame_buffer(
      I420Buffer::Create(kWidth, kHeight));
  VideoFrame frame(video_frame_buffer, kVideoRotation_0, 0);


  for (int i = 0; i < kDefaultFps; ++i) {
    // Since OnRenderedFrame is never called the fps in each sample will be 0,
    // i.e. bad
    frame.set_ntp_time_ms(fake_clock_.CurrentNtpInMilliseconds());
    statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(),
    statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(),
                                      VideoContentType::UNSPECIFIED);
    statistics_proxy_->OnRenderedFrame(frame);
    fake_clock_.AdvanceTimeMilliseconds(1000 / kDefaultFps);
  }


  EXPECT_EQ(kDefaultFps, statistics_proxy_->GetStats().decode_frame_rate);
  EXPECT_EQ(kDefaultFps, statistics_proxy_->GetStats().render_frame_rate);


  // FPS trackers in stats proxy have a 1000ms sliding window.
  // FPS trackers in stats proxy have a 1000ms sliding window.
  fake_clock_.AdvanceTimeMilliseconds(1000);
  EXPECT_EQ(0, statistics_proxy_->GetStats().decode_frame_rate);
  EXPECT_EQ(0, statistics_proxy_->GetStats().render_frame_rate);
  EXPECT_EQ(0, statistics_proxy_->GetStats().render_frame_rate);
}

TEST_F(ReceiveStatisticsProxyTest, GetStatsReportsReceivedFrameStats) {
  const int kWidth = 160;
  const int kHeight = 120;
  const int kHeight = 120;
  EXPECT_EQ(0, statistics_proxy_->GetStats().width);
  EXPECT_EQ(0, statistics_proxy_->GetStats().height);
  EXPECT_EQ(0u, statistics_proxy_->GetStats().frames_rendered);

  statistics_proxy_->OnRenderedFrame(CreateFrame(kWidth, kHeight));
  statistics_proxy_->OnRenderedFrame(CreateFrame(kWidth, kHeight));

  EXPECT_EQ(kWidth, statistics_proxy_->GetStats().width);
  EXPECT_EQ(kHeight, statistics_proxy_->GetStats().height);
  EXPECT_EQ(1u, statistics_proxy_->GetStats().frames_rendered);
  EXPECT_EQ(1u, statistics_proxy_->GetStats().frames_rendered);
}

TEST_F(ReceiveStatisticsProxyTest,
       ReceivedFrameHistogramsAreNotUpdatedForTooFewSamples) {
  const int kWidth = 160;
  const int kWidth = 160;
  const int kHeight = 120;

  for (int i = 0; i < kMinRequiredSamples - 1; ++i)
    statistics_proxy_->OnRenderedFrame(CreateFrame(kWidth, kHeight));


  statistics_proxy_.reset();
  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.ReceivedWidthInPixels"));
  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.ReceivedHeightInPixels"));
  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.RenderFramesPerSecond"));
  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.RenderSqrtPixelsPerSecond"));
  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.RenderSqrtPixelsPerSecond"));
}

TEST_F(ReceiveStatisticsProxyTest, ReceivedFrameHistogramsAreUpdated) {
  const int kWidth = 160;
  const int kWidth = 160;
  const int kHeight = 120;

  for (int i = 0; i < kMinRequiredSamples; ++i)
    statistics_proxy_->OnRenderedFrame(CreateFrame(kWidth, kHeight));


  statistics_proxy_.reset();
  EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.ReceivedWidthInPixels"));
  EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.ReceivedHeightInPixels"));
  EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.RenderFramesPerSecond"));
  EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.RenderSqrtPixelsPerSecond"));
  EXPECT_EQ(1,
            metrics::NumEvents("WebRTC.Video.ReceivedWidthInPixels", kWidth));
            metrics::NumEvents("WebRTC.Video.ReceivedWidthInPixels", kWidth));
  EXPECT_EQ(1,
            metrics::NumEvents("WebRTC.Video.ReceivedHeightInPixels", kHeight));
}

TEST_F(ReceiveStatisticsProxyTest,
TEST_F(ReceiveStatisticsProxyTest,
       RtcpHistogramsNotUpdatedIfMinRuntimeHasNotPassed) {
  InsertFirstRtpPacket(kRemoteSsrc);
  fake_clock_.AdvanceTimeMilliseconds((metrics::kMinRunTimeInSeconds * 1000) -
                                      1);


  RtcpPacketTypeCounter counter;
  statistics_proxy_->RtcpPacketTypesCounterUpdated(kRemoteSsrc, counter);

  statistics_proxy_.reset();
  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.FirPacketsSentPerMinute"));
  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.FirPacketsSentPerMinute"));
  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.PliPacketsSentPerMinute"));
  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.NackPacketsSentPerMinute"));
}

TEST_F(ReceiveStatisticsProxyTest, RtcpHistogramsAreUpdated) {
TEST_F(ReceiveStatisticsProxyTest, RtcpHistogramsAreUpdated) {
  InsertFirstRtpPacket(kRemoteSsrc);
  fake_clock_.AdvanceTimeMilliseconds(metrics::kMinRunTimeInSeconds * 1000);

  const uint32_t kFirPackets = 100;
  const uint32_t kPliPackets = 200;
  const uint32_t kPliPackets = 200;
  const uint32_t kNackPackets = 300;

  RtcpPacketTypeCounter counter;
  counter.fir_packets = kFirPackets;
  counter.pli_packets = kPliPackets;
  counter.nack_packets = kNackPackets;
  statistics_proxy_->RtcpPacketTypesCounterUpdated(kRemoteSsrc, counter);
  statistics_proxy_->RtcpPacketTypesCounterUpdated(kRemoteSsrc, counter);

  statistics_proxy_.reset();
  EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.FirPacketsSentPerMinute"));
  EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.PliPacketsSentPerMinute"));
  EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.NackPacketsSentPerMinute"));
  EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.NackPacketsSentPerMinute"));
  EXPECT_EQ(
      1, metrics::NumEvents("WebRTC.Video.FirPacketsSentPerMinute",
                            kFirPackets * 60 / metrics::kMinRunTimeInSeconds));
  EXPECT_EQ(
      1, metrics::NumEvents("WebRTC.Video.PliPacketsSentPerMinute",
      1, metrics::NumEvents("WebRTC.Video.PliPacketsSentPerMinute",
                            kPliPackets * 60 / metrics::kMinRunTimeInSeconds));
  EXPECT_EQ(
      1, metrics::NumEvents("WebRTC.Video.NackPacketsSentPerMinute",
                            kNackPackets * 60 / metrics::kMinRunTimeInSeconds));
}
}

INSTANTIATE_TEST_CASE_P(ContentTypes,
                        ReceiveStatisticsProxyTest,
                        ::testing::Values(VideoContentType::UNSPECIFIED,
                                          VideoContentType::SCREENSHARE));

TEST_P(ReceiveStatisticsProxyTest, InterFrameDelaysAreReported) {
TEST_P(ReceiveStatisticsProxyTest, InterFrameDelaysAreReported) {
  const VideoContentType content_type = GetParam();
  const int kInterFrameDelayMs = 33;
  for (int i = 0; i < kMinRequiredSamples; ++i) {
    statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(), content_type);
    fake_clock_.AdvanceTimeMilliseconds(kInterFrameDelayMs);
  }
  }
  // One extra with double the interval.
  // One extra with double the interval.
  fake_clock_.AdvanceTimeMilliseconds(kInterFrameDelayMs);
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(), content_type);


  statistics_proxy_.reset();
  const int kExpectedInterFrame =
      (kInterFrameDelayMs * (kMinRequiredSamples - 1) +
       kInterFrameDelayMs * 2) /
      kMinRequiredSamples;
      kMinRequiredSamples;
  if (videocontenttypehelpers::IsScreenshare(content_type)) {
    EXPECT_EQ(
        kExpectedInterFrame,
        metrics::MinSample("WebRTC.Video.Screenshare.InterframeDelayInMs"));
    EXPECT_EQ(
    EXPECT_EQ(
        kInterFrameDelayMs * 2,
        metrics::MinSample("WebRTC.Video.Screenshare.InterframeDelayMaxInMs"));
  } else {
    EXPECT_EQ(kExpectedInterFrame,
              metrics::MinSample("WebRTC.Video.InterframeDelayInMs"));
              metrics::MinSample("WebRTC.Video.InterframeDelayInMs"));
    EXPECT_EQ(kInterFrameDelayMs * 2,
              metrics::MinSample("WebRTC.Video.InterframeDelayMaxInMs"));
  }
}


TEST_P(ReceiveStatisticsProxyTest, InterFrameDelaysPercentilesAreReported) {
  const VideoContentType content_type = GetParam();
  const int kInterFrameDelayMs = 33;
  const int kLastFivePercentsSamples = kMinRequiredSamples * 5 / 100;
  const int kLastFivePercentsSamples = kMinRequiredSamples * 5 / 100;
  for (int i = 0; i <= kMinRequiredSamples - kLastFivePercentsSamples; ++i) {
    fake_clock_.AdvanceTimeMilliseconds(kInterFrameDelayMs);
    fake_clock_.AdvanceTimeMilliseconds(kInterFrameDelayMs);
    statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(), content_type);
  }
  // Last 5% of intervals are double in size.
  for (int i = 0; i < kLastFivePercentsSamples; ++i) {
  for (int i = 0; i < kLastFivePercentsSamples; ++i) {
    fake_clock_.AdvanceTimeMilliseconds(2 * kInterFrameDelayMs);
    statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(), content_type);
  }
  // Final sample is outlier and 10 times as big.
  fake_clock_.AdvanceTimeMilliseconds(10 * kInterFrameDelayMs);
  fake_clock_.AdvanceTimeMilliseconds(10 * kInterFrameDelayMs);
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(), content_type);

  statistics_proxy_.reset();
  const int kExpectedInterFrame = kInterFrameDelayMs * 2;
  if (videocontenttypehelpers::IsScreenshare(content_type)) {
  if (videocontenttypehelpers::IsScreenshare(content_type)) {
    EXPECT_EQ(kExpectedInterFrame,
              metrics::MinSample(
                  "WebRTC.Video.Screenshare.InterframeDelay95PercentileInMs"));
  } else {
    EXPECT_EQ(
    EXPECT_EQ(
        kExpectedInterFrame,
        metrics::MinSample("WebRTC.Video.InterframeDelay95PercentileInMs"));
  }
}


TEST_P(ReceiveStatisticsProxyTest, MaxInterFrameDelayOnlyWithValidAverage) {
  const VideoContentType content_type = GetParam();
  const int kInterFrameDelayMs = 33;
  for (int i = 0; i < kMinRequiredSamples; ++i) {
    statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(), content_type);
    fake_clock_.AdvanceTimeMilliseconds(kInterFrameDelayMs);
    fake_clock_.AdvanceTimeMilliseconds(kInterFrameDelayMs);
  }

  // |kMinRequiredSamples| samples, and thereby intervals, is required. That
  // means we're one frame short of having a valid data set.
  statistics_proxy_.reset();
  statistics_proxy_.reset();
  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.InterframeDelayInMs"));
  EXPECT_EQ(0, metrics::NumSamples("WebRTC.Video.InterframeDelayMaxInMs"));
  EXPECT_EQ(
      0, metrics::NumSamples("WebRTC.Video.Screenshare.InterframeDelayInMs"));
  EXPECT_EQ(0, metrics::NumSamples(
                   "WebRTC.Video.Screenshare.InterframeDelayMaxInMs"));
}

TEST_P(ReceiveStatisticsProxyTest, MaxInterFrameDelayOnlyWithPause) {
TEST_P(ReceiveStatisticsProxyTest, MaxInterFrameDelayOnlyWithPause) {
  const VideoContentType content_type = GetParam();
  const int kInterFrameDelayMs = 33;
  for (int i = 0; i <= kMinRequiredSamples; ++i) {
    statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(), content_type);
    fake_clock_.AdvanceTimeMilliseconds(kInterFrameDelayMs);
    fake_clock_.AdvanceTimeMilliseconds(kInterFrameDelayMs);
  }

  // At this state, we should have a valid inter-frame delay.
  // Indicate stream paused and make a large jump in time.
  statistics_proxy_->OnStreamInactive();
  statistics_proxy_->OnStreamInactive();
  fake_clock_.AdvanceTimeMilliseconds(5000);

  // Insert two more frames. The interval during the pause should be disregarded
  // in the stats.
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(), content_type);
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(), content_type);
  fake_clock_.AdvanceTimeMilliseconds(kInterFrameDelayMs);
  statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(), content_type);

  statistics_proxy_.reset();
  if (videocontenttypehelpers::IsScreenshare(content_type)) {
  if (videocontenttypehelpers::IsScreenshare(content_type)) {
    EXPECT_EQ(
        1, metrics::NumSamples("WebRTC.Video.Screenshare.InterframeDelayInMs"));
    EXPECT_EQ(1, metrics::NumSamples(
                     "WebRTC.Video.Screenshare.InterframeDelayMaxInMs"));
    EXPECT_EQ(
    EXPECT_EQ(
        kInterFrameDelayMs,
        metrics::MinSample("WebRTC.Video.Screenshare.InterframeDelayInMs"));
    EXPECT_EQ(
        kInterFrameDelayMs,
        metrics::MinSample("WebRTC.Video.Screenshare.InterframeDelayMaxInMs"));
        metrics::MinSample("WebRTC.Video.Screenshare.InterframeDelayMaxInMs"));
  } else {
    EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.InterframeDelayInMs"));
    EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.InterframeDelayMaxInMs"));
    EXPECT_EQ(kInterFrameDelayMs,
              metrics::MinSample("WebRTC.Video.InterframeDelayInMs"));
              metrics::MinSample("WebRTC.Video.InterframeDelayInMs"));
    EXPECT_EQ(kInterFrameDelayMs,
              metrics::MinSample("WebRTC.Video.InterframeDelayMaxInMs"));
  }
}

TEST_P(ReceiveStatisticsProxyTest, StatsAreSlicedOnSimulcastAndExperiment) {
  VideoContentType content_type = GetParam();
  VideoContentType content_type = GetParam();
  const uint8_t experiment_id = 1;
  videocontenttypehelpers::SetExperimentId(&content_type, experiment_id);
  const int kInterFrameDelayMs1 = 30;
  const int kInterFrameDelayMs2 = 50;
  const int kInterFrameDelayMs2 = 50;

  videocontenttypehelpers::SetSimulcastId(&content_type, 1);
  for (int i = 0; i <= kMinRequiredSamples; ++i) {
    fake_clock_.AdvanceTimeMilliseconds(kInterFrameDelayMs1);
    statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(), content_type);
    statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(), content_type);
  }

  videocontenttypehelpers::SetSimulcastId(&content_type, 2);
  for (int i = 0; i <= kMinRequiredSamples; ++i) {
    fake_clock_.AdvanceTimeMilliseconds(kInterFrameDelayMs2);
    fake_clock_.AdvanceTimeMilliseconds(kInterFrameDelayMs2);
    statistics_proxy_->OnDecodedFrame(rtc::Optional<uint8_t>(), content_type);
  }
  statistics_proxy_.reset();

  if (videocontenttypehelpers::IsScreenshare(content_type)) {
  if (videocontenttypehelpers::IsScreenshare(content_type)) {
    EXPECT_EQ(
        1, metrics::NumSamples("WebRTC.Video.Screenshare.InterframeDelayInMs"));
    EXPECT_EQ(1, metrics::NumSamples(
                     "WebRTC.Video.Screenshare.InterframeDelayMaxInMs"));
    EXPECT_EQ(1, metrics::NumSamples(
    EXPECT_EQ(1, metrics::NumSamples(
                     "WebRTC.Video.Screenshare.InterframeDelayInMs.S0"));
    EXPECT_EQ(1, metrics::NumSamples(
                     "WebRTC.Video.Screenshare.InterframeDelayMaxInMs.S0"));
    EXPECT_EQ(1, metrics::NumSamples(
                     "WebRTC.Video.Screenshare.InterframeDelayInMs.S1"));
                     "WebRTC.Video.Screenshare.InterframeDelayInMs.S1"));
    EXPECT_EQ(1, metrics::NumSamples(
                     "WebRTC.Video.Screenshare.InterframeDelayMaxInMs.S1"));
    EXPECT_EQ(1,
              metrics::NumSamples("WebRTC.Video.Screenshare.InterframeDelayInMs"
              metrics::NumSamples("WebRTC.Video.Screenshare.InterframeDelayInMs"
                                  ".ExperimentGroup0"));
    EXPECT_EQ(
        1, metrics::NumSamples("WebRTC.Video.Screenshare.InterframeDelayMaxInMs"
                               ".ExperimentGroup0"));
    EXPECT_EQ(
    EXPECT_EQ(
        kInterFrameDelayMs1,
        metrics::MinSample("WebRTC.Video.Screenshare.InterframeDelayInMs.S0"));
    EXPECT_EQ(
        kInterFrameDelayMs2,
        metrics::MinSample("WebRTC.Video.Screenshare.InterframeDelayInMs.S1"));
        metrics::MinSample("WebRTC.Video.Screenshare.InterframeDelayInMs.S1"));
    EXPECT_EQ(
        (kInterFrameDelayMs1 + kInterFrameDelayMs2) / 2,
        metrics::MinSample("WebRTC.Video.Screenshare.InterframeDelayInMs"));
    EXPECT_EQ(
        kInterFrameDelayMs2,
        metrics::MinSample("WebRTC.Video.Screenshare.InterframeDelayMaxInMs"));
    EXPECT_EQ(
    EXPECT_EQ(
        (kInterFrameDelayMs1 + kInterFrameDelayMs2) / 2,
        metrics::MinSample(
            "WebRTC.Video.Screenshare.InterframeDelayInMs.ExperimentGroup0"));
  } else {
    EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.InterframeDelayInMs"));
    EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.InterframeDelayInMs"));
    EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.InterframeDelayMaxInMs"));
    EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.InterframeDelayInMs.S0"));
    EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.InterframeDelayMaxInMs.S0"));
    EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.InterframeDelayInMs.S1"));
    EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.InterframeDelayMaxInMs.S1"));
    EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.InterframeDelayInMs"
    EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.InterframeDelayInMs"
                                     ".ExperimentGroup0"));
    EXPECT_EQ(1, metrics::NumSamples("WebRTC.Video.InterframeDelayMaxInMs"
                                     ".ExperimentGroup0"));
    EXPECT_EQ(kInterFrameDelayMs1,
              metrics::MinSample("WebRTC.Video.InterframeDelayInMs.S0"));
              metrics::MinSample("WebRTC.Video.InterframeDelayInMs.S0"));
    EXPECT_EQ(kInterFrameDelayMs2,
              metrics::MinSample("WebRTC.Video.InterframeDelayInMs.S1"));
    EXPECT_EQ((kInterFrameDelayMs1 + kInterFrameDelayMs2) / 2,
              metrics::MinSample("WebRTC.Video.InterframeDelayInMs"));
    EXPECT_EQ(kInterFrameDelayMs2,
    EXPECT_EQ(kInterFrameDelayMs2,
              metrics::MinSample("WebRTC.Video.InterframeDelayMaxInMs"));
    EXPECT_EQ((kInterFrameDelayMs1 + kInterFrameDelayMs2) / 2,
              metrics::MinSample(
                  "WebRTC.Video.InterframeDelayInMs.ExperimentGroup0"));
  }
  }
}
}  // namespace webrtc