summaryrefslogtreecommitdiffstats
path: root/media/cast/test/end2end_unittest.cc
blob: 216be8951d5c89d29d0cddb2622d8a276045fd75 (plain)
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
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This test generate synthetic data. For audio it's a sinusoid waveform with
// frequency kSoundFrequency and different amplitudes. For video it's a pattern
// that is shifting by one pixel per frame, each pixels neighbors right and down
// is this pixels value +1, since the pixel value is 8 bit it will wrap
// frequently within the image. Visually this will create diagonally color bands
// that moves across the screen

#include <math.h>

#include <functional>
#include <list>
#include <map>

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/simple_test_tick_clock.h"
#include "base/time/tick_clock.h"
#include "media/base/video_frame.h"
#include "media/cast/cast_config.h"
#include "media/cast/cast_environment.h"
#include "media/cast/cast_receiver.h"
#include "media/cast/cast_sender.h"
#include "media/cast/logging/simple_event_subscriber.h"
#include "media/cast/test/fake_single_thread_task_runner.h"
#include "media/cast/test/utility/audio_utility.h"
#include "media/cast/test/utility/video_utility.h"
#include "media/cast/transport/cast_transport_config.h"
#include "media/cast/transport/cast_transport_defines.h"
#include "media/cast/transport/cast_transport_sender.h"
#include "media/cast/transport/cast_transport_sender_impl.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace media {
namespace cast {

namespace {

static const int64 kStartMillisecond = GG_INT64_C(1245);
static const int kAudioChannels = 2;
static const double kSoundFrequency = 314.15926535897;  // Freq of sine wave.
static const float kSoundVolume = 0.5f;
static const int kVideoHdWidth = 1280;
static const int kVideoHdHeight = 720;
static const int kVideoQcifWidth = 176;
static const int kVideoQcifHeight = 144;
static const int kCommonRtpHeaderLength = 12;
static const uint8 kCastReferenceFrameIdBitReset = 0xDF;  // Mask is 0x40.

// Since the video encoded and decoded an error will be introduced; when
// comparing individual pixels the error can be quite large; we allow a PSNR of
// at least |kVideoAcceptedPSNR|.
static const double kVideoAcceptedPSNR = 38.0;

// The tests are commonly implemented with |kFrameTimerMs| RunTask function;
// a normal video is 30 fps hence the 33 ms between frames.
static const int kFrameTimerMs = 33;

// The packets pass through the pacer which can delay the beginning of the
// frame by 10 ms if there is packets belonging to the previous frame being
// retransmitted.
// In addition, audio packets are sent in 10mS intervals in audio_encoder.cc,
// although we send an audio frame every 33mS, which adds an extra delay.
// A TODO was added in the code to resolve this.
static const int kTimerErrorMs = 20;

// Start the video synthetic start value to medium range value, to avoid edge
// effects cause by encoding and quantization.
static const int kVideoStart = 100;

std::string ConvertFromBase16String(const std::string base_16) {
  std::string compressed;
  DCHECK_EQ(base_16.size() % 2, 0u) << "Must be a multiple of 2";
  compressed.reserve(base_16.size() / 2);

  std::vector<uint8> v;
  if (!base::HexStringToBytes(base_16, &v)) {
    NOTREACHED();
  }
  compressed.assign(reinterpret_cast<const char*>(&v[0]), v.size());
  return compressed;
}

void UpdateCastTransportStatus(transport::CastTransportStatus status) {
  bool result = (status == transport::TRANSPORT_AUDIO_INITIALIZED ||
                 status == transport::TRANSPORT_VIDEO_INITIALIZED);
  EXPECT_TRUE(result);
}

void AudioInitializationStatus(CastInitializationStatus status) {
  EXPECT_EQ(STATUS_AUDIO_INITIALIZED, status);
}

void VideoInitializationStatus(CastInitializationStatus status) {
  EXPECT_EQ(STATUS_VIDEO_INITIALIZED, status);
}

// This is wrapped in a struct because it needs to be put into a std::map.
typedef struct {
  int counter[kNumOfLoggingEvents];
} LoggingEventCounts;

// Constructs a map from each frame (RTP timestamp) to counts of each event
// type logged for that frame.
std::map<RtpTimestamp, LoggingEventCounts> GetEventCountForFrameEvents(
    const std::vector<FrameEvent>& frame_events) {
  std::map<RtpTimestamp, LoggingEventCounts> event_counter_for_frame;
  for (std::vector<FrameEvent>::const_iterator it = frame_events.begin();
       it != frame_events.end();
       ++it) {
    std::map<RtpTimestamp, LoggingEventCounts>::iterator map_it =
        event_counter_for_frame.find(it->rtp_timestamp);
    if (map_it == event_counter_for_frame.end()) {
      LoggingEventCounts new_counter;
      memset(&new_counter, 0, sizeof(new_counter));
      ++(new_counter.counter[it->type]);
      event_counter_for_frame.insert(
          std::make_pair(it->rtp_timestamp, new_counter));
    } else {
      ++(map_it->second.counter[it->type]);
    }
  }
  return event_counter_for_frame;
}

// Constructs a map from each packet (Packet ID) to counts of each event
// type logged for that packet.
std::map<uint16, LoggingEventCounts> GetEventCountForPacketEvents(
    const std::vector<PacketEvent>& packet_events) {
  std::map<uint16, LoggingEventCounts> event_counter_for_packet;
  for (std::vector<PacketEvent>::const_iterator it = packet_events.begin();
       it != packet_events.end();
       ++it) {
    std::map<uint16, LoggingEventCounts>::iterator map_it =
        event_counter_for_packet.find(it->packet_id);
    if (map_it == event_counter_for_packet.end()) {
      LoggingEventCounts new_counter;
      memset(&new_counter, 0, sizeof(new_counter));
      ++(new_counter.counter[it->type]);
      event_counter_for_packet.insert(
          std::make_pair(it->packet_id, new_counter));
    } else {
      ++(map_it->second.counter[it->type]);
    }
  }
  return event_counter_for_packet;
}

}  // namespace

// Class that sends the packet direct from sender into the receiver with the
// ability to drop packets between the two.
class LoopBackTransport : public transport::PacketSender {
 public:
  explicit LoopBackTransport(scoped_refptr<CastEnvironment> cast_environment)
      : send_packets_(true),
        drop_packets_belonging_to_odd_frames_(false),
        reset_reference_frame_id_(false),
        cast_environment_(cast_environment) {}

  void SetPacketReceiver(
      const transport::PacketReceiverCallback& packet_receiver) {
    packet_receiver_ = packet_receiver;
  }

  virtual bool SendPacket(const Packet& packet) OVERRIDE {
    DCHECK(cast_environment_->CurrentlyOn(CastEnvironment::MAIN));
    if (!send_packets_)
      return false;

    if (drop_packets_belonging_to_odd_frames_) {
      uint32 frame_id = packet[13];
      if (frame_id % 2 == 1)
        return true;
    }

    scoped_ptr<Packet> packet_copy(new Packet(packet));
    if (reset_reference_frame_id_) {
      // Reset the is_reference bit in the cast header.
      (*packet_copy)[kCommonRtpHeaderLength] &= kCastReferenceFrameIdBitReset;
    }
    packet_receiver_.Run(packet_copy.Pass());
    return true;
  }

  void SetSendPackets(bool send_packets) { send_packets_ = send_packets; }

  void DropAllPacketsBelongingToOddFrames() {
    drop_packets_belonging_to_odd_frames_ = true;
  }

  void AlwaysResetReferenceFrameId() { reset_reference_frame_id_ = true; }

 private:
  transport::PacketReceiverCallback packet_receiver_;
  bool send_packets_;
  bool drop_packets_belonging_to_odd_frames_;
  bool reset_reference_frame_id_;
  scoped_refptr<CastEnvironment> cast_environment_;
};

// Class that verifies the audio frames coming out of the receiver.
class TestReceiverAudioCallback
    : public base::RefCountedThreadSafe<TestReceiverAudioCallback> {
 public:
  struct ExpectedAudioFrame {
    PcmAudioFrame audio_frame;
    int num_10ms_blocks;
    base::TimeTicks record_time;
  };

  TestReceiverAudioCallback() : num_called_(0) {}

  void SetExpectedSamplingFrequency(int expected_sampling_frequency) {
    expected_sampling_frequency_ = expected_sampling_frequency;
  }

  void AddExpectedResult(scoped_ptr<PcmAudioFrame> audio_frame,
                         int expected_num_10ms_blocks,
                         const base::TimeTicks& record_time) {
    ExpectedAudioFrame expected_audio_frame;
    expected_audio_frame.audio_frame = *audio_frame;
    expected_audio_frame.num_10ms_blocks = expected_num_10ms_blocks;
    expected_audio_frame.record_time = record_time;
    expected_frame_.push_back(expected_audio_frame);
  }

  void IgnoreAudioFrame(scoped_ptr<PcmAudioFrame> audio_frame,
                        const base::TimeTicks& playout_time) {}

  // Check the audio frame parameters but not the audio samples.
  void CheckBasicAudioFrame(const scoped_ptr<PcmAudioFrame>& audio_frame,
                            const base::TimeTicks& playout_time) {
    EXPECT_FALSE(expected_frame_.empty());  // Test for bug in test code.
    ExpectedAudioFrame expected_audio_frame = expected_frame_.front();
    EXPECT_EQ(audio_frame->channels, kAudioChannels);
    EXPECT_EQ(audio_frame->frequency, expected_sampling_frequency_);
    EXPECT_EQ(static_cast<int>(audio_frame->samples.size()),
              expected_audio_frame.num_10ms_blocks * kAudioChannels *
                  expected_sampling_frequency_ / 100);

    const base::TimeTicks upper_bound =
        expected_audio_frame.record_time +
        base::TimeDelta::FromMilliseconds(kDefaultRtpMaxDelayMs +
                                          kTimerErrorMs);
    EXPECT_GE(upper_bound, playout_time)
        << "playout_time - upper_bound == "
        << (playout_time - upper_bound).InMicroseconds() << " usec";
    EXPECT_LT(expected_audio_frame.record_time, playout_time)
        << "playout_time - expected == "
        << (playout_time - expected_audio_frame.record_time).InMilliseconds()
        << " mS";

    EXPECT_EQ(audio_frame->samples.size(),
              expected_audio_frame.audio_frame.samples.size());
  }

  void CheckPcmAudioFrame(scoped_ptr<PcmAudioFrame> audio_frame,
                          const base::TimeTicks& playout_time) {
    ++num_called_;

    CheckBasicAudioFrame(audio_frame, playout_time);
    ExpectedAudioFrame expected_audio_frame = expected_frame_.front();
    expected_frame_.pop_front();
    if (audio_frame->samples.size() == 0)
      return;  // No more checks needed.

    EXPECT_NEAR(CountZeroCrossings(expected_audio_frame.audio_frame.samples),
                CountZeroCrossings(audio_frame->samples),
                1);
  }

  void CheckCodedPcmAudioFrame(
      scoped_ptr<transport::EncodedAudioFrame> audio_frame,
      const base::TimeTicks& playout_time) {
    ++num_called_;

    EXPECT_FALSE(expected_frame_.empty());  // Test for bug in test code.
    ExpectedAudioFrame expected_audio_frame = expected_frame_.front();
    expected_frame_.pop_front();

    EXPECT_EQ(static_cast<int>(audio_frame->data.size()),
              2 * kAudioChannels * expected_sampling_frequency_ / 100);

    base::TimeDelta time_since_recording =
        playout_time - expected_audio_frame.record_time;

    EXPECT_LE(time_since_recording,
              base::TimeDelta::FromMilliseconds(kDefaultRtpMaxDelayMs +
                                                kTimerErrorMs));

    EXPECT_LT(expected_audio_frame.record_time, playout_time);
    if (audio_frame->data.size() == 0)
      return;  // No more checks needed.

    // We need to convert our "coded" audio frame to our raw format.
    std::vector<int16> output_audio_samples;
    size_t number_of_samples = audio_frame->data.size() / 2;

    for (size_t i = 0; i < number_of_samples; ++i) {
      uint16 sample =
          static_cast<uint8>(audio_frame->data[1 + i * sizeof(uint16)]) +
          (static_cast<uint16>(audio_frame->data[i * sizeof(uint16)]) << 8);
      output_audio_samples.push_back(static_cast<int16>(sample));
    }

    EXPECT_NEAR(CountZeroCrossings(expected_audio_frame.audio_frame.samples),
                CountZeroCrossings(output_audio_samples),
                1);
  }

  int number_times_called() const { return num_called_; }

 protected:
  virtual ~TestReceiverAudioCallback() {}

 private:
  friend class base::RefCountedThreadSafe<TestReceiverAudioCallback>;

  int num_called_;
  int expected_sampling_frequency_;
  std::list<ExpectedAudioFrame> expected_frame_;
};

// Class that verifies the video frames coming out of the receiver.
class TestReceiverVideoCallback
    : public base::RefCountedThreadSafe<TestReceiverVideoCallback> {
 public:
  struct ExpectedVideoFrame {
    int start_value;
    int width;
    int height;
    base::TimeTicks capture_time;
  };

  TestReceiverVideoCallback() : num_called_(0) {}

  void AddExpectedResult(int start_value,
                         int width,
                         int height,
                         const base::TimeTicks& capture_time) {
    ExpectedVideoFrame expected_video_frame;
    expected_video_frame.start_value = start_value;
    expected_video_frame.capture_time = capture_time;
    expected_video_frame.width = width;
    expected_video_frame.height = height;
    expected_frame_.push_back(expected_video_frame);
  }

  void CheckVideoFrame(const scoped_refptr<media::VideoFrame>& video_frame,
                       const base::TimeTicks& render_time) {
    ++num_called_;

    EXPECT_FALSE(expected_frame_.empty());  // Test for bug in test code.
    ExpectedVideoFrame expected_video_frame = expected_frame_.front();
    expected_frame_.pop_front();

    base::TimeDelta time_since_capture =
        render_time - expected_video_frame.capture_time;
    const base::TimeDelta upper_bound = base::TimeDelta::FromMilliseconds(
        kDefaultRtpMaxDelayMs + kTimerErrorMs);

    EXPECT_GE(upper_bound, time_since_capture)
        << "time_since_capture - upper_bound == "
        << (time_since_capture - upper_bound).InMilliseconds() << " mS";
    EXPECT_LE(expected_video_frame.capture_time, render_time);
    EXPECT_EQ(expected_video_frame.width, video_frame->coded_size().width());
    EXPECT_EQ(expected_video_frame.height, video_frame->coded_size().height());

    gfx::Size size(expected_video_frame.width, expected_video_frame.height);
    scoped_refptr<media::VideoFrame> expected_I420_frame =
        media::VideoFrame::CreateFrame(
            VideoFrame::I420, size, gfx::Rect(size), size, base::TimeDelta());
    PopulateVideoFrame(expected_I420_frame, expected_video_frame.start_value);

    EXPECT_GE(I420PSNR(expected_I420_frame, video_frame), kVideoAcceptedPSNR);
  }

  int number_times_called() const { return num_called_; }

 protected:
  virtual ~TestReceiverVideoCallback() {}

 private:
  friend class base::RefCountedThreadSafe<TestReceiverVideoCallback>;

  int num_called_;
  std::list<ExpectedVideoFrame> expected_frame_;
};

// The actual test class, generate synthetic data for both audio and video and
// send those through the sender and receiver and analyzes the result.
class End2EndTest : public ::testing::Test {
 protected:
  End2EndTest()
      : start_time_(),
        testing_clock_sender_(new base::SimpleTestTickClock()),
        testing_clock_receiver_(new base::SimpleTestTickClock()),
        task_runner_(
            new test::FakeSingleThreadTaskRunner(testing_clock_sender_)),
        logging_config_(GetLoggingConfigWithRawEventsAndStatsEnabled()),
        cast_environment_sender_(new CastEnvironment(
            scoped_ptr<base::TickClock>(testing_clock_sender_).Pass(),
            task_runner_,
            task_runner_,
            task_runner_,
            logging_config_)),
        cast_environment_receiver_(new CastEnvironment(
            scoped_ptr<base::TickClock>(testing_clock_receiver_).Pass(),
            task_runner_,
            task_runner_,
            task_runner_,
            logging_config_)),
        receiver_to_sender_(cast_environment_receiver_),
        sender_to_receiver_(cast_environment_sender_),
        test_receiver_audio_callback_(new TestReceiverAudioCallback()),
        test_receiver_video_callback_(new TestReceiverVideoCallback()) {
    testing_clock_sender_->Advance(
        base::TimeDelta::FromMilliseconds(kStartMillisecond));
    testing_clock_receiver_->Advance(
        base::TimeDelta::FromMilliseconds(kStartMillisecond));
    cast_environment_sender_->Logging()->AddRawEventSubscriber(
        &event_subscriber_sender_);
  }

  void SetupConfig(transport::AudioCodec audio_codec,
                   int audio_sampling_frequency,
                   // TODO(miu): 3rd arg is meaningless?!?
                   bool external_audio_decoder,
                   int max_number_of_video_buffers_used) {
    audio_sender_config_.sender_ssrc = 1;
    audio_sender_config_.incoming_feedback_ssrc = 2;
    audio_sender_config_.rtp_config.payload_type = 96;
    audio_sender_config_.use_external_encoder = false;
    audio_sender_config_.frequency = audio_sampling_frequency;
    audio_sender_config_.channels = kAudioChannels;
    audio_sender_config_.bitrate = kDefaultAudioEncoderBitrate;
    audio_sender_config_.codec = audio_codec;

    audio_receiver_config_.feedback_ssrc =
        audio_sender_config_.incoming_feedback_ssrc;
    audio_receiver_config_.incoming_ssrc = audio_sender_config_.sender_ssrc;
    audio_receiver_config_.rtp_payload_type =
        audio_sender_config_.rtp_config.payload_type;
    audio_receiver_config_.use_external_decoder = external_audio_decoder;
    audio_receiver_config_.frequency = audio_sender_config_.frequency;
    audio_receiver_config_.channels = kAudioChannels;
    audio_receiver_config_.codec = audio_sender_config_.codec;

    test_receiver_audio_callback_->SetExpectedSamplingFrequency(
        audio_receiver_config_.frequency);

    video_sender_config_.sender_ssrc = 3;
    video_sender_config_.incoming_feedback_ssrc = 4;
    video_sender_config_.rtp_config.payload_type = 97;
    video_sender_config_.use_external_encoder = false;
    video_sender_config_.width = kVideoHdWidth;
    video_sender_config_.height = kVideoHdHeight;
    video_sender_config_.max_bitrate = 5000000;
    video_sender_config_.min_bitrate = 1000000;
    video_sender_config_.start_bitrate = 5000000;
    video_sender_config_.max_qp = 30;
    video_sender_config_.min_qp = 4;
    video_sender_config_.max_frame_rate = 30;
    video_sender_config_.max_number_of_video_buffers_used =
        max_number_of_video_buffers_used;
    video_sender_config_.codec = transport::kVp8;
    video_sender_config_.number_of_cores = 1;

    video_receiver_config_.feedback_ssrc =
        video_sender_config_.incoming_feedback_ssrc;
    video_receiver_config_.incoming_ssrc = video_sender_config_.sender_ssrc;
    video_receiver_config_.rtp_payload_type =
        video_sender_config_.rtp_config.payload_type;
    video_receiver_config_.use_external_decoder = false;
    video_receiver_config_.codec = video_sender_config_.codec;

    transport_audio_config_.base.ssrc = audio_sender_config_.sender_ssrc;
    transport_audio_config_.codec = audio_sender_config_.codec;
    transport_audio_config_.base.rtp_config = audio_sender_config_.rtp_config;
    transport_audio_config_.frequency = audio_sender_config_.frequency;
    transport_audio_config_.channels = audio_sender_config_.channels;
    transport_video_config_.base.ssrc = video_sender_config_.sender_ssrc;
    transport_video_config_.codec = video_sender_config_.codec;
    transport_video_config_.base.rtp_config = video_sender_config_.rtp_config;
  }

  void Create() {
    cast_receiver_ = CastReceiver::Create(cast_environment_receiver_,
                                          audio_receiver_config_,
                                          video_receiver_config_,
                                          &receiver_to_sender_);
    net::IPEndPoint dummy_endpoint;
    transport_sender_.reset(new transport::CastTransportSenderImpl(
        NULL,
        testing_clock_sender_,
        dummy_endpoint,
        logging_config_,
        base::Bind(&UpdateCastTransportStatus),
        base::Bind(&End2EndTest::LogRawEvents, base::Unretained(this)),
        base::TimeDelta::FromSeconds(1),
        task_runner_,
        &sender_to_receiver_));
    transport_sender_->InitializeAudio(transport_audio_config_);
    transport_sender_->InitializeVideo(transport_video_config_);

    cast_sender_ =
        CastSender::Create(cast_environment_sender_, transport_sender_.get());

    // Initializing audio and video senders.
    cast_sender_->InitializeAudio(audio_sender_config_,
                                  base::Bind(&AudioInitializationStatus));
    cast_sender_->InitializeVideo(
        video_sender_config_, base::Bind(&VideoInitializationStatus), NULL);

    receiver_to_sender_.SetPacketReceiver(cast_sender_->packet_receiver());
    sender_to_receiver_.SetPacketReceiver(cast_receiver_->packet_receiver());

    audio_frame_input_ = cast_sender_->audio_frame_input();
    video_frame_input_ = cast_sender_->video_frame_input();

    frame_receiver_ = cast_receiver_->frame_receiver();

    audio_bus_factory_.reset(
        new TestAudioBusFactory(audio_sender_config_.channels,
                                audio_sender_config_.frequency,
                                kSoundFrequency,
                                kSoundVolume));
  }

  virtual ~End2EndTest() {
    cast_environment_sender_->Logging()->RemoveRawEventSubscriber(
        &event_subscriber_sender_);
  }

  virtual void TearDown() OVERRIDE {
    cast_sender_.reset();
    cast_receiver_.reset();
    task_runner_->RunTasks();
  }

  void SendVideoFrame(int start_value, const base::TimeTicks& capture_time) {
    if (start_time_.is_null())
      start_time_ = capture_time;
    base::TimeDelta time_diff = capture_time - start_time_;
    gfx::Size size(video_sender_config_.width, video_sender_config_.height);
    EXPECT_TRUE(VideoFrame::IsValidConfig(
        VideoFrame::I420, size, gfx::Rect(size), size));
    scoped_refptr<media::VideoFrame> video_frame =
        media::VideoFrame::CreateFrame(
            VideoFrame::I420, size, gfx::Rect(size), size, time_diff);
    PopulateVideoFrame(video_frame, start_value);
    video_frame_input_->InsertRawVideoFrame(video_frame, capture_time);
  }

  void RunTasks(int during_ms) {
    for (int i = 0; i < during_ms; ++i) {
      // Call process the timers every 1 ms.
      testing_clock_sender_->Advance(base::TimeDelta::FromMilliseconds(1));
      testing_clock_receiver_->Advance(base::TimeDelta::FromMilliseconds(1));
      task_runner_->RunTasks();
    }
  }

  void LogRawEvents(const std::vector<PacketEvent>& packet_events) {
    EXPECT_FALSE(packet_events.empty());
    for (std::vector<media::cast::PacketEvent>::const_iterator it =
             packet_events.begin();
         it != packet_events.end();
         ++it) {
      cast_environment_sender_->Logging()->InsertPacketEvent(it->timestamp,
                                                             it->type,
                                                             it->rtp_timestamp,
                                                             it->frame_id,
                                                             it->packet_id,
                                                             it->max_packet_id,
                                                             it->size);
    }
  }

  AudioReceiverConfig audio_receiver_config_;
  VideoReceiverConfig video_receiver_config_;
  AudioSenderConfig audio_sender_config_;
  VideoSenderConfig video_sender_config_;
  transport::CastTransportAudioConfig transport_audio_config_;
  transport::CastTransportVideoConfig transport_video_config_;

  base::TimeTicks start_time_;
  base::SimpleTestTickClock* testing_clock_sender_;
  base::SimpleTestTickClock* testing_clock_receiver_;
  scoped_refptr<test::FakeSingleThreadTaskRunner> task_runner_;
  CastLoggingConfig logging_config_;
  scoped_refptr<CastEnvironment> cast_environment_sender_;
  scoped_refptr<CastEnvironment> cast_environment_receiver_;

  LoopBackTransport receiver_to_sender_;
  LoopBackTransport sender_to_receiver_;
  scoped_ptr<transport::CastTransportSenderImpl> transport_sender_;

  scoped_ptr<CastReceiver> cast_receiver_;
  scoped_ptr<CastSender> cast_sender_;
  scoped_refptr<AudioFrameInput> audio_frame_input_;
  scoped_refptr<VideoFrameInput> video_frame_input_;
  scoped_refptr<FrameReceiver> frame_receiver_;

  scoped_refptr<TestReceiverAudioCallback> test_receiver_audio_callback_;
  scoped_refptr<TestReceiverVideoCallback> test_receiver_video_callback_;

  scoped_ptr<TestAudioBusFactory> audio_bus_factory_;

  SimpleEventSubscriber event_subscriber_sender_;
  std::vector<FrameEvent> frame_events_;
  std::vector<PacketEvent> packet_events_;
  std::vector<GenericEvent> generic_events_;
  // |transport_sender_| has a RepeatingTimer which needs a MessageLoop.
  base::MessageLoop message_loop_;
};

TEST_F(End2EndTest, LoopNoLossPcm16) {
  SetupConfig(transport::kPcm16, 32000, false, 1);
  // Reduce video resolution to allow processing multiple frames within a
  // reasonable time frame.
  video_sender_config_.width = kVideoQcifWidth;
  video_sender_config_.height = kVideoQcifHeight;
  Create();

  int video_start = kVideoStart;
  int audio_diff = kFrameTimerMs;
  int i = 0;

  for (; i < 300; ++i) {
    int num_10ms_blocks = audio_diff / 10;
    audio_diff -= num_10ms_blocks * 10;

    scoped_ptr<AudioBus> audio_bus(audio_bus_factory_->NextAudioBus(
        base::TimeDelta::FromMilliseconds(10) * num_10ms_blocks));

    base::TimeTicks send_time = testing_clock_sender_->NowTicks();
    if (i != 0) {
      // Due to the re-sampler and NetEq in the webrtc AudioCodingModule the
      // first samples will be 0 and then slowly ramp up to its real
      // amplitude;
      // ignore the first frame.
      test_receiver_audio_callback_->AddExpectedResult(
          ToPcmAudioFrame(*audio_bus, audio_sender_config_.frequency),
          num_10ms_blocks,
          send_time);
    }

    audio_frame_input_->InsertAudio(audio_bus.Pass(), send_time);

    test_receiver_video_callback_->AddExpectedResult(
        video_start,
        video_sender_config_.width,
        video_sender_config_.height,
        send_time);
    SendVideoFrame(video_start, send_time);

    if (i == 0) {
      frame_receiver_->GetRawAudioFrame(
          num_10ms_blocks,
          audio_sender_config_.frequency,
          base::Bind(&TestReceiverAudioCallback::IgnoreAudioFrame,
                     test_receiver_audio_callback_));
    } else {
      frame_receiver_->GetRawAudioFrame(
          num_10ms_blocks,
          audio_sender_config_.frequency,
          base::Bind(&TestReceiverAudioCallback::CheckPcmAudioFrame,
                     test_receiver_audio_callback_));
    }

    frame_receiver_->GetRawVideoFrame(
        base::Bind(&TestReceiverVideoCallback::CheckVideoFrame,
                   test_receiver_video_callback_));

    RunTasks(kFrameTimerMs);
    audio_diff += kFrameTimerMs;
    video_start++;
  }

  RunTasks(2 * kFrameTimerMs + 1);  // Empty the receiver pipeline.
  EXPECT_EQ(i - 1, test_receiver_audio_callback_->number_times_called());
  EXPECT_EQ(i, test_receiver_video_callback_->number_times_called());
}

// This tests our external decoder interface for Audio.
// Audio test without packet loss using raw PCM 16 audio "codec";
TEST_F(End2EndTest, LoopNoLossPcm16ExternalDecoder) {
  SetupConfig(transport::kPcm16, 32000, true, 1);
  Create();

  int i = 0;
  for (; i < 10; ++i) {
    base::TimeTicks send_time = testing_clock_sender_->NowTicks();
    scoped_ptr<AudioBus> audio_bus(audio_bus_factory_->NextAudioBus(
        base::TimeDelta::FromMilliseconds(10)));
    test_receiver_audio_callback_->AddExpectedResult(
        ToPcmAudioFrame(*audio_bus, audio_sender_config_.frequency),
        1,
        send_time);

    audio_frame_input_->InsertAudio(audio_bus.Pass(), send_time);

    RunTasks(10);
    frame_receiver_->GetCodedAudioFrame(
        base::Bind(&TestReceiverAudioCallback::CheckCodedPcmAudioFrame,
                   test_receiver_audio_callback_));
  }
  RunTasks(2 * kFrameTimerMs + 1);  // Empty the receiver pipeline.
  EXPECT_EQ(10, test_receiver_audio_callback_->number_times_called());
}

// This tests our Opus audio codec without video.
TEST_F(End2EndTest, LoopNoLossOpus) {
  SetupConfig(transport::kOpus, kDefaultAudioSamplingRate, false, 1);
  Create();

  int i = 0;
  for (; i < 10; ++i) {
    int num_10ms_blocks = 3;
    base::TimeTicks send_time = testing_clock_sender_->NowTicks();

    scoped_ptr<AudioBus> audio_bus(audio_bus_factory_->NextAudioBus(
        base::TimeDelta::FromMilliseconds(10) * num_10ms_blocks));

    if (i != 0) {
      test_receiver_audio_callback_->AddExpectedResult(
          ToPcmAudioFrame(*audio_bus, audio_sender_config_.frequency),
          num_10ms_blocks,
          send_time);
    }

    audio_frame_input_->InsertAudio(audio_bus.Pass(), send_time);

    RunTasks(30);

    if (i == 0) {
      frame_receiver_->GetRawAudioFrame(
          num_10ms_blocks,
          audio_sender_config_.frequency,
          base::Bind(&TestReceiverAudioCallback::IgnoreAudioFrame,
                     test_receiver_audio_callback_));
    } else {
      frame_receiver_->GetRawAudioFrame(
          num_10ms_blocks,
          audio_sender_config_.frequency,
          base::Bind(&TestReceiverAudioCallback::CheckPcmAudioFrame,
                     test_receiver_audio_callback_));
    }
  }
  RunTasks(2 * kFrameTimerMs + 1);  // Empty the receiver pipeline.
  EXPECT_EQ(i - 1, test_receiver_audio_callback_->number_times_called());
}

// This tests start sending audio and video at start-up time before the receiver
// is ready; it sends 2 frames before the receiver comes online.
TEST_F(End2EndTest, StartSenderBeforeReceiver) {
  SetupConfig(transport::kOpus, kDefaultAudioSamplingRate, false, 1);
  Create();

  int video_start = kVideoStart;
  int audio_diff = kFrameTimerMs;

  sender_to_receiver_.SetSendPackets(false);

  const int test_delay_ms = 100;

  base::TimeTicks initial_send_time;
  for (int i = 0; i < 2; ++i) {
    int num_10ms_blocks = audio_diff / 10;
    audio_diff -= num_10ms_blocks * 10;

    base::TimeTicks send_time = testing_clock_sender_->NowTicks();
    if (initial_send_time.is_null())
      initial_send_time = send_time;
    scoped_ptr<AudioBus> audio_bus(audio_bus_factory_->NextAudioBus(
        base::TimeDelta::FromMilliseconds(10) * num_10ms_blocks));

    audio_frame_input_->InsertAudio(audio_bus.Pass(), send_time);

    // Frame will be rendered with 100mS delay, as the transmission is delayed.
    // The receiver at this point cannot be synced to the sender's clock, as no
    // packets, and specifically no RTCP packets were sent.
    test_receiver_video_callback_->AddExpectedResult(
        video_start,
        video_sender_config_.width,
        video_sender_config_.height,
        initial_send_time +
            base::TimeDelta::FromMilliseconds(test_delay_ms + kFrameTimerMs));

    SendVideoFrame(video_start, send_time);
    RunTasks(kFrameTimerMs);
    audio_diff += kFrameTimerMs;
    video_start++;
  }

  RunTasks(test_delay_ms);
  sender_to_receiver_.SetSendPackets(true);

  int j = 0;
  const int number_of_audio_frames_to_ignore = 2;
  for (; j < 10; ++j) {
    int num_10ms_blocks = audio_diff / 10;
    audio_diff -= num_10ms_blocks * 10;
    base::TimeTicks send_time = testing_clock_sender_->NowTicks();

    scoped_ptr<AudioBus> audio_bus(audio_bus_factory_->NextAudioBus(
        base::TimeDelta::FromMilliseconds(10) * num_10ms_blocks));

    if (j >= number_of_audio_frames_to_ignore) {
      test_receiver_audio_callback_->AddExpectedResult(
          ToPcmAudioFrame(*audio_bus, audio_sender_config_.frequency),
          num_10ms_blocks,
          send_time);
    }

    audio_frame_input_->InsertAudio(audio_bus.Pass(), send_time);

    test_receiver_video_callback_->AddExpectedResult(
        video_start,
        video_sender_config_.width,
        video_sender_config_.height,
        send_time);

    SendVideoFrame(video_start, send_time);
    RunTasks(kFrameTimerMs);
    audio_diff += kFrameTimerMs;

    if (j < number_of_audio_frames_to_ignore) {
      frame_receiver_->GetRawAudioFrame(
          num_10ms_blocks,
          audio_sender_config_.frequency,
          base::Bind(&TestReceiverAudioCallback::IgnoreAudioFrame,
                     test_receiver_audio_callback_));
    } else {
      frame_receiver_->GetRawAudioFrame(
          num_10ms_blocks,
          audio_sender_config_.frequency,
          base::Bind(&TestReceiverAudioCallback::CheckPcmAudioFrame,
                     test_receiver_audio_callback_));
    }
    frame_receiver_->GetRawVideoFrame(
        base::Bind(&TestReceiverVideoCallback::CheckVideoFrame,
                   test_receiver_video_callback_));
    video_start++;
  }
  RunTasks(2 * kFrameTimerMs + 1);  // Empty the receiver pipeline.
  EXPECT_EQ(j - number_of_audio_frames_to_ignore,
            test_receiver_audio_callback_->number_times_called());
  EXPECT_EQ(j, test_receiver_video_callback_->number_times_called());
}

// This tests a network glitch lasting for 10 video frames.
// Flaky. See crbug.com/351596.
TEST_F(End2EndTest, DISABLED_GlitchWith3Buffers) {
  SetupConfig(transport::kOpus, kDefaultAudioSamplingRate, false, 3);
  video_sender_config_.rtp_config.max_delay_ms = 67;
  video_receiver_config_.rtp_max_delay_ms = 67;
  Create();

  int video_start = kVideoStart;
  base::TimeTicks send_time;
  // Frames will rendered on completion until the render time stabilizes, i.e.
  // we got enough data.
  const int frames_before_glitch = 20;
  for (int i = 0; i < frames_before_glitch; ++i) {
    send_time = testing_clock_sender_->NowTicks();
    SendVideoFrame(video_start, send_time);
    test_receiver_video_callback_->AddExpectedResult(
        video_start,
        video_sender_config_.width,
        video_sender_config_.height,
        send_time);
    frame_receiver_->GetRawVideoFrame(
        base::Bind(&TestReceiverVideoCallback::CheckVideoFrame,
                   test_receiver_video_callback_));
    RunTasks(kFrameTimerMs);
    video_start++;
  }

  // Introduce a glitch lasting for 10 frames.
  sender_to_receiver_.SetSendPackets(false);
  for (int i = 0; i < 10; ++i) {
    send_time = testing_clock_sender_->NowTicks();
    // First 3 will be sent and lost.
    SendVideoFrame(video_start, send_time);
    RunTasks(kFrameTimerMs);
    video_start++;
  }
  sender_to_receiver_.SetSendPackets(true);
  RunTasks(100);
  send_time = testing_clock_sender_->NowTicks();

  // Frame 1 should be acked by now and we should have an opening to send 4.
  SendVideoFrame(video_start, send_time);
  RunTasks(kFrameTimerMs);

  // Frames 1-3 are old frames by now, and therefore should be decoded, but
  // not rendered. The next frame we expect to render is frame #4.
  test_receiver_video_callback_->AddExpectedResult(video_start,
                                                   video_sender_config_.width,
                                                   video_sender_config_.height,
                                                   send_time);

  frame_receiver_->GetRawVideoFrame(
      base::Bind(&TestReceiverVideoCallback::CheckVideoFrame,
                 test_receiver_video_callback_));

  RunTasks(2 * kFrameTimerMs + 1);  // Empty the receiver pipeline.
  EXPECT_EQ(frames_before_glitch + 1,
            test_receiver_video_callback_->number_times_called());
}

TEST_F(End2EndTest, DropEveryOtherFrame3Buffers) {
  SetupConfig(transport::kOpus, kDefaultAudioSamplingRate, false, 3);
  video_sender_config_.rtp_config.max_delay_ms = 67;
  video_receiver_config_.rtp_max_delay_ms = 67;
  Create();
  sender_to_receiver_.DropAllPacketsBelongingToOddFrames();

  int video_start = kVideoStart;
  base::TimeTicks send_time;

  int i = 0;
  for (; i < 20; ++i) {
    send_time = testing_clock_sender_->NowTicks();
    SendVideoFrame(video_start, send_time);

    if (i % 2 == 0) {
      test_receiver_video_callback_->AddExpectedResult(
          video_start,
          video_sender_config_.width,
          video_sender_config_.height,
          send_time);

      // GetRawVideoFrame will not return the frame until we are close in
      // time before we should render the frame.
      frame_receiver_->GetRawVideoFrame(
          base::Bind(&TestReceiverVideoCallback::CheckVideoFrame,
                     test_receiver_video_callback_));
    }
    RunTasks(kFrameTimerMs);
    video_start++;
  }

  RunTasks(2 * kFrameTimerMs + 1);  // Empty the pipeline.
  EXPECT_EQ(i / 2, test_receiver_video_callback_->number_times_called());
}

TEST_F(End2EndTest, ResetReferenceFrameId) {
  SetupConfig(transport::kOpus, kDefaultAudioSamplingRate, false, 3);
  video_sender_config_.rtp_config.max_delay_ms = 67;
  video_receiver_config_.rtp_max_delay_ms = 67;
  Create();
  sender_to_receiver_.AlwaysResetReferenceFrameId();

  int frames_counter = 0;
  for (; frames_counter < 10; ++frames_counter) {
    const base::TimeTicks send_time = testing_clock_sender_->NowTicks();
    SendVideoFrame(frames_counter, send_time);

    test_receiver_video_callback_->AddExpectedResult(
        frames_counter,
        video_sender_config_.width,
        video_sender_config_.height,
        send_time);

    // GetRawVideoFrame will not return the frame until we are close to the
    // time in which we should render the frame.
    frame_receiver_->GetRawVideoFrame(
        base::Bind(&TestReceiverVideoCallback::CheckVideoFrame,
                   test_receiver_video_callback_));
    RunTasks(kFrameTimerMs);
  }
  RunTasks(2 * kFrameTimerMs + 1);  // Empty the pipeline.
  EXPECT_EQ(frames_counter,
            test_receiver_video_callback_->number_times_called());
}

TEST_F(End2EndTest, CryptoVideo) {
  SetupConfig(transport::kPcm16, 32000, false, 1);

  transport_video_config_.base.aes_iv_mask =
      ConvertFromBase16String("1234567890abcdeffedcba0987654321");
  transport_video_config_.base.aes_key =
      ConvertFromBase16String("deadbeefcafeb0b0b0b0cafedeadbeef");

  video_receiver_config_.aes_iv_mask = transport_video_config_.base.aes_iv_mask;
  video_receiver_config_.aes_key = transport_video_config_.base.aes_key;

  Create();

  int frames_counter = 0;
  for (; frames_counter < 3; ++frames_counter) {
    const base::TimeTicks send_time = testing_clock_sender_->NowTicks();

    SendVideoFrame(frames_counter, send_time);

    test_receiver_video_callback_->AddExpectedResult(
        frames_counter,
        video_sender_config_.width,
        video_sender_config_.height,
        send_time);

    // GetRawVideoFrame will not return the frame until we are close to the
    // time in which we should render the frame.
    frame_receiver_->GetRawVideoFrame(
        base::Bind(&TestReceiverVideoCallback::CheckVideoFrame,
                   test_receiver_video_callback_));
    RunTasks(kFrameTimerMs);
  }
  RunTasks(2 * kFrameTimerMs + 1);  // Empty the pipeline.
  EXPECT_EQ(frames_counter,
            test_receiver_video_callback_->number_times_called());
}

TEST_F(End2EndTest, CryptoAudio) {
  SetupConfig(transport::kPcm16, 32000, false, 1);

  transport_audio_config_.base.aes_iv_mask =
      ConvertFromBase16String("abcdeffedcba12345678900987654321");
  transport_audio_config_.base.aes_key =
      ConvertFromBase16String("deadbeefcafecafedeadbeefb0b0b0b0");

  audio_receiver_config_.aes_iv_mask = transport_audio_config_.base.aes_iv_mask;
  audio_receiver_config_.aes_key = transport_audio_config_.base.aes_key;

  Create();

  int frames_counter = 0;
  for (; frames_counter < 3; ++frames_counter) {
    int num_10ms_blocks = 2;

    const base::TimeTicks send_time = testing_clock_sender_->NowTicks();

    scoped_ptr<AudioBus> audio_bus(audio_bus_factory_->NextAudioBus(
        base::TimeDelta::FromMilliseconds(10) * num_10ms_blocks));

    if (frames_counter != 0) {
      // Due to the re-sampler and NetEq in the webrtc AudioCodingModule the
      // first samples will be 0 and then slowly ramp up to its real
      // amplitude;
      // ignore the first frame.
      test_receiver_audio_callback_->AddExpectedResult(
          ToPcmAudioFrame(*audio_bus, audio_sender_config_.frequency),
          num_10ms_blocks,
          send_time);
    }
    audio_frame_input_->InsertAudio(audio_bus.Pass(), send_time);

    RunTasks(num_10ms_blocks * 10);

    if (frames_counter == 0) {
      frame_receiver_->GetRawAudioFrame(
          num_10ms_blocks,
          32000,
          base::Bind(&TestReceiverAudioCallback::IgnoreAudioFrame,
                     test_receiver_audio_callback_));
    } else {
      frame_receiver_->GetRawAudioFrame(
          num_10ms_blocks,
          32000,
          base::Bind(&TestReceiverAudioCallback::CheckPcmAudioFrame,
                     test_receiver_audio_callback_));
    }
  }
  RunTasks(2 * kFrameTimerMs + 1);  // Empty the pipeline.
  EXPECT_EQ(frames_counter - 1,
            test_receiver_audio_callback_->number_times_called());
}

// Video test without packet loss - tests the logging aspects of the end2end,
// but is basically equivalent to LoopNoLossPcm16.
TEST_F(End2EndTest, VideoLogging) {
  SetupConfig(transport::kPcm16, 32000, false, 1);
  Create();

  int video_start = kVideoStart;
  const int num_frames = 5;
  for (int i = 0; i < num_frames; ++i) {
    base::TimeTicks send_time = testing_clock_sender_->NowTicks();
    test_receiver_video_callback_->AddExpectedResult(
        video_start,
        video_sender_config_.width,
        video_sender_config_.height,
        send_time);

    SendVideoFrame(video_start, send_time);
    RunTasks(kFrameTimerMs);

    frame_receiver_->GetRawVideoFrame(
        base::Bind(&TestReceiverVideoCallback::CheckVideoFrame,
                   test_receiver_video_callback_));

    video_start++;
  }

  // Basic tests.
  RunTasks(2 * kFrameTimerMs + 1);  // Empty the receiver pipeline.
  int num_callbacks_called =
      test_receiver_video_callback_->number_times_called();
  EXPECT_EQ(num_frames, num_callbacks_called);

  RunTasks(750);  // Make sure that we send a RTCP message with the log.

  // Logging tests.
  // Frame logging.
  // Verify that all frames and all required events were logged.
  event_subscriber_sender_.GetFrameEventsAndReset(&frame_events_);

  // For each frame, count the number of events that occurred for each event
  // for that frame.
  std::map<RtpTimestamp, LoggingEventCounts> event_counter_for_frame =
      GetEventCountForFrameEvents(frame_events_);

  // Verify that there are logs for expected number of frames.
  EXPECT_EQ(num_frames, static_cast<int>(event_counter_for_frame.size()));

  // Verify that each frame have the expected types of events logged.
  for (std::map<RtpTimestamp, LoggingEventCounts>::iterator map_it =
           event_counter_for_frame.begin();
       map_it != event_counter_for_frame.end();
       ++map_it) {
    int total_event_count_for_frame = 0;
    for (int i = 0; i < kNumOfLoggingEvents; ++i) {
      total_event_count_for_frame += map_it->second.counter[i];
    }

    int expected_event_count_for_frame = 0;

    EXPECT_EQ(1, map_it->second.counter[kVideoFrameSentToEncoder]);
    expected_event_count_for_frame +=
        map_it->second.counter[kVideoFrameSentToEncoder];

    EXPECT_EQ(1, map_it->second.counter[kVideoFrameEncoded]);
    expected_event_count_for_frame +=
        map_it->second.counter[kVideoFrameEncoded];

    EXPECT_EQ(1, map_it->second.counter[kVideoFrameReceived]);
    expected_event_count_for_frame +=
        map_it->second.counter[kVideoFrameReceived];

    EXPECT_EQ(1, map_it->second.counter[kVideoRenderDelay]);
    expected_event_count_for_frame += map_it->second.counter[kVideoRenderDelay];

    EXPECT_EQ(1, map_it->second.counter[kVideoFrameDecoded]);
    expected_event_count_for_frame +=
        map_it->second.counter[kVideoFrameDecoded];

    // There is no guarantee that kVideoAckSent is loggeed exactly once per
    // frame.
    EXPECT_GT(map_it->second.counter[kVideoAckSent], 0);
    expected_event_count_for_frame += map_it->second.counter[kVideoAckSent];

    // There is no guarantee that kVideoAckReceived is loggeed exactly once per
    // frame.
    EXPECT_GT(map_it->second.counter[kVideoAckReceived], 0);
    expected_event_count_for_frame += map_it->second.counter[kVideoAckReceived];

    // Verify that there were no other events logged with respect to this
    // frame.
    // (i.e. Total event count = expected event count)
    EXPECT_EQ(total_event_count_for_frame, expected_event_count_for_frame);
  }

  // Packet logging.
  // Verify that all packet related events were logged.
  event_subscriber_sender_.GetPacketEventsAndReset(&packet_events_);
  std::map<uint16, LoggingEventCounts> event_count_for_packet =
      GetEventCountForPacketEvents(packet_events_);

  // Verify that each packet have the expected types of events logged.
  for (std::map<uint16, LoggingEventCounts>::iterator map_it =
           event_count_for_packet.begin();
       map_it != event_count_for_packet.end();
       ++map_it) {
    int total_event_count_for_packet = 0;
    for (int i = 0; i < kNumOfLoggingEvents; ++i) {
      total_event_count_for_packet += map_it->second.counter[i];
    }

    int expected_event_count_for_packet = 0;
    EXPECT_GT(map_it->second.counter[kVideoPacketReceived], 0);
    expected_event_count_for_packet +=
        map_it->second.counter[kVideoPacketReceived];

    // Verify that there were no other events logged with respect to this
    // packet. (i.e. Total event count = expected event count)
    EXPECT_EQ(total_event_count_for_packet, expected_event_count_for_packet);
  }
}

// Audio test without packet loss - tests the logging aspects of the end2end,
// but is basically equivalent to LoopNoLossPcm16.
TEST_F(End2EndTest, AudioLogging) {
  SetupConfig(transport::kPcm16, 32000, false, 1);
  Create();

  int audio_diff = kFrameTimerMs;
  const int num_audio_buses = 10;
  int num_frames = 0;
  for (int i = 0; i < num_audio_buses; ++i) {
    int num_10ms_blocks = audio_diff / 10;
    audio_diff -= num_10ms_blocks * 10;
    base::TimeTicks send_time = testing_clock_sender_->NowTicks();

    // Each audio bus can contain more than one frame.
    scoped_ptr<AudioBus> audio_bus(audio_bus_factory_->NextAudioBus(
        base::TimeDelta::FromMilliseconds(10) * num_10ms_blocks));
    num_frames += num_10ms_blocks;

    if (i != 0) {
      // Due to the re-sampler and NetEq in the webrtc AudioCodingModule the
      // first samples will be 0 and then slowly ramp up to its real
      // amplitude;
      // ignore the first frame.
      test_receiver_audio_callback_->AddExpectedResult(
          ToPcmAudioFrame(*audio_bus, audio_sender_config_.frequency),
          num_10ms_blocks,
          send_time);
    }

    audio_frame_input_->InsertAudio(audio_bus.Pass(), send_time);

    RunTasks(kFrameTimerMs);
    audio_diff += kFrameTimerMs;

    if (i == 0) {
      frame_receiver_->GetRawAudioFrame(
          num_10ms_blocks,
          audio_sender_config_.frequency,
          base::Bind(&TestReceiverAudioCallback::IgnoreAudioFrame,
                     test_receiver_audio_callback_));
    } else {
      frame_receiver_->GetRawAudioFrame(
          num_10ms_blocks,
          audio_sender_config_.frequency,
          base::Bind(&TestReceiverAudioCallback::CheckPcmAudioFrame,
                     test_receiver_audio_callback_));
    }
  }

  // Basic tests.
  RunTasks(2 * kFrameTimerMs + 1);  // Empty the receiver pipeline.

  int num_times_called = test_receiver_audio_callback_->number_times_called();
  EXPECT_EQ(num_audio_buses - 1, num_times_called);

  // Logging tests.
  // Verify that all frames and all required events were logged.
  event_subscriber_sender_.GetFrameEventsAndReset(&frame_events_);

  // Construct a map from each frame (RTP timestamp) to a count of each event
  // type logged for that frame.
  std::map<RtpTimestamp, LoggingEventCounts> event_counter_for_frame =
      GetEventCountForFrameEvents(frame_events_);

  int received_count = 0;
  int encoded_count = 0;

  // Verify the right number of events were logged for each event type.
  for (std::map<RtpTimestamp, LoggingEventCounts>::iterator it =
           event_counter_for_frame.begin();
       it != event_counter_for_frame.end();
       ++it) {
    received_count += it->second.counter[kAudioFrameReceived];
    encoded_count += it->second.counter[kAudioFrameEncoded];
  }

  EXPECT_EQ(num_frames, received_count);
  EXPECT_EQ(num_frames, encoded_count);

  std::map<RtpTimestamp, LoggingEventCounts>::iterator map_it =
      event_counter_for_frame.begin();

  // Verify that each frame have the expected types of events logged.
  // TODO(imcheng): This only checks the first frame. This doesn't work
  // properly for all frames because:
  // 1. kAudioPlayoutDelay and kAudioFrameDecoded RTP timestamps aren't
  // exactly aligned with those of kAudioFrameReceived and kAudioFrameEncoded.
  // Note that these RTP timestamps are output from webrtc::AudioCodingModule
  // which are different from RTP timestamps that the cast library generates
  // during the encode step (and which are sent to receiver). The first frame
  // just happen to be aligned.
  // 2. Currently, kAudioFrameDecoded and kAudioPlayoutDelay are logged per
  // audio bus.
  // Both 1 and 2 may change since we are currently refactoring audio_decoder.
  // 3. There is no guarantee that exactly one kAudioAckSent is sent per frame.
  int total_event_count_for_frame = 0;
  for (int j = 0; j < kNumOfLoggingEvents; ++j)
    total_event_count_for_frame += map_it->second.counter[j];

  int expected_event_count_for_frame = 0;

  EXPECT_EQ(1, map_it->second.counter[kAudioFrameReceived]);
  expected_event_count_for_frame += map_it->second.counter[kAudioFrameReceived];

  EXPECT_EQ(1, map_it->second.counter[kAudioFrameEncoded]);
  expected_event_count_for_frame += map_it->second.counter[kAudioFrameEncoded];

  EXPECT_EQ(1, map_it->second.counter[kAudioPlayoutDelay]);
  expected_event_count_for_frame += map_it->second.counter[kAudioPlayoutDelay];

  EXPECT_EQ(1, map_it->second.counter[kAudioFrameDecoded]);
  expected_event_count_for_frame += map_it->second.counter[kAudioFrameDecoded];

  EXPECT_GT(map_it->second.counter[kAudioAckSent], 0);
  expected_event_count_for_frame += map_it->second.counter[kAudioAckSent];

  // Verify that there were no other events logged with respect to this frame.
  // (i.e. Total event count = expected event count)
  EXPECT_EQ(total_event_count_for_frame, expected_event_count_for_frame);
}

// TODO(pwestin): Add repeatable packet loss test.
// TODO(pwestin): Add test for misaligned send get calls.
// TODO(pwestin): Add more tests that does not resample.
// TODO(pwestin): Add test when we have starvation for our RunTask.

}  // namespace cast
}  // namespace media