Repo created

This commit is contained in:
Fr4nz D13trich 2025-11-22 14:04:28 +01:00
parent 81b91f4139
commit f8c34fa5ee
22732 changed files with 4815320 additions and 2 deletions

View file

@ -0,0 +1,2 @@
srte@webrtc.org
terelius@webrtc.org

View file

@ -0,0 +1,27 @@
/*
* Copyright (c) 2024 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
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef API_TRANSPORT_BANDWIDTH_ESTIMATION_SETTINGS_H_
#define API_TRANSPORT_BANDWIDTH_ESTIMATION_SETTINGS_H_
#include "rtc_base/system/rtc_export.h"
namespace webrtc {
// Configuration settings affecting bandwidth estimation.
// These settings can be set and changed by an application.
struct RTC_EXPORT BandwidthEstimationSettings {
// A bandwith estimation probe may be sent using a RtpTransceiver with
// direction SendOnly or SendRecv that supports RTX. The probe can be sent
// without first sending media packets in which case Rtp padding packets are
// used.
bool allow_probe_without_media = false;
};
} // namespace webrtc
#endif // API_TRANSPORT_BANDWIDTH_ESTIMATION_SETTINGS_H_

View file

@ -0,0 +1,19 @@
/*
* Copyright (c) 2018 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
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "api/transport/bitrate_settings.h"
namespace webrtc {
BitrateSettings::BitrateSettings() = default;
BitrateSettings::~BitrateSettings() = default;
BitrateSettings::BitrateSettings(const BitrateSettings&) = default;
} // namespace webrtc

View file

@ -0,0 +1,50 @@
/*
* Copyright (c) 2018 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
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef API_TRANSPORT_BITRATE_SETTINGS_H_
#define API_TRANSPORT_BITRATE_SETTINGS_H_
#include <algorithm>
#include "absl/types/optional.h"
#include "rtc_base/system/rtc_export.h"
namespace webrtc {
// Configuration of send bitrate. The `start_bitrate_bps` value is
// used for multiple purposes, both as a prior in the bandwidth
// estimator, and for initial configuration of the encoder. We may
// want to create separate apis for those, and use a smaller struct
// with only the min and max constraints.
struct RTC_EXPORT BitrateSettings {
BitrateSettings();
~BitrateSettings();
BitrateSettings(const BitrateSettings&);
// 0 <= min <= start <= max should hold for set parameters.
absl::optional<int> min_bitrate_bps;
absl::optional<int> start_bitrate_bps;
absl::optional<int> max_bitrate_bps;
};
// TODO(srte): BitrateConstraints and BitrateSettings should be merged.
// Both represent the same kind data, but are using different default
// initializer and representation of unset values.
struct BitrateConstraints {
int min_bitrate_bps = 0;
int start_bitrate_bps = kDefaultStartBitrateBps;
int max_bitrate_bps = -1;
private:
static constexpr int kDefaultStartBitrateBps = 300000;
};
} // namespace webrtc
#endif // API_TRANSPORT_BITRATE_SETTINGS_H_

View file

@ -0,0 +1,125 @@
/* Copyright 2019 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
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
// This is an experimental interface and is subject to change without notice.
#ifndef API_TRANSPORT_DATA_CHANNEL_TRANSPORT_INTERFACE_H_
#define API_TRANSPORT_DATA_CHANNEL_TRANSPORT_INTERFACE_H_
#include "absl/types/optional.h"
#include "api/rtc_error.h"
#include "rtc_base/copy_on_write_buffer.h"
namespace webrtc {
// Supported types of application data messages.
enum class DataMessageType {
// Application data buffer with the binary bit unset.
kText,
// Application data buffer with the binary bit set.
kBinary,
// Transport-agnostic control messages, such as open or open-ack messages.
kControl,
};
// Parameters for sending data. The parameters may change from message to
// message, even within a single channel. For example, control messages may be
// sent reliably and in-order, even if the data channel is configured for
// unreliable delivery.
struct SendDataParams {
DataMessageType type = DataMessageType::kText;
// Whether to deliver the message in order with respect to other ordered
// messages with the same channel_id.
bool ordered = false;
// If set, the maximum number of times this message may be
// retransmitted by the transport before it is dropped.
// Setting this value to zero disables retransmission.
// Valid values are in the range [0-UINT16_MAX].
// `max_rtx_count` and `max_rtx_ms` may not be set simultaneously.
absl::optional<int> max_rtx_count;
// If set, the maximum number of milliseconds for which the transport
// may retransmit this message before it is dropped.
// Setting this value to zero disables retransmission.
// Valid values are in the range [0-UINT16_MAX].
// `max_rtx_count` and `max_rtx_ms` may not be set simultaneously.
absl::optional<int> max_rtx_ms;
};
// Sink for callbacks related to a data channel.
class DataChannelSink {
public:
virtual ~DataChannelSink() = default;
// Callback issued when data is received by the transport.
virtual void OnDataReceived(int channel_id,
DataMessageType type,
const rtc::CopyOnWriteBuffer& buffer) = 0;
// Callback issued when a remote data channel begins the closing procedure.
// Messages sent after the closing procedure begins will not be transmitted.
virtual void OnChannelClosing(int channel_id) = 0;
// Callback issued when a (remote or local) data channel completes the closing
// procedure. Closing channels become closed after all pending data has been
// transmitted.
virtual void OnChannelClosed(int channel_id) = 0;
// Callback issued when the data channel becomes ready to send.
// This callback will be issued immediately when the data channel sink is
// registered if the transport is ready at that time. This callback may be
// invoked again following send errors (eg. due to the transport being
// temporarily blocked or unavailable).
virtual void OnReadyToSend() = 0;
// Callback issued when the data channel becomes unusable (closed).
// TODO(https://crbug.com/webrtc/10360): Make pure virtual when all
// consumers updated.
virtual void OnTransportClosed(RTCError error) {}
};
// Transport for data channels.
class DataChannelTransportInterface {
public:
virtual ~DataChannelTransportInterface() = default;
// Opens a data `channel_id` for sending. May return an error if the
// specified `channel_id` is unusable. Must be called before `SendData`.
virtual RTCError OpenChannel(int channel_id) = 0;
// Sends a data buffer to the remote endpoint using the given send parameters.
// `buffer` may not be larger than 256 KiB. Returns an error if the send
// fails.
virtual RTCError SendData(int channel_id,
const SendDataParams& params,
const rtc::CopyOnWriteBuffer& buffer) = 0;
// Closes `channel_id` gracefully. Returns an error if `channel_id` is not
// open. Data sent after the closing procedure begins will not be
// transmitted. The channel becomes closed after pending data is transmitted.
virtual RTCError CloseChannel(int channel_id) = 0;
// Sets a sink for data messages and channel state callbacks. Before media
// transport is destroyed, the sink must be unregistered by setting it to
// nullptr.
virtual void SetDataSink(DataChannelSink* sink) = 0;
// Returns whether this data channel transport is ready to send.
// Note: the default implementation always returns false (as it assumes no one
// has implemented the interface). This default implementation is temporary.
virtual bool IsReadyToSend() const = 0;
};
} // namespace webrtc
#endif // API_TRANSPORT_DATA_CHANNEL_TRANSPORT_INTERFACE_H_

View file

@ -0,0 +1,49 @@
/*
* Copyright 2018 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
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef API_TRANSPORT_ENUMS_H_
#define API_TRANSPORT_ENUMS_H_
namespace webrtc {
// See https://w3c.github.io/webrtc-pc/#rtcicetransportstate
// Note that kFailed is currently not a terminal state, and a transport might
// incorrectly be marked as failed while gathering candidates, see
// bugs.webrtc.org/8833
enum class IceTransportState {
kNew,
kChecking,
kConnected,
kCompleted,
kFailed,
kDisconnected,
kClosed,
};
enum PortPrunePolicy {
NO_PRUNE, // Do not prune.
PRUNE_BASED_ON_PRIORITY, // Prune lower-priority ports on the same network.
KEEP_FIRST_READY // Keep the first ready port and prune the rest
// on the same network.
};
enum class VpnPreference {
kDefault, // No VPN preference.
kOnlyUseVpn, // only use VPN connections.
kNeverUseVpn, // never use VPN connections
kPreferVpn, // use a VPN connection if possible,
// i.e VPN connections sorts first.
kAvoidVpn, // only use VPN if there is no other connections,
// i.e VPN connections sorts last.
};
} // namespace webrtc
#endif // API_TRANSPORT_ENUMS_H_

View file

@ -0,0 +1,18 @@
/*
* Copyright 2019 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
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "api/transport/field_trial_based_config.h"
#include "system_wrappers/include/field_trial.h"
namespace webrtc {
std::string FieldTrialBasedConfig::GetValue(absl::string_view key) const {
return webrtc::field_trial::FindFullName(std::string(key));
}
} // namespace webrtc

View file

@ -0,0 +1,27 @@
/*
* Copyright 2019 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
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef API_TRANSPORT_FIELD_TRIAL_BASED_CONFIG_H_
#define API_TRANSPORT_FIELD_TRIAL_BASED_CONFIG_H_
#include <string>
#include "absl/strings/string_view.h"
#include "api/field_trials_registry.h"
#include "rtc_base/system/rtc_export.h"
namespace webrtc {
// Implementation using the field trial API fo the key value lookup.
class RTC_EXPORT FieldTrialBasedConfig : public FieldTrialsRegistry {
private:
std::string GetValue(absl::string_view key) const override;
};
} // namespace webrtc
#endif // API_TRANSPORT_FIELD_TRIAL_BASED_CONFIG_H_

View file

@ -0,0 +1,65 @@
/*
* Copyright (c) 2018 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
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "api/transport/goog_cc_factory.h"
#include <memory>
#include <utility>
#include "modules/congestion_controller/goog_cc/goog_cc_network_control.h"
namespace webrtc {
GoogCcNetworkControllerFactory::GoogCcNetworkControllerFactory(
RtcEventLog* event_log)
: event_log_(event_log) {}
GoogCcNetworkControllerFactory::GoogCcNetworkControllerFactory(
NetworkStatePredictorFactoryInterface* network_state_predictor_factory) {
factory_config_.network_state_predictor_factory =
network_state_predictor_factory;
}
GoogCcNetworkControllerFactory::GoogCcNetworkControllerFactory(
GoogCcFactoryConfig config)
: factory_config_(std::move(config)) {}
std::unique_ptr<NetworkControllerInterface>
GoogCcNetworkControllerFactory::Create(NetworkControllerConfig config) {
if (event_log_)
config.event_log = event_log_;
GoogCcConfig goog_cc_config;
goog_cc_config.feedback_only = factory_config_.feedback_only;
if (factory_config_.network_state_estimator_factory) {
RTC_DCHECK(config.key_value_config);
goog_cc_config.network_state_estimator =
factory_config_.network_state_estimator_factory->Create(
config.key_value_config);
}
if (factory_config_.network_state_predictor_factory) {
goog_cc_config.network_state_predictor =
factory_config_.network_state_predictor_factory
->CreateNetworkStatePredictor();
}
return std::make_unique<GoogCcNetworkController>(config,
std::move(goog_cc_config));
}
TimeDelta GoogCcNetworkControllerFactory::GetProcessInterval() const {
const int64_t kUpdateIntervalMs = 25;
return TimeDelta::Millis(kUpdateIntervalMs);
}
GoogCcFeedbackNetworkControllerFactory::GoogCcFeedbackNetworkControllerFactory(
RtcEventLog* event_log)
: GoogCcNetworkControllerFactory(event_log) {
factory_config_.feedback_only = true;
}
} // namespace webrtc

View file

@ -0,0 +1,61 @@
/*
* Copyright (c) 2018 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
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef API_TRANSPORT_GOOG_CC_FACTORY_H_
#define API_TRANSPORT_GOOG_CC_FACTORY_H_
#include <memory>
#include "absl/base/attributes.h"
#include "api/network_state_predictor.h"
#include "api/transport/network_control.h"
namespace webrtc {
class RtcEventLog;
struct GoogCcFactoryConfig {
std::unique_ptr<NetworkStateEstimatorFactory>
network_state_estimator_factory = nullptr;
NetworkStatePredictorFactoryInterface* network_state_predictor_factory =
nullptr;
bool feedback_only = false;
};
class GoogCcNetworkControllerFactory
: public NetworkControllerFactoryInterface {
public:
GoogCcNetworkControllerFactory() = default;
ABSL_DEPRECATED("")
explicit GoogCcNetworkControllerFactory(RtcEventLog* event_log);
explicit GoogCcNetworkControllerFactory(
NetworkStatePredictorFactoryInterface* network_state_predictor_factory);
explicit GoogCcNetworkControllerFactory(GoogCcFactoryConfig config);
std::unique_ptr<NetworkControllerInterface> Create(
NetworkControllerConfig config) override;
TimeDelta GetProcessInterval() const override;
protected:
RtcEventLog* const event_log_ = nullptr;
GoogCcFactoryConfig factory_config_;
};
// Deprecated, use GoogCcFactoryConfig to enable feedback only mode instead.
// Factory to create packet feedback only GoogCC, this can be used for
// connections providing packet receive time feedback but no other reports.
class ABSL_DEPRECATED("use GoogCcFactoryConfig instead")
GoogCcFeedbackNetworkControllerFactory
: public GoogCcNetworkControllerFactory {
public:
explicit GoogCcFeedbackNetworkControllerFactory(RtcEventLog* event_log);
};
} // namespace webrtc
#endif // API_TRANSPORT_GOOG_CC_FACTORY_H_

View file

@ -0,0 +1,140 @@
/*
* Copyright (c) 2018 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
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef API_TRANSPORT_NETWORK_CONTROL_H_
#define API_TRANSPORT_NETWORK_CONTROL_H_
#include <stdint.h>
#include <memory>
#include "absl/base/attributes.h"
#include "api/field_trials_view.h"
#include "api/rtc_event_log/rtc_event_log.h"
#include "api/transport/network_types.h"
namespace webrtc {
class TargetTransferRateObserver {
public:
virtual ~TargetTransferRateObserver() = default;
// Called to indicate target transfer rate as well as giving information about
// the current estimate of network parameters.
virtual void OnTargetTransferRate(TargetTransferRate) = 0;
// Called to provide updates to the expected target rate in case it changes
// before the first call to OnTargetTransferRate.
virtual void OnStartRateUpdate(DataRate) {}
};
// Configuration sent to factory create function. The parameters here are
// optional to use for a network controller implementation.
struct NetworkControllerConfig {
// The initial constraints to start with, these can be changed at any later
// time by calls to OnTargetRateConstraints. Note that the starting rate
// has to be set initially to provide a starting state for the network
// controller, even though the field is marked as optional.
TargetRateConstraints constraints;
// Initial stream specific configuration, these are changed at any later time
// by calls to OnStreamsConfig.
StreamsConfig stream_based_config;
// Optional override of configuration of WebRTC internals. Using nullptr here
// indicates that the field trial API will be used.
const FieldTrialsView* key_value_config = nullptr;
// Optional override of event log.
RtcEventLog* event_log = nullptr;
};
// NetworkControllerInterface is implemented by network controllers. A network
// controller is a class that uses information about network state and traffic
// to estimate network parameters such as round trip time and bandwidth. Network
// controllers does not guarantee thread safety, the interface must be used in a
// non-concurrent fashion.
class NetworkControllerInterface {
public:
virtual ~NetworkControllerInterface() = default;
// Called when network availabilty changes.
ABSL_MUST_USE_RESULT virtual NetworkControlUpdate OnNetworkAvailability(
NetworkAvailability) = 0;
// Called when the receiving or sending endpoint changes address.
ABSL_MUST_USE_RESULT virtual NetworkControlUpdate OnNetworkRouteChange(
NetworkRouteChange) = 0;
// Called periodically with a periodicy as specified by
// NetworkControllerFactoryInterface::GetProcessInterval.
ABSL_MUST_USE_RESULT virtual NetworkControlUpdate OnProcessInterval(
ProcessInterval) = 0;
// Called when remotely calculated bitrate is received.
ABSL_MUST_USE_RESULT virtual NetworkControlUpdate OnRemoteBitrateReport(
RemoteBitrateReport) = 0;
// Called round trip time has been calculated by protocol specific mechanisms.
ABSL_MUST_USE_RESULT virtual NetworkControlUpdate OnRoundTripTimeUpdate(
RoundTripTimeUpdate) = 0;
// Called when a packet is sent on the network.
ABSL_MUST_USE_RESULT virtual NetworkControlUpdate OnSentPacket(
SentPacket) = 0;
// Called when a packet is received from the remote client.
ABSL_MUST_USE_RESULT virtual NetworkControlUpdate OnReceivedPacket(
ReceivedPacket) = 0;
// Called when the stream specific configuration has been updated.
ABSL_MUST_USE_RESULT virtual NetworkControlUpdate OnStreamsConfig(
StreamsConfig) = 0;
// Called when target transfer rate constraints has been changed.
ABSL_MUST_USE_RESULT virtual NetworkControlUpdate OnTargetRateConstraints(
TargetRateConstraints) = 0;
// Called when a protocol specific calculation of packet loss has been made.
ABSL_MUST_USE_RESULT virtual NetworkControlUpdate OnTransportLossReport(
TransportLossReport) = 0;
// Called with per packet feedback regarding receive time.
ABSL_MUST_USE_RESULT virtual NetworkControlUpdate OnTransportPacketsFeedback(
TransportPacketsFeedback) = 0;
// Called with network state estimate updates.
ABSL_MUST_USE_RESULT virtual NetworkControlUpdate OnNetworkStateEstimate(
NetworkStateEstimate) = 0;
};
// NetworkControllerFactoryInterface is an interface for creating a network
// controller.
class NetworkControllerFactoryInterface {
public:
virtual ~NetworkControllerFactoryInterface() = default;
// Used to create a new network controller, requires an observer to be
// provided to handle callbacks.
virtual std::unique_ptr<NetworkControllerInterface> Create(
NetworkControllerConfig config) = 0;
// Returns the interval by which the network controller expects
// OnProcessInterval calls.
virtual TimeDelta GetProcessInterval() const = 0;
};
// Under development, subject to change without notice.
class NetworkStateEstimator {
public:
// Gets the current best estimate according to the estimator.
virtual absl::optional<NetworkStateEstimate> GetCurrentEstimate() = 0;
// Called with per packet feedback regarding receive time.
// Used when the NetworkStateEstimator runs in the sending endpoint.
virtual void OnTransportPacketsFeedback(const TransportPacketsFeedback&) = 0;
// Called with per packet feedback regarding receive time.
// Used when the NetworkStateEstimator runs in the receiving endpoint.
virtual void OnReceivedPacket(const PacketResult&) {}
// Called when the receiving or sending endpoint changes address.
virtual void OnRouteChange(const NetworkRouteChange&) = 0;
virtual ~NetworkStateEstimator() = default;
};
class NetworkStateEstimatorFactory {
public:
virtual std::unique_ptr<NetworkStateEstimator> Create(
const FieldTrialsView* key_value_config) = 0;
virtual ~NetworkStateEstimatorFactory() = default;
};
} // namespace webrtc
#endif // API_TRANSPORT_NETWORK_CONTROL_H_

View file

@ -0,0 +1,106 @@
/*
* Copyright (c) 2018 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
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "api/transport/network_types.h"
#include <algorithm>
namespace webrtc {
StreamsConfig::StreamsConfig() = default;
StreamsConfig::StreamsConfig(const StreamsConfig&) = default;
StreamsConfig::~StreamsConfig() = default;
TargetRateConstraints::TargetRateConstraints() = default;
TargetRateConstraints::TargetRateConstraints(const TargetRateConstraints&) =
default;
TargetRateConstraints::~TargetRateConstraints() = default;
NetworkRouteChange::NetworkRouteChange() = default;
NetworkRouteChange::NetworkRouteChange(const NetworkRouteChange&) = default;
NetworkRouteChange::~NetworkRouteChange() = default;
PacketResult::PacketResult() = default;
PacketResult::PacketResult(const PacketResult& other) = default;
PacketResult::~PacketResult() = default;
bool PacketResult::ReceiveTimeOrder::operator()(const PacketResult& lhs,
const PacketResult& rhs) {
if (lhs.receive_time != rhs.receive_time)
return lhs.receive_time < rhs.receive_time;
if (lhs.sent_packet.send_time != rhs.sent_packet.send_time)
return lhs.sent_packet.send_time < rhs.sent_packet.send_time;
return lhs.sent_packet.sequence_number < rhs.sent_packet.sequence_number;
}
TransportPacketsFeedback::TransportPacketsFeedback() = default;
TransportPacketsFeedback::TransportPacketsFeedback(
const TransportPacketsFeedback& other) = default;
TransportPacketsFeedback::~TransportPacketsFeedback() = default;
std::vector<PacketResult> TransportPacketsFeedback::ReceivedWithSendInfo()
const {
std::vector<PacketResult> res;
for (const PacketResult& fb : packet_feedbacks) {
if (fb.IsReceived()) {
res.push_back(fb);
}
}
return res;
}
std::vector<PacketResult> TransportPacketsFeedback::LostWithSendInfo() const {
std::vector<PacketResult> res;
for (const PacketResult& fb : packet_feedbacks) {
if (!fb.IsReceived()) {
res.push_back(fb);
}
}
return res;
}
std::vector<PacketResult> TransportPacketsFeedback::PacketsWithFeedback()
const {
return packet_feedbacks;
}
std::vector<PacketResult> TransportPacketsFeedback::SortedByReceiveTime()
const {
std::vector<PacketResult> res;
for (const PacketResult& fb : packet_feedbacks) {
if (fb.IsReceived()) {
res.push_back(fb);
}
}
std::sort(res.begin(), res.end(), PacketResult::ReceiveTimeOrder());
return res;
}
NetworkControlUpdate::NetworkControlUpdate() = default;
NetworkControlUpdate::NetworkControlUpdate(const NetworkControlUpdate&) =
default;
NetworkControlUpdate::~NetworkControlUpdate() = default;
PacedPacketInfo::PacedPacketInfo() = default;
PacedPacketInfo::PacedPacketInfo(int probe_cluster_id,
int probe_cluster_min_probes,
int probe_cluster_min_bytes)
: probe_cluster_id(probe_cluster_id),
probe_cluster_min_probes(probe_cluster_min_probes),
probe_cluster_min_bytes(probe_cluster_min_bytes) {}
bool PacedPacketInfo::operator==(const PacedPacketInfo& rhs) const {
return send_bitrate == rhs.send_bitrate &&
probe_cluster_id == rhs.probe_cluster_id &&
probe_cluster_min_probes == rhs.probe_cluster_min_probes &&
probe_cluster_min_bytes == rhs.probe_cluster_min_bytes;
}
} // namespace webrtc

View file

@ -0,0 +1,284 @@
/*
* Copyright (c) 2018 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
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef API_TRANSPORT_NETWORK_TYPES_H_
#define API_TRANSPORT_NETWORK_TYPES_H_
#include <stdint.h>
#include <vector>
#include "absl/types/optional.h"
#include "api/units/data_rate.h"
#include "api/units/data_size.h"
#include "api/units/time_delta.h"
#include "api/units/timestamp.h"
namespace webrtc {
// Configuration
// Represents constraints and rates related to the currently enabled streams.
// This is used as input to the congestion controller via the StreamsConfig
// struct.
struct BitrateAllocationLimits {
// The total minimum send bitrate required by all sending streams.
DataRate min_allocatable_rate = DataRate::Zero();
// The total maximum allocatable bitrate for all currently available streams.
DataRate max_allocatable_rate = DataRate::Zero();
// The max bitrate to use for padding. The sum of the per-stream max padding
// rate.
DataRate max_padding_rate = DataRate::Zero();
};
// Use StreamsConfig for information about streams that is required for specific
// adjustments to the algorithms in network controllers. Especially useful
// for experiments.
struct StreamsConfig {
StreamsConfig();
StreamsConfig(const StreamsConfig&);
~StreamsConfig();
Timestamp at_time = Timestamp::PlusInfinity();
absl::optional<bool> requests_alr_probing;
absl::optional<double> pacing_factor;
// TODO(srte): Use BitrateAllocationLimits here.
absl::optional<DataRate> min_total_allocated_bitrate;
absl::optional<DataRate> max_padding_rate;
absl::optional<DataRate> max_total_allocated_bitrate;
};
struct TargetRateConstraints {
TargetRateConstraints();
TargetRateConstraints(const TargetRateConstraints&);
~TargetRateConstraints();
Timestamp at_time = Timestamp::PlusInfinity();
absl::optional<DataRate> min_data_rate;
absl::optional<DataRate> max_data_rate;
// The initial bandwidth estimate to base target rate on. This should be used
// as the basis for initial OnTargetTransferRate and OnPacerConfig callbacks.
absl::optional<DataRate> starting_rate;
};
// Send side information
struct NetworkAvailability {
Timestamp at_time = Timestamp::PlusInfinity();
bool network_available = false;
};
struct NetworkRouteChange {
NetworkRouteChange();
NetworkRouteChange(const NetworkRouteChange&);
~NetworkRouteChange();
Timestamp at_time = Timestamp::PlusInfinity();
// The TargetRateConstraints are set here so they can be changed synchronously
// when network route changes.
TargetRateConstraints constraints;
};
struct PacedPacketInfo {
PacedPacketInfo();
PacedPacketInfo(int probe_cluster_id,
int probe_cluster_min_probes,
int probe_cluster_min_bytes);
bool operator==(const PacedPacketInfo& rhs) const;
// TODO(srte): Move probing info to a separate, optional struct.
static constexpr int kNotAProbe = -1;
DataRate send_bitrate = DataRate::BitsPerSec(0);
int probe_cluster_id = kNotAProbe;
int probe_cluster_min_probes = -1;
int probe_cluster_min_bytes = -1;
int probe_cluster_bytes_sent = 0;
};
struct SentPacket {
Timestamp send_time = Timestamp::PlusInfinity();
// Size of packet with overhead up to IP layer.
DataSize size = DataSize::Zero();
// Size of preceeding packets that are not part of feedback.
DataSize prior_unacked_data = DataSize::Zero();
// Probe cluster id and parameters including bitrate, number of packets and
// number of bytes.
PacedPacketInfo pacing_info;
// True if the packet is an audio packet, false for video, padding, RTX etc.
bool audio = false;
// Transport independent sequence number, any tracked packet should have a
// sequence number that is unique over the whole call and increasing by 1 for
// each packet.
int64_t sequence_number;
// Tracked data in flight when the packet was sent, excluding unacked data.
DataSize data_in_flight = DataSize::Zero();
};
struct ReceivedPacket {
Timestamp send_time = Timestamp::MinusInfinity();
Timestamp receive_time = Timestamp::PlusInfinity();
DataSize size = DataSize::Zero();
};
// Transport level feedback
struct RemoteBitrateReport {
Timestamp receive_time = Timestamp::PlusInfinity();
DataRate bandwidth = DataRate::Infinity();
};
struct RoundTripTimeUpdate {
Timestamp receive_time = Timestamp::PlusInfinity();
TimeDelta round_trip_time = TimeDelta::PlusInfinity();
bool smoothed = false;
};
struct TransportLossReport {
Timestamp receive_time = Timestamp::PlusInfinity();
Timestamp start_time = Timestamp::PlusInfinity();
Timestamp end_time = Timestamp::PlusInfinity();
uint64_t packets_lost_delta = 0;
uint64_t packets_received_delta = 0;
};
// Packet level feedback
struct PacketResult {
class ReceiveTimeOrder {
public:
bool operator()(const PacketResult& lhs, const PacketResult& rhs);
};
PacketResult();
PacketResult(const PacketResult&);
~PacketResult();
inline bool IsReceived() const { return !receive_time.IsPlusInfinity(); }
SentPacket sent_packet;
Timestamp receive_time = Timestamp::PlusInfinity();
};
struct TransportPacketsFeedback {
TransportPacketsFeedback();
TransportPacketsFeedback(const TransportPacketsFeedback& other);
~TransportPacketsFeedback();
Timestamp feedback_time = Timestamp::PlusInfinity();
Timestamp first_unacked_send_time = Timestamp::PlusInfinity();
DataSize data_in_flight = DataSize::Zero();
DataSize prior_in_flight = DataSize::Zero();
std::vector<PacketResult> packet_feedbacks;
// Arrival times for messages without send time information.
std::vector<Timestamp> sendless_arrival_times;
std::vector<PacketResult> ReceivedWithSendInfo() const;
std::vector<PacketResult> LostWithSendInfo() const;
std::vector<PacketResult> PacketsWithFeedback() const;
std::vector<PacketResult> SortedByReceiveTime() const;
};
// Network estimation
struct NetworkEstimate {
Timestamp at_time = Timestamp::PlusInfinity();
// Deprecated, use TargetTransferRate::target_rate instead.
DataRate bandwidth = DataRate::Infinity();
TimeDelta round_trip_time = TimeDelta::PlusInfinity();
TimeDelta bwe_period = TimeDelta::PlusInfinity();
float loss_rate_ratio = 0;
};
// Network control
struct PacerConfig {
Timestamp at_time = Timestamp::PlusInfinity();
// Pacer should send at most data_window data over time_window duration.
DataSize data_window = DataSize::Infinity();
TimeDelta time_window = TimeDelta::PlusInfinity();
// Pacer should send at least pad_window data over time_window duration.
DataSize pad_window = DataSize::Zero();
DataRate data_rate() const { return data_window / time_window; }
DataRate pad_rate() const { return pad_window / time_window; }
};
struct ProbeClusterConfig {
Timestamp at_time = Timestamp::PlusInfinity();
DataRate target_data_rate = DataRate::Zero();
TimeDelta target_duration = TimeDelta::Zero();
int32_t target_probe_count = 0;
int32_t id = 0;
};
struct TargetTransferRate {
Timestamp at_time = Timestamp::PlusInfinity();
// The estimate on which the target rate is based on.
NetworkEstimate network_estimate;
DataRate target_rate = DataRate::Zero();
DataRate stable_target_rate = DataRate::Zero();
double cwnd_reduce_ratio = 0;
};
// Contains updates of network controller comand state. Using optionals to
// indicate whether a member has been updated. The array of probe clusters
// should be used to send out probes if not empty.
struct NetworkControlUpdate {
NetworkControlUpdate();
NetworkControlUpdate(const NetworkControlUpdate&);
~NetworkControlUpdate();
bool has_updates() const {
return congestion_window.has_value() || pacer_config.has_value() ||
!probe_cluster_configs.empty() || target_rate.has_value();
}
absl::optional<DataSize> congestion_window;
absl::optional<PacerConfig> pacer_config;
std::vector<ProbeClusterConfig> probe_cluster_configs;
absl::optional<TargetTransferRate> target_rate;
};
// Process control
struct ProcessInterval {
Timestamp at_time = Timestamp::PlusInfinity();
absl::optional<DataSize> pacer_queue;
};
// Under development, subject to change without notice.
struct NetworkStateEstimate {
double confidence = NAN;
// The time the estimate was received/calculated.
Timestamp update_time = Timestamp::MinusInfinity();
Timestamp last_receive_time = Timestamp::MinusInfinity();
Timestamp last_send_time = Timestamp::MinusInfinity();
// Total estimated link capacity.
DataRate link_capacity = DataRate::MinusInfinity();
// Used as a safe measure of available capacity.
DataRate link_capacity_lower = DataRate::MinusInfinity();
// Used as limit for increasing bitrate.
DataRate link_capacity_upper = DataRate::MinusInfinity();
TimeDelta pre_link_buffer_delay = TimeDelta::MinusInfinity();
TimeDelta post_link_buffer_delay = TimeDelta::MinusInfinity();
TimeDelta propagation_delay = TimeDelta::MinusInfinity();
// Only for debugging
TimeDelta time_delta = TimeDelta::MinusInfinity();
Timestamp last_feed_time = Timestamp::MinusInfinity();
double cross_delay_rate = NAN;
double spike_delay_rate = NAN;
DataRate link_capacity_std_dev = DataRate::MinusInfinity();
DataRate link_capacity_min = DataRate::MinusInfinity();
double cross_traffic_ratio = NAN;
};
} // namespace webrtc
#endif // API_TRANSPORT_NETWORK_TYPES_H_

View file

@ -0,0 +1,38 @@
# Copyright (c) 2019 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
# in the file PATENTS. All contributing project authors may
# be found in the AUTHORS file in the root of the source tree.
import("../../../webrtc.gni")
rtc_source_set("rtp_source") {
visibility = [ "*" ]
sources = [ "rtp_source.h" ]
deps = [
"../../../api:rtp_headers",
"../../../api/units:time_delta",
"../../../api/units:timestamp",
"../../../rtc_base:checks",
]
absl_deps = [ "//third_party/abseil-cpp/absl/types:optional" ]
}
rtc_source_set("dependency_descriptor") {
visibility = [ "*" ]
sources = [
"dependency_descriptor.cc",
"dependency_descriptor.h",
]
deps = [
"../../../rtc_base:checks",
"../../video:render_resolution",
]
absl_deps = [
"//third_party/abseil-cpp/absl/container:inlined_vector",
"//third_party/abseil-cpp/absl/strings",
"//third_party/abseil-cpp/absl/types:optional",
]
}

View file

@ -0,0 +1,54 @@
/*
* Copyright (c) 2020 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
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "api/transport/rtp/dependency_descriptor.h"
#include "absl/container/inlined_vector.h"
#include "absl/strings/string_view.h"
#include "rtc_base/checks.h"
namespace webrtc {
constexpr int DependencyDescriptor::kMaxSpatialIds;
constexpr int DependencyDescriptor::kMaxTemporalIds;
constexpr int DependencyDescriptor::kMaxTemplates;
constexpr int DependencyDescriptor::kMaxDecodeTargets;
namespace webrtc_impl {
absl::InlinedVector<DecodeTargetIndication, 10> StringToDecodeTargetIndications(
absl::string_view symbols) {
absl::InlinedVector<DecodeTargetIndication, 10> dtis;
dtis.reserve(symbols.size());
for (char symbol : symbols) {
DecodeTargetIndication indication;
switch (symbol) {
case '-':
indication = DecodeTargetIndication::kNotPresent;
break;
case 'D':
indication = DecodeTargetIndication::kDiscardable;
break;
case 'R':
indication = DecodeTargetIndication::kRequired;
break;
case 'S':
indication = DecodeTargetIndication::kSwitch;
break;
default:
RTC_DCHECK_NOTREACHED();
}
dtis.push_back(indication);
}
return dtis;
}
} // namespace webrtc_impl
} // namespace webrtc

View file

@ -0,0 +1,150 @@
/*
* Copyright (c) 2020 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
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef API_TRANSPORT_RTP_DEPENDENCY_DESCRIPTOR_H_
#define API_TRANSPORT_RTP_DEPENDENCY_DESCRIPTOR_H_
#include <stdint.h>
#include <initializer_list>
#include <memory>
#include <vector>
#include "absl/container/inlined_vector.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "api/video/render_resolution.h"
namespace webrtc {
// Structures to build and parse dependency descriptor as described in
// https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension
// Relationship of a frame to a Decode target.
enum class DecodeTargetIndication {
kNotPresent = 0, // DecodeTargetInfo symbol '-'
kDiscardable = 1, // DecodeTargetInfo symbol 'D'
kSwitch = 2, // DecodeTargetInfo symbol 'S'
kRequired = 3 // DecodeTargetInfo symbol 'R'
};
struct FrameDependencyTemplate {
// Setters are named briefly to chain them when building the template.
FrameDependencyTemplate& S(int spatial_layer);
FrameDependencyTemplate& T(int temporal_layer);
FrameDependencyTemplate& Dtis(absl::string_view dtis);
FrameDependencyTemplate& FrameDiffs(std::initializer_list<int> diffs);
FrameDependencyTemplate& ChainDiffs(std::initializer_list<int> diffs);
friend bool operator==(const FrameDependencyTemplate& lhs,
const FrameDependencyTemplate& rhs) {
return lhs.spatial_id == rhs.spatial_id &&
lhs.temporal_id == rhs.temporal_id &&
lhs.decode_target_indications == rhs.decode_target_indications &&
lhs.frame_diffs == rhs.frame_diffs &&
lhs.chain_diffs == rhs.chain_diffs;
}
int spatial_id = 0;
int temporal_id = 0;
absl::InlinedVector<DecodeTargetIndication, 10> decode_target_indications;
absl::InlinedVector<int, 4> frame_diffs;
absl::InlinedVector<int, 4> chain_diffs;
};
struct FrameDependencyStructure {
friend bool operator==(const FrameDependencyStructure& lhs,
const FrameDependencyStructure& rhs) {
return lhs.num_decode_targets == rhs.num_decode_targets &&
lhs.num_chains == rhs.num_chains &&
lhs.decode_target_protected_by_chain ==
rhs.decode_target_protected_by_chain &&
lhs.resolutions == rhs.resolutions && lhs.templates == rhs.templates;
}
int structure_id = 0;
int num_decode_targets = 0;
int num_chains = 0;
// If chains are used (num_chains > 0), maps decode target index into index of
// the chain protecting that target.
absl::InlinedVector<int, 10> decode_target_protected_by_chain;
absl::InlinedVector<RenderResolution, 4> resolutions;
std::vector<FrameDependencyTemplate> templates;
};
class DependencyDescriptorMandatory {
public:
void set_frame_number(int frame_number) { frame_number_ = frame_number; }
int frame_number() const { return frame_number_; }
void set_template_id(int template_id) { template_id_ = template_id; }
int template_id() const { return template_id_; }
void set_first_packet_in_frame(bool first) { first_packet_in_frame_ = first; }
bool first_packet_in_frame() const { return first_packet_in_frame_; }
void set_last_packet_in_frame(bool last) { last_packet_in_frame_ = last; }
bool last_packet_in_frame() const { return last_packet_in_frame_; }
private:
int frame_number_;
int template_id_;
bool first_packet_in_frame_;
bool last_packet_in_frame_;
};
struct DependencyDescriptor {
static constexpr int kMaxSpatialIds = 4;
static constexpr int kMaxTemporalIds = 8;
static constexpr int kMaxDecodeTargets = 32;
static constexpr int kMaxTemplates = 64;
bool first_packet_in_frame = true;
bool last_packet_in_frame = true;
int frame_number = 0;
FrameDependencyTemplate frame_dependencies;
absl::optional<RenderResolution> resolution;
absl::optional<uint32_t> active_decode_targets_bitmask;
std::unique_ptr<FrameDependencyStructure> attached_structure;
};
// Below are implementation details.
namespace webrtc_impl {
absl::InlinedVector<DecodeTargetIndication, 10> StringToDecodeTargetIndications(
absl::string_view indication_symbols);
} // namespace webrtc_impl
inline FrameDependencyTemplate& FrameDependencyTemplate::S(int spatial_layer) {
this->spatial_id = spatial_layer;
return *this;
}
inline FrameDependencyTemplate& FrameDependencyTemplate::T(int temporal_layer) {
this->temporal_id = temporal_layer;
return *this;
}
inline FrameDependencyTemplate& FrameDependencyTemplate::Dtis(
absl::string_view dtis) {
this->decode_target_indications =
webrtc_impl::StringToDecodeTargetIndications(dtis);
return *this;
}
inline FrameDependencyTemplate& FrameDependencyTemplate::FrameDiffs(
std::initializer_list<int> diffs) {
this->frame_diffs.assign(diffs.begin(), diffs.end());
return *this;
}
inline FrameDependencyTemplate& FrameDependencyTemplate::ChainDiffs(
std::initializer_list<int> diffs) {
this->chain_diffs.assign(diffs.begin(), diffs.end());
return *this;
}
} // namespace webrtc
#endif // API_TRANSPORT_RTP_DEPENDENCY_DESCRIPTOR_H_

View file

@ -0,0 +1,108 @@
/*
* Copyright 2019 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
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef API_TRANSPORT_RTP_RTP_SOURCE_H_
#define API_TRANSPORT_RTP_RTP_SOURCE_H_
#include <stdint.h>
#include "absl/types/optional.h"
#include "api/rtp_headers.h"
#include "api/units/time_delta.h"
#include "api/units/timestamp.h"
#include "rtc_base/checks.h"
namespace webrtc {
enum class RtpSourceType {
SSRC,
CSRC,
};
class RtpSource {
public:
struct Extensions {
absl::optional<uint8_t> audio_level;
// Fields from the Absolute Capture Time header extension:
// http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time
absl::optional<AbsoluteCaptureTime> absolute_capture_time;
// Clock offset between the local clock and the capturer's clock.
// Do not confuse with `AbsoluteCaptureTime::estimated_capture_clock_offset`
// which instead represents the clock offset between a remote sender and the
// capturer. The following holds:
// Capture's NTP Clock = Local NTP Clock + Local-Capture Clock Offset
absl::optional<TimeDelta> local_capture_clock_offset;
};
RtpSource() = delete;
RtpSource(Timestamp timestamp,
uint32_t source_id,
RtpSourceType source_type,
uint32_t rtp_timestamp,
const RtpSource::Extensions& extensions)
: timestamp_(timestamp),
source_id_(source_id),
source_type_(source_type),
extensions_(extensions),
rtp_timestamp_(rtp_timestamp) {}
RtpSource(const RtpSource&) = default;
RtpSource& operator=(const RtpSource&) = default;
~RtpSource() = default;
Timestamp timestamp() const { return timestamp_; }
// The identifier of the source can be the CSRC or the SSRC.
uint32_t source_id() const { return source_id_; }
// The source can be either a contributing source or a synchronization source.
RtpSourceType source_type() const { return source_type_; }
absl::optional<uint8_t> audio_level() const {
return extensions_.audio_level;
}
void set_audio_level(const absl::optional<uint8_t>& level) {
extensions_.audio_level = level;
}
uint32_t rtp_timestamp() const { return rtp_timestamp_; }
absl::optional<AbsoluteCaptureTime> absolute_capture_time() const {
return extensions_.absolute_capture_time;
}
absl::optional<TimeDelta> local_capture_clock_offset() const {
return extensions_.local_capture_clock_offset;
}
bool operator==(const RtpSource& o) const {
return timestamp_ == o.timestamp() && source_id_ == o.source_id() &&
source_type_ == o.source_type() &&
extensions_.audio_level == o.extensions_.audio_level &&
extensions_.absolute_capture_time ==
o.extensions_.absolute_capture_time &&
rtp_timestamp_ == o.rtp_timestamp();
}
private:
Timestamp timestamp_;
uint32_t source_id_;
RtpSourceType source_type_;
RtpSource::Extensions extensions_;
uint32_t rtp_timestamp_;
};
} // namespace webrtc
#endif // API_TRANSPORT_RTP_RTP_SOURCE_H_

View file

@ -0,0 +1,42 @@
/*
* Copyright 2020 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
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef API_TRANSPORT_SCTP_TRANSPORT_FACTORY_INTERFACE_H_
#define API_TRANSPORT_SCTP_TRANSPORT_FACTORY_INTERFACE_H_
#include <memory>
// These classes are not part of the API, and are treated as opaque pointers.
namespace cricket {
class SctpTransportInternal;
} // namespace cricket
namespace rtc {
class PacketTransportInternal;
} // namespace rtc
namespace webrtc {
// Factory class which can be used to allow fake SctpTransports to be injected
// for testing. An application is not intended to implement this interface nor
// 'cricket::SctpTransportInternal' because SctpTransportInternal is not
// guaranteed to remain stable in future WebRTC versions.
class SctpTransportFactoryInterface {
public:
virtual ~SctpTransportFactoryInterface() = default;
// Create an SCTP transport using `channel` for the underlying transport.
virtual std::unique_ptr<cricket::SctpTransportInternal> CreateSctpTransport(
rtc::PacketTransportInternal* channel) = 0;
};
} // namespace webrtc
#endif // API_TRANSPORT_SCTP_TRANSPORT_FACTORY_INTERFACE_H_

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,808 @@
/*
* Copyright 2004 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
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef API_TRANSPORT_STUN_H_
#define API_TRANSPORT_STUN_H_
// This file contains classes for dealing with the STUN protocol, as specified
// in RFC 5389, and its descendants.
#include <stddef.h>
#include <stdint.h>
#include <functional>
#include <memory>
#include <string>
#include <vector>
#include "absl/strings/string_view.h"
#include "api/array_view.h"
#include "rtc_base/byte_buffer.h"
#include "rtc_base/ip_address.h"
#include "rtc_base/socket_address.h"
namespace cricket {
// These are the types of STUN messages defined in RFC 5389.
enum StunMessageType : uint16_t {
STUN_INVALID_MESSAGE_TYPE = 0x0000,
STUN_BINDING_REQUEST = 0x0001,
STUN_BINDING_INDICATION = 0x0011,
STUN_BINDING_RESPONSE = 0x0101,
STUN_BINDING_ERROR_RESPONSE = 0x0111,
// Method 0x80, GOOG-PING is a variant of STUN BINDING
// that is sent instead of a STUN BINDING if the binding
// was identical to the one before.
GOOG_PING_REQUEST = 0x200,
GOOG_PING_RESPONSE = 0x300,
GOOG_PING_ERROR_RESPONSE = 0x310,
};
// These are all known STUN attributes, defined in RFC 5389 and elsewhere.
// Next to each is the name of the class (T is StunTAttribute) that implements
// that type.
// RETRANSMIT_COUNT is the number of outstanding pings without a response at
// the time the packet is generated.
enum StunAttributeType {
STUN_ATTR_MAPPED_ADDRESS = 0x0001, // Address
STUN_ATTR_USERNAME = 0x0006, // ByteString
STUN_ATTR_MESSAGE_INTEGRITY = 0x0008, // ByteString, 20 bytes
STUN_ATTR_ERROR_CODE = 0x0009, // ErrorCode
STUN_ATTR_UNKNOWN_ATTRIBUTES = 0x000a, // UInt16List
STUN_ATTR_REALM = 0x0014, // ByteString
STUN_ATTR_NONCE = 0x0015, // ByteString
STUN_ATTR_XOR_MAPPED_ADDRESS = 0x0020, // XorAddress
STUN_ATTR_SOFTWARE = 0x8022, // ByteString
STUN_ATTR_ALTERNATE_SERVER = 0x8023, // Address
STUN_ATTR_FINGERPRINT = 0x8028, // UInt32
STUN_ATTR_RETRANSMIT_COUNT = 0xFF00 // UInt32
};
// These are the types of the values associated with the attributes above.
// This allows us to perform some basic validation when reading or adding
// attributes. Note that these values are for our own use, and not defined in
// RFC 5389.
enum StunAttributeValueType {
STUN_VALUE_UNKNOWN = 0,
STUN_VALUE_ADDRESS = 1,
STUN_VALUE_XOR_ADDRESS = 2,
STUN_VALUE_UINT32 = 3,
STUN_VALUE_UINT64 = 4,
STUN_VALUE_BYTE_STRING = 5,
STUN_VALUE_ERROR_CODE = 6,
STUN_VALUE_UINT16_LIST = 7
};
// These are the types of STUN addresses defined in RFC 5389.
enum StunAddressFamily {
// NB: UNDEF is not part of the STUN spec.
STUN_ADDRESS_UNDEF = 0,
STUN_ADDRESS_IPV4 = 1,
STUN_ADDRESS_IPV6 = 2
};
// These are the types of STUN error codes defined in RFC 5389.
enum StunErrorCode {
STUN_ERROR_TRY_ALTERNATE = 300,
STUN_ERROR_BAD_REQUEST = 400,
STUN_ERROR_UNAUTHORIZED = 401,
STUN_ERROR_UNKNOWN_ATTRIBUTE = 420,
STUN_ERROR_STALE_NONCE = 438,
STUN_ERROR_SERVER_ERROR = 500,
STUN_ERROR_GLOBAL_FAILURE = 600
};
// Strings for the error codes above.
extern const char STUN_ERROR_REASON_TRY_ALTERNATE_SERVER[];
extern const char STUN_ERROR_REASON_BAD_REQUEST[];
extern const char STUN_ERROR_REASON_UNAUTHORIZED[];
extern const char STUN_ERROR_REASON_UNKNOWN_ATTRIBUTE[];
extern const char STUN_ERROR_REASON_STALE_NONCE[];
extern const char STUN_ERROR_REASON_SERVER_ERROR[];
// The mask used to determine whether a STUN message is a request/response etc.
const uint32_t kStunTypeMask = 0x0110;
// STUN Attribute header length.
const size_t kStunAttributeHeaderSize = 4;
// Following values correspond to RFC5389.
const size_t kStunHeaderSize = 20;
const size_t kStunTransactionIdOffset = 8;
const size_t kStunTransactionIdLength = 12;
const uint32_t kStunMagicCookie = 0x2112A442;
constexpr size_t kStunMagicCookieLength = sizeof(kStunMagicCookie);
// Following value corresponds to an earlier version of STUN from
// RFC3489.
const size_t kStunLegacyTransactionIdLength = 16;
// STUN Message Integrity HMAC length.
const size_t kStunMessageIntegritySize = 20;
// Size of STUN_ATTR_MESSAGE_INTEGRITY_32
const size_t kStunMessageIntegrity32Size = 4;
class StunAddressAttribute;
class StunAttribute;
class StunByteStringAttribute;
class StunErrorCodeAttribute;
class StunUInt16ListAttribute;
class StunUInt32Attribute;
class StunUInt64Attribute;
class StunXorAddressAttribute;
// Records a complete STUN/TURN message. Each message consists of a type and
// any number of attributes. Each attribute is parsed into an instance of an
// appropriate class (see above). The Get* methods will return instances of
// that attribute class.
class StunMessage {
public:
// Constructs a StunMessage with an invalid type and empty, legacy length
// (16 bytes, RFC3489) transaction id.
StunMessage();
// Construct a `StunMessage` with a specific type and generate a new
// 12 byte transaction id (RFC5389).
explicit StunMessage(uint16_t type);
StunMessage(uint16_t type, absl::string_view transaction_id);
virtual ~StunMessage();
// The verification status of the message. This is checked on parsing,
// or set by AddMessageIntegrity.
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class IntegrityStatus {
kNotSet = 0,
kNoIntegrity = 1, // Message-integrity attribute missing
kIntegrityOk = 2, // Message-integrity checked OK
kIntegrityBad = 3, // Message-integrity verification failed
kMaxValue = kIntegrityBad,
};
int type() const { return type_; }
size_t length() const { return length_; }
const std::string& transaction_id() const { return transaction_id_; }
uint32_t reduced_transaction_id() const { return reduced_transaction_id_; }
// Returns true if the message confirms to RFC3489 rather than
// RFC5389. The main difference between the two versions of the STUN
// protocol is the presence of the magic cookie and different length
// of transaction ID. For outgoing packets the version of the protocol
// is determined by the lengths of the transaction ID.
bool IsLegacy() const;
[[deprecated]] void SetType(int type) { type_ = static_cast<uint16_t>(type); }
[[deprecated]] bool SetTransactionID(absl::string_view transaction_id) {
if (!IsValidTransactionId(transaction_id))
return false;
SetTransactionIdForTesting(transaction_id);
return true;
}
// Get a list of all of the attribute types in the "comprehension required"
// range that were not recognized.
std::vector<uint16_t> GetNonComprehendedAttributes() const;
// Gets the desired attribute value, or NULL if no such attribute type exists.
const StunAddressAttribute* GetAddress(int type) const;
const StunUInt32Attribute* GetUInt32(int type) const;
const StunUInt64Attribute* GetUInt64(int type) const;
const StunByteStringAttribute* GetByteString(int type) const;
const StunUInt16ListAttribute* GetUInt16List(int type) const;
// Gets these specific attribute values.
const StunErrorCodeAttribute* GetErrorCode() const;
// Returns the code inside the error code attribute, if present, and
// STUN_ERROR_GLOBAL_FAILURE otherwise.
int GetErrorCodeValue() const;
const StunUInt16ListAttribute* GetUnknownAttributes() const;
// Takes ownership of the specified attribute and adds it to the message.
void AddAttribute(std::unique_ptr<StunAttribute> attr);
// Remove the last occurrence of an attribute.
std::unique_ptr<StunAttribute> RemoveAttribute(int type);
// Remote all attributes and releases them.
void ClearAttributes();
// Validates that a STUN message has a correct MESSAGE-INTEGRITY value.
// This uses the buffered raw-format message stored by Read().
IntegrityStatus ValidateMessageIntegrity(const std::string& password);
// Revalidates the STUN message with (possibly) a new password.
// Indicates that calling logic needs review - probably previous call
// was checking with the wrong password.
IntegrityStatus RevalidateMessageIntegrity(const std::string& password);
// Returns the current integrity status of the message.
IntegrityStatus integrity() const { return integrity_; }
// Shortcut for checking if integrity is verified.
bool IntegrityOk() const {
return integrity_ == IntegrityStatus::kIntegrityOk;
}
// Returns the password attribute used to set or check the integrity.
// Can only be called after adding or checking the integrity.
std::string password() const {
RTC_DCHECK(integrity_ != IntegrityStatus::kNotSet);
return password_;
}
// Adds a MESSAGE-INTEGRITY attribute that is valid for the current message.
bool AddMessageIntegrity(absl::string_view password);
// Adds a STUN_ATTR_GOOG_MESSAGE_INTEGRITY_32 attribute that is valid for the
// current message.
bool AddMessageIntegrity32(absl::string_view password);
// Verify that a buffer has stun magic cookie and one of the specified
// methods. Note that it does not check for the existance of FINGERPRINT.
static bool IsStunMethod(rtc::ArrayView<int> methods,
const char* data,
size_t size);
// Verifies that a given buffer is STUN by checking for a correct FINGERPRINT.
static bool ValidateFingerprint(const char* data, size_t size);
// Generates a new 12 byte (RFC5389) transaction id.
static std::string GenerateTransactionId();
// Adds a FINGERPRINT attribute that is valid for the current message.
bool AddFingerprint();
// Parses the STUN packet in the given buffer and records it here. The
// return value indicates whether this was successful.
bool Read(rtc::ByteBufferReader* buf);
// Writes this object into a STUN packet. The return value indicates whether
// this was successful.
bool Write(rtc::ByteBufferWriter* buf) const;
// Creates an empty message. Overridable by derived classes.
virtual StunMessage* CreateNew() const;
// Modify the stun magic cookie used for this STUN message.
// This is used for testing.
[[deprecated]] void SetStunMagicCookie(uint32_t val);
// Change the internal transaction id. Used only for testing.
void SetTransactionIdForTesting(absl::string_view transaction_id);
// Contruct a copy of `this`.
std::unique_ptr<StunMessage> Clone() const;
// Check if the attributes of this StunMessage equals those of `other`
// for all attributes that `attribute_type_mask` return true
bool EqualAttributes(const StunMessage* other,
std::function<bool(int type)> attribute_type_mask) const;
// Validates that a STUN message in byte buffer form
// has a correct MESSAGE-INTEGRITY value.
// These functions are not recommended and will be deprecated; use
// ValidateMessageIntegrity(password) on the parsed form instead.
[[deprecated("Use member function")]] static bool ValidateMessageIntegrity(
const char* data,
size_t size,
const std::string& password);
[[deprecated("Use member function")]] static bool ValidateMessageIntegrity32(
const char* data,
size_t size,
const std::string& password);
// Expose raw-buffer ValidateMessageIntegrity function for testing.
static bool ValidateMessageIntegrityForTesting(const char* data,
size_t size,
const std::string& password);
// Expose raw-buffer ValidateMessageIntegrity function for testing.
static bool ValidateMessageIntegrity32ForTesting(const char* data,
size_t size,
const std::string& password);
protected:
// Verifies that the given attribute is allowed for this message.
virtual StunAttributeValueType GetAttributeValueType(int type) const;
std::vector<std::unique_ptr<StunAttribute>> attrs_;
private:
StunAttribute* CreateAttribute(int type, size_t length) /* const*/;
const StunAttribute* GetAttribute(int type) const;
static bool IsValidTransactionId(absl::string_view transaction_id);
bool AddMessageIntegrityOfType(int mi_attr_type,
size_t mi_attr_size,
absl::string_view key);
static bool ValidateMessageIntegrityOfType(int mi_attr_type,
size_t mi_attr_size,
const char* data,
size_t size,
const std::string& password);
uint16_t type_ = STUN_INVALID_MESSAGE_TYPE;
uint16_t length_ = 0;
std::string transaction_id_;
uint32_t reduced_transaction_id_ = 0;
uint32_t stun_magic_cookie_ = kStunMagicCookie;
// The original buffer for messages created by Read().
std::string buffer_;
IntegrityStatus integrity_ = IntegrityStatus::kNotSet;
std::string password_;
};
// Base class for all STUN/TURN attributes.
class StunAttribute {
public:
virtual ~StunAttribute() {}
int type() const { return type_; }
size_t length() const { return length_; }
// Return the type of this attribute.
virtual StunAttributeValueType value_type() const = 0;
// Only XorAddressAttribute needs this so far.
virtual void SetOwner(StunMessage* owner) {}
// Reads the body (not the type or length) for this type of attribute from
// the given buffer. Return value is true if successful.
virtual bool Read(rtc::ByteBufferReader* buf) = 0;
// Writes the body (not the type or length) to the given buffer. Return
// value is true if successful.
virtual bool Write(rtc::ByteBufferWriter* buf) const = 0;
// Creates an attribute object with the given type and smallest length.
static StunAttribute* Create(StunAttributeValueType value_type,
uint16_t type,
uint16_t length,
StunMessage* owner);
// TODO(?): Allow these create functions to take parameters, to reduce
// the amount of work callers need to do to initialize attributes.
static std::unique_ptr<StunAddressAttribute> CreateAddress(uint16_t type);
static std::unique_ptr<StunXorAddressAttribute> CreateXorAddress(
uint16_t type);
static std::unique_ptr<StunUInt32Attribute> CreateUInt32(uint16_t type);
static std::unique_ptr<StunUInt64Attribute> CreateUInt64(uint16_t type);
static std::unique_ptr<StunByteStringAttribute> CreateByteString(
uint16_t type);
static std::unique_ptr<StunUInt16ListAttribute> CreateUInt16ListAttribute(
uint16_t type);
static std::unique_ptr<StunErrorCodeAttribute> CreateErrorCode();
static std::unique_ptr<StunUInt16ListAttribute> CreateUnknownAttributes();
protected:
StunAttribute(uint16_t type, uint16_t length);
void SetLength(uint16_t length) { length_ = length; }
void WritePadding(rtc::ByteBufferWriter* buf) const;
void ConsumePadding(rtc::ByteBufferReader* buf) const;
private:
uint16_t type_;
uint16_t length_;
};
// Implements STUN attributes that record an Internet address.
class StunAddressAttribute : public StunAttribute {
public:
static const uint16_t SIZE_UNDEF = 0;
static const uint16_t SIZE_IP4 = 8;
static const uint16_t SIZE_IP6 = 20;
StunAddressAttribute(uint16_t type, const rtc::SocketAddress& addr);
StunAddressAttribute(uint16_t type, uint16_t length);
StunAttributeValueType value_type() const override;
StunAddressFamily family() const {
switch (address_.ipaddr().family()) {
case AF_INET:
return STUN_ADDRESS_IPV4;
case AF_INET6:
return STUN_ADDRESS_IPV6;
}
return STUN_ADDRESS_UNDEF;
}
const rtc::SocketAddress& GetAddress() const { return address_; }
const rtc::IPAddress& ipaddr() const { return address_.ipaddr(); }
uint16_t port() const { return address_.port(); }
void SetAddress(const rtc::SocketAddress& addr) {
address_ = addr;
EnsureAddressLength();
}
void SetIP(const rtc::IPAddress& ip) {
address_.SetIP(ip);
EnsureAddressLength();
}
void SetPort(uint16_t port) { address_.SetPort(port); }
bool Read(rtc::ByteBufferReader* buf) override;
bool Write(rtc::ByteBufferWriter* buf) const override;
private:
void EnsureAddressLength() {
switch (family()) {
case STUN_ADDRESS_IPV4: {
SetLength(SIZE_IP4);
break;
}
case STUN_ADDRESS_IPV6: {
SetLength(SIZE_IP6);
break;
}
default: {
SetLength(SIZE_UNDEF);
break;
}
}
}
rtc::SocketAddress address_;
};
// Implements STUN attributes that record an Internet address. When encoded
// in a STUN message, the address contained in this attribute is XORed with the
// transaction ID of the message.
class StunXorAddressAttribute : public StunAddressAttribute {
public:
StunXorAddressAttribute(uint16_t type, const rtc::SocketAddress& addr);
StunXorAddressAttribute(uint16_t type, uint16_t length, StunMessage* owner);
StunAttributeValueType value_type() const override;
void SetOwner(StunMessage* owner) override;
bool Read(rtc::ByteBufferReader* buf) override;
bool Write(rtc::ByteBufferWriter* buf) const override;
private:
rtc::IPAddress GetXoredIP() const;
StunMessage* owner_;
};
// Implements STUN attributes that record a 32-bit integer.
class StunUInt32Attribute : public StunAttribute {
public:
static const uint16_t SIZE = 4;
StunUInt32Attribute(uint16_t type, uint32_t value);
explicit StunUInt32Attribute(uint16_t type);
StunAttributeValueType value_type() const override;
uint32_t value() const { return bits_; }
void SetValue(uint32_t bits) { bits_ = bits; }
bool GetBit(size_t index) const;
void SetBit(size_t index, bool value);
bool Read(rtc::ByteBufferReader* buf) override;
bool Write(rtc::ByteBufferWriter* buf) const override;
private:
uint32_t bits_;
};
class StunUInt64Attribute : public StunAttribute {
public:
static const uint16_t SIZE = 8;
StunUInt64Attribute(uint16_t type, uint64_t value);
explicit StunUInt64Attribute(uint16_t type);
StunAttributeValueType value_type() const override;
uint64_t value() const { return bits_; }
void SetValue(uint64_t bits) { bits_ = bits; }
bool Read(rtc::ByteBufferReader* buf) override;
bool Write(rtc::ByteBufferWriter* buf) const override;
private:
uint64_t bits_;
};
// Implements STUN attributes that record an arbitrary byte string.
class StunByteStringAttribute : public StunAttribute {
public:
explicit StunByteStringAttribute(uint16_t type);
StunByteStringAttribute(uint16_t type, absl::string_view str);
StunByteStringAttribute(uint16_t type, const void* bytes, size_t length);
StunByteStringAttribute(uint16_t type, uint16_t length);
~StunByteStringAttribute() override;
StunAttributeValueType value_type() const override;
[[deprecated("Use array_view")]] const char* bytes() const {
return reinterpret_cast<const char*>(bytes_);
}
// Returns the attribute value as a string.
// Use this for attributes that are text or text-compatible.
absl::string_view string_view() const {
return absl::string_view(reinterpret_cast<const char*>(bytes_), length());
}
// Returns the attribute value as an uint8_t view.
// Use this function for values that are not text.
rtc::ArrayView<uint8_t> array_view() const {
return rtc::MakeArrayView(bytes_, length());
}
[[deprecated]] std::string GetString() const {
return std::string(reinterpret_cast<const char*>(bytes_), length());
}
void CopyBytes(const void* bytes, size_t length);
void CopyBytes(absl::string_view bytes);
uint8_t GetByte(size_t index) const;
void SetByte(size_t index, uint8_t value);
bool Read(rtc::ByteBufferReader* buf) override;
bool Write(rtc::ByteBufferWriter* buf) const override;
private:
void SetBytes(uint8_t* bytes, size_t length);
uint8_t* bytes_;
};
// Implements STUN attributes that record an error code.
class StunErrorCodeAttribute : public StunAttribute {
public:
static const uint16_t MIN_SIZE;
StunErrorCodeAttribute(uint16_t type, int code, const std::string& reason);
StunErrorCodeAttribute(uint16_t type, uint16_t length);
~StunErrorCodeAttribute() override;
StunAttributeValueType value_type() const override;
// The combined error and class, e.g. 0x400.
int code() const;
void SetCode(int code);
// The individual error components.
int eclass() const { return class_; }
int number() const { return number_; }
const std::string& reason() const { return reason_; }
void SetClass(uint8_t eclass) { class_ = eclass; }
void SetNumber(uint8_t number) { number_ = number; }
void SetReason(const std::string& reason);
bool Read(rtc::ByteBufferReader* buf) override;
bool Write(rtc::ByteBufferWriter* buf) const override;
private:
uint8_t class_;
uint8_t number_;
std::string reason_;
};
// Implements STUN attributes that record a list of attribute names.
class StunUInt16ListAttribute : public StunAttribute {
public:
StunUInt16ListAttribute(uint16_t type, uint16_t length);
~StunUInt16ListAttribute() override;
StunAttributeValueType value_type() const override;
size_t Size() const;
uint16_t GetType(int index) const;
void SetType(int index, uint16_t value);
void AddType(uint16_t value);
void AddTypeAtIndex(uint16_t index, uint16_t value);
bool Read(rtc::ByteBufferReader* buf) override;
bool Write(rtc::ByteBufferWriter* buf) const override;
private:
std::vector<uint16_t>* attr_types_;
};
// Return a string e.g "STUN BINDING request".
std::string StunMethodToString(int msg_type);
// Returns the (successful) response type for the given request type.
// Returns -1 if `request_type` is not a valid request type.
int GetStunSuccessResponseType(int request_type);
// Returns the error response type for the given request type.
// Returns -1 if `request_type` is not a valid request type.
int GetStunErrorResponseType(int request_type);
// Returns whether a given message is a request type.
bool IsStunRequestType(int msg_type);
// Returns whether a given message is an indication type.
bool IsStunIndicationType(int msg_type);
// Returns whether a given response is a success type.
bool IsStunSuccessResponseType(int msg_type);
// Returns whether a given response is an error type.
bool IsStunErrorResponseType(int msg_type);
// Computes the STUN long-term credential hash.
bool ComputeStunCredentialHash(const std::string& username,
const std::string& realm,
const std::string& password,
std::string* hash);
// Make a copy af `attribute` and return a new StunAttribute.
// This is useful if you don't care about what kind of attribute you
// are handling.
//
// The implementation copies by calling Write() followed by Read().
//
// If `tmp_buffer` is supplied this buffer will be used, otherwise
// a buffer will created in the method.
std::unique_ptr<StunAttribute> CopyStunAttribute(
const StunAttribute& attribute,
rtc::ByteBufferWriter* tmp_buffer_ptr = 0);
// TODO(?): Move the TURN/ICE stuff below out to separate files.
extern const char TURN_MAGIC_COOKIE_VALUE[4];
// "GTURN" STUN methods.
// TODO(?): Rename these methods to GTURN_ to make it clear they aren't
// part of standard STUN/TURN.
enum RelayMessageType {
// For now, using the same defs from TurnMessageType below.
// STUN_ALLOCATE_REQUEST = 0x0003,
// STUN_ALLOCATE_RESPONSE = 0x0103,
// STUN_ALLOCATE_ERROR_RESPONSE = 0x0113,
STUN_SEND_REQUEST = 0x0004,
STUN_SEND_RESPONSE = 0x0104,
STUN_SEND_ERROR_RESPONSE = 0x0114,
STUN_DATA_INDICATION = 0x0115,
};
// "GTURN"-specific STUN attributes.
// TODO(?): Rename these attributes to GTURN_ to avoid conflicts.
enum RelayAttributeType {
STUN_ATTR_LIFETIME = 0x000d, // UInt32
STUN_ATTR_MAGIC_COOKIE = 0x000f, // ByteString, 4 bytes
STUN_ATTR_BANDWIDTH = 0x0010, // UInt32
STUN_ATTR_DESTINATION_ADDRESS = 0x0011, // Address
STUN_ATTR_SOURCE_ADDRESS2 = 0x0012, // Address
STUN_ATTR_DATA = 0x0013, // ByteString
STUN_ATTR_OPTIONS = 0x8001, // UInt32
};
// A "GTURN" STUN message.
class RelayMessage : public StunMessage {
public:
using StunMessage::StunMessage;
protected:
StunAttributeValueType GetAttributeValueType(int type) const override;
StunMessage* CreateNew() const override;
};
// Defined in TURN RFC 5766.
enum TurnMessageType : uint16_t {
STUN_ALLOCATE_REQUEST = 0x0003,
STUN_ALLOCATE_RESPONSE = 0x0103,
STUN_ALLOCATE_ERROR_RESPONSE = 0x0113,
TURN_REFRESH_REQUEST = 0x0004,
TURN_REFRESH_RESPONSE = 0x0104,
TURN_REFRESH_ERROR_RESPONSE = 0x0114,
TURN_SEND_INDICATION = 0x0016,
TURN_DATA_INDICATION = 0x0017,
TURN_CREATE_PERMISSION_REQUEST = 0x0008,
TURN_CREATE_PERMISSION_RESPONSE = 0x0108,
TURN_CREATE_PERMISSION_ERROR_RESPONSE = 0x0118,
TURN_CHANNEL_BIND_REQUEST = 0x0009,
TURN_CHANNEL_BIND_RESPONSE = 0x0109,
TURN_CHANNEL_BIND_ERROR_RESPONSE = 0x0119,
};
enum TurnAttributeType {
STUN_ATTR_CHANNEL_NUMBER = 0x000C, // UInt32
STUN_ATTR_TURN_LIFETIME = 0x000d, // UInt32
STUN_ATTR_XOR_PEER_ADDRESS = 0x0012, // XorAddress
// TODO(mallinath) - Uncomment after RelayAttributes are renamed.
// STUN_ATTR_DATA = 0x0013, // ByteString
STUN_ATTR_XOR_RELAYED_ADDRESS = 0x0016, // XorAddress
STUN_ATTR_EVEN_PORT = 0x0018, // ByteString, 1 byte.
STUN_ATTR_REQUESTED_TRANSPORT = 0x0019, // UInt32
STUN_ATTR_DONT_FRAGMENT = 0x001A, // No content, Length = 0
STUN_ATTR_RESERVATION_TOKEN = 0x0022, // ByteString, 8 bytes.
// TODO(mallinath) - Rename STUN_ATTR_TURN_LIFETIME to STUN_ATTR_LIFETIME and
// STUN_ATTR_TURN_DATA to STUN_ATTR_DATA. Also rename RelayMessage attributes
// by appending G to attribute name.
};
// RFC 5766-defined errors.
enum TurnErrorType {
STUN_ERROR_FORBIDDEN = 403,
STUN_ERROR_ALLOCATION_MISMATCH = 437,
STUN_ERROR_WRONG_CREDENTIALS = 441,
STUN_ERROR_UNSUPPORTED_PROTOCOL = 442
};
extern const int SERVER_NOT_REACHABLE_ERROR;
extern const char STUN_ERROR_REASON_FORBIDDEN[];
extern const char STUN_ERROR_REASON_ALLOCATION_MISMATCH[];
extern const char STUN_ERROR_REASON_WRONG_CREDENTIALS[];
extern const char STUN_ERROR_REASON_UNSUPPORTED_PROTOCOL[];
class TurnMessage : public StunMessage {
public:
using StunMessage::StunMessage;
protected:
StunAttributeValueType GetAttributeValueType(int type) const override;
StunMessage* CreateNew() const override;
};
enum IceAttributeType {
// RFC 5245 ICE STUN attributes.
STUN_ATTR_PRIORITY = 0x0024, // UInt32
STUN_ATTR_USE_CANDIDATE = 0x0025, // No content, Length = 0
STUN_ATTR_ICE_CONTROLLED = 0x8029, // UInt64
STUN_ATTR_ICE_CONTROLLING = 0x802A, // UInt64
// The following attributes are in the comprehension-optional range
// (0xC000-0xFFFF) and are not registered with IANA. These STUN attributes are
// intended for ICE and should NOT be used in generic use cases of STUN
// messages.
//
// Note that the value 0xC001 has already been assigned by IANA to
// ENF-FLOW-DESCRIPTION
// (https://www.iana.org/assignments/stun-parameters/stun-parameters.xml).
STUN_ATTR_NOMINATION = 0xC001, // UInt32
// UInt32. The higher 16 bits are the network ID. The lower 16 bits are the
// network cost.
STUN_ATTR_GOOG_NETWORK_INFO = 0xC057,
// Experimental: Transaction ID of the last connectivity check received.
STUN_ATTR_GOOG_LAST_ICE_CHECK_RECEIVED = 0xC058,
// Uint16List. Miscellaneous attributes for future extension.
STUN_ATTR_GOOG_MISC_INFO = 0xC059,
// Obsolete.
STUN_ATTR_GOOG_OBSOLETE_1 = 0xC05A,
STUN_ATTR_GOOG_CONNECTION_ID = 0xC05B, // Not yet implemented.
STUN_ATTR_GOOG_DELTA = 0xC05C, // Not yet implemented.
STUN_ATTR_GOOG_DELTA_ACK = 0xC05D, // Not yet implemented.
STUN_ATTR_GOOG_DELTA_SYNC_REQ = 0xC05E, // Not yet implemented.
// MESSAGE-INTEGRITY truncated to 32-bit.
STUN_ATTR_GOOG_MESSAGE_INTEGRITY_32 = 0xC060,
};
// When adding new attributes to STUN_ATTR_GOOG_MISC_INFO
// (which is a list of uint16_t), append the indices of these attributes below
// and do NOT change the existing indices. The indices of attributes must be
// consistent with those used in ConnectionRequest::Prepare when forming a STUN
// message for the ICE connectivity check, and they are used when parsing a
// received STUN message.
enum class IceGoogMiscInfoBindingRequestAttributeIndex {
SUPPORT_GOOG_PING_VERSION = 0,
};
enum class IceGoogMiscInfoBindingResponseAttributeIndex {
SUPPORT_GOOG_PING_VERSION = 0,
};
// RFC 5245-defined errors.
enum IceErrorCode {
STUN_ERROR_ROLE_CONFLICT = 487,
};
extern const char STUN_ERROR_REASON_ROLE_CONFLICT[];
// A RFC 5245 ICE STUN message.
class IceMessage : public StunMessage {
public:
using StunMessage::StunMessage;
protected:
StunAttributeValueType GetAttributeValueType(int type) const override;
StunMessage* CreateNew() const override;
};
} // namespace cricket
#endif // API_TRANSPORT_STUN_H_

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,23 @@
/*
* Copyright 2019 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
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "api/transport/test/create_feedback_generator.h"
#include <memory>
#include "test/network/feedback_generator.h"
namespace webrtc {
std::unique_ptr<FeedbackGenerator> CreateFeedbackGenerator(
FeedbackGenerator::Config confg) {
return std::make_unique<FeedbackGeneratorImpl>(confg);
}
} // namespace webrtc

View file

@ -0,0 +1,21 @@
/*
* Copyright 2019 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
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef API_TRANSPORT_TEST_CREATE_FEEDBACK_GENERATOR_H_
#define API_TRANSPORT_TEST_CREATE_FEEDBACK_GENERATOR_H_
#include <memory>
#include "api/transport/test/feedback_generator_interface.h"
namespace webrtc {
std::unique_ptr<FeedbackGenerator> CreateFeedbackGenerator(
FeedbackGenerator::Config confg);
} // namespace webrtc
#endif // API_TRANSPORT_TEST_CREATE_FEEDBACK_GENERATOR_H_

View file

@ -0,0 +1,37 @@
/*
* Copyright 2019 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
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef API_TRANSPORT_TEST_FEEDBACK_GENERATOR_INTERFACE_H_
#define API_TRANSPORT_TEST_FEEDBACK_GENERATOR_INTERFACE_H_
#include <vector>
#include "api/test/simulated_network.h"
#include "api/transport/network_types.h"
namespace webrtc {
class FeedbackGenerator {
public:
struct Config {
BuiltInNetworkBehaviorConfig send_link;
BuiltInNetworkBehaviorConfig return_link;
TimeDelta feedback_interval = TimeDelta::Millis(50);
DataSize feedback_packet_size = DataSize::Bytes(20);
};
virtual ~FeedbackGenerator() = default;
virtual Timestamp Now() = 0;
virtual void Sleep(TimeDelta duration) = 0;
virtual void SendPacket(size_t size) = 0;
virtual std::vector<TransportPacketsFeedback> PopFeedback() = 0;
virtual void SetSendConfig(BuiltInNetworkBehaviorConfig config) = 0;
virtual void SetReturnConfig(BuiltInNetworkBehaviorConfig config) = 0;
virtual void SetSendLinkCapacity(DataRate capacity) = 0;
};
} // namespace webrtc
#endif // API_TRANSPORT_TEST_FEEDBACK_GENERATOR_INTERFACE_H_

View file

@ -0,0 +1,84 @@
/*
* Copyright (c) 2019 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
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef API_TRANSPORT_TEST_MOCK_NETWORK_CONTROL_H_
#define API_TRANSPORT_TEST_MOCK_NETWORK_CONTROL_H_
#include "api/transport/network_control.h"
#include "test/gmock.h"
namespace webrtc {
class MockNetworkControllerInterface : public NetworkControllerInterface {
public:
MOCK_METHOD(NetworkControlUpdate,
OnNetworkAvailability,
(NetworkAvailability),
(override));
MOCK_METHOD(NetworkControlUpdate,
OnProcessInterval,
(ProcessInterval),
(override));
MOCK_METHOD(NetworkControlUpdate,
OnNetworkRouteChange,
(NetworkRouteChange),
(override));
MOCK_METHOD(NetworkControlUpdate,
OnRemoteBitrateReport,
(RemoteBitrateReport),
(override));
MOCK_METHOD(NetworkControlUpdate,
OnRoundTripTimeUpdate,
(RoundTripTimeUpdate),
(override));
MOCK_METHOD(NetworkControlUpdate, OnSentPacket, (SentPacket), (override));
MOCK_METHOD(NetworkControlUpdate,
OnReceivedPacket,
(ReceivedPacket),
(override));
MOCK_METHOD(NetworkControlUpdate,
OnStreamsConfig,
(StreamsConfig),
(override));
MOCK_METHOD(NetworkControlUpdate,
OnTargetRateConstraints,
(TargetRateConstraints),
(override));
MOCK_METHOD(NetworkControlUpdate,
OnTransportLossReport,
(TransportLossReport),
(override));
MOCK_METHOD(NetworkControlUpdate,
OnTransportPacketsFeedback,
(TransportPacketsFeedback),
(override));
MOCK_METHOD(NetworkControlUpdate,
OnNetworkStateEstimate,
(NetworkStateEstimate),
(override));
};
class MockNetworkStateEstimator : public NetworkStateEstimator {
public:
MOCK_METHOD(absl::optional<NetworkStateEstimate>,
GetCurrentEstimate,
(),
(override));
MOCK_METHOD(void,
OnTransportPacketsFeedback,
(const TransportPacketsFeedback&),
(override));
MOCK_METHOD(void, OnReceivedPacket, (const PacketResult&), (override));
MOCK_METHOD(void, OnRouteChange, (const NetworkRouteChange&), (override));
};
} // namespace webrtc
#endif // API_TRANSPORT_TEST_MOCK_NETWORK_CONTROL_H_