neteq.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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 packet_loss_rate; // Loss rate (network + late) in Q14.
  33. uint16_t expand_rate; // Fraction (of original stream) of synthesized
  34. // audio inserted through expansion (in Q14).
  35. uint16_t speech_expand_rate; // Fraction (of original stream) of synthesized
  36. // speech inserted through expansion (in Q14).
  37. uint16_t preemptive_rate; // Fraction of data inserted through pre-emptive
  38. // expansion (in Q14).
  39. uint16_t accelerate_rate; // Fraction of data removed through acceleration
  40. // (in Q14).
  41. uint16_t secondary_decoded_rate; // Fraction of data coming from FEC/RED
  42. // decoding (in Q14).
  43. uint16_t secondary_discarded_rate; // Fraction of discarded FEC/RED data (in
  44. // Q14).
  45. size_t added_zero_samples; // Number of zero samples added in "off" mode.
  46. // Statistics for packet waiting times, i.e., the time between a packet
  47. // arrives until it is decoded.
  48. int mean_waiting_time_ms;
  49. int median_waiting_time_ms;
  50. int min_waiting_time_ms;
  51. int max_waiting_time_ms;
  52. };
  53. // NetEq statistics that persist over the lifetime of the class.
  54. // These metrics are never reset.
  55. struct NetEqLifetimeStatistics {
  56. // Stats below correspond to similarly-named fields in the WebRTC stats spec.
  57. // https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats
  58. uint64_t total_samples_received = 0;
  59. uint64_t concealed_samples = 0;
  60. uint64_t concealment_events = 0;
  61. uint64_t jitter_buffer_delay_ms = 0;
  62. uint64_t jitter_buffer_emitted_count = 0;
  63. uint64_t jitter_buffer_target_delay_ms = 0;
  64. uint64_t inserted_samples_for_deceleration = 0;
  65. uint64_t removed_samples_for_acceleration = 0;
  66. uint64_t silent_concealed_samples = 0;
  67. uint64_t fec_packets_received = 0;
  68. uint64_t fec_packets_discarded = 0;
  69. // Below stats are not part of the spec.
  70. uint64_t delayed_packet_outage_samples = 0;
  71. // This is sum of relative packet arrival delays of received packets so far.
  72. // Since end-to-end delay of a packet is difficult to measure and is not
  73. // necessarily useful for measuring jitter buffer performance, we report a
  74. // relative packet arrival delay. The relative packet arrival delay of a
  75. // packet is defined as the arrival delay compared to the first packet
  76. // received, given that it had zero delay. To avoid clock drift, the "first"
  77. // packet can be made dynamic.
  78. uint64_t relative_packet_arrival_delay_ms = 0;
  79. uint64_t jitter_buffer_packets_received = 0;
  80. // An interruption is a loss-concealment event lasting at least 150 ms. The
  81. // two stats below count the number os such events and the total duration of
  82. // these events.
  83. int32_t interruption_count = 0;
  84. int32_t total_interruption_duration_ms = 0;
  85. };
  86. // Metrics that describe the operations performed in NetEq, and the internal
  87. // state.
  88. struct NetEqOperationsAndState {
  89. // These sample counters are cumulative, and don't reset. As a reference, the
  90. // total number of output samples can be found in
  91. // NetEqLifetimeStatistics::total_samples_received.
  92. uint64_t preemptive_samples = 0;
  93. uint64_t accelerate_samples = 0;
  94. // Count of the number of buffer flushes.
  95. uint64_t packet_buffer_flushes = 0;
  96. // The number of primary packets that were discarded.
  97. uint64_t discarded_primary_packets = 0;
  98. // The statistics below are not cumulative.
  99. // The waiting time of the last decoded packet.
  100. uint64_t last_waiting_time_ms = 0;
  101. // The sum of the packet and jitter buffer size in ms.
  102. uint64_t current_buffer_size_ms = 0;
  103. // The current frame size in ms.
  104. uint64_t current_frame_size_ms = 0;
  105. // Flag to indicate that the next packet is available.
  106. bool next_packet_available = false;
  107. };
  108. // This is the interface class for NetEq.
  109. class NetEq {
  110. public:
  111. struct Config {
  112. Config();
  113. Config(const Config&);
  114. Config(Config&&);
  115. ~Config();
  116. Config& operator=(const Config&);
  117. Config& operator=(Config&&);
  118. std::string ToString() const;
  119. int sample_rate_hz = 16000; // Initial value. Will change with input data.
  120. bool enable_post_decode_vad = false;
  121. size_t max_packets_in_buffer = 200;
  122. int max_delay_ms = 0;
  123. int min_delay_ms = 0;
  124. bool enable_fast_accelerate = false;
  125. bool enable_muted_state = false;
  126. bool enable_rtx_handling = false;
  127. absl::optional<AudioCodecPairId> codec_pair_id;
  128. bool for_test_no_time_stretching = false; // Use only for testing.
  129. // Adds extra delay to the output of NetEq, without affecting jitter or
  130. // loss behavior. This is mainly for testing. Value must be a non-negative
  131. // multiple of 10 ms.
  132. int extra_output_delay_ms = 0;
  133. };
  134. enum ReturnCodes { kOK = 0, kFail = -1 };
  135. enum class Operation {
  136. kNormal,
  137. kMerge,
  138. kExpand,
  139. kAccelerate,
  140. kFastAccelerate,
  141. kPreemptiveExpand,
  142. kRfc3389Cng,
  143. kRfc3389CngNoPacket,
  144. kCodecInternalCng,
  145. kDtmf,
  146. kUndefined,
  147. };
  148. enum class Mode {
  149. kNormal,
  150. kExpand,
  151. kMerge,
  152. kAccelerateSuccess,
  153. kAccelerateLowEnergy,
  154. kAccelerateFail,
  155. kPreemptiveExpandSuccess,
  156. kPreemptiveExpandLowEnergy,
  157. kPreemptiveExpandFail,
  158. kRfc3389Cng,
  159. kCodecInternalCng,
  160. kCodecPlc,
  161. kDtmf,
  162. kError,
  163. kUndefined,
  164. };
  165. // Return type for GetDecoderFormat.
  166. struct DecoderFormat {
  167. int sample_rate_hz;
  168. int num_channels;
  169. SdpAudioFormat sdp_format;
  170. };
  171. // Creates a new NetEq object, with parameters set in |config|. The |config|
  172. // object will only have to be valid for the duration of the call to this
  173. // method.
  174. static NetEq* Create(
  175. const NetEq::Config& config,
  176. Clock* clock,
  177. const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory);
  178. virtual ~NetEq() {}
  179. // Inserts a new packet into NetEq.
  180. // Returns 0 on success, -1 on failure.
  181. virtual int InsertPacket(const RTPHeader& rtp_header,
  182. rtc::ArrayView<const uint8_t> payload) = 0;
  183. // Lets NetEq know that a packet arrived with an empty payload. This typically
  184. // happens when empty packets are used for probing the network channel, and
  185. // these packets use RTP sequence numbers from the same series as the actual
  186. // audio packets.
  187. virtual void InsertEmptyPacket(const RTPHeader& rtp_header) = 0;
  188. // Instructs NetEq to deliver 10 ms of audio data. The data is written to
  189. // |audio_frame|. All data in |audio_frame| is wiped; |data_|, |speech_type_|,
  190. // |num_channels_|, |sample_rate_hz_|, |samples_per_channel_|, and
  191. // |vad_activity_| are updated upon success. If an error is returned, some
  192. // fields may not have been updated, or may contain inconsistent values.
  193. // If muted state is enabled (through Config::enable_muted_state), |muted|
  194. // may be set to true after a prolonged expand period. When this happens, the
  195. // |data_| in |audio_frame| is not written, but should be interpreted as being
  196. // all zeros. For testing purposes, an override can be supplied in the
  197. // |action_override| argument, which will cause NetEq to take this action
  198. // next, instead of the action it would normally choose.
  199. // Returns kOK on success, or kFail in case of an error.
  200. virtual int GetAudio(
  201. AudioFrame* audio_frame,
  202. bool* muted,
  203. absl::optional<Operation> action_override = absl::nullopt) = 0;
  204. // Replaces the current set of decoders with the given one.
  205. virtual void SetCodecs(const std::map<int, SdpAudioFormat>& codecs) = 0;
  206. // Associates |rtp_payload_type| with the given codec, which NetEq will
  207. // instantiate when it needs it. Returns true iff successful.
  208. virtual bool RegisterPayloadType(int rtp_payload_type,
  209. const SdpAudioFormat& audio_format) = 0;
  210. // Removes |rtp_payload_type| from the codec database. Returns 0 on success,
  211. // -1 on failure. Removing a payload type that is not registered is ok and
  212. // will not result in an error.
  213. virtual int RemovePayloadType(uint8_t rtp_payload_type) = 0;
  214. // Removes all payload types from the codec database.
  215. virtual void RemoveAllPayloadTypes() = 0;
  216. // Sets a minimum delay in millisecond for packet buffer. The minimum is
  217. // maintained unless a higher latency is dictated by channel condition.
  218. // Returns true if the minimum is successfully applied, otherwise false is
  219. // returned.
  220. virtual bool SetMinimumDelay(int delay_ms) = 0;
  221. // Sets a maximum delay in milliseconds for packet buffer. The latency will
  222. // not exceed the given value, even required delay (given the channel
  223. // conditions) is higher. Calling this method has the same effect as setting
  224. // the |max_delay_ms| value in the NetEq::Config struct.
  225. virtual bool SetMaximumDelay(int delay_ms) = 0;
  226. // Sets a base minimum delay in milliseconds for packet buffer. The minimum
  227. // delay which is set via |SetMinimumDelay| can't be lower than base minimum
  228. // delay. Calling this method is similar to setting the |min_delay_ms| value
  229. // in the NetEq::Config struct. Returns true if the base minimum is
  230. // successfully applied, otherwise false is returned.
  231. virtual bool SetBaseMinimumDelayMs(int delay_ms) = 0;
  232. // Returns current value of base minimum delay in milliseconds.
  233. virtual int GetBaseMinimumDelayMs() const = 0;
  234. // Returns the current target delay in ms. This includes any extra delay
  235. // requested through SetMinimumDelay.
  236. virtual int TargetDelayMs() const = 0;
  237. // Returns the current total delay (packet buffer and sync buffer) in ms,
  238. // with smoothing applied to even out short-time fluctuations due to jitter.
  239. // The packet buffer part of the delay is not updated during DTX/CNG periods.
  240. virtual int FilteredCurrentDelayMs() const = 0;
  241. // Writes the current network statistics to |stats|. The statistics are reset
  242. // after the call.
  243. virtual int NetworkStatistics(NetEqNetworkStatistics* stats) = 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_