1 /*
2  *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #ifndef CALL_FAKE_NETWORK_PIPE_H_
12 #define CALL_FAKE_NETWORK_PIPE_H_
13 
14 #include <deque>
15 #include <map>
16 #include <memory>
17 #include <queue>
18 #include <set>
19 #include <string>
20 #include <vector>
21 
22 #include "api/call/transport.h"
23 #include "api/test/simulated_network.h"
24 #include "call/call.h"
25 #include "call/simulated_packet_receiver.h"
26 #include "rtc_base/constructor_magic.h"
27 #include "rtc_base/synchronization/mutex.h"
28 #include "rtc_base/thread_annotations.h"
29 
30 namespace webrtc {
31 
32 class Clock;
33 class PacketReceiver;
34 enum class MediaType;
35 
36 class NetworkPacket {
37  public:
38   NetworkPacket(rtc::CopyOnWriteBuffer packet,
39                 int64_t send_time,
40                 int64_t arrival_time,
41                 absl::optional<PacketOptions> packet_options,
42                 bool is_rtcp,
43                 MediaType media_type,
44                 absl::optional<int64_t> packet_time_us,
45                 Transport* transport);
46 
47   // Disallow copy constructor and copy assignment (no deep copies of |data_|).
48   NetworkPacket(const NetworkPacket&) = delete;
49   ~NetworkPacket();
50   NetworkPacket& operator=(const NetworkPacket&) = delete;
51   // Allow move constructor/assignment, so that we can use in stl containers.
52   NetworkPacket(NetworkPacket&&);
53   NetworkPacket& operator=(NetworkPacket&&);
54 
data()55   const uint8_t* data() const { return packet_.data(); }
data_length()56   size_t data_length() const { return packet_.size(); }
raw_packet()57   rtc::CopyOnWriteBuffer* raw_packet() { return &packet_; }
send_time()58   int64_t send_time() const { return send_time_; }
arrival_time()59   int64_t arrival_time() const { return arrival_time_; }
IncrementArrivalTime(int64_t extra_delay)60   void IncrementArrivalTime(int64_t extra_delay) {
61     arrival_time_ += extra_delay;
62   }
packet_options()63   PacketOptions packet_options() const {
64     return packet_options_.value_or(PacketOptions());
65   }
is_rtcp()66   bool is_rtcp() const { return is_rtcp_; }
media_type()67   MediaType media_type() const { return media_type_; }
packet_time_us()68   absl::optional<int64_t> packet_time_us() const { return packet_time_us_; }
transport()69   Transport* transport() const { return transport_; }
70 
71  private:
72   rtc::CopyOnWriteBuffer packet_;
73   // The time the packet was sent out on the network.
74   int64_t send_time_;
75   // The time the packet should arrive at the receiver.
76   int64_t arrival_time_;
77   // If using a Transport for outgoing degradation, populate with
78   // PacketOptions (transport-wide sequence number) for RTP.
79   absl::optional<PacketOptions> packet_options_;
80   bool is_rtcp_;
81   // If using a PacketReceiver for incoming degradation, populate with
82   // appropriate MediaType and packet time. This type/timing will be kept and
83   // forwarded. The packet time might be altered to reflect time spent in fake
84   // network pipe.
85   MediaType media_type_;
86   absl::optional<int64_t> packet_time_us_;
87   Transport* transport_;
88 };
89 
90 // Class faking a network link, internally is uses an implementation of a
91 // SimulatedNetworkInterface to simulate network behavior.
92 class FakeNetworkPipe : public SimulatedPacketReceiverInterface {
93  public:
94   // Will keep |network_behavior| alive while pipe is alive itself.
95   FakeNetworkPipe(Clock* clock,
96                   std::unique_ptr<NetworkBehaviorInterface> network_behavior);
97   FakeNetworkPipe(Clock* clock,
98                   std::unique_ptr<NetworkBehaviorInterface> network_behavior,
99                   PacketReceiver* receiver);
100   FakeNetworkPipe(Clock* clock,
101                   std::unique_ptr<NetworkBehaviorInterface> network_behavior,
102                   PacketReceiver* receiver,
103                   uint64_t seed);
104 
105   // Use this constructor if you plan to insert packets using SendRt[c?]p().
106   FakeNetworkPipe(Clock* clock,
107                   std::unique_ptr<NetworkBehaviorInterface> network_behavior,
108                   Transport* transport);
109 
110   ~FakeNetworkPipe() override;
111 
112   void SetClockOffset(int64_t offset_ms);
113 
114   // Must not be called in parallel with DeliverPacket or Process.
115   void SetReceiver(PacketReceiver* receiver) override;
116 
117   // Adds/subtracts references to Transport instances. If a Transport is
118   // destroyed we cannot use to forward a potential delayed packet, these
119   // methods are used to maintain a map of which instances are live.
120   void AddActiveTransport(Transport* transport);
121   void RemoveActiveTransport(Transport* transport);
122 
123   // Implements Transport interface. When/if packets are delivered, they will
124   // be passed to the transport instance given in SetReceiverTransport(). These
125   // methods should only be called if a Transport instance was provided in the
126   // constructor.
127   bool SendRtp(const uint8_t* packet,
128                size_t length,
129                const PacketOptions& options);
130   bool SendRtcp(const uint8_t* packet, size_t length);
131 
132   // Methods for use with Transport interface. When/if packets are delivered,
133   // they will be passed to the instance specified by the |transport| parameter.
134   // Note that that instance must be in the map of active transports.
135   bool SendRtp(const uint8_t* packet,
136                size_t length,
137                const PacketOptions& options,
138                Transport* transport);
139   bool SendRtcp(const uint8_t* packet, size_t length, Transport* transport);
140 
141   // Implements the PacketReceiver interface. When/if packets are delivered,
142   // they will be passed directly to the receiver instance given in
143   // SetReceiver(), without passing through a Demuxer. The receive time
144   // will be increased by the amount of time the packet spent in the
145   // fake network pipe.
146   PacketReceiver::DeliveryStatus DeliverPacket(MediaType media_type,
147                                                rtc::CopyOnWriteBuffer packet,
148                                                int64_t packet_time_us) override;
149 
150   // TODO(bugs.webrtc.org/9584): Needed to inherit the alternative signature for
151   // this method.
152   using PacketReceiver::DeliverPacket;
153 
154   // Processes the network queues and trigger PacketReceiver::IncomingPacket for
155   // packets ready to be delivered.
156   void Process() override;
157   absl::optional<int64_t> TimeUntilNextProcess() override;
158 
159   // Get statistics.
160   float PercentageLoss();
161   int AverageDelay() override;
162   size_t DroppedPackets();
163   size_t SentPackets();
164   void ResetStats();
165 
166  protected:
167   void DeliverPacketWithLock(NetworkPacket* packet);
168   int64_t GetTimeInMicroseconds() const;
169   bool ShouldProcess(int64_t time_now_us) const;
170   void SetTimeToNextProcess(int64_t skip_us);
171 
172  private:
173   struct StoredPacket {
174     NetworkPacket packet;
175     bool removed = false;
176     explicit StoredPacket(NetworkPacket&& packet);
177     StoredPacket(StoredPacket&&) = default;
178     StoredPacket(const StoredPacket&) = delete;
179     StoredPacket& operator=(const StoredPacket&) = delete;
180     StoredPacket() = delete;
181   };
182 
183   // Returns true if enqueued, or false if packet was dropped. Use this method
184   // when enqueueing packets that should be received by PacketReceiver instance.
185   bool EnqueuePacket(rtc::CopyOnWriteBuffer packet,
186                      absl::optional<PacketOptions> options,
187                      bool is_rtcp,
188                      MediaType media_type,
189                      absl::optional<int64_t> packet_time_us);
190 
191   // Returns true if enqueued, or false if packet was dropped. Use this method
192   // when enqueueing packets that should be received by Transport instance.
193   bool EnqueuePacket(rtc::CopyOnWriteBuffer packet,
194                      absl::optional<PacketOptions> options,
195                      bool is_rtcp,
196                      Transport* transport);
197 
198   bool EnqueuePacket(NetworkPacket&& net_packet)
199       RTC_EXCLUSIVE_LOCKS_REQUIRED(process_lock_);
200 
201   void DeliverNetworkPacket(NetworkPacket* packet)
202       RTC_EXCLUSIVE_LOCKS_REQUIRED(config_lock_);
203   bool HasReceiver() const;
204 
205   Clock* const clock_;
206   // |config_lock| guards the mostly constant things like the callbacks.
207   mutable Mutex config_lock_;
208   const std::unique_ptr<NetworkBehaviorInterface> network_behavior_;
209   PacketReceiver* receiver_ RTC_GUARDED_BY(config_lock_);
210   Transport* const global_transport_;
211 
212   // |process_lock| guards the data structures involved in delay and loss
213   // processes, such as the packet queues.
214   Mutex process_lock_;
215   // Packets  are added at the back of the deque, this makes the deque ordered
216   // by increasing send time. The common case when removing packets from the
217   // deque is removing early packets, which will be close to the front of the
218   // deque. This makes finding the packets in the deque efficient in the common
219   // case.
220   std::deque<StoredPacket> packets_in_flight_ RTC_GUARDED_BY(process_lock_);
221 
222   int64_t clock_offset_ms_ RTC_GUARDED_BY(config_lock_);
223 
224   // Statistics.
225   size_t dropped_packets_ RTC_GUARDED_BY(process_lock_);
226   size_t sent_packets_ RTC_GUARDED_BY(process_lock_);
227   int64_t total_packet_delay_us_ RTC_GUARDED_BY(process_lock_);
228   int64_t last_log_time_us_;
229 
230   std::map<Transport*, size_t> active_transports_ RTC_GUARDED_BY(config_lock_);
231 
232   RTC_DISALLOW_COPY_AND_ASSIGN(FakeNetworkPipe);
233 };
234 
235 }  // namespace webrtc
236 
237 #endif  // CALL_FAKE_NETWORK_PIPE_H_
238