blob: 036117fea6317f85b7b7a8fd8fc43f8005f9ab7d [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
108 // TODO(pthatcher): Rename to SetOptions and replace the old
109 // flags-based SetOptions.
110 bool SetAudioOptions(const AudioOptions& options);
111 // Eventually, we will replace them with AudioOptions.
112 // In the meantime, we leave this here for backwards compat.
113 bool SetOptions(int flags);
114 // Overrides, when set, take precedence over the options on a
115 // per-option basis. For example, if AGC is set in options and AEC
116 // is set in overrides, AGC and AEC will be both be set. Overrides
117 // can also turn off options. For example, if AGC is set to "on" in
118 // options and AGC is set to "off" in overrides, the result is that
119 // AGC will be off until different overrides are applied or until
120 // the overrides are cleared. Only one set of overrides is present
121 // at a time (they do not "stack"). And when the overrides are
122 // cleared, the media engine's state reverts back to the options set
123 // via SetOptions. This allows us to have both "persistent options"
124 // (the normal options) and "temporary options" (overrides).
125 bool SetOptionOverrides(const AudioOptions& options);
126 bool ClearOptionOverrides();
127 bool SetDelayOffset(int offset);
128 bool SetDevices(const Device* in_device, const Device* out_device);
129 bool GetOutputVolume(int* level);
130 bool SetOutputVolume(int level);
131 int GetInputLevel();
132 bool SetLocalMonitor(bool enable);
133
134 const std::vector<AudioCodec>& codecs();
135 bool FindCodec(const AudioCodec& codec);
136 bool FindWebRtcCodec(const AudioCodec& codec, webrtc::CodecInst* gcodec);
137
138 const std::vector<RtpHeaderExtension>& rtp_header_extensions() const;
139
140 void SetLogging(int min_sev, const char* filter);
141
142 bool RegisterProcessor(uint32 ssrc,
143 VoiceProcessor* voice_processor,
144 MediaProcessorDirection direction);
145 bool UnregisterProcessor(uint32 ssrc,
146 VoiceProcessor* voice_processor,
147 MediaProcessorDirection direction);
148
149 // Method from webrtc::VoEMediaProcess
150 virtual void Process(int channel,
151 webrtc::ProcessingTypes type,
152 int16_t audio10ms[],
153 int length,
154 int sampling_freq,
155 bool is_stereo);
156
157 // For tracking WebRtc channels. Needed because we have to pause them
158 // all when switching devices.
159 // May only be called by WebRtcVoiceMediaChannel.
160 void RegisterChannel(WebRtcVoiceMediaChannel *channel);
161 void UnregisterChannel(WebRtcVoiceMediaChannel *channel);
162
163 // May only be called by WebRtcSoundclipMedia.
164 void RegisterSoundclip(WebRtcSoundclipMedia *channel);
165 void UnregisterSoundclip(WebRtcSoundclipMedia *channel);
166
167 // Called by WebRtcVoiceMediaChannel to set a gain offset from
168 // the default AGC target level.
169 bool AdjustAgcLevel(int delta);
170
171 VoEWrapper* voe() { return voe_wrapper_.get(); }
172 VoEWrapper* voe_sc() { return voe_wrapper_sc_.get(); }
173 int GetLastEngineError();
174
175 // Set the external ADMs. This can only be called before Init.
176 bool SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
177 webrtc::AudioDeviceModule* adm_sc);
178
179 // Check whether the supplied trace should be ignored.
180 bool ShouldIgnoreTrace(const std::string& trace);
181
182 private:
183 typedef std::vector<WebRtcSoundclipMedia *> SoundclipList;
184 typedef std::vector<WebRtcVoiceMediaChannel *> ChannelList;
185 typedef sigslot::
186 signal3<uint32, MediaProcessorDirection, AudioFrame*> FrameSignal;
187
188 void Construct();
189 void ConstructCodecs();
190 bool InitInternal();
191 void SetTraceFilter(int filter);
192 void SetTraceOptions(const std::string& options);
193 // Applies either options or overrides. Every option that is "set"
194 // will be applied. Every option not "set" will be ignored. This
195 // allows us to selectively turn on and off different options easily
196 // at any time.
197 bool ApplyOptions(const AudioOptions& options);
198 virtual void Print(webrtc::TraceLevel level, const char* trace, int length);
199 virtual void CallbackOnError(int channel, int errCode);
200 // Given the device type, name, and id, find device id. Return true and
201 // set the output parameter rtc_id if successful.
202 bool FindWebRtcAudioDeviceId(
203 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id);
204 bool FindChannelAndSsrc(int channel_num,
205 WebRtcVoiceMediaChannel** channel,
206 uint32* ssrc) const;
207 bool FindChannelNumFromSsrc(uint32 ssrc,
208 MediaProcessorDirection direction,
209 int* channel_num);
210 bool ChangeLocalMonitor(bool enable);
211 bool PauseLocalMonitor();
212 bool ResumeLocalMonitor();
213
214 bool UnregisterProcessorChannel(MediaProcessorDirection channel_direction,
215 uint32 ssrc,
216 VoiceProcessor* voice_processor,
217 MediaProcessorDirection processor_direction);
218
219 void StartAecDump(const std::string& filename);
220 void StopAecDump();
221
222 // When a voice processor registers with the engine, it is connected
223 // to either the Rx or Tx signals, based on the direction parameter.
224 // SignalXXMediaFrame will be invoked for every audio packet.
225 FrameSignal SignalRxMediaFrame;
226 FrameSignal SignalTxMediaFrame;
227
228 static const int kDefaultLogSeverity = talk_base::LS_WARNING;
229
230 // The primary instance of WebRtc VoiceEngine.
231 talk_base::scoped_ptr<VoEWrapper> voe_wrapper_;
232 // A secondary instance, for playing out soundclips (on the 'ring' device).
233 talk_base::scoped_ptr<VoEWrapper> voe_wrapper_sc_;
234 talk_base::scoped_ptr<VoETraceWrapper> tracing_;
235 // The external audio device manager
236 webrtc::AudioDeviceModule* adm_;
237 webrtc::AudioDeviceModule* adm_sc_;
238 int log_filter_;
239 std::string log_options_;
240 bool is_dumping_aec_;
241 std::vector<AudioCodec> codecs_;
242 std::vector<RtpHeaderExtension> rtp_header_extensions_;
243 bool desired_local_monitor_enable_;
244 talk_base::scoped_ptr<WebRtcMonitorStream> monitor_;
245 SoundclipList soundclips_;
246 ChannelList channels_;
247 // channels_ can be read from WebRtc callback thread. We need a lock on that
248 // callback as well as the RegisterChannel/UnregisterChannel.
249 talk_base::CriticalSection channels_cs_;
250 webrtc::AgcConfig default_agc_config_;
251 bool initialized_;
252 // See SetOptions and SetOptionOverrides for a description of the
253 // difference between options and overrides.
254 // options_ are the base options, which combined with the
255 // option_overrides_, create the current options being used.
256 // options_ is stored so that when option_overrides_ is cleared, we
257 // can restore the options_ without the option_overrides.
258 AudioOptions options_;
259 AudioOptions option_overrides_;
260
261 // When the media processor registers with the engine, the ssrc is cached
262 // here so that a look up need not be made when the callback is invoked.
263 // This is necessary because the lookup results in mux_channels_cs lock being
264 // held and if a remote participant leaves the hangout at the same time
265 // we hit a deadlock.
266 uint32 tx_processor_ssrc_;
267 uint32 rx_processor_ssrc_;
268
269 talk_base::CriticalSection signal_media_critical_;
270};
271
272// WebRtcMediaChannel is a class that implements the common WebRtc channel
273// functionality.
274template <class T, class E>
275class WebRtcMediaChannel : public T, public webrtc::Transport {
276 public:
277 WebRtcMediaChannel(E *engine, int channel)
278 : engine_(engine), voe_channel_(channel), sequence_number_(-1) {}
279 E *engine() { return engine_; }
280 int voe_channel() const { return voe_channel_; }
281 bool valid() const { return voe_channel_ != -1; }
282
283 protected:
284 // implements Transport interface
285 virtual int SendPacket(int channel, const void *data, int len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000286 // We need to store the sequence number to be able to pick up
287 // the same sequence when the device is restarted.
288 // TODO(oja): Remove when WebRtc has fixed the problem.
289 int seq_num;
290 if (!GetRtpSeqNum(data, len, &seq_num)) {
291 return -1;
292 }
293 if (sequence_number() == -1) {
294 LOG(INFO) << "WebRtcVoiceMediaChannel sends first packet seqnum="
295 << seq_num;
296 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000297
298 talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000299 if (!T::SendPacket(&packet)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000300 return -1;
301 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000302 sequence_number_ = seq_num;
303 return len;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000304 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000305
306 virtual int SendRTCPPacket(int channel, const void *data, int len) {
307 talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
308 return T::SendRtcp(&packet) ? len : -1;
309 }
310
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000311 int sequence_number() const {
312 return sequence_number_;
313 }
314
315 private:
316 E *engine_;
317 int voe_channel_;
318 int sequence_number_;
319};
320
321// WebRtcVoiceMediaChannel is an implementation of VoiceMediaChannel that uses
322// WebRtc Voice Engine.
323class WebRtcVoiceMediaChannel
324 : public WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine> {
325 public:
326 explicit WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine);
327 virtual ~WebRtcVoiceMediaChannel();
328 virtual bool SetOptions(const AudioOptions& options);
329 virtual bool GetOptions(AudioOptions* options) const {
330 *options = options_;
331 return true;
332 }
333 virtual bool SetRecvCodecs(const std::vector<AudioCodec> &codecs);
334 virtual bool SetSendCodecs(const std::vector<AudioCodec> &codecs);
335 virtual bool SetRecvRtpHeaderExtensions(
336 const std::vector<RtpHeaderExtension>& extensions);
337 virtual bool SetSendRtpHeaderExtensions(
338 const std::vector<RtpHeaderExtension>& extensions);
339 virtual bool SetPlayout(bool playout);
340 bool PausePlayout();
341 bool ResumePlayout();
342 virtual bool SetSend(SendFlags send);
343 bool PauseSend();
344 bool ResumeSend();
345 virtual bool AddSendStream(const StreamParams& sp);
346 virtual bool RemoveSendStream(uint32 ssrc);
347 virtual bool AddRecvStream(const StreamParams& sp);
348 virtual bool RemoveRecvStream(uint32 ssrc);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000349 virtual bool SetRemoteRenderer(uint32 ssrc, AudioRenderer* renderer);
350 virtual bool SetLocalRenderer(uint32 ssrc, AudioRenderer* renderer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000351 virtual bool GetActiveStreams(AudioInfo::StreamList* actives);
352 virtual int GetOutputLevel();
353 virtual int GetTimeSinceLastTyping();
354 virtual void SetTypingDetectionParameters(int time_window,
355 int cost_per_typing, int reporting_threshold, int penalty_decay,
356 int type_event_delay);
357 virtual bool SetOutputScaling(uint32 ssrc, double left, double right);
358 virtual bool GetOutputScaling(uint32 ssrc, double* left, double* right);
359
360 virtual bool SetRingbackTone(const char *buf, int len);
361 virtual bool PlayRingbackTone(uint32 ssrc, bool play, bool loop);
362 virtual bool CanInsertDtmf();
363 virtual bool InsertDtmf(uint32 ssrc, int event, int duration, int flags);
364
365 virtual void OnPacketReceived(talk_base::Buffer* packet);
366 virtual void OnRtcpReceived(talk_base::Buffer* packet);
367 virtual void OnReadyToSend(bool ready) {}
368 virtual bool MuteStream(uint32 ssrc, bool on);
369 virtual bool SetSendBandwidth(bool autobw, int bps);
370 virtual bool GetStats(VoiceMediaInfo* info);
371 // Gets last reported error from WebRtc voice engine. This should be only
372 // called in response a failure.
373 virtual void GetLastMediaError(uint32* ssrc,
374 VoiceMediaChannel::Error* error);
375 bool FindSsrc(int channel_num, uint32* ssrc);
376 void OnError(uint32 ssrc, int error);
377
378 bool sending() const { return send_ != SEND_NOTHING; }
379 int GetReceiveChannelNum(uint32 ssrc);
380 int GetSendChannelNum(uint32 ssrc);
381
382 protected:
383 int GetLastEngineError() { return engine()->GetLastEngineError(); }
384 int GetOutputLevel(int channel);
385 bool GetRedSendCodec(const AudioCodec& red_codec,
386 const std::vector<AudioCodec>& all_codecs,
387 webrtc::CodecInst* send_codec);
388 bool EnableRtcp(int channel);
389 bool ResetRecvCodecs(int channel);
390 bool SetPlayout(int channel, bool playout);
391 static uint32 ParseSsrc(const void* data, size_t len, bool rtcp);
392 static Error WebRtcErrorToChannelError(int err_code);
393
394 private:
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000395 struct WebRtcVoiceChannelInfo;
396
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000397 void SetNack(uint32 ssrc, int channel, bool nack_enabled);
398 bool SetSendCodec(const webrtc::CodecInst& send_codec);
399 bool ChangePlayout(bool playout);
400 bool ChangeSend(SendFlags send);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000401 bool InConferenceMode() const {
402 return options_.conference_mode.GetWithDefaultIfUnset(false);
403 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000404
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000405 typedef std::map<uint32, WebRtcVoiceChannelInfo> ChannelMap;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000406 talk_base::scoped_ptr<WebRtcSoundclipStream> ringback_tone_;
407 std::set<int> ringback_channels_; // channels playing ringback
408 std::vector<AudioCodec> recv_codecs_;
409 talk_base::scoped_ptr<webrtc::CodecInst> send_codec_;
410 AudioOptions options_;
411 bool dtmf_allowed_;
412 bool desired_playout_;
413 bool nack_enabled_;
414 bool playout_;
415 SendFlags desired_send_;
416 SendFlags send_;
417
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000418 // TODO(xians): Add support for multiple send channels.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000419 uint32 send_ssrc_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000420 // Weak pointer to the renderer of the local audio track. It is owned by the
421 // track and will set to NULL when the track is going away or channel gets
422 // deleted. Used to notify the audio track that the media channel is added
423 // or removed.
424 AudioRenderer* local_renderer_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000425 uint32 default_receive_ssrc_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000426 // Note the default channel (voe_channel()) can reside in both
427 // receive_channels_ and send channel in non-conference mode and in that case
428 // it will only be there if a non-zero default_receive_ssrc_ is set.
429 ChannelMap receive_channels_; // for multiple sources
430 // receive_channels_ can be read from WebRtc callback thread. Access from
431 // the WebRtc thread must be synchronized with edits on the worker thread.
432 // Reads on the worker thread are ok.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000433 //
434 // Do not lock this on the VoE media processor thread; potential for deadlock
435 // exists.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000436 mutable talk_base::CriticalSection receive_channels_cs_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000437};
438
439} // namespace cricket
440
441#endif // TALK_MEDIA_WEBRTCVOICEENGINE_H_