media_channel.h 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. /*
  2. * Copyright (c) 2004 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. #ifndef MEDIA_BASE_MEDIA_CHANNEL_H_
  11. #define MEDIA_BASE_MEDIA_CHANNEL_H_
  12. #include <map>
  13. #include <memory>
  14. #include <string>
  15. #include <utility>
  16. #include <vector>
  17. #include "absl/types/optional.h"
  18. #include "api/audio_codecs/audio_encoder.h"
  19. #include "api/audio_options.h"
  20. #include "api/crypto/frame_decryptor_interface.h"
  21. #include "api/crypto/frame_encryptor_interface.h"
  22. #include "api/frame_transformer_interface.h"
  23. #include "api/media_stream_interface.h"
  24. #include "api/rtc_error.h"
  25. #include "api/rtp_parameters.h"
  26. #include "api/transport/rtp/rtp_source.h"
  27. #include "api/video/video_content_type.h"
  28. #include "api/video/video_sink_interface.h"
  29. #include "api/video/video_source_interface.h"
  30. #include "api/video/video_timing.h"
  31. #include "api/video_codecs/video_encoder_config.h"
  32. #include "call/video_receive_stream.h"
  33. #include "common_video/include/quality_limitation_reason.h"
  34. #include "media/base/codec.h"
  35. #include "media/base/delayable.h"
  36. #include "media/base/media_config.h"
  37. #include "media/base/media_constants.h"
  38. #include "media/base/stream_params.h"
  39. #include "modules/audio_processing/include/audio_processing_statistics.h"
  40. #include "modules/rtp_rtcp/include/report_block_data.h"
  41. #include "rtc_base/async_packet_socket.h"
  42. #include "rtc_base/buffer.h"
  43. #include "rtc_base/callback.h"
  44. #include "rtc_base/copy_on_write_buffer.h"
  45. #include "rtc_base/dscp.h"
  46. #include "rtc_base/logging.h"
  47. #include "rtc_base/network_route.h"
  48. #include "rtc_base/socket.h"
  49. #include "rtc_base/string_encode.h"
  50. #include "rtc_base/strings/string_builder.h"
  51. #include "rtc_base/synchronization/mutex.h"
  52. #include "rtc_base/third_party/sigslot/sigslot.h"
  53. namespace rtc {
  54. class Timing;
  55. }
  56. namespace webrtc {
  57. class AudioSinkInterface;
  58. class VideoFrame;
  59. } // namespace webrtc
  60. namespace cricket {
  61. class AudioSource;
  62. class VideoCapturer;
  63. struct RtpHeader;
  64. struct VideoFormat;
  65. const int kScreencastDefaultFps = 5;
  66. template <class T>
  67. static std::string ToStringIfSet(const char* key,
  68. const absl::optional<T>& val) {
  69. std::string str;
  70. if (val) {
  71. str = key;
  72. str += ": ";
  73. str += val ? rtc::ToString(*val) : "";
  74. str += ", ";
  75. }
  76. return str;
  77. }
  78. template <class T>
  79. static std::string VectorToString(const std::vector<T>& vals) {
  80. rtc::StringBuilder ost; // no-presubmit-check TODO(webrtc:8982)
  81. ost << "[";
  82. for (size_t i = 0; i < vals.size(); ++i) {
  83. if (i > 0) {
  84. ost << ", ";
  85. }
  86. ost << vals[i].ToString();
  87. }
  88. ost << "]";
  89. return ost.Release();
  90. }
  91. // Options that can be applied to a VideoMediaChannel or a VideoMediaEngine.
  92. // Used to be flags, but that makes it hard to selectively apply options.
  93. // We are moving all of the setting of options to structs like this,
  94. // but some things currently still use flags.
  95. struct VideoOptions {
  96. VideoOptions();
  97. ~VideoOptions();
  98. void SetAll(const VideoOptions& change) {
  99. SetFrom(&video_noise_reduction, change.video_noise_reduction);
  100. SetFrom(&screencast_min_bitrate_kbps, change.screencast_min_bitrate_kbps);
  101. SetFrom(&is_screencast, change.is_screencast);
  102. }
  103. bool operator==(const VideoOptions& o) const {
  104. return video_noise_reduction == o.video_noise_reduction &&
  105. screencast_min_bitrate_kbps == o.screencast_min_bitrate_kbps &&
  106. is_screencast == o.is_screencast;
  107. }
  108. bool operator!=(const VideoOptions& o) const { return !(*this == o); }
  109. std::string ToString() const {
  110. rtc::StringBuilder ost;
  111. ost << "VideoOptions {";
  112. ost << ToStringIfSet("noise reduction", video_noise_reduction);
  113. ost << ToStringIfSet("screencast min bitrate kbps",
  114. screencast_min_bitrate_kbps);
  115. ost << ToStringIfSet("is_screencast ", is_screencast);
  116. ost << "}";
  117. return ost.Release();
  118. }
  119. // Enable denoising? This flag comes from the getUserMedia
  120. // constraint 'googNoiseReduction', and WebRtcVideoEngine passes it
  121. // on to the codec options. Disabled by default.
  122. absl::optional<bool> video_noise_reduction;
  123. // Force screencast to use a minimum bitrate. This flag comes from
  124. // the PeerConnection constraint 'googScreencastMinBitrate'. It is
  125. // copied to the encoder config by WebRtcVideoChannel.
  126. absl::optional<int> screencast_min_bitrate_kbps;
  127. // Set by screencast sources. Implies selection of encoding settings
  128. // suitable for screencast. Most likely not the right way to do
  129. // things, e.g., screencast of a text document and screencast of a
  130. // youtube video have different needs.
  131. absl::optional<bool> is_screencast;
  132. webrtc::VideoTrackInterface::ContentHint content_hint;
  133. private:
  134. template <typename T>
  135. static void SetFrom(absl::optional<T>* s, const absl::optional<T>& o) {
  136. if (o) {
  137. *s = o;
  138. }
  139. }
  140. };
  141. class MediaChannel : public sigslot::has_slots<> {
  142. public:
  143. class NetworkInterface {
  144. public:
  145. enum SocketType { ST_RTP, ST_RTCP };
  146. virtual bool SendPacket(rtc::CopyOnWriteBuffer* packet,
  147. const rtc::PacketOptions& options) = 0;
  148. virtual bool SendRtcp(rtc::CopyOnWriteBuffer* packet,
  149. const rtc::PacketOptions& options) = 0;
  150. virtual int SetOption(SocketType type,
  151. rtc::Socket::Option opt,
  152. int option) = 0;
  153. virtual ~NetworkInterface() {}
  154. };
  155. explicit MediaChannel(const MediaConfig& config);
  156. MediaChannel();
  157. ~MediaChannel() override;
  158. virtual cricket::MediaType media_type() const = 0;
  159. // Sets the abstract interface class for sending RTP/RTCP data.
  160. virtual void SetInterface(NetworkInterface* iface)
  161. RTC_LOCKS_EXCLUDED(network_interface_mutex_);
  162. // Called when a RTP packet is received.
  163. virtual void OnPacketReceived(rtc::CopyOnWriteBuffer packet,
  164. int64_t packet_time_us) = 0;
  165. // Called when the socket's ability to send has changed.
  166. virtual void OnReadyToSend(bool ready) = 0;
  167. // Called when the network route used for sending packets changed.
  168. virtual void OnNetworkRouteChanged(
  169. const std::string& transport_name,
  170. const rtc::NetworkRoute& network_route) = 0;
  171. // Creates a new outgoing media stream with SSRCs and CNAME as described
  172. // by sp.
  173. virtual bool AddSendStream(const StreamParams& sp) = 0;
  174. // Removes an outgoing media stream.
  175. // SSRC must be the first SSRC of the media stream if the stream uses
  176. // multiple SSRCs. In the case of an ssrc of 0, the possibly cached
  177. // StreamParams is removed.
  178. virtual bool RemoveSendStream(uint32_t ssrc) = 0;
  179. // Creates a new incoming media stream with SSRCs, CNAME as described
  180. // by sp. In the case of a sp without SSRCs, the unsignaled sp is cached
  181. // to be used later for unsignaled streams received.
  182. virtual bool AddRecvStream(const StreamParams& sp) = 0;
  183. // Removes an incoming media stream.
  184. // ssrc must be the first SSRC of the media stream if the stream uses
  185. // multiple SSRCs.
  186. virtual bool RemoveRecvStream(uint32_t ssrc) = 0;
  187. // Resets any cached StreamParams for an unsignaled RecvStream, and removes
  188. // any existing unsignaled streams.
  189. virtual void ResetUnsignaledRecvStream() = 0;
  190. // Returns the absoulte sendtime extension id value from media channel.
  191. virtual int GetRtpSendTimeExtnId() const;
  192. // Set the frame encryptor to use on all outgoing frames. This is optional.
  193. // This pointers lifetime is managed by the set of RtpSender it is attached
  194. // to.
  195. // TODO(benwright) make pure virtual once internal supports it.
  196. virtual void SetFrameEncryptor(
  197. uint32_t ssrc,
  198. rtc::scoped_refptr<webrtc::FrameEncryptorInterface> frame_encryptor);
  199. // Set the frame decryptor to use on all incoming frames. This is optional.
  200. // This pointers lifetimes is managed by the set of RtpReceivers it is
  201. // attached to.
  202. // TODO(benwright) make pure virtual once internal supports it.
  203. virtual void SetFrameDecryptor(
  204. uint32_t ssrc,
  205. rtc::scoped_refptr<webrtc::FrameDecryptorInterface> frame_decryptor);
  206. // Enable network condition based codec switching.
  207. virtual void SetVideoCodecSwitchingEnabled(bool enabled);
  208. // Base method to send packet using NetworkInterface.
  209. bool SendPacket(rtc::CopyOnWriteBuffer* packet,
  210. const rtc::PacketOptions& options) {
  211. return DoSendPacket(packet, false, options);
  212. }
  213. bool SendRtcp(rtc::CopyOnWriteBuffer* packet,
  214. const rtc::PacketOptions& options) {
  215. return DoSendPacket(packet, true, options);
  216. }
  217. int SetOption(NetworkInterface::SocketType type,
  218. rtc::Socket::Option opt,
  219. int option) RTC_LOCKS_EXCLUDED(network_interface_mutex_) {
  220. webrtc::MutexLock lock(&network_interface_mutex_);
  221. return SetOptionLocked(type, opt, option);
  222. }
  223. // Corresponds to the SDP attribute extmap-allow-mixed, see RFC8285.
  224. // Set to true if it's allowed to mix one- and two-byte RTP header extensions
  225. // in the same stream. The setter and getter must only be called from
  226. // worker_thread.
  227. void SetExtmapAllowMixed(bool extmap_allow_mixed) {
  228. extmap_allow_mixed_ = extmap_allow_mixed;
  229. }
  230. bool ExtmapAllowMixed() const { return extmap_allow_mixed_; }
  231. virtual webrtc::RtpParameters GetRtpSendParameters(uint32_t ssrc) const = 0;
  232. virtual webrtc::RTCError SetRtpSendParameters(
  233. uint32_t ssrc,
  234. const webrtc::RtpParameters& parameters) = 0;
  235. virtual void SetEncoderToPacketizerFrameTransformer(
  236. uint32_t ssrc,
  237. rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer);
  238. virtual void SetDepacketizerToDecoderFrameTransformer(
  239. uint32_t ssrc,
  240. rtc::scoped_refptr<webrtc::FrameTransformerInterface> frame_transformer);
  241. protected:
  242. int SetOptionLocked(NetworkInterface::SocketType type,
  243. rtc::Socket::Option opt,
  244. int option)
  245. RTC_EXCLUSIVE_LOCKS_REQUIRED(network_interface_mutex_) {
  246. if (!network_interface_)
  247. return -1;
  248. return network_interface_->SetOption(type, opt, option);
  249. }
  250. bool DscpEnabled() const { return enable_dscp_; }
  251. // This is the DSCP value used for both RTP and RTCP channels if DSCP is
  252. // enabled. It can be changed at any time via |SetPreferredDscp|.
  253. rtc::DiffServCodePoint PreferredDscp() const
  254. RTC_LOCKS_EXCLUDED(network_interface_mutex_) {
  255. webrtc::MutexLock lock(&network_interface_mutex_);
  256. return preferred_dscp_;
  257. }
  258. int SetPreferredDscp(rtc::DiffServCodePoint preferred_dscp)
  259. RTC_LOCKS_EXCLUDED(network_interface_mutex_) {
  260. webrtc::MutexLock lock(&network_interface_mutex_);
  261. if (preferred_dscp == preferred_dscp_) {
  262. return 0;
  263. }
  264. preferred_dscp_ = preferred_dscp;
  265. return UpdateDscp();
  266. }
  267. private:
  268. // Apply the preferred DSCP setting to the underlying network interface RTP
  269. // and RTCP channels. If DSCP is disabled, then apply the default DSCP value.
  270. int UpdateDscp() RTC_EXCLUSIVE_LOCKS_REQUIRED(network_interface_mutex_) {
  271. rtc::DiffServCodePoint value =
  272. enable_dscp_ ? preferred_dscp_ : rtc::DSCP_DEFAULT;
  273. int ret =
  274. SetOptionLocked(NetworkInterface::ST_RTP, rtc::Socket::OPT_DSCP, value);
  275. if (ret == 0) {
  276. ret = SetOptionLocked(NetworkInterface::ST_RTCP, rtc::Socket::OPT_DSCP,
  277. value);
  278. }
  279. return ret;
  280. }
  281. bool DoSendPacket(rtc::CopyOnWriteBuffer* packet,
  282. bool rtcp,
  283. const rtc::PacketOptions& options)
  284. RTC_LOCKS_EXCLUDED(network_interface_mutex_) {
  285. webrtc::MutexLock lock(&network_interface_mutex_);
  286. if (!network_interface_)
  287. return false;
  288. return (!rtcp) ? network_interface_->SendPacket(packet, options)
  289. : network_interface_->SendRtcp(packet, options);
  290. }
  291. const bool enable_dscp_;
  292. // |network_interface_| can be accessed from the worker_thread and
  293. // from any MediaEngine threads. This critical section is to protect accessing
  294. // of network_interface_ object.
  295. mutable webrtc::Mutex network_interface_mutex_;
  296. NetworkInterface* network_interface_
  297. RTC_GUARDED_BY(network_interface_mutex_) = nullptr;
  298. rtc::DiffServCodePoint preferred_dscp_
  299. RTC_GUARDED_BY(network_interface_mutex_) = rtc::DSCP_DEFAULT;
  300. bool extmap_allow_mixed_ = false;
  301. };
  302. // The stats information is structured as follows:
  303. // Media are represented by either MediaSenderInfo or MediaReceiverInfo.
  304. // Media contains a vector of SSRC infos that are exclusively used by this
  305. // media. (SSRCs shared between media streams can't be represented.)
  306. // Information about an SSRC.
  307. // This data may be locally recorded, or received in an RTCP SR or RR.
  308. struct SsrcSenderInfo {
  309. uint32_t ssrc = 0;
  310. double timestamp = 0.0; // NTP timestamp, represented as seconds since epoch.
  311. };
  312. struct SsrcReceiverInfo {
  313. uint32_t ssrc = 0;
  314. double timestamp = 0.0;
  315. };
  316. struct MediaSenderInfo {
  317. MediaSenderInfo();
  318. ~MediaSenderInfo();
  319. void add_ssrc(const SsrcSenderInfo& stat) { local_stats.push_back(stat); }
  320. // Temporary utility function for call sites that only provide SSRC.
  321. // As more info is added into SsrcSenderInfo, this function should go away.
  322. void add_ssrc(uint32_t ssrc) {
  323. SsrcSenderInfo stat;
  324. stat.ssrc = ssrc;
  325. add_ssrc(stat);
  326. }
  327. // Utility accessor for clients that are only interested in ssrc numbers.
  328. std::vector<uint32_t> ssrcs() const {
  329. std::vector<uint32_t> retval;
  330. for (std::vector<SsrcSenderInfo>::const_iterator it = local_stats.begin();
  331. it != local_stats.end(); ++it) {
  332. retval.push_back(it->ssrc);
  333. }
  334. return retval;
  335. }
  336. // Returns true if the media has been connected.
  337. bool connected() const { return local_stats.size() > 0; }
  338. // Utility accessor for clients that make the assumption only one ssrc
  339. // exists per media.
  340. // This will eventually go away.
  341. // Call sites that compare this to zero should use connected() instead.
  342. // https://bugs.webrtc.org/8694
  343. uint32_t ssrc() const {
  344. if (connected()) {
  345. return local_stats[0].ssrc;
  346. } else {
  347. return 0;
  348. }
  349. }
  350. // https://w3c.github.io/webrtc-stats/#dom-rtcsentrtpstreamstats-bytessent
  351. int64_t payload_bytes_sent = 0;
  352. // https://w3c.github.io/webrtc-stats/#dom-rtcoutboundrtpstreamstats-headerbytessent
  353. int64_t header_and_padding_bytes_sent = 0;
  354. // https://w3c.github.io/webrtc-stats/#dom-rtcoutboundrtpstreamstats-retransmittedbytessent
  355. uint64_t retransmitted_bytes_sent = 0;
  356. int packets_sent = 0;
  357. // https://w3c.github.io/webrtc-stats/#dom-rtcoutboundrtpstreamstats-retransmittedpacketssent
  358. uint64_t retransmitted_packets_sent = 0;
  359. int packets_lost = 0;
  360. float fraction_lost = 0.0f;
  361. int64_t rtt_ms = 0;
  362. std::string codec_name;
  363. absl::optional<int> codec_payload_type;
  364. std::vector<SsrcSenderInfo> local_stats;
  365. std::vector<SsrcReceiverInfo> remote_stats;
  366. // A snapshot of the most recent Report Block with additional data of interest
  367. // to statistics. Used to implement RTCRemoteInboundRtpStreamStats. Within
  368. // this list, the ReportBlockData::RTCPReportBlock::source_ssrc(), which is
  369. // the SSRC of the corresponding outbound RTP stream, is unique.
  370. std::vector<webrtc::ReportBlockData> report_block_datas;
  371. };
  372. struct MediaReceiverInfo {
  373. MediaReceiverInfo();
  374. ~MediaReceiverInfo();
  375. void add_ssrc(const SsrcReceiverInfo& stat) { local_stats.push_back(stat); }
  376. // Temporary utility function for call sites that only provide SSRC.
  377. // As more info is added into SsrcSenderInfo, this function should go away.
  378. void add_ssrc(uint32_t ssrc) {
  379. SsrcReceiverInfo stat;
  380. stat.ssrc = ssrc;
  381. add_ssrc(stat);
  382. }
  383. std::vector<uint32_t> ssrcs() const {
  384. std::vector<uint32_t> retval;
  385. for (std::vector<SsrcReceiverInfo>::const_iterator it = local_stats.begin();
  386. it != local_stats.end(); ++it) {
  387. retval.push_back(it->ssrc);
  388. }
  389. return retval;
  390. }
  391. // Returns true if the media has been connected.
  392. bool connected() const { return local_stats.size() > 0; }
  393. // Utility accessor for clients that make the assumption only one ssrc
  394. // exists per media.
  395. // This will eventually go away.
  396. // Call sites that compare this to zero should use connected();
  397. // https://bugs.webrtc.org/8694
  398. uint32_t ssrc() const {
  399. if (connected()) {
  400. return local_stats[0].ssrc;
  401. } else {
  402. return 0;
  403. }
  404. }
  405. // https://w3c.github.io/webrtc-stats/#dom-rtcinboundrtpstreamstats-bytesreceived
  406. int64_t payload_bytes_rcvd = 0;
  407. // https://w3c.github.io/webrtc-stats/#dom-rtcinboundrtpstreamstats-headerbytesreceived
  408. int64_t header_and_padding_bytes_rcvd = 0;
  409. int packets_rcvd = 0;
  410. int packets_lost = 0;
  411. // The timestamp at which the last packet was received, i.e. the time of the
  412. // local clock when it was received - not the RTP timestamp of that packet.
  413. // https://w3c.github.io/webrtc-stats/#dom-rtcinboundrtpstreamstats-lastpacketreceivedtimestamp
  414. absl::optional<int64_t> last_packet_received_timestamp_ms;
  415. // https://w3c.github.io/webrtc-stats/#dom-rtcinboundrtpstreamstats-estimatedplayouttimestamp
  416. absl::optional<int64_t> estimated_playout_ntp_timestamp_ms;
  417. std::string codec_name;
  418. absl::optional<int> codec_payload_type;
  419. std::vector<SsrcReceiverInfo> local_stats;
  420. std::vector<SsrcSenderInfo> remote_stats;
  421. };
  422. struct VoiceSenderInfo : public MediaSenderInfo {
  423. VoiceSenderInfo();
  424. ~VoiceSenderInfo();
  425. int jitter_ms = 0;
  426. // Current audio level, expressed linearly [0,32767].
  427. int audio_level = 0;
  428. // See description of "totalAudioEnergy" in the WebRTC stats spec:
  429. // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats-totalaudioenergy
  430. double total_input_energy = 0.0;
  431. double total_input_duration = 0.0;
  432. bool typing_noise_detected = false;
  433. webrtc::ANAStats ana_statistics;
  434. webrtc::AudioProcessingStats apm_statistics;
  435. };
  436. struct VoiceReceiverInfo : public MediaReceiverInfo {
  437. VoiceReceiverInfo();
  438. ~VoiceReceiverInfo();
  439. int jitter_ms = 0;
  440. int jitter_buffer_ms = 0;
  441. int jitter_buffer_preferred_ms = 0;
  442. int delay_estimate_ms = 0;
  443. int audio_level = 0;
  444. // Stats below correspond to similarly-named fields in the WebRTC stats spec.
  445. // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats
  446. double total_output_energy = 0.0;
  447. uint64_t total_samples_received = 0;
  448. double total_output_duration = 0.0;
  449. uint64_t concealed_samples = 0;
  450. uint64_t silent_concealed_samples = 0;
  451. uint64_t concealment_events = 0;
  452. double jitter_buffer_delay_seconds = 0.0;
  453. uint64_t jitter_buffer_emitted_count = 0;
  454. double jitter_buffer_target_delay_seconds = 0.0;
  455. uint64_t inserted_samples_for_deceleration = 0;
  456. uint64_t removed_samples_for_acceleration = 0;
  457. uint64_t fec_packets_received = 0;
  458. uint64_t fec_packets_discarded = 0;
  459. // Stats below DO NOT correspond directly to anything in the WebRTC stats
  460. // fraction of synthesized audio inserted through expansion.
  461. float expand_rate = 0.0f;
  462. // fraction of synthesized speech inserted through expansion.
  463. float speech_expand_rate = 0.0f;
  464. // fraction of data out of secondary decoding, including FEC and RED.
  465. float secondary_decoded_rate = 0.0f;
  466. // Fraction of secondary data, including FEC and RED, that is discarded.
  467. // Discarding of secondary data can be caused by the reception of the primary
  468. // data, obsoleting the secondary data. It can also be caused by early
  469. // or late arrival of secondary data. This metric is the percentage of
  470. // discarded secondary data since last query of receiver info.
  471. float secondary_discarded_rate = 0.0f;
  472. // Fraction of data removed through time compression.
  473. float accelerate_rate = 0.0f;
  474. // Fraction of data inserted through time stretching.
  475. float preemptive_expand_rate = 0.0f;
  476. int decoding_calls_to_silence_generator = 0;
  477. int decoding_calls_to_neteq = 0;
  478. int decoding_normal = 0;
  479. // TODO(alexnarest): Consider decoding_neteq_plc for consistency
  480. int decoding_plc = 0;
  481. int decoding_codec_plc = 0;
  482. int decoding_cng = 0;
  483. int decoding_plc_cng = 0;
  484. int decoding_muted_output = 0;
  485. // Estimated capture start time in NTP time in ms.
  486. int64_t capture_start_ntp_time_ms = -1;
  487. // Count of the number of buffer flushes.
  488. uint64_t jitter_buffer_flushes = 0;
  489. // Number of samples expanded due to delayed packets.
  490. uint64_t delayed_packet_outage_samples = 0;
  491. // Arrival delay of received audio packets.
  492. double relative_packet_arrival_delay_seconds = 0.0;
  493. // Count and total duration of audio interruptions (loss-concealement periods
  494. // longer than 150 ms).
  495. int32_t interruption_count = 0;
  496. int32_t total_interruption_duration_ms = 0;
  497. };
  498. struct VideoSenderInfo : public MediaSenderInfo {
  499. VideoSenderInfo();
  500. ~VideoSenderInfo();
  501. std::vector<SsrcGroup> ssrc_groups;
  502. std::string encoder_implementation_name;
  503. int firs_rcvd = 0;
  504. int plis_rcvd = 0;
  505. int nacks_rcvd = 0;
  506. int send_frame_width = 0;
  507. int send_frame_height = 0;
  508. int framerate_input = 0;
  509. int framerate_sent = 0;
  510. int aggregated_framerate_sent = 0;
  511. int nominal_bitrate = 0;
  512. int adapt_reason = 0;
  513. int adapt_changes = 0;
  514. // https://w3c.github.io/webrtc-stats/#dom-rtcoutboundrtpstreamstats-qualitylimitationreason
  515. webrtc::QualityLimitationReason quality_limitation_reason =
  516. webrtc::QualityLimitationReason::kNone;
  517. // https://w3c.github.io/webrtc-stats/#dom-rtcoutboundrtpstreamstats-qualitylimitationdurations
  518. std::map<webrtc::QualityLimitationReason, int64_t>
  519. quality_limitation_durations_ms;
  520. // https://w3c.github.io/webrtc-stats/#dom-rtcoutboundrtpstreamstats-qualitylimitationresolutionchanges
  521. uint32_t quality_limitation_resolution_changes = 0;
  522. int avg_encode_ms = 0;
  523. int encode_usage_percent = 0;
  524. uint32_t frames_encoded = 0;
  525. uint32_t key_frames_encoded = 0;
  526. // https://w3c.github.io/webrtc-stats/#dom-rtcoutboundrtpstreamstats-totalencodetime
  527. uint64_t total_encode_time_ms = 0;
  528. // https://w3c.github.io/webrtc-stats/#dom-rtcoutboundrtpstreamstats-totalencodedbytestarget
  529. uint64_t total_encoded_bytes_target = 0;
  530. uint64_t total_packet_send_delay_ms = 0;
  531. bool has_entered_low_resolution = false;
  532. absl::optional<uint64_t> qp_sum;
  533. webrtc::VideoContentType content_type = webrtc::VideoContentType::UNSPECIFIED;
  534. uint32_t frames_sent = 0;
  535. // https://w3c.github.io/webrtc-stats/#dom-rtcvideosenderstats-hugeframessent
  536. uint32_t huge_frames_sent = 0;
  537. uint32_t aggregated_huge_frames_sent = 0;
  538. absl::optional<std::string> rid;
  539. };
  540. struct VideoReceiverInfo : public MediaReceiverInfo {
  541. VideoReceiverInfo();
  542. ~VideoReceiverInfo();
  543. std::vector<SsrcGroup> ssrc_groups;
  544. std::string decoder_implementation_name;
  545. int packets_concealed = 0;
  546. int firs_sent = 0;
  547. int plis_sent = 0;
  548. int nacks_sent = 0;
  549. int frame_width = 0;
  550. int frame_height = 0;
  551. int framerate_rcvd = 0;
  552. int framerate_decoded = 0;
  553. int framerate_output = 0;
  554. // Framerate as sent to the renderer.
  555. int framerate_render_input = 0;
  556. // Framerate that the renderer reports.
  557. int framerate_render_output = 0;
  558. uint32_t frames_received = 0;
  559. uint32_t frames_dropped = 0;
  560. uint32_t frames_decoded = 0;
  561. uint32_t key_frames_decoded = 0;
  562. uint32_t frames_rendered = 0;
  563. absl::optional<uint64_t> qp_sum;
  564. // https://w3c.github.io/webrtc-stats/#dom-rtcinboundrtpstreamstats-totaldecodetime
  565. uint64_t total_decode_time_ms = 0;
  566. double total_inter_frame_delay = 0;
  567. double total_squared_inter_frame_delay = 0;
  568. int64_t interframe_delay_max_ms = -1;
  569. uint32_t freeze_count = 0;
  570. uint32_t pause_count = 0;
  571. uint32_t total_freezes_duration_ms = 0;
  572. uint32_t total_pauses_duration_ms = 0;
  573. uint32_t total_frames_duration_ms = 0;
  574. double sum_squared_frame_durations = 0.0;
  575. webrtc::VideoContentType content_type = webrtc::VideoContentType::UNSPECIFIED;
  576. // All stats below are gathered per-VideoReceiver, but some will be correlated
  577. // across MediaStreamTracks. NOTE(hta): when sinking stats into per-SSRC
  578. // structures, reflect this in the new layout.
  579. // Current frame decode latency.
  580. int decode_ms = 0;
  581. // Maximum observed frame decode latency.
  582. int max_decode_ms = 0;
  583. // Jitter (network-related) latency.
  584. int jitter_buffer_ms = 0;
  585. // Jitter (network-related) latency (cumulative).
  586. // https://w3c.github.io/webrtc-stats/#dom-rtcvideoreceiverstats-jitterbufferdelay
  587. double jitter_buffer_delay_seconds = 0;
  588. // Number of observations for cumulative jitter latency.
  589. // https://w3c.github.io/webrtc-stats/#dom-rtcvideoreceiverstats-jitterbufferemittedcount
  590. uint64_t jitter_buffer_emitted_count = 0;
  591. // Requested minimum playout latency.
  592. int min_playout_delay_ms = 0;
  593. // Requested latency to account for rendering delay.
  594. int render_delay_ms = 0;
  595. // Target overall delay: network+decode+render, accounting for
  596. // min_playout_delay_ms.
  597. int target_delay_ms = 0;
  598. // Current overall delay, possibly ramping towards target_delay_ms.
  599. int current_delay_ms = 0;
  600. // Estimated capture start time in NTP time in ms.
  601. int64_t capture_start_ntp_time_ms = -1;
  602. // First frame received to first frame decoded latency.
  603. int64_t first_frame_received_to_decoded_ms = -1;
  604. // Timing frame info: all important timestamps for a full lifetime of a
  605. // single 'timing frame'.
  606. absl::optional<webrtc::TimingFrameInfo> timing_frame_info;
  607. };
  608. struct DataSenderInfo : public MediaSenderInfo {
  609. uint32_t ssrc = 0;
  610. };
  611. struct DataReceiverInfo : public MediaReceiverInfo {
  612. uint32_t ssrc = 0;
  613. };
  614. struct BandwidthEstimationInfo {
  615. int available_send_bandwidth = 0;
  616. int available_recv_bandwidth = 0;
  617. int target_enc_bitrate = 0;
  618. int actual_enc_bitrate = 0;
  619. int retransmit_bitrate = 0;
  620. int transmit_bitrate = 0;
  621. int64_t bucket_delay = 0;
  622. };
  623. // Maps from payload type to |RtpCodecParameters|.
  624. typedef std::map<int, webrtc::RtpCodecParameters> RtpCodecParametersMap;
  625. struct VoiceMediaInfo {
  626. VoiceMediaInfo();
  627. ~VoiceMediaInfo();
  628. void Clear() {
  629. senders.clear();
  630. receivers.clear();
  631. send_codecs.clear();
  632. receive_codecs.clear();
  633. }
  634. std::vector<VoiceSenderInfo> senders;
  635. std::vector<VoiceReceiverInfo> receivers;
  636. RtpCodecParametersMap send_codecs;
  637. RtpCodecParametersMap receive_codecs;
  638. int32_t device_underrun_count = 0;
  639. };
  640. struct VideoMediaInfo {
  641. VideoMediaInfo();
  642. ~VideoMediaInfo();
  643. void Clear() {
  644. senders.clear();
  645. aggregated_senders.clear();
  646. receivers.clear();
  647. send_codecs.clear();
  648. receive_codecs.clear();
  649. }
  650. // Each sender info represents one "outbound-rtp" stream.In non - simulcast,
  651. // this means one info per RtpSender but if simulcast is used this means
  652. // one info per simulcast layer.
  653. std::vector<VideoSenderInfo> senders;
  654. // Used for legacy getStats() API's "ssrc" stats and modern getStats() API's
  655. // "track" stats. If simulcast is used, instead of having one sender info per
  656. // simulcast layer, the metrics of all layers of an RtpSender are aggregated
  657. // into a single sender info per RtpSender.
  658. std::vector<VideoSenderInfo> aggregated_senders;
  659. std::vector<VideoReceiverInfo> receivers;
  660. RtpCodecParametersMap send_codecs;
  661. RtpCodecParametersMap receive_codecs;
  662. };
  663. struct DataMediaInfo {
  664. DataMediaInfo();
  665. ~DataMediaInfo();
  666. void Clear() {
  667. senders.clear();
  668. receivers.clear();
  669. }
  670. std::vector<DataSenderInfo> senders;
  671. std::vector<DataReceiverInfo> receivers;
  672. };
  673. struct RtcpParameters {
  674. bool reduced_size = false;
  675. bool remote_estimate = false;
  676. };
  677. template <class Codec>
  678. struct RtpParameters {
  679. virtual ~RtpParameters() = default;
  680. std::vector<Codec> codecs;
  681. std::vector<webrtc::RtpExtension> extensions;
  682. // For a send stream this is true if we've neogtiated a send direction,
  683. // for a receive stream this is true if we've negotiated a receive direction.
  684. bool is_stream_active = true;
  685. // TODO(pthatcher): Add streams.
  686. RtcpParameters rtcp;
  687. std::string ToString() const {
  688. rtc::StringBuilder ost;
  689. ost << "{";
  690. const char* separator = "";
  691. for (const auto& entry : ToStringMap()) {
  692. ost << separator << entry.first << ": " << entry.second;
  693. separator = ", ";
  694. }
  695. ost << "}";
  696. return ost.Release();
  697. }
  698. protected:
  699. virtual std::map<std::string, std::string> ToStringMap() const {
  700. return {{"codecs", VectorToString(codecs)},
  701. {"extensions", VectorToString(extensions)}};
  702. }
  703. };
  704. // TODO(deadbeef): Rename to RtpSenderParameters, since they're intended to
  705. // encapsulate all the parameters needed for an RtpSender.
  706. template <class Codec>
  707. struct RtpSendParameters : RtpParameters<Codec> {
  708. int max_bandwidth_bps = -1;
  709. // This is the value to be sent in the MID RTP header extension (if the header
  710. // extension in included in the list of extensions).
  711. std::string mid;
  712. bool extmap_allow_mixed = false;
  713. protected:
  714. std::map<std::string, std::string> ToStringMap() const override {
  715. auto params = RtpParameters<Codec>::ToStringMap();
  716. params["max_bandwidth_bps"] = rtc::ToString(max_bandwidth_bps);
  717. params["mid"] = (mid.empty() ? "<not set>" : mid);
  718. params["extmap-allow-mixed"] = extmap_allow_mixed ? "true" : "false";
  719. return params;
  720. }
  721. };
  722. struct AudioSendParameters : RtpSendParameters<AudioCodec> {
  723. AudioSendParameters();
  724. ~AudioSendParameters() override;
  725. AudioOptions options;
  726. protected:
  727. std::map<std::string, std::string> ToStringMap() const override;
  728. };
  729. struct AudioRecvParameters : RtpParameters<AudioCodec> {};
  730. class VoiceMediaChannel : public MediaChannel, public Delayable {
  731. public:
  732. VoiceMediaChannel() {}
  733. explicit VoiceMediaChannel(const MediaConfig& config)
  734. : MediaChannel(config) {}
  735. ~VoiceMediaChannel() override {}
  736. cricket::MediaType media_type() const override;
  737. virtual bool SetSendParameters(const AudioSendParameters& params) = 0;
  738. virtual bool SetRecvParameters(const AudioRecvParameters& params) = 0;
  739. // Get the receive parameters for the incoming stream identified by |ssrc|.
  740. virtual webrtc::RtpParameters GetRtpReceiveParameters(
  741. uint32_t ssrc) const = 0;
  742. // Retrieve the receive parameters for the default receive
  743. // stream, which is used when SSRCs are not signaled.
  744. virtual webrtc::RtpParameters GetDefaultRtpReceiveParameters() const = 0;
  745. // Starts or stops playout of received audio.
  746. virtual void SetPlayout(bool playout) = 0;
  747. // Starts or stops sending (and potentially capture) of local audio.
  748. virtual void SetSend(bool send) = 0;
  749. // Configure stream for sending.
  750. virtual bool SetAudioSend(uint32_t ssrc,
  751. bool enable,
  752. const AudioOptions* options,
  753. AudioSource* source) = 0;
  754. // Set speaker output volume of the specified ssrc.
  755. virtual bool SetOutputVolume(uint32_t ssrc, double volume) = 0;
  756. // Set speaker output volume for future unsignaled streams.
  757. virtual bool SetDefaultOutputVolume(double volume) = 0;
  758. // Returns if the telephone-event has been negotiated.
  759. virtual bool CanInsertDtmf() = 0;
  760. // Send a DTMF |event|. The DTMF out-of-band signal will be used.
  761. // The |ssrc| should be either 0 or a valid send stream ssrc.
  762. // The valid value for the |event| are 0 to 15 which corresponding to
  763. // DTMF event 0-9, *, #, A-D.
  764. virtual bool InsertDtmf(uint32_t ssrc, int event, int duration) = 0;
  765. // Gets quality stats for the channel.
  766. virtual bool GetStats(VoiceMediaInfo* info,
  767. bool get_and_clear_legacy_stats) = 0;
  768. virtual void SetRawAudioSink(
  769. uint32_t ssrc,
  770. std::unique_ptr<webrtc::AudioSinkInterface> sink) = 0;
  771. virtual void SetDefaultRawAudioSink(
  772. std::unique_ptr<webrtc::AudioSinkInterface> sink) = 0;
  773. virtual std::vector<webrtc::RtpSource> GetSources(uint32_t ssrc) const = 0;
  774. };
  775. // TODO(deadbeef): Rename to VideoSenderParameters, since they're intended to
  776. // encapsulate all the parameters needed for a video RtpSender.
  777. struct VideoSendParameters : RtpSendParameters<VideoCodec> {
  778. VideoSendParameters();
  779. ~VideoSendParameters() override;
  780. // Use conference mode? This flag comes from the remote
  781. // description's SDP line 'a=x-google-flag:conference', copied over
  782. // by VideoChannel::SetRemoteContent_w, and ultimately used by
  783. // conference mode screencast logic in
  784. // WebRtcVideoChannel::WebRtcVideoSendStream::CreateVideoEncoderConfig.
  785. // The special screencast behaviour is disabled by default.
  786. bool conference_mode = false;
  787. protected:
  788. std::map<std::string, std::string> ToStringMap() const override;
  789. };
  790. // TODO(deadbeef): Rename to VideoReceiverParameters, since they're intended to
  791. // encapsulate all the parameters needed for a video RtpReceiver.
  792. struct VideoRecvParameters : RtpParameters<VideoCodec> {};
  793. class VideoMediaChannel : public MediaChannel, public Delayable {
  794. public:
  795. VideoMediaChannel() {}
  796. explicit VideoMediaChannel(const MediaConfig& config)
  797. : MediaChannel(config) {}
  798. ~VideoMediaChannel() override {}
  799. cricket::MediaType media_type() const override;
  800. virtual bool SetSendParameters(const VideoSendParameters& params) = 0;
  801. virtual bool SetRecvParameters(const VideoRecvParameters& params) = 0;
  802. // Get the receive parameters for the incoming stream identified by |ssrc|.
  803. virtual webrtc::RtpParameters GetRtpReceiveParameters(
  804. uint32_t ssrc) const = 0;
  805. // Retrieve the receive parameters for the default receive
  806. // stream, which is used when SSRCs are not signaled.
  807. virtual webrtc::RtpParameters GetDefaultRtpReceiveParameters() const = 0;
  808. // Gets the currently set codecs/payload types to be used for outgoing media.
  809. virtual bool GetSendCodec(VideoCodec* send_codec) = 0;
  810. // Starts or stops transmission (and potentially capture) of local video.
  811. virtual bool SetSend(bool send) = 0;
  812. // Configure stream for sending and register a source.
  813. // The |ssrc| must correspond to a registered send stream.
  814. virtual bool SetVideoSend(
  815. uint32_t ssrc,
  816. const VideoOptions* options,
  817. rtc::VideoSourceInterface<webrtc::VideoFrame>* source) = 0;
  818. // Sets the sink object to be used for the specified stream.
  819. virtual bool SetSink(uint32_t ssrc,
  820. rtc::VideoSinkInterface<webrtc::VideoFrame>* sink) = 0;
  821. // The sink is used for the 'default' stream.
  822. virtual void SetDefaultSink(
  823. rtc::VideoSinkInterface<webrtc::VideoFrame>* sink) = 0;
  824. // This fills the "bitrate parts" (rtx, video bitrate) of the
  825. // BandwidthEstimationInfo, since that part that isn't possible to get
  826. // through webrtc::Call::GetStats, as they are statistics of the send
  827. // streams.
  828. // TODO(holmer): We should change this so that either BWE graphs doesn't
  829. // need access to bitrates of the streams, or change the (RTC)StatsCollector
  830. // so that it's getting the send stream stats separately by calling
  831. // GetStats(), and merges with BandwidthEstimationInfo by itself.
  832. virtual void FillBitrateInfo(BandwidthEstimationInfo* bwe_info) = 0;
  833. // Gets quality stats for the channel.
  834. virtual bool GetStats(VideoMediaInfo* info) = 0;
  835. // Set recordable encoded frame callback for |ssrc|
  836. virtual void SetRecordableEncodedFrameCallback(
  837. uint32_t ssrc,
  838. std::function<void(const webrtc::RecordableEncodedFrame&)> callback) = 0;
  839. // Clear recordable encoded frame callback for |ssrc|
  840. virtual void ClearRecordableEncodedFrameCallback(uint32_t ssrc) = 0;
  841. // Cause generation of a keyframe for |ssrc|
  842. virtual void GenerateKeyFrame(uint32_t ssrc) = 0;
  843. virtual std::vector<webrtc::RtpSource> GetSources(uint32_t ssrc) const = 0;
  844. };
  845. enum DataMessageType {
  846. // Chrome-Internal use only. See SctpDataMediaChannel for the actual PPID
  847. // values.
  848. DMT_NONE = 0,
  849. DMT_CONTROL = 1,
  850. DMT_BINARY = 2,
  851. DMT_TEXT = 3,
  852. };
  853. // Info about data received in DataMediaChannel. For use in
  854. // DataMediaChannel::SignalDataReceived and in all of the signals that
  855. // signal fires, on up the chain.
  856. struct ReceiveDataParams {
  857. // The in-packet stream indentifier.
  858. // RTP data channels use SSRCs, SCTP data channels use SIDs.
  859. union {
  860. uint32_t ssrc;
  861. int sid = 0;
  862. };
  863. // The type of message (binary, text, or control).
  864. DataMessageType type = DMT_TEXT;
  865. // A per-stream value incremented per packet in the stream.
  866. int seq_num = 0;
  867. // A per-stream value monotonically increasing with time.
  868. int timestamp = 0;
  869. };
  870. struct SendDataParams {
  871. // The in-packet stream indentifier.
  872. // RTP data channels use SSRCs, SCTP data channels use SIDs.
  873. union {
  874. uint32_t ssrc;
  875. int sid = 0;
  876. };
  877. // The type of message (binary, text, or control).
  878. DataMessageType type = DMT_TEXT;
  879. // TODO(pthatcher): Make |ordered| and |reliable| true by default?
  880. // For SCTP, whether to send messages flagged as ordered or not.
  881. // If false, messages can be received out of order.
  882. bool ordered = false;
  883. // For SCTP, whether the messages are sent reliably or not.
  884. // If false, messages may be lost.
  885. bool reliable = false;
  886. // For SCTP, if reliable == false, provide partial reliability by
  887. // resending up to this many times. Either count or millis
  888. // is supported, not both at the same time.
  889. int max_rtx_count = 0;
  890. // For SCTP, if reliable == false, provide partial reliability by
  891. // resending for up to this many milliseconds. Either count or millis
  892. // is supported, not both at the same time.
  893. int max_rtx_ms = 0;
  894. };
  895. enum SendDataResult { SDR_SUCCESS, SDR_ERROR, SDR_BLOCK };
  896. struct DataSendParameters : RtpSendParameters<DataCodec> {};
  897. struct DataRecvParameters : RtpParameters<DataCodec> {};
  898. class DataMediaChannel : public MediaChannel {
  899. public:
  900. DataMediaChannel();
  901. explicit DataMediaChannel(const MediaConfig& config);
  902. ~DataMediaChannel() override;
  903. cricket::MediaType media_type() const override;
  904. virtual bool SetSendParameters(const DataSendParameters& params) = 0;
  905. virtual bool SetRecvParameters(const DataRecvParameters& params) = 0;
  906. // RtpParameter methods are not supported for Data channel.
  907. webrtc::RtpParameters GetRtpSendParameters(uint32_t ssrc) const override;
  908. webrtc::RTCError SetRtpSendParameters(
  909. uint32_t ssrc,
  910. const webrtc::RtpParameters& parameters) override;
  911. // TODO(pthatcher): Implement this.
  912. virtual bool GetStats(DataMediaInfo* info);
  913. virtual bool SetSend(bool send) = 0;
  914. virtual bool SetReceive(bool receive) = 0;
  915. void OnNetworkRouteChanged(const std::string& transport_name,
  916. const rtc::NetworkRoute& network_route) override {}
  917. virtual bool SendData(const SendDataParams& params,
  918. const rtc::CopyOnWriteBuffer& payload,
  919. SendDataResult* result = NULL) = 0;
  920. // Signals when data is received (params, data, len)
  921. sigslot::signal3<const ReceiveDataParams&, const char*, size_t>
  922. SignalDataReceived;
  923. // Signal when the media channel is ready to send the stream. Arguments are:
  924. // writable(bool)
  925. sigslot::signal1<bool> SignalReadyToSend;
  926. };
  927. } // namespace cricket
  928. #endif // MEDIA_BASE_MEDIA_CHANNEL_H_