neteq.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /*
  2. * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef API_NETEQ_NETEQ_H_
  11. #define API_NETEQ_NETEQ_H_
  12. #include <stddef.h> // Provide access to size_t.
  13. #include <map>
  14. #include <string>
  15. #include <vector>
  16. #include "absl/types/optional.h"
  17. #include "api/audio_codecs/audio_codec_pair_id.h"
  18. #include "api/audio_codecs/audio_decoder.h"
  19. #include "api/audio_codecs/audio_format.h"
  20. #include "api/rtp_headers.h"
  21. #include "api/scoped_refptr.h"
  22. namespace webrtc {
  23. // Forward declarations.
  24. class AudioFrame;
  25. class AudioDecoderFactory;
  26. class Clock;
  27. struct NetEqNetworkStatistics {
  28. uint16_t current_buffer_size_ms; // Current jitter buffer size in ms.
  29. uint16_t preferred_buffer_size_ms; // Target buffer size in ms.
  30. uint16_t jitter_peaks_found; // 1 if adding extra delay due to peaky
  31. // jitter; 0 otherwise.
  32. uint16_t expand_rate; // Fraction (of original stream) of synthesized
  33. // audio inserted through expansion (in Q14).
  34. uint16_t speech_expand_rate; // Fraction (of original stream) of synthesized
  35. // speech inserted through expansion (in Q14).
  36. uint16_t preemptive_rate; // Fraction of data inserted through pre-emptive
  37. // expansion (in Q14).
  38. uint16_t accelerate_rate; // Fraction of data removed through acceleration
  39. // (in Q14).
  40. uint16_t secondary_decoded_rate; // Fraction of data coming from FEC/RED
  41. // decoding (in Q14).
  42. uint16_t secondary_discarded_rate; // Fraction of discarded FEC/RED data (in
  43. // Q14).
  44. // Statistics for packet waiting times, i.e., the time between a packet
  45. // arrives until it is decoded.
  46. int mean_waiting_time_ms;
  47. int median_waiting_time_ms;
  48. int min_waiting_time_ms;
  49. int max_waiting_time_ms;
  50. };
  51. // NetEq statistics that persist over the lifetime of the class.
  52. // These metrics are never reset.
  53. struct NetEqLifetimeStatistics {
  54. // Stats below correspond to similarly-named fields in the WebRTC stats spec.
  55. // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats
  56. uint64_t total_samples_received = 0;
  57. uint64_t concealed_samples = 0;
  58. uint64_t concealment_events = 0;
  59. uint64_t jitter_buffer_delay_ms = 0;
  60. uint64_t jitter_buffer_emitted_count = 0;
  61. uint64_t jitter_buffer_target_delay_ms = 0;
  62. uint64_t inserted_samples_for_deceleration = 0;
  63. uint64_t removed_samples_for_acceleration = 0;
  64. uint64_t silent_concealed_samples = 0;
  65. uint64_t fec_packets_received = 0;
  66. uint64_t fec_packets_discarded = 0;
  67. // Below stats are not part of the spec.
  68. uint64_t delayed_packet_outage_samples = 0;
  69. // This is sum of relative packet arrival delays of received packets so far.
  70. // Since end-to-end delay of a packet is difficult to measure and is not
  71. // necessarily useful for measuring jitter buffer performance, we report a
  72. // relative packet arrival delay. The relative packet arrival delay of a
  73. // packet is defined as the arrival delay compared to the first packet
  74. // received, given that it had zero delay. To avoid clock drift, the "first"
  75. // packet can be made dynamic.
  76. uint64_t relative_packet_arrival_delay_ms = 0;
  77. uint64_t jitter_buffer_packets_received = 0;
  78. // An interruption is a loss-concealment event lasting at least 150 ms. The
  79. // two stats below count the number os such events and the total duration of
  80. // these events.
  81. int32_t interruption_count = 0;
  82. int32_t total_interruption_duration_ms = 0;
  83. };
  84. // Metrics that describe the operations performed in NetEq, and the internal
  85. // state.
  86. struct NetEqOperationsAndState {
  87. // These sample counters are cumulative, and don't reset. As a reference, the
  88. // total number of output samples can be found in
  89. // NetEqLifetimeStatistics::total_samples_received.
  90. uint64_t preemptive_samples = 0;
  91. uint64_t accelerate_samples = 0;
  92. // Count of the number of buffer flushes.
  93. uint64_t packet_buffer_flushes = 0;
  94. // The number of primary packets that were discarded.
  95. uint64_t discarded_primary_packets = 0;
  96. // The statistics below are not cumulative.
  97. // The waiting time of the last decoded packet.
  98. uint64_t last_waiting_time_ms = 0;
  99. // The sum of the packet and jitter buffer size in ms.
  100. uint64_t current_buffer_size_ms = 0;
  101. // The current frame size in ms.
  102. uint64_t current_frame_size_ms = 0;
  103. // Flag to indicate that the next packet is available.
  104. bool next_packet_available = false;
  105. };
  106. // This is the interface class for NetEq.
  107. class NetEq {
  108. public:
  109. struct Config {
  110. Config();
  111. Config(const Config&);
  112. Config(Config&&);
  113. ~Config();
  114. Config& operator=(const Config&);
  115. Config& operator=(Config&&);
  116. std::string ToString() const;
  117. int sample_rate_hz = 16000; // Initial value. Will change with input data.
  118. bool enable_post_decode_vad = false;
  119. size_t max_packets_in_buffer = 200;
  120. int max_delay_ms = 0;
  121. int min_delay_ms = 0;
  122. bool enable_fast_accelerate = false;
  123. bool enable_muted_state = false;
  124. bool enable_rtx_handling = false;
  125. absl::optional<AudioCodecPairId> codec_pair_id;
  126. bool for_test_no_time_stretching = false; // Use only for testing.
  127. // Adds extra delay to the output of NetEq, without affecting jitter or
  128. // loss behavior. This is mainly for testing. Value must be a non-negative
  129. // multiple of 10 ms.
  130. int extra_output_delay_ms = 0;
  131. };
  132. enum ReturnCodes { kOK = 0, kFail = -1 };
  133. enum class Operation {
  134. kNormal,
  135. kMerge,
  136. kExpand,
  137. kAccelerate,
  138. kFastAccelerate,
  139. kPreemptiveExpand,
  140. kRfc3389Cng,
  141. kRfc3389CngNoPacket,
  142. kCodecInternalCng,
  143. kDtmf,
  144. kUndefined,
  145. };
  146. enum class Mode {
  147. kNormal,
  148. kExpand,
  149. kMerge,
  150. kAccelerateSuccess,
  151. kAccelerateLowEnergy,
  152. kAccelerateFail,
  153. kPreemptiveExpandSuccess,
  154. kPreemptiveExpandLowEnergy,
  155. kPreemptiveExpandFail,
  156. kRfc3389Cng,
  157. kCodecInternalCng,
  158. kCodecPlc,
  159. kDtmf,
  160. kError,
  161. kUndefined,
  162. };
  163. // Return type for GetDecoderFormat.
  164. struct DecoderFormat {
  165. int sample_rate_hz;
  166. int num_channels;
  167. SdpAudioFormat sdp_format;
  168. };
  169. // Creates a new NetEq object, with parameters set in |config|. The |config|
  170. // object will only have to be valid for the duration of the call to this
  171. // method.
  172. static NetEq* Create(
  173. const NetEq::Config& config,
  174. Clock* clock,
  175. const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory);
  176. virtual ~NetEq() {}
  177. // Inserts a new packet into NetEq.
  178. // Returns 0 on success, -1 on failure.
  179. virtual int InsertPacket(const RTPHeader& rtp_header,
  180. rtc::ArrayView<const uint8_t> payload) = 0;
  181. // Lets NetEq know that a packet arrived with an empty payload. This typically
  182. // happens when empty packets are used for probing the network channel, and
  183. // these packets use RTP sequence numbers from the same series as the actual
  184. // audio packets.
  185. virtual void InsertEmptyPacket(const RTPHeader& rtp_header) = 0;
  186. // Instructs NetEq to deliver 10 ms of audio data. The data is written to
  187. // |audio_frame|. All data in |audio_frame| is wiped; |data_|, |speech_type_|,
  188. // |num_channels_|, |sample_rate_hz_|, |samples_per_channel_|, and
  189. // |vad_activity_| are updated upon success. If an error is returned, some
  190. // fields may not have been updated, or may contain inconsistent values.
  191. // If muted state is enabled (through Config::enable_muted_state), |muted|
  192. // may be set to true after a prolonged expand period. When this happens, the
  193. // |data_| in |audio_frame| is not written, but should be interpreted as being
  194. // all zeros. For testing purposes, an override can be supplied in the
  195. // |action_override| argument, which will cause NetEq to take this action
  196. // next, instead of the action it would normally choose.
  197. // Returns kOK on success, or kFail in case of an error.
  198. virtual int GetAudio(
  199. AudioFrame* audio_frame,
  200. bool* muted,
  201. absl::optional<Operation> action_override = absl::nullopt) = 0;
  202. // Replaces the current set of decoders with the given one.
  203. virtual void SetCodecs(const std::map<int, SdpAudioFormat>& codecs) = 0;
  204. // Associates |rtp_payload_type| with the given codec, which NetEq will
  205. // instantiate when it needs it. Returns true iff successful.
  206. virtual bool RegisterPayloadType(int rtp_payload_type,
  207. const SdpAudioFormat& audio_format) = 0;
  208. // Removes |rtp_payload_type| from the codec database. Returns 0 on success,
  209. // -1 on failure. Removing a payload type that is not registered is ok and
  210. // will not result in an error.
  211. virtual int RemovePayloadType(uint8_t rtp_payload_type) = 0;
  212. // Removes all payload types from the codec database.
  213. virtual void RemoveAllPayloadTypes() = 0;
  214. // Sets a minimum delay in millisecond for packet buffer. The minimum is
  215. // maintained unless a higher latency is dictated by channel condition.
  216. // Returns true if the minimum is successfully applied, otherwise false is
  217. // returned.
  218. virtual bool SetMinimumDelay(int delay_ms) = 0;
  219. // Sets a maximum delay in milliseconds for packet buffer. The latency will
  220. // not exceed the given value, even required delay (given the channel
  221. // conditions) is higher. Calling this method has the same effect as setting
  222. // the |max_delay_ms| value in the NetEq::Config struct.
  223. virtual bool SetMaximumDelay(int delay_ms) = 0;
  224. // Sets a base minimum delay in milliseconds for packet buffer. The minimum
  225. // delay which is set via |SetMinimumDelay| can't be lower than base minimum
  226. // delay. Calling this method is similar to setting the |min_delay_ms| value
  227. // in the NetEq::Config struct. Returns true if the base minimum is
  228. // successfully applied, otherwise false is returned.
  229. virtual bool SetBaseMinimumDelayMs(int delay_ms) = 0;
  230. // Returns current value of base minimum delay in milliseconds.
  231. virtual int GetBaseMinimumDelayMs() const = 0;
  232. // Returns the current target delay in ms. This includes any extra delay
  233. // requested through SetMinimumDelay.
  234. virtual int TargetDelayMs() const = 0;
  235. // Returns the current total delay (packet buffer and sync buffer) in ms,
  236. // with smoothing applied to even out short-time fluctuations due to jitter.
  237. // The packet buffer part of the delay is not updated during DTX/CNG periods.
  238. virtual int FilteredCurrentDelayMs() const = 0;
  239. // Writes the current network statistics to |stats|. The statistics are reset
  240. // after the call.
  241. virtual int NetworkStatistics(NetEqNetworkStatistics* stats) = 0;
  242. // Current values only, not resetting any state.
  243. virtual NetEqNetworkStatistics CurrentNetworkStatistics() const = 0;
  244. // Returns a copy of this class's lifetime statistics. These statistics are
  245. // never reset.
  246. virtual NetEqLifetimeStatistics GetLifetimeStatistics() const = 0;
  247. // Returns statistics about the performed operations and internal state. These
  248. // statistics are never reset.
  249. virtual NetEqOperationsAndState GetOperationsAndState() const = 0;
  250. // Enables post-decode VAD. When enabled, GetAudio() will return
  251. // kOutputVADPassive when the signal contains no speech.
  252. virtual void EnableVad() = 0;
  253. // Disables post-decode VAD.
  254. virtual void DisableVad() = 0;
  255. // Returns the RTP timestamp for the last sample delivered by GetAudio().
  256. // The return value will be empty if no valid timestamp is available.
  257. virtual absl::optional<uint32_t> GetPlayoutTimestamp() const = 0;
  258. // Returns the sample rate in Hz of the audio produced in the last GetAudio
  259. // call. If GetAudio has not been called yet, the configured sample rate
  260. // (Config::sample_rate_hz) is returned.
  261. virtual int last_output_sample_rate_hz() const = 0;
  262. // Returns the decoder info for the given payload type. Returns empty if no
  263. // such payload type was registered.
  264. virtual absl::optional<DecoderFormat> GetDecoderFormat(
  265. int payload_type) const = 0;
  266. // Flushes both the packet buffer and the sync buffer.
  267. virtual void FlushBuffers() = 0;
  268. // Enables NACK and sets the maximum size of the NACK list, which should be
  269. // positive and no larger than Nack::kNackListSizeLimit. If NACK is already
  270. // enabled then the maximum NACK list size is modified accordingly.
  271. virtual void EnableNack(size_t max_nack_list_size) = 0;
  272. virtual void DisableNack() = 0;
  273. // Returns a list of RTP sequence numbers corresponding to packets to be
  274. // retransmitted, given an estimate of the round-trip time in milliseconds.
  275. virtual std::vector<uint16_t> GetNackList(
  276. int64_t round_trip_time_ms) const = 0;
  277. // Returns a vector containing the timestamps of the packets that were decoded
  278. // in the last GetAudio call. If no packets were decoded in the last call, the
  279. // vector is empty.
  280. // Mainly intended for testing.
  281. virtual std::vector<uint32_t> LastDecodedTimestamps() const = 0;
  282. // Returns the length of the audio yet to play in the sync buffer.
  283. // Mainly intended for testing.
  284. virtual int SyncBufferSizeMs() const = 0;
  285. };
  286. } // namespace webrtc
  287. #endif // API_NETEQ_NETEQ_H_