blob: 6e11485fc9e0ae4a8a684cb2edb4f3f814d4e2ce [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2004 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#ifndef TALK_MEDIA_WEBRTCVOICEENGINE_H_
29#define TALK_MEDIA_WEBRTCVOICEENGINE_H_
30
31#include <map>
32#include <set>
33#include <string>
34#include <vector>
35
36#include "talk/base/buffer.h"
37#include "talk/base/byteorder.h"
38#include "talk/base/logging.h"
39#include "talk/base/scoped_ptr.h"
40#include "talk/base/stream.h"
41#include "talk/media/base/rtputils.h"
42#include "talk/media/webrtc/webrtccommon.h"
43#include "talk/media/webrtc/webrtcexport.h"
44#include "talk/media/webrtc/webrtcvoe.h"
45#include "talk/session/media/channel.h"
46
47#if !defined(LIBPEERCONNECTION_LIB) && \
48 !defined(LIBPEERCONNECTION_IMPLEMENTATION)
49#error "Bogus include."
50#endif
51
52
53namespace cricket {
54
55// WebRtcSoundclipStream is an adapter object that allows a memory stream to be
56// passed into WebRtc, and support looping.
57class WebRtcSoundclipStream : public webrtc::InStream {
58 public:
59 WebRtcSoundclipStream(const char* buf, size_t len)
60 : mem_(buf, len), loop_(true) {
61 }
62 void set_loop(bool loop) { loop_ = loop; }
63 virtual int Read(void* buf, int len);
64 virtual int Rewind();
65
66 private:
67 talk_base::MemoryStream mem_;
68 bool loop_;
69};
70
71// WebRtcMonitorStream is used to monitor a stream coming from WebRtc.
72// For now we just dump the data.
73class WebRtcMonitorStream : public webrtc::OutStream {
74 virtual bool Write(const void *buf, int len) {
75 return true;
76 }
77};
78
79class AudioDeviceModule;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000080class AudioRenderer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000081class VoETraceWrapper;
82class VoEWrapper;
83class VoiceProcessor;
84class WebRtcSoundclipMedia;
85class WebRtcVoiceMediaChannel;
86
87// WebRtcVoiceEngine is a class to be used with CompositeMediaEngine.
88// It uses the WebRtc VoiceEngine library for audio handling.
89class WebRtcVoiceEngine
90 : public webrtc::VoiceEngineObserver,
91 public webrtc::TraceCallback,
92 public webrtc::VoEMediaProcess {
93 public:
94 WebRtcVoiceEngine();
95 // Dependency injection for testing.
96 WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
97 VoEWrapper* voe_wrapper_sc,
98 VoETraceWrapper* tracing);
99 ~WebRtcVoiceEngine();
100 bool Init(talk_base::Thread* worker_thread);
101 void Terminate();
102
103 int GetCapabilities();
104 VoiceMediaChannel* CreateChannel();
105
106 SoundclipMedia* CreateSoundclip();
107
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000108 AudioOptions GetOptions() const { return options_; }
109 bool SetOptions(const AudioOptions& options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110 // Overrides, when set, take precedence over the options on a
111 // per-option basis. For example, if AGC is set in options and AEC
112 // is set in overrides, AGC and AEC will be both be set. Overrides
113 // can also turn off options. For example, if AGC is set to "on" in
114 // options and AGC is set to "off" in overrides, the result is that
115 // AGC will be off until different overrides are applied or until
116 // the overrides are cleared. Only one set of overrides is present
117 // at a time (they do not "stack"). And when the overrides are
118 // cleared, the media engine's state reverts back to the options set
119 // via SetOptions. This allows us to have both "persistent options"
120 // (the normal options) and "temporary options" (overrides).
121 bool SetOptionOverrides(const AudioOptions& options);
122 bool ClearOptionOverrides();
123 bool SetDelayOffset(int offset);
124 bool SetDevices(const Device* in_device, const Device* out_device);
125 bool GetOutputVolume(int* level);
126 bool SetOutputVolume(int level);
127 int GetInputLevel();
128 bool SetLocalMonitor(bool enable);
129
130 const std::vector<AudioCodec>& codecs();
131 bool FindCodec(const AudioCodec& codec);
132 bool FindWebRtcCodec(const AudioCodec& codec, webrtc::CodecInst* gcodec);
133
134 const std::vector<RtpHeaderExtension>& rtp_header_extensions() const;
135
136 void SetLogging(int min_sev, const char* filter);
137
138 bool RegisterProcessor(uint32 ssrc,
139 VoiceProcessor* voice_processor,
140 MediaProcessorDirection direction);
141 bool UnregisterProcessor(uint32 ssrc,
142 VoiceProcessor* voice_processor,
143 MediaProcessorDirection direction);
144
145 // Method from webrtc::VoEMediaProcess
146 virtual void Process(int channel,
147 webrtc::ProcessingTypes type,
148 int16_t audio10ms[],
149 int length,
150 int sampling_freq,
151 bool is_stereo);
152
153 // For tracking WebRtc channels. Needed because we have to pause them
154 // all when switching devices.
155 // May only be called by WebRtcVoiceMediaChannel.
156 void RegisterChannel(WebRtcVoiceMediaChannel *channel);
157 void UnregisterChannel(WebRtcVoiceMediaChannel *channel);
158
159 // May only be called by WebRtcSoundclipMedia.
160 void RegisterSoundclip(WebRtcSoundclipMedia *channel);
161 void UnregisterSoundclip(WebRtcSoundclipMedia *channel);
162
163 // Called by WebRtcVoiceMediaChannel to set a gain offset from
164 // the default AGC target level.
165 bool AdjustAgcLevel(int delta);
166
167 VoEWrapper* voe() { return voe_wrapper_.get(); }
168 VoEWrapper* voe_sc() { return voe_wrapper_sc_.get(); }
169 int GetLastEngineError();
170
171 // Set the external ADMs. This can only be called before Init.
172 bool SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
173 webrtc::AudioDeviceModule* adm_sc);
174
175 // Check whether the supplied trace should be ignored.
176 bool ShouldIgnoreTrace(const std::string& trace);
177
178 private:
179 typedef std::vector<WebRtcSoundclipMedia *> SoundclipList;
180 typedef std::vector<WebRtcVoiceMediaChannel *> ChannelList;
181 typedef sigslot::
182 signal3<uint32, MediaProcessorDirection, AudioFrame*> FrameSignal;
183
184 void Construct();
185 void ConstructCodecs();
186 bool InitInternal();
187 void SetTraceFilter(int filter);
188 void SetTraceOptions(const std::string& options);
189 // Applies either options or overrides. Every option that is "set"
190 // will be applied. Every option not "set" will be ignored. This
191 // allows us to selectively turn on and off different options easily
192 // at any time.
193 bool ApplyOptions(const AudioOptions& options);
194 virtual void Print(webrtc::TraceLevel level, const char* trace, int length);
195 virtual void CallbackOnError(int channel, int errCode);
196 // Given the device type, name, and id, find device id. Return true and
197 // set the output parameter rtc_id if successful.
198 bool FindWebRtcAudioDeviceId(
199 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id);
200 bool FindChannelAndSsrc(int channel_num,
201 WebRtcVoiceMediaChannel** channel,
202 uint32* ssrc) const;
203 bool FindChannelNumFromSsrc(uint32 ssrc,
204 MediaProcessorDirection direction,
205 int* channel_num);
206 bool ChangeLocalMonitor(bool enable);
207 bool PauseLocalMonitor();
208 bool ResumeLocalMonitor();
209
210 bool UnregisterProcessorChannel(MediaProcessorDirection channel_direction,
211 uint32 ssrc,
212 VoiceProcessor* voice_processor,
213 MediaProcessorDirection processor_direction);
214
215 void StartAecDump(const std::string& filename);
216 void StopAecDump();
217
218 // When a voice processor registers with the engine, it is connected
219 // to either the Rx or Tx signals, based on the direction parameter.
220 // SignalXXMediaFrame will be invoked for every audio packet.
221 FrameSignal SignalRxMediaFrame;
222 FrameSignal SignalTxMediaFrame;
223
224 static const int kDefaultLogSeverity = talk_base::LS_WARNING;
225
226 // The primary instance of WebRtc VoiceEngine.
227 talk_base::scoped_ptr<VoEWrapper> voe_wrapper_;
228 // A secondary instance, for playing out soundclips (on the 'ring' device).
229 talk_base::scoped_ptr<VoEWrapper> voe_wrapper_sc_;
230 talk_base::scoped_ptr<VoETraceWrapper> tracing_;
231 // The external audio device manager
232 webrtc::AudioDeviceModule* adm_;
233 webrtc::AudioDeviceModule* adm_sc_;
234 int log_filter_;
235 std::string log_options_;
236 bool is_dumping_aec_;
237 std::vector<AudioCodec> codecs_;
238 std::vector<RtpHeaderExtension> rtp_header_extensions_;
239 bool desired_local_monitor_enable_;
240 talk_base::scoped_ptr<WebRtcMonitorStream> monitor_;
241 SoundclipList soundclips_;
242 ChannelList channels_;
243 // channels_ can be read from WebRtc callback thread. We need a lock on that
244 // callback as well as the RegisterChannel/UnregisterChannel.
245 talk_base::CriticalSection channels_cs_;
246 webrtc::AgcConfig default_agc_config_;
247 bool initialized_;
248 // See SetOptions and SetOptionOverrides for a description of the
249 // difference between options and overrides.
250 // options_ are the base options, which combined with the
251 // option_overrides_, create the current options being used.
252 // options_ is stored so that when option_overrides_ is cleared, we
253 // can restore the options_ without the option_overrides.
254 AudioOptions options_;
255 AudioOptions option_overrides_;
256
257 // When the media processor registers with the engine, the ssrc is cached
258 // here so that a look up need not be made when the callback is invoked.
259 // This is necessary because the lookup results in mux_channels_cs lock being
260 // held and if a remote participant leaves the hangout at the same time
261 // we hit a deadlock.
262 uint32 tx_processor_ssrc_;
263 uint32 rx_processor_ssrc_;
264
265 talk_base::CriticalSection signal_media_critical_;
266};
267
268// WebRtcMediaChannel is a class that implements the common WebRtc channel
269// functionality.
270template <class T, class E>
271class WebRtcMediaChannel : public T, public webrtc::Transport {
272 public:
273 WebRtcMediaChannel(E *engine, int channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000274 : engine_(engine), voe_channel_(channel) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000275 E *engine() { return engine_; }
276 int voe_channel() const { return voe_channel_; }
277 bool valid() const { return voe_channel_ != -1; }
278
279 protected:
280 // implements Transport interface
281 virtual int SendPacket(int channel, const void *data, int len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000282 talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000283 if (!T::SendPacket(&packet)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000284 return -1;
285 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000286 return len;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000287 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000288
289 virtual int SendRTCPPacket(int channel, const void *data, int len) {
290 talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
291 return T::SendRtcp(&packet) ? len : -1;
292 }
293
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000294 private:
295 E *engine_;
296 int voe_channel_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000297};
298
299// WebRtcVoiceMediaChannel is an implementation of VoiceMediaChannel that uses
300// WebRtc Voice Engine.
301class WebRtcVoiceMediaChannel
302 : public WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine> {
303 public:
304 explicit WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine);
305 virtual ~WebRtcVoiceMediaChannel();
306 virtual bool SetOptions(const AudioOptions& options);
307 virtual bool GetOptions(AudioOptions* options) const {
308 *options = options_;
309 return true;
310 }
311 virtual bool SetRecvCodecs(const std::vector<AudioCodec> &codecs);
312 virtual bool SetSendCodecs(const std::vector<AudioCodec> &codecs);
313 virtual bool SetRecvRtpHeaderExtensions(
314 const std::vector<RtpHeaderExtension>& extensions);
315 virtual bool SetSendRtpHeaderExtensions(
316 const std::vector<RtpHeaderExtension>& extensions);
317 virtual bool SetPlayout(bool playout);
318 bool PausePlayout();
319 bool ResumePlayout();
320 virtual bool SetSend(SendFlags send);
321 bool PauseSend();
322 bool ResumeSend();
323 virtual bool AddSendStream(const StreamParams& sp);
324 virtual bool RemoveSendStream(uint32 ssrc);
325 virtual bool AddRecvStream(const StreamParams& sp);
326 virtual bool RemoveRecvStream(uint32 ssrc);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000327 virtual bool SetRemoteRenderer(uint32 ssrc, AudioRenderer* renderer);
328 virtual bool SetLocalRenderer(uint32 ssrc, AudioRenderer* renderer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000329 virtual bool GetActiveStreams(AudioInfo::StreamList* actives);
330 virtual int GetOutputLevel();
331 virtual int GetTimeSinceLastTyping();
332 virtual void SetTypingDetectionParameters(int time_window,
333 int cost_per_typing, int reporting_threshold, int penalty_decay,
334 int type_event_delay);
335 virtual bool SetOutputScaling(uint32 ssrc, double left, double right);
336 virtual bool GetOutputScaling(uint32 ssrc, double* left, double* right);
337
338 virtual bool SetRingbackTone(const char *buf, int len);
339 virtual bool PlayRingbackTone(uint32 ssrc, bool play, bool loop);
340 virtual bool CanInsertDtmf();
341 virtual bool InsertDtmf(uint32 ssrc, int event, int duration, int flags);
342
343 virtual void OnPacketReceived(talk_base::Buffer* packet);
344 virtual void OnRtcpReceived(talk_base::Buffer* packet);
345 virtual void OnReadyToSend(bool ready) {}
346 virtual bool MuteStream(uint32 ssrc, bool on);
347 virtual bool SetSendBandwidth(bool autobw, int bps);
348 virtual bool GetStats(VoiceMediaInfo* info);
349 // Gets last reported error from WebRtc voice engine. This should be only
350 // called in response a failure.
351 virtual void GetLastMediaError(uint32* ssrc,
352 VoiceMediaChannel::Error* error);
353 bool FindSsrc(int channel_num, uint32* ssrc);
354 void OnError(uint32 ssrc, int error);
355
356 bool sending() const { return send_ != SEND_NOTHING; }
357 int GetReceiveChannelNum(uint32 ssrc);
358 int GetSendChannelNum(uint32 ssrc);
359
360 protected:
361 int GetLastEngineError() { return engine()->GetLastEngineError(); }
362 int GetOutputLevel(int channel);
363 bool GetRedSendCodec(const AudioCodec& red_codec,
364 const std::vector<AudioCodec>& all_codecs,
365 webrtc::CodecInst* send_codec);
366 bool EnableRtcp(int channel);
367 bool ResetRecvCodecs(int channel);
368 bool SetPlayout(int channel, bool playout);
369 static uint32 ParseSsrc(const void* data, size_t len, bool rtcp);
370 static Error WebRtcErrorToChannelError(int err_code);
371
372 private:
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000373 struct WebRtcVoiceChannelInfo;
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000374 typedef std::map<uint32, WebRtcVoiceChannelInfo> ChannelMap;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000375
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000376 void SetNack(int channel, bool nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000377 void SetNack(const ChannelMap& channels, bool nack_enabled);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000378 bool SetSendCodec(const webrtc::CodecInst& send_codec);
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000379 bool SetSendCodec(int channel, const webrtc::CodecInst& send_codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000380 bool ChangePlayout(bool playout);
381 bool ChangeSend(SendFlags send);
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000382 bool ChangeSend(int channel, SendFlags send);
383 void ConfigureSendChannel(int channel);
384 bool DeleteChannel(int channel);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000385 bool InConferenceMode() const {
386 return options_.conference_mode.GetWithDefaultIfUnset(false);
387 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000388 bool IsDefaultChannel(int channel_id) const {
389 return channel_id == voe_channel();
390 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000391 bool SetSendCodecs(int channel, const std::vector<AudioCodec>& codecs);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000392
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000393 talk_base::scoped_ptr<WebRtcSoundclipStream> ringback_tone_;
394 std::set<int> ringback_channels_; // channels playing ringback
395 std::vector<AudioCodec> recv_codecs_;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000396 std::vector<AudioCodec> send_codecs_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000397 talk_base::scoped_ptr<webrtc::CodecInst> send_codec_;
398 AudioOptions options_;
399 bool dtmf_allowed_;
400 bool desired_playout_;
401 bool nack_enabled_;
402 bool playout_;
wu@webrtc.org967bfff2013-09-19 05:49:50 +0000403 bool typing_noise_detected_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000404 SendFlags desired_send_;
405 SendFlags send_;
406
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000407 // send_channels_ contains the channels which are being used for sending.
408 // When the default channel (voe_channel) is used for sending, it is
409 // contained in send_channels_, otherwise not.
410 ChannelMap send_channels_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000411 uint32 default_receive_ssrc_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000412 // Note the default channel (voe_channel()) can reside in both
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000413 // receive_channels_ and send_channels_ in non-conference mode and in that
414 // case it will only be there if a non-zero default_receive_ssrc_ is set.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000415 ChannelMap receive_channels_; // for multiple sources
416 // receive_channels_ can be read from WebRtc callback thread. Access from
417 // the WebRtc thread must be synchronized with edits on the worker thread.
418 // Reads on the worker thread are ok.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000419 //
420 // Do not lock this on the VoE media processor thread; potential for deadlock
421 // exists.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000422 mutable talk_base::CriticalSection receive_channels_cs_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000423};
424
425} // namespace cricket
426
427#endif // TALK_MEDIA_WEBRTCVOICEENGINE_H_