blob: 95cb9e95f59ec5161d10aa8ade6874f6ae689084 [file] [log] [blame]
jlmiller@webrtc.org5f93d0a2015-01-20 21:36:13 +00001/*
2 * libjingle
3 * Copyright 2010 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
henrike@webrtc.org28e20752013-07-10 00:45:36 +000028// Declaration of abstract class VideoCapturer
29
30#ifndef TALK_MEDIA_BASE_VIDEOCAPTURER_H_
31#define TALK_MEDIA_BASE_VIDEOCAPTURER_H_
32
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000033#include <algorithm>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000034#include <string>
35#include <vector>
36
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000037#include "talk/media/base/mediachannel.h"
38#include "talk/media/base/videoadapter.h"
39#include "talk/media/base/videocommon.h"
40#include "talk/media/base/videoframefactory.h"
41#include "talk/media/devices/devicemanager.h"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000042#include "webrtc/base/basictypes.h"
43#include "webrtc/base/criticalsection.h"
44#include "webrtc/base/messagehandler.h"
45#include "webrtc/base/rollingaccumulator.h"
46#include "webrtc/base/scoped_ptr.h"
47#include "webrtc/base/sigslot.h"
48#include "webrtc/base/thread.h"
49#include "webrtc/base/timing.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000050
51
52namespace cricket {
53
henrike@webrtc.org28e20752013-07-10 00:45:36 +000054// Current state of the capturer.
55// TODO(hellner): CS_NO_DEVICE is an error code not a capture state. Separate
56// error codes and states.
57enum CaptureState {
58 CS_STOPPED, // The capturer has been stopped or hasn't started yet.
59 CS_STARTING, // The capturer is in the process of starting. Note, it may
60 // still fail to start.
61 CS_RUNNING, // The capturer has been started successfully and is now
62 // capturing.
63 CS_PAUSED, // The capturer has been paused.
64 CS_FAILED, // The capturer failed to start.
65 CS_NO_DEVICE, // The capturer has no device and consequently failed to start.
66};
67
68class VideoFrame;
69
70struct CapturedFrame {
71 static const uint32 kFrameHeaderSize = 40; // Size from width to data_size.
72 static const uint32 kUnknownDataSize = 0xFFFFFFFF;
73
74 CapturedFrame();
75
76 // Get the number of bytes of the frame data. If data_size is known, return
77 // it directly. Otherwise, calculate the size based on width, height, and
78 // fourcc. Return true if succeeded.
79 bool GetDataSize(uint32* size) const;
80
guoweis@webrtc.org6c930c72015-02-09 01:28:12 +000081 // TODO(guoweis): Change the type of |rotation| from int to
82 // webrtc::VideoRotation once chromium gets the code.
83 webrtc::VideoRotation GetRotation() const;
84
henrike@webrtc.org28e20752013-07-10 00:45:36 +000085 // The width and height of the captured frame could be different from those
86 // of VideoFormat. Once the first frame is captured, the width, height,
87 // fourcc, pixel_width, and pixel_height should keep the same over frames.
88 int width; // in number of pixels
89 int height; // in number of pixels
90 uint32 fourcc; // compression
91 uint32 pixel_width; // width of a pixel, default is 1
92 uint32 pixel_height; // height of a pixel, default is 1
93 int64 elapsed_time; // elapsed time since the creation of the frame
94 // source (that is, the camera), in nanoseconds.
95 int64 time_stamp; // timestamp of when the frame was captured, in unix
96 // time with nanosecond units.
97 uint32 data_size; // number of bytes of the frame data
guoweis@webrtc.org6c930c72015-02-09 01:28:12 +000098
99 // TODO(guoweis): This can't be converted to VideoRotation yet as it's
100 // used by chrome now.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000101 int rotation; // rotation in degrees of the frame (0, 90, 180, 270)
guoweis@webrtc.org6c930c72015-02-09 01:28:12 +0000102
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103 void* data; // pointer to the frame data. This object allocates the
104 // memory or points to an existing memory.
105
106 private:
henrikg3c089d72015-09-16 05:37:44 -0700107 RTC_DISALLOW_COPY_AND_ASSIGN(CapturedFrame);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108};
109
110// VideoCapturer is an abstract class that defines the interfaces for video
111// capturing. The subclasses implement the video capturer for various types of
112// capturers and various platforms.
113//
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000114// The captured frames may need to be adapted (for example, cropping).
115// Video adaptation is built into and enabled by default. After a frame has
Magnus Jedvertc2320962015-08-21 11:40:30 +0200116// been captured from the device, it is sent to the video adapter, then out to
117// the encoder.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000118//
119// Programming model:
120// Create an object of a subclass of VideoCapturer
121// Initialize
122// SignalStateChange.connect()
123// SignalFrameCaptured.connect()
124// Find the capture format for Start() by either calling GetSupportedFormats()
125// and selecting one of the supported or calling GetBestCaptureFormat().
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000126// video_adapter()->OnOutputFormatRequest(desired_encoding_format)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000127// Start()
128// GetCaptureFormat() optionally
129// Stop()
130//
131// Assumption:
132// The Start() and Stop() methods are called by a single thread (E.g., the
133// media engine thread). Hence, the VideoCapture subclasses dont need to be
134// thread safe.
135//
136class VideoCapturer
137 : public sigslot::has_slots<>,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000138 public rtc::MessageHandler {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000139 public:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000140 // All signals are marshalled to |thread| or the creating thread if
141 // none is provided.
142 VideoCapturer();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000143 explicit VideoCapturer(rtc::Thread* thread);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000144 virtual ~VideoCapturer() {}
145
146 // Gets the id of the underlying device, which is available after the capturer
147 // is initialized. Can be used to determine if two capturers reference the
148 // same device.
149 const std::string& GetId() const { return id_; }
150
151 // Get the capture formats supported by the video capturer. The supported
152 // formats are non empty after the device has been opened successfully.
153 const std::vector<VideoFormat>* GetSupportedFormats() const;
154
155 // Get the best capture format for the desired format. The best format is the
156 // same as one of the supported formats except that the frame interval may be
157 // different. If the application asks for 16x9 and the camera does not support
158 // 16x9 HD or the application asks for 16x10, we find the closest 4x3 and then
159 // crop; Otherwise, we find what the application asks for. Note that we assume
160 // that for HD, the desired format is always 16x9. The subclasses can override
161 // the default implementation.
162 // Parameters
163 // desired: the input desired format. If desired.fourcc is not kAnyFourcc,
164 // the best capture format has the exactly same fourcc. Otherwise,
165 // the best capture format uses a fourcc in GetPreferredFourccs().
166 // best_format: the output of the best capture format.
167 // Return false if there is no such a best format, that is, the desired format
168 // is not supported.
169 virtual bool GetBestCaptureFormat(const VideoFormat& desired,
170 VideoFormat* best_format);
171
172 // TODO(hellner): deprecate (make private) the Start API in favor of this one.
173 // Also remove CS_STARTING as it is implied by the return
174 // value of StartCapturing().
175 bool StartCapturing(const VideoFormat& capture_format);
176 // Start the video capturer with the specified capture format.
177 // Parameter
178 // capture_format: The caller got this parameter by either calling
179 // GetSupportedFormats() and selecting one of the supported
180 // or calling GetBestCaptureFormat().
181 // Return
182 // CS_STARTING: The capturer is trying to start. Success or failure will
183 // be notified via the |SignalStateChange| callback.
184 // CS_RUNNING: if the capturer is started and capturing.
185 // CS_PAUSED: Will never be returned.
186 // CS_FAILED: if the capturer failes to start..
187 // CS_NO_DEVICE: if the capturer has no device and fails to start.
188 virtual CaptureState Start(const VideoFormat& capture_format) = 0;
189 // Sets the desired aspect ratio. If the capturer is capturing at another
190 // aspect ratio it will crop the width or the height so that asked for
191 // aspect ratio is acheived. Note that ratio_w and ratio_h do not need to be
192 // relatively prime.
193 void UpdateAspectRatio(int ratio_w, int ratio_h);
194 void ClearAspectRatio();
195
196 // Get the current capture format, which is set by the Start() call.
197 // Note that the width and height of the captured frames may differ from the
198 // capture format. For example, the capture format is HD but the captured
199 // frames may be smaller than HD.
200 const VideoFormat* GetCaptureFormat() const {
201 return capture_format_.get();
202 }
203
204 // Pause the video capturer.
205 virtual bool Pause(bool paused);
206 // Stop the video capturer.
207 virtual void Stop() = 0;
208 // Check if the video capturer is running.
209 virtual bool IsRunning() = 0;
210 // Restart the video capturer with the new |capture_format|.
211 // Default implementation stops and starts the capturer.
212 virtual bool Restart(const VideoFormat& capture_format);
213 // TODO(thorcarpenter): This behavior of keeping the camera open just to emit
214 // black frames is a total hack and should be fixed.
215 // When muting, produce black frames then pause the camera.
216 // When unmuting, start the camera. Camera starts unmuted.
217 virtual bool MuteToBlackThenPause(bool muted);
218 virtual bool IsMuted() const {
219 return muted_;
220 }
221 CaptureState capture_state() const {
222 return capture_state_;
223 }
224
guoweis@webrtc.org1226e922015-02-11 18:37:54 +0000225 // Tells videocapturer whether to apply the pending rotation. By default, the
226 // rotation is applied and the generated frame is up right. When set to false,
227 // generated frames will carry the rotation information from
228 // SetCaptureRotation. Return value indicates whether this operation succeeds.
229 virtual bool SetApplyRotation(bool enable);
230 virtual bool GetApplyRotation() { return apply_rotation_; }
231
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000232 // Returns true if the capturer is screencasting. This can be used to
233 // implement screencast specific behavior.
234 virtual bool IsScreencast() const = 0;
235
236 // Caps the VideoCapturer's format according to max_format. It can e.g. be
237 // used to prevent cameras from capturing at a resolution or framerate that
238 // the capturer is capable of but not performing satisfactorily at.
239 // The capping is an upper bound for each component of the capturing format.
240 // The fourcc component is ignored.
241 void ConstrainSupportedFormats(const VideoFormat& max_format);
242
243 void set_enable_camera_list(bool enable_camera_list) {
244 enable_camera_list_ = enable_camera_list;
245 }
246 bool enable_camera_list() {
247 return enable_camera_list_;
248 }
mallinath@webrtc.org1b15f422013-09-06 22:56:28 +0000249
250 // Enable scaling to ensure square pixels.
251 void set_square_pixel_aspect_ratio(bool square_pixel_aspect_ratio) {
252 square_pixel_aspect_ratio_ = square_pixel_aspect_ratio;
253 }
254 bool square_pixel_aspect_ratio() {
255 return square_pixel_aspect_ratio_;
256 }
257
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000258 // Signal all capture state changes that are not a direct result of calling
259 // Start().
260 sigslot::signal2<VideoCapturer*, CaptureState> SignalStateChange;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000261 // Frame callbacks are multithreaded to allow disconnect and connect to be
262 // called concurrently. It also ensures that it is safe to call disconnect
263 // at any time which is needed since the signal may be called from an
264 // unmarshalled thread owned by the VideoCapturer.
265 // Signal the captured frame to downstream.
266 sigslot::signal2<VideoCapturer*, const CapturedFrame*,
267 sigslot::multi_threaded_local> SignalFrameCaptured;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000268 // Signal the captured and possibly adapted frame to downstream consumers
269 // such as the encoder.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000270 sigslot::signal2<VideoCapturer*, const VideoFrame*,
271 sigslot::multi_threaded_local> SignalVideoFrame;
272
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000273 // If 'screencast_max_pixels' is set greater than zero, screencasts will be
274 // scaled to be no larger than this value.
275 // If set to zero, the max pixels will be limited to
276 // Retina MacBookPro 15" resolution of 2880 x 1800.
277 // For high fps, maximum pixels limit is set based on common 24" monitor
278 // resolution of 2048 x 1280.
279 int screencast_max_pixels() const { return screencast_max_pixels_; }
280 void set_screencast_max_pixels(int p) {
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000281 screencast_max_pixels_ = std::max(0, p);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000282 }
283
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000284 // If true, run video adaptation. By default, video adaptation is enabled
285 // and users must call video_adapter()->OnOutputFormatRequest()
286 // to receive frames.
287 bool enable_video_adapter() const { return enable_video_adapter_; }
288 void set_enable_video_adapter(bool enable_video_adapter) {
289 enable_video_adapter_ = enable_video_adapter;
290 }
291
292 CoordinatedVideoAdapter* video_adapter() { return &video_adapter_; }
293 const CoordinatedVideoAdapter* video_adapter() const {
294 return &video_adapter_;
295 }
296
buildbot@webrtc.org4f0d4012014-08-07 04:47:36 +0000297 // Takes ownership.
guoweis@webrtc.org1226e922015-02-11 18:37:54 +0000298 void set_frame_factory(VideoFrameFactory* frame_factory);
buildbot@webrtc.org4f0d4012014-08-07 04:47:36 +0000299
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000300 // Gets statistics for tracked variables recorded since the last call to
301 // GetStats. Note that calling GetStats resets any gathered data so it
302 // should be called only periodically to log statistics.
303 void GetStats(VariableInfo<int>* adapt_drop_stats,
304 VariableInfo<int>* effect_drop_stats,
buildbot@webrtc.org0b53bd22014-05-06 17:12:36 +0000305 VariableInfo<double>* frame_time_stats,
306 VideoFormat* last_captured_frame_format);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000307
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000308 protected:
309 // Callback attached to SignalFrameCaptured where SignalVideoFrames is called.
310 void OnFrameCaptured(VideoCapturer* video_capturer,
311 const CapturedFrame* captured_frame);
312 void SetCaptureState(CaptureState state);
313
314 // Marshals SignalStateChange onto thread_.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000315 void OnMessage(rtc::Message* message);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000316
317 // subclasses override this virtual method to provide a vector of fourccs, in
318 // order of preference, that are expected by the media engine.
319 virtual bool GetPreferredFourccs(std::vector<uint32>* fourccs) = 0;
320
321 // mutators to set private attributes
322 void SetId(const std::string& id) {
323 id_ = id;
324 }
325
326 void SetCaptureFormat(const VideoFormat* format) {
327 capture_format_.reset(format ? new VideoFormat(*format) : NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000328 if (capture_format_) {
329 ASSERT(capture_format_->interval > 0 &&
330 "Capture format expected to have positive interval.");
331 // Video adapter really only cares about capture format interval.
332 video_adapter_.SetInputFormat(*capture_format_);
333 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000334 }
335
336 void SetSupportedFormats(const std::vector<VideoFormat>& formats);
buildbot@webrtc.org4f0d4012014-08-07 04:47:36 +0000337 VideoFrameFactory* frame_factory() { return frame_factory_.get(); }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000338
339 private:
340 void Construct();
341 // Get the distance between the desired format and the supported format.
342 // Return the max distance if they mismatch. See the implementation for
343 // details.
344 int64 GetFormatDistance(const VideoFormat& desired,
345 const VideoFormat& supported);
346
347 // Convert captured frame to readable string for LOG messages.
348 std::string ToString(const CapturedFrame* frame) const;
349
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000350 // Updates filtered_supported_formats_ so that it contains the formats in
351 // supported_formats_ that fulfill all applied restrictions.
352 void UpdateFilteredSupportedFormats();
353 // Returns true if format doesn't fulfill all applied restrictions.
354 bool ShouldFilterFormat(const VideoFormat& format) const;
355
buildbot@webrtc.org0b53bd22014-05-06 17:12:36 +0000356 void UpdateStats(const CapturedFrame* captured_frame);
357
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000358 // Helper function to save statistics on the current data from a
359 // RollingAccumulator into stats.
360 template<class T>
361 static void GetVariableSnapshot(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000362 const rtc::RollingAccumulator<T>& data,
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000363 VariableInfo<T>* stats);
364
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000365 rtc::Thread* thread_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000366 std::string id_;
367 CaptureState capture_state_;
buildbot@webrtc.org4f0d4012014-08-07 04:47:36 +0000368 rtc::scoped_ptr<VideoFrameFactory> frame_factory_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000369 rtc::scoped_ptr<VideoFormat> capture_format_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000370 std::vector<VideoFormat> supported_formats_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000371 rtc::scoped_ptr<VideoFormat> max_format_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000372 std::vector<VideoFormat> filtered_supported_formats_;
373
374 int ratio_w_; // View resolution. e.g. 1280 x 720.
375 int ratio_h_;
376 bool enable_camera_list_;
mallinath@webrtc.org1b15f422013-09-06 22:56:28 +0000377 bool square_pixel_aspect_ratio_; // Enable scaling to square pixels.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000378 int scaled_width_; // Current output size from ComputeScale.
379 int scaled_height_;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000380 int screencast_max_pixels_; // Downscale screencasts further if requested.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000381 bool muted_;
382 int black_frame_count_down_;
383
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000384 bool enable_video_adapter_;
385 CoordinatedVideoAdapter video_adapter_;
386
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000387 rtc::Timing frame_length_time_reporter_;
388 rtc::CriticalSection frame_stats_crit_;
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000389
390 int adapt_frame_drops_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000391 rtc::RollingAccumulator<int> adapt_frame_drops_data_;
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000392 double previous_frame_time_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000393 rtc::RollingAccumulator<double> frame_time_data_;
buildbot@webrtc.org0b53bd22014-05-06 17:12:36 +0000394 // The captured frame format before potential adapation.
395 VideoFormat last_captured_frame_format_;
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000396
guoweis@webrtc.org1226e922015-02-11 18:37:54 +0000397 // Whether capturer should apply rotation to the frame before signaling it.
398 bool apply_rotation_;
399
henrikg3c089d72015-09-16 05:37:44 -0700400 RTC_DISALLOW_COPY_AND_ASSIGN(VideoCapturer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000401};
402
403} // namespace cricket
404
405#endif // TALK_MEDIA_BASE_VIDEOCAPTURER_H_