blob: f2dc18c78dcbdff68d88c4cd8233b4bb97971ac6 [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_WEBRTCVIDEOENGINE_H_
29#define TALK_MEDIA_WEBRTCVIDEOENGINE_H_
30
31#include <map>
32#include <vector>
33
34#include "talk/base/scoped_ptr.h"
35#include "talk/media/base/codec.h"
36#include "talk/media/base/videocommon.h"
37#include "talk/media/webrtc/webrtccommon.h"
38#include "talk/media/webrtc/webrtcexport.h"
39#include "talk/media/webrtc/webrtcvideoencoderfactory.h"
40#include "talk/session/media/channel.h"
41#include "webrtc/video_engine/include/vie_base.h"
42
43#if !defined(LIBPEERCONNECTION_LIB) && \
44 !defined(LIBPEERCONNECTION_IMPLEMENTATION)
45#error "Bogus include."
46#endif
47
48namespace webrtc {
49class VideoCaptureModule;
50class VideoDecoder;
51class VideoEncoder;
52class VideoRender;
53class ViEExternalCapture;
54class ViERTP_RTCP;
55}
56
57namespace talk_base {
58class CpuMonitor;
59} // namespace talk_base
60
61namespace cricket {
62
63class VideoCapturer;
64class VideoFrame;
65class VideoProcessor;
66class VideoRenderer;
67class ViETraceWrapper;
68class ViEWrapper;
69class VoiceMediaChannel;
70class WebRtcDecoderObserver;
71class WebRtcEncoderObserver;
72class WebRtcLocalStreamInfo;
73class WebRtcRenderAdapter;
74class WebRtcVideoChannelRecvInfo;
75class WebRtcVideoChannelSendInfo;
76class WebRtcVideoDecoderFactory;
77class WebRtcVideoEncoderFactory;
78class WebRtcVideoMediaChannel;
79class WebRtcVoiceEngine;
80
81struct CapturedFrame;
82struct Device;
83
84class WebRtcVideoEngine : public sigslot::has_slots<>,
85 public webrtc::TraceCallback,
86 public WebRtcVideoEncoderFactory::Observer {
87 public:
88 // Creates the WebRtcVideoEngine with internal VideoCaptureModule.
89 WebRtcVideoEngine();
90 // For testing purposes. Allows the WebRtcVoiceEngine,
91 // ViEWrapper and CpuMonitor to be mocks.
92 // TODO(juberti): Remove the 3-arg ctor once fake tracing is implemented.
93 WebRtcVideoEngine(WebRtcVoiceEngine* voice_engine,
94 ViEWrapper* vie_wrapper,
95 talk_base::CpuMonitor* cpu_monitor);
96 WebRtcVideoEngine(WebRtcVoiceEngine* voice_engine,
97 ViEWrapper* vie_wrapper,
98 ViETraceWrapper* tracing,
99 talk_base::CpuMonitor* cpu_monitor);
100 ~WebRtcVideoEngine();
101
102 // Basic video engine implementation.
103 bool Init(talk_base::Thread* worker_thread);
104 void Terminate();
105
106 int GetCapabilities();
107 bool SetOptions(int options);
108 bool SetDefaultEncoderConfig(const VideoEncoderConfig& config);
109
110 WebRtcVideoMediaChannel* CreateChannel(VoiceMediaChannel* voice_channel);
111
112 const std::vector<VideoCodec>& codecs() const;
113 const std::vector<RtpHeaderExtension>& rtp_header_extensions() const;
114 void SetLogging(int min_sev, const char* filter);
115
116 // If capturer is NULL, unregisters the capturer and stops capturing.
117 // Otherwise sets the capturer and starts capturing.
118 bool SetVideoCapturer(VideoCapturer* capturer);
119 VideoCapturer* GetVideoCapturer() const;
120 bool SetLocalRenderer(VideoRenderer* renderer);
121 bool SetCapture(bool capture);
122 sigslot::repeater2<VideoCapturer*, CaptureState> SignalCaptureStateChange;
123 CaptureState UpdateCapturingState();
124 bool IsCapturing() const;
125 void OnFrameCaptured(VideoCapturer* capturer, const CapturedFrame* frame);
126
127 // Set the VoiceEngine for A/V sync. This can only be called before Init.
128 bool SetVoiceEngine(WebRtcVoiceEngine* voice_engine);
129 // Set a WebRtcVideoDecoderFactory for external decoding. Video engine does
130 // not take the ownership of |decoder_factory|. The caller needs to make sure
131 // that |decoder_factory| outlives the video engine.
132 void SetExternalDecoderFactory(WebRtcVideoDecoderFactory* decoder_factory);
133 // Set a WebRtcVideoEncoderFactory for external encoding. Video engine does
134 // not take the ownership of |encoder_factory|. The caller needs to make sure
135 // that |encoder_factory| outlives the video engine.
136 void SetExternalEncoderFactory(WebRtcVideoEncoderFactory* encoder_factory);
137 // Enable the render module with timing control.
138 bool EnableTimedRender();
139
140 bool RegisterProcessor(VideoProcessor* video_processor);
141 bool UnregisterProcessor(VideoProcessor* video_processor);
142
143 // Returns an external decoder for the given codec type. The return value
144 // can be NULL if decoder factory is not given or it does not support the
145 // codec type. The caller takes the ownership of the returned object.
146 webrtc::VideoDecoder* CreateExternalDecoder(webrtc::VideoCodecType type);
147 // Releases the decoder instance created by CreateExternalDecoder().
148 void DestroyExternalDecoder(webrtc::VideoDecoder* decoder);
149
150 // Returns an external encoder for the given codec type. The return value
151 // can be NULL if encoder factory is not given or it does not support the
152 // codec type. The caller takes the ownership of the returned object.
153 webrtc::VideoEncoder* CreateExternalEncoder(webrtc::VideoCodecType type);
154 // Releases the encoder instance created by CreateExternalEncoder().
155 void DestroyExternalEncoder(webrtc::VideoEncoder* encoder);
156
157 // Returns true if the codec type is supported by the external encoder.
158 bool IsExternalEncoderCodecType(webrtc::VideoCodecType type) const;
159
160 // Functions called by WebRtcVideoMediaChannel.
161 talk_base::Thread* worker_thread() { return worker_thread_; }
162 ViEWrapper* vie() { return vie_wrapper_.get(); }
163 const VideoFormat& default_codec_format() const {
164 return default_codec_format_;
165 }
166 int GetLastEngineError();
167 bool FindCodec(const VideoCodec& in);
168 bool CanSendCodec(const VideoCodec& in, const VideoCodec& current,
169 VideoCodec* out);
170 void RegisterChannel(WebRtcVideoMediaChannel* channel);
171 void UnregisterChannel(WebRtcVideoMediaChannel* channel);
172 bool ConvertFromCricketVideoCodec(const VideoCodec& in_codec,
173 webrtc::VideoCodec* out_codec);
174 // Check whether the supplied trace should be ignored.
175 bool ShouldIgnoreTrace(const std::string& trace);
176 int GetNumOfChannels();
177
178 void IncrementFrameListeners();
179 void DecrementFrameListeners();
180
181 VideoFormat GetStartCaptureFormat() const { return default_codec_format_; }
182
183 talk_base::CpuMonitor* cpu_monitor() { return cpu_monitor_.get(); }
184
185 protected:
186 // When a video processor registers with the engine.
187 // SignalMediaFrame will be invoked for every video frame.
188 // See videoprocessor.h for param reference.
189 sigslot::signal3<uint32, VideoFrame*, bool*> SignalMediaFrame;
190
191 private:
192 typedef std::vector<WebRtcVideoMediaChannel*> VideoChannels;
193 struct VideoCodecPref {
194 const char* name;
195 int payload_type;
196 int pref;
197 };
198
199 static const VideoCodecPref kVideoCodecPrefs[];
200 static const VideoFormatPod kVideoFormats[];
201 static const VideoFormatPod kDefaultVideoFormat;
202
203 void Construct(ViEWrapper* vie_wrapper,
204 ViETraceWrapper* tracing,
205 WebRtcVoiceEngine* voice_engine,
206 talk_base::CpuMonitor* cpu_monitor);
207 bool SetDefaultCodec(const VideoCodec& codec);
208 bool RebuildCodecList(const VideoCodec& max_codec);
209 void SetTraceFilter(int filter);
210 void SetTraceOptions(const std::string& options);
211 bool InitVideoEngine();
212 bool SetCapturer(VideoCapturer* capturer);
213
214 // webrtc::TraceCallback implementation.
215 virtual void Print(webrtc::TraceLevel level, const char* trace, int length);
216 void ClearCapturer();
217
218 // WebRtcVideoEncoderFactory::Observer implementation.
219 virtual void OnCodecsAvailable();
220
221 talk_base::Thread* worker_thread_;
222 talk_base::scoped_ptr<ViEWrapper> vie_wrapper_;
223 bool vie_wrapper_base_initialized_;
224 talk_base::scoped_ptr<ViETraceWrapper> tracing_;
225 WebRtcVoiceEngine* voice_engine_;
226 talk_base::scoped_ptr<webrtc::VideoRender> render_module_;
227 WebRtcVideoEncoderFactory* encoder_factory_;
228 WebRtcVideoDecoderFactory* decoder_factory_;
229 std::vector<VideoCodec> video_codecs_;
230 std::vector<RtpHeaderExtension> rtp_header_extensions_;
231 VideoFormat default_codec_format_;
232
233 bool initialized_;
234 talk_base::CriticalSection channels_crit_;
235 VideoChannels channels_;
236
237 VideoCapturer* video_capturer_;
238 int frame_listeners_;
239 bool capture_started_;
240 int local_renderer_w_;
241 int local_renderer_h_;
242 VideoRenderer* local_renderer_;
243
244 // Critical section to protect the media processor register/unregister
245 // while processing a frame
246 talk_base::CriticalSection signal_media_critical_;
247
248 talk_base::scoped_ptr<talk_base::CpuMonitor> cpu_monitor_;
249};
250
251class WebRtcVideoMediaChannel : public talk_base::MessageHandler,
252 public VideoMediaChannel,
253 public webrtc::Transport {
254 public:
255 WebRtcVideoMediaChannel(WebRtcVideoEngine* engine,
256 VoiceMediaChannel* voice_channel);
257 ~WebRtcVideoMediaChannel();
258 bool Init();
259
260 WebRtcVideoEngine* engine() { return engine_; }
261 VoiceMediaChannel* voice_channel() { return voice_channel_; }
262 int video_channel() const { return vie_channel_; }
263 bool sending() const { return sending_; }
264
265 // VideoMediaChannel implementation
266 virtual bool SetRecvCodecs(const std::vector<VideoCodec> &codecs);
267 virtual bool SetSendCodecs(const std::vector<VideoCodec> &codecs);
268 virtual bool GetSendCodec(VideoCodec* send_codec);
269 virtual bool SetSendStreamFormat(uint32 ssrc, const VideoFormat& format);
270 virtual bool SetRender(bool render);
271 virtual bool SetSend(bool send);
272
273 virtual bool AddSendStream(const StreamParams& sp);
274 virtual bool RemoveSendStream(uint32 ssrc);
275 virtual bool AddRecvStream(const StreamParams& sp);
276 virtual bool RemoveRecvStream(uint32 ssrc);
277 virtual bool SetRenderer(uint32 ssrc, VideoRenderer* renderer);
278 virtual bool GetStats(VideoMediaInfo* info);
279 virtual bool SetCapturer(uint32 ssrc, VideoCapturer* capturer);
280 virtual bool SendIntraFrame();
281 virtual bool RequestIntraFrame();
282
283 virtual void OnPacketReceived(talk_base::Buffer* packet);
284 virtual void OnRtcpReceived(talk_base::Buffer* packet);
285 virtual void OnReadyToSend(bool ready);
286 virtual bool MuteStream(uint32 ssrc, bool on);
287 virtual bool SetRecvRtpHeaderExtensions(
288 const std::vector<RtpHeaderExtension>& extensions);
289 virtual bool SetSendRtpHeaderExtensions(
290 const std::vector<RtpHeaderExtension>& extensions);
291 virtual bool SetSendBandwidth(bool autobw, int bps);
292 virtual bool SetOptions(const VideoOptions &options);
293 virtual bool GetOptions(VideoOptions *options) const {
294 *options = options_;
295 return true;
296 }
297 virtual void SetInterface(NetworkInterface* iface);
298 virtual void UpdateAspectRatio(int ratio_w, int ratio_h);
299
300 // Public functions for use by tests and other specialized code.
301 uint32 send_ssrc() const { return 0; }
302 bool GetRenderer(uint32 ssrc, VideoRenderer** renderer);
303 void SendFrame(VideoCapturer* capturer, const VideoFrame* frame);
304 bool SendFrame(WebRtcVideoChannelSendInfo* channel_info,
305 const VideoFrame* frame, bool is_screencast);
306
307 void AdaptAndSendFrame(VideoCapturer* capturer, const VideoFrame* frame);
308
309 // Thunk functions for use with HybridVideoEngine
310 void OnLocalFrame(VideoCapturer* capturer, const VideoFrame* frame) {
311 SendFrame(0u, frame, capturer->IsScreencast());
312 }
313 void OnLocalFrameFormat(VideoCapturer* capturer, const VideoFormat* format) {
314 }
315
316 virtual void OnMessage(talk_base::Message* msg);
317
318 protected:
319 int GetLastEngineError() { return engine()->GetLastEngineError(); }
320 virtual int SendPacket(int channel, const void* data, int len);
321 virtual int SendRTCPPacket(int channel, const void* data, int len);
322
323 private:
324 typedef std::map<uint32, WebRtcVideoChannelRecvInfo*> RecvChannelMap;
325 typedef std::map<uint32, WebRtcVideoChannelSendInfo*> SendChannelMap;
326 typedef int (webrtc::ViERTP_RTCP::* ExtensionSetterFunction)(int, bool, int);
327
328 enum MediaDirection { MD_RECV, MD_SEND, MD_SENDRECV };
329
330 // Creates and initializes a ViE channel. When successful |channel_id| will
331 // contain the new channel's ID. If |receiving| is true |ssrc| is the
332 // remote ssrc. If |sending| is true the ssrc is local ssrc. If both
333 // |receiving| and |sending| is true the ssrc must be 0 and the channel will
334 // be created as a default channel. The ssrc must be different for receive
335 // channels and it must be different for send channels. If the same SSRC is
336 // being used for creating channel more than once, this function will fail
337 // returning false.
338 bool CreateChannel(uint32 ssrc_key, MediaDirection direction,
339 int* channel_id);
340 bool ConfigureChannel(int channel_id, MediaDirection direction,
341 uint32 ssrc_key);
342 bool ConfigureReceiving(int channel_id, uint32 remote_ssrc_key);
343 bool ConfigureSending(int channel_id, uint32 local_ssrc_key);
344 bool SetNackFec(int channel_id, int red_payload_type, int fec_payload_type,
345 bool nack_enabled);
346 bool SetSendCodec(const webrtc::VideoCodec& codec, int min_bitrate,
347 int start_bitrate, int max_bitrate);
348 bool SetSendCodec(WebRtcVideoChannelSendInfo* send_channel,
349 const webrtc::VideoCodec& codec, int min_bitrate,
350 int start_bitrate, int max_bitrate);
351 void LogSendCodecChange(const std::string& reason);
352 // Prepares the channel with channel id |info->channel_id()| to receive all
353 // codecs in |receive_codecs_| and start receive packets.
354 bool SetReceiveCodecs(WebRtcVideoChannelRecvInfo* info);
355 // Returns the channel number that receives the stream with SSRC |ssrc|.
356 int GetRecvChannelNum(uint32 ssrc);
357 // Given captured video frame size, checks if we need to reset vie send codec.
358 // |reset| is set to whether resetting has happened on vie or not.
359 // Returns false on error.
360 bool MaybeResetVieSendCodec(WebRtcVideoChannelSendInfo* send_channel,
361 int new_width, int new_height, bool is_screencast,
362 bool* reset);
363 // Checks the current bitrate estimate and modifies the start bitrate
364 // accordingly.
365 void MaybeChangeStartBitrate(int channel_id, webrtc::VideoCodec* video_codec);
366 // Helper function for starting the sending of media on all channels or
367 // |channel_id|. Note that these two function do not change |sending_|.
368 bool StartSend();
369 bool StartSend(WebRtcVideoChannelSendInfo* send_channel);
370 // Helper function for stop the sending of media on all channels or
371 // |channel_id|. Note that these two function do not change |sending_|.
372 bool StopSend();
373 bool StopSend(WebRtcVideoChannelSendInfo* send_channel);
374 bool SendIntraFrame(int channel_id);
375
376 // Send with one local SSRC. Normal case.
377 bool IsOneSsrcStream(const StreamParams& sp);
378
379 bool HasReadySendChannels();
380
381 // Send channel key returns the key corresponding to the provided local SSRC
382 // in |key|. The return value is true upon success.
383 // If the local ssrc correspond to that of the default channel the key is 0.
384 // For all other channels the returned key will be the same as the local ssrc.
385 bool GetSendChannelKey(uint32 local_ssrc, uint32* key);
386 WebRtcVideoChannelSendInfo* GetSendChannel(VideoCapturer* video_capturer);
387 WebRtcVideoChannelSendInfo* GetSendChannel(uint32 local_ssrc);
388 // Creates a new unique key that can be used for inserting a new send channel
389 // into |send_channels_|
390 bool CreateSendChannelKey(uint32 local_ssrc, uint32* key);
391
392 bool IsDefaultChannel(int channel_id) const {
393 return channel_id == vie_channel_;
394 }
395 uint32 GetDefaultChannelSsrc();
396
397 bool DeleteSendChannel(uint32 ssrc_key);
398
399 bool InConferenceMode() const {
400 return options_.conference_mode.GetWithDefaultIfUnset(false);
401 }
402 bool RemoveCapturer(uint32 ssrc);
403
404
405 talk_base::MessageQueue* worker_thread() { return engine_->worker_thread(); }
406 void QueueBlackFrame(uint32 ssrc, int64 timestamp, int framerate);
407 void FlushBlackFrame(uint32 ssrc, int64 timestamp);
408
409 void SetNetworkTransmissionState(bool is_transmitting);
410
411 bool SetHeaderExtension(ExtensionSetterFunction setter, int channel_id,
412 const RtpHeaderExtension* extension);
413 bool SetHeaderExtension(ExtensionSetterFunction setter, int channel_id,
414 const std::vector<RtpHeaderExtension>& extensions,
415 const char header_extension_uri[]);
416
417 // Global state.
418 WebRtcVideoEngine* engine_;
419 VoiceMediaChannel* voice_channel_;
420 int vie_channel_;
421 bool nack_enabled_;
422 // Receiver Estimated Max Bitrate
423 bool remb_enabled_;
424 VideoOptions options_;
425
426 // Global recv side state.
427 // Note the default channel (vie_channel_), i.e. the send channel
428 // corresponding to all the receive channels (this must be done for REMB to
429 // work properly), resides in both recv_channels_ and send_channels_ with the
430 // ssrc key 0.
431 RecvChannelMap recv_channels_; // Contains all receive channels.
432 std::vector<webrtc::VideoCodec> receive_codecs_;
433 bool render_started_;
434 uint32 first_receive_ssrc_;
435 std::vector<RtpHeaderExtension> receive_extensions_;
436
437 // Global send side state.
438 SendChannelMap send_channels_;
439 talk_base::scoped_ptr<webrtc::VideoCodec> send_codec_;
440 int send_red_type_;
441 int send_fec_type_;
442 int send_min_bitrate_;
443 int send_start_bitrate_;
444 int send_max_bitrate_;
445 bool sending_;
446 std::vector<RtpHeaderExtension> send_extensions_;
447
448 // The aspect ratio that the channel desires. 0 means there is no desired
449 // aspect ratio
450 int ratio_w_;
451 int ratio_h_;
452};
453
454} // namespace cricket
455
456#endif // TALK_MEDIA_WEBRTCVIDEOENGINE_H_