• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #ifndef API_AUDIO_CODECS_AUDIO_ENCODER_H_
12 #define API_AUDIO_CODECS_AUDIO_ENCODER_H_
13 
14 #include <memory>
15 #include <string>
16 #include <utility>
17 #include <vector>
18 
19 #include "absl/types/optional.h"
20 #include "api/array_view.h"
21 #include "api/call/bitrate_allocation.h"
22 #include "api/units/time_delta.h"
23 #include "rtc_base/buffer.h"
24 #include "rtc_base/deprecation.h"
25 
26 namespace webrtc {
27 
28 class RtcEventLog;
29 
30 // Statistics related to Audio Network Adaptation.
31 struct ANAStats {
32   ANAStats();
33   ANAStats(const ANAStats&);
34   ~ANAStats();
35   // Number of actions taken by the ANA bitrate controller since the start of
36   // the call. If this value is not set, it indicates that the bitrate
37   // controller is disabled.
38   absl::optional<uint32_t> bitrate_action_counter;
39   // Number of actions taken by the ANA channel controller since the start of
40   // the call. If this value is not set, it indicates that the channel
41   // controller is disabled.
42   absl::optional<uint32_t> channel_action_counter;
43   // Number of actions taken by the ANA DTX controller since the start of the
44   // call. If this value is not set, it indicates that the DTX controller is
45   // disabled.
46   absl::optional<uint32_t> dtx_action_counter;
47   // Number of actions taken by the ANA FEC controller since the start of the
48   // call. If this value is not set, it indicates that the FEC controller is
49   // disabled.
50   absl::optional<uint32_t> fec_action_counter;
51   // Number of times the ANA frame length controller decided to increase the
52   // frame length since the start of the call. If this value is not set, it
53   // indicates that the frame length controller is disabled.
54   absl::optional<uint32_t> frame_length_increase_counter;
55   // Number of times the ANA frame length controller decided to decrease the
56   // frame length since the start of the call. If this value is not set, it
57   // indicates that the frame length controller is disabled.
58   absl::optional<uint32_t> frame_length_decrease_counter;
59   // The uplink packet loss fractions as set by the ANA FEC controller. If this
60   // value is not set, it indicates that the ANA FEC controller is not active.
61   absl::optional<float> uplink_packet_loss_fraction;
62 };
63 
64 // This is the interface class for encoders in AudioCoding module. Each codec
65 // type must have an implementation of this class.
66 class AudioEncoder {
67  public:
68   // Used for UMA logging of codec usage. The same codecs, with the
69   // same values, must be listed in
70   // src/tools/metrics/histograms/histograms.xml in chromium to log
71   // correct values.
72   enum class CodecType {
73     kOther = 0,  // Codec not specified, and/or not listed in this enum
74     kOpus = 1,
75     kIsac = 2,
76     kPcmA = 3,
77     kPcmU = 4,
78     kG722 = 5,
79     kIlbc = 6,
80 
81     // Number of histogram bins in the UMA logging of codec types. The
82     // total number of different codecs that are logged cannot exceed this
83     // number.
84     kMaxLoggedAudioCodecTypes
85   };
86 
87   struct EncodedInfoLeaf {
88     size_t encoded_bytes = 0;
89     uint32_t encoded_timestamp = 0;
90     int payload_type = 0;
91     bool send_even_if_empty = false;
92     bool speech = true;
93     CodecType encoder_type = CodecType::kOther;
94   };
95 
96   // This is the main struct for auxiliary encoding information. Each encoded
97   // packet should be accompanied by one EncodedInfo struct, containing the
98   // total number of |encoded_bytes|, the |encoded_timestamp| and the
99   // |payload_type|. If the packet contains redundant encodings, the |redundant|
100   // vector will be populated with EncodedInfoLeaf structs. Each struct in the
101   // vector represents one encoding; the order of structs in the vector is the
102   // same as the order in which the actual payloads are written to the byte
103   // stream. When EncoderInfoLeaf structs are present in the vector, the main
104   // struct's |encoded_bytes| will be the sum of all the |encoded_bytes| in the
105   // vector.
106   struct EncodedInfo : public EncodedInfoLeaf {
107     EncodedInfo();
108     EncodedInfo(const EncodedInfo&);
109     EncodedInfo(EncodedInfo&&);
110     ~EncodedInfo();
111     EncodedInfo& operator=(const EncodedInfo&);
112     EncodedInfo& operator=(EncodedInfo&&);
113 
114     std::vector<EncodedInfoLeaf> redundant;
115   };
116 
117   virtual ~AudioEncoder() = default;
118 
119   // Returns the input sample rate in Hz and the number of input channels.
120   // These are constants set at instantiation time.
121   virtual int SampleRateHz() const = 0;
122   virtual size_t NumChannels() const = 0;
123 
124   // Returns the rate at which the RTP timestamps are updated. The default
125   // implementation returns SampleRateHz().
126   virtual int RtpTimestampRateHz() const;
127 
128   // Returns the number of 10 ms frames the encoder will put in the next
129   // packet. This value may only change when Encode() outputs a packet; i.e.,
130   // the encoder may vary the number of 10 ms frames from packet to packet, but
131   // it must decide the length of the next packet no later than when outputting
132   // the preceding packet.
133   virtual size_t Num10MsFramesInNextPacket() const = 0;
134 
135   // Returns the maximum value that can be returned by
136   // Num10MsFramesInNextPacket().
137   virtual size_t Max10MsFramesInAPacket() const = 0;
138 
139   // Returns the current target bitrate in bits/s. The value -1 means that the
140   // codec adapts the target automatically, and a current target cannot be
141   // provided.
142   virtual int GetTargetBitrate() const = 0;
143 
144   // Accepts one 10 ms block of input audio (i.e., SampleRateHz() / 100 *
145   // NumChannels() samples). Multi-channel audio must be sample-interleaved.
146   // The encoder appends zero or more bytes of output to |encoded| and returns
147   // additional encoding information.  Encode() checks some preconditions, calls
148   // EncodeImpl() which does the actual work, and then checks some
149   // postconditions.
150   EncodedInfo Encode(uint32_t rtp_timestamp,
151                      rtc::ArrayView<const int16_t> audio,
152                      rtc::Buffer* encoded);
153 
154   // Resets the encoder to its starting state, discarding any input that has
155   // been fed to the encoder but not yet emitted in a packet.
156   virtual void Reset() = 0;
157 
158   // Enables or disables codec-internal FEC (forward error correction). Returns
159   // true if the codec was able to comply. The default implementation returns
160   // true when asked to disable FEC and false when asked to enable it (meaning
161   // that FEC isn't supported).
162   virtual bool SetFec(bool enable);
163 
164   // Enables or disables codec-internal VAD/DTX. Returns true if the codec was
165   // able to comply. The default implementation returns true when asked to
166   // disable DTX and false when asked to enable it (meaning that DTX isn't
167   // supported).
168   virtual bool SetDtx(bool enable);
169 
170   // Returns the status of codec-internal DTX. The default implementation always
171   // returns false.
172   virtual bool GetDtx() const;
173 
174   // Sets the application mode. Returns true if the codec was able to comply.
175   // The default implementation just returns false.
176   enum class Application { kSpeech, kAudio };
177   virtual bool SetApplication(Application application);
178 
179   // Tells the encoder about the highest sample rate the decoder is expected to
180   // use when decoding the bitstream. The encoder would typically use this
181   // information to adjust the quality of the encoding. The default
182   // implementation does nothing.
183   virtual void SetMaxPlaybackRate(int frequency_hz);
184 
185   // This is to be deprecated. Please use |OnReceivedTargetAudioBitrate|
186   // instead.
187   // Tells the encoder what average bitrate we'd like it to produce. The
188   // encoder is free to adjust or disregard the given bitrate (the default
189   // implementation does the latter).
190   RTC_DEPRECATED virtual void SetTargetBitrate(int target_bps);
191 
192   // Causes this encoder to let go of any other encoders it contains, and
193   // returns a pointer to an array where they are stored (which is required to
194   // live as long as this encoder). Unless the returned array is empty, you may
195   // not call any methods on this encoder afterwards, except for the
196   // destructor. The default implementation just returns an empty array.
197   // NOTE: This method is subject to change. Do not call or override it.
198   virtual rtc::ArrayView<std::unique_ptr<AudioEncoder>>
199   ReclaimContainedEncoders();
200 
201   // Enables audio network adaptor. Returns true if successful.
202   virtual bool EnableAudioNetworkAdaptor(const std::string& config_string,
203                                          RtcEventLog* event_log);
204 
205   // Disables audio network adaptor.
206   virtual void DisableAudioNetworkAdaptor();
207 
208   // Provides uplink packet loss fraction to this encoder to allow it to adapt.
209   // |uplink_packet_loss_fraction| is in the range [0.0, 1.0].
210   virtual void OnReceivedUplinkPacketLossFraction(
211       float uplink_packet_loss_fraction);
212 
213   RTC_DEPRECATED virtual void OnReceivedUplinkRecoverablePacketLossFraction(
214       float uplink_recoverable_packet_loss_fraction);
215 
216   // Provides target audio bitrate to this encoder to allow it to adapt.
217   virtual void OnReceivedTargetAudioBitrate(int target_bps);
218 
219   // Provides target audio bitrate and corresponding probing interval of
220   // the bandwidth estimator to this encoder to allow it to adapt.
221   virtual void OnReceivedUplinkBandwidth(int target_audio_bitrate_bps,
222                                          absl::optional<int64_t> bwe_period_ms);
223 
224   // Provides target audio bitrate and corresponding probing interval of
225   // the bandwidth estimator to this encoder to allow it to adapt.
226   virtual void OnReceivedUplinkAllocation(BitrateAllocationUpdate update);
227 
228   // Provides RTT to this encoder to allow it to adapt.
229   virtual void OnReceivedRtt(int rtt_ms);
230 
231   // Provides overhead to this encoder to adapt. The overhead is the number of
232   // bytes that will be added to each packet the encoder generates.
233   virtual void OnReceivedOverhead(size_t overhead_bytes_per_packet);
234 
235   // To allow encoder to adapt its frame length, it must be provided the frame
236   // length range that receivers can accept.
237   virtual void SetReceiverFrameLengthRange(int min_frame_length_ms,
238                                            int max_frame_length_ms);
239 
240   // Get statistics related to audio network adaptation.
241   virtual ANAStats GetANAStats() const;
242 
243   // The range of frame lengths that are supported or nullopt if there's no sch
244   // information. This is used to calculated the full bitrate range, including
245   // overhead.
246   virtual absl::optional<std::pair<TimeDelta, TimeDelta>> GetFrameLengthRange()
247       const = 0;
248 
249  protected:
250   // Subclasses implement this to perform the actual encoding. Called by
251   // Encode().
252   virtual EncodedInfo EncodeImpl(uint32_t rtp_timestamp,
253                                  rtc::ArrayView<const int16_t> audio,
254                                  rtc::Buffer* encoded) = 0;
255 };
256 }  // namespace webrtc
257 #endif  // API_AUDIO_CODECS_AUDIO_ENCODER_H_
258