blob: 37b37ba7be33a150bfd573a2d8d2a9c643788301 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001// libjingle
2// Copyright 2010 Google Inc.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are met:
6//
7// 1. Redistributions of source code must retain the above copyright notice,
8// this list of conditions and the following disclaimer.
9// 2. Redistributions in binary form must reproduce the above copyright notice,
10// this list of conditions and the following disclaimer in the documentation
11// and/or other materials provided with the distribution.
12// 3. The name of the author may not be used to endorse or promote products
13// derived from this software without specific prior written permission.
14//
15// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
16// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
17// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
18// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
19// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
21// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
22// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
23// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
24// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25//
26// Declaration of abstract class VideoCapturer
27
28#ifndef TALK_MEDIA_BASE_VIDEOCAPTURER_H_
29#define TALK_MEDIA_BASE_VIDEOCAPTURER_H_
30
31#include <string>
32#include <vector>
33
34#include "talk/base/basictypes.h"
35#include "talk/base/criticalsection.h"
36#include "talk/base/messagehandler.h"
37#include "talk/base/scoped_ptr.h"
38#include "talk/base/sigslot.h"
39#include "talk/base/thread.h"
henrike@webrtc.orga7b98182014-02-21 15:51:43 +000040#include "talk/media/base/videoadapter.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000041#include "talk/media/base/videocommon.h"
42#include "talk/media/devices/devicemanager.h"
43
44
45namespace cricket {
46
47class VideoProcessor;
48
49// Current state of the capturer.
50// TODO(hellner): CS_NO_DEVICE is an error code not a capture state. Separate
51// error codes and states.
52enum CaptureState {
53 CS_STOPPED, // The capturer has been stopped or hasn't started yet.
54 CS_STARTING, // The capturer is in the process of starting. Note, it may
55 // still fail to start.
56 CS_RUNNING, // The capturer has been started successfully and is now
57 // capturing.
58 CS_PAUSED, // The capturer has been paused.
59 CS_FAILED, // The capturer failed to start.
60 CS_NO_DEVICE, // The capturer has no device and consequently failed to start.
61};
62
63class VideoFrame;
64
65struct CapturedFrame {
66 static const uint32 kFrameHeaderSize = 40; // Size from width to data_size.
67 static const uint32 kUnknownDataSize = 0xFFFFFFFF;
68
69 CapturedFrame();
70
71 // Get the number of bytes of the frame data. If data_size is known, return
72 // it directly. Otherwise, calculate the size based on width, height, and
73 // fourcc. Return true if succeeded.
74 bool GetDataSize(uint32* size) const;
75
76 // The width and height of the captured frame could be different from those
77 // of VideoFormat. Once the first frame is captured, the width, height,
78 // fourcc, pixel_width, and pixel_height should keep the same over frames.
79 int width; // in number of pixels
80 int height; // in number of pixels
81 uint32 fourcc; // compression
82 uint32 pixel_width; // width of a pixel, default is 1
83 uint32 pixel_height; // height of a pixel, default is 1
84 int64 elapsed_time; // elapsed time since the creation of the frame
85 // source (that is, the camera), in nanoseconds.
86 int64 time_stamp; // timestamp of when the frame was captured, in unix
87 // time with nanosecond units.
88 uint32 data_size; // number of bytes of the frame data
89 int rotation; // rotation in degrees of the frame (0, 90, 180, 270)
90 void* data; // pointer to the frame data. This object allocates the
91 // memory or points to an existing memory.
92
93 private:
94 DISALLOW_COPY_AND_ASSIGN(CapturedFrame);
95};
96
97// VideoCapturer is an abstract class that defines the interfaces for video
98// capturing. The subclasses implement the video capturer for various types of
99// capturers and various platforms.
100//
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000101// The captured frames may need to be adapted (for example, cropping).
102// Video adaptation is built into and enabled by default. After a frame has
103// been captured from the device, it is sent to the video adapter, then video
104// processors, then out to the encoder.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105//
106// Programming model:
107// Create an object of a subclass of VideoCapturer
108// Initialize
109// SignalStateChange.connect()
110// SignalFrameCaptured.connect()
111// Find the capture format for Start() by either calling GetSupportedFormats()
112// and selecting one of the supported or calling GetBestCaptureFormat().
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000113// video_adapter()->OnOutputFormatRequest(desired_encoding_format)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000114// Start()
115// GetCaptureFormat() optionally
116// Stop()
117//
118// Assumption:
119// The Start() and Stop() methods are called by a single thread (E.g., the
120// media engine thread). Hence, the VideoCapture subclasses dont need to be
121// thread safe.
122//
123class VideoCapturer
124 : public sigslot::has_slots<>,
125 public talk_base::MessageHandler {
126 public:
127 typedef std::vector<VideoProcessor*> VideoProcessors;
128
129 // All signals are marshalled to |thread| or the creating thread if
130 // none is provided.
131 VideoCapturer();
132 explicit VideoCapturer(talk_base::Thread* thread);
133 virtual ~VideoCapturer() {}
134
135 // Gets the id of the underlying device, which is available after the capturer
136 // is initialized. Can be used to determine if two capturers reference the
137 // same device.
138 const std::string& GetId() const { return id_; }
139
140 // Get the capture formats supported by the video capturer. The supported
141 // formats are non empty after the device has been opened successfully.
142 const std::vector<VideoFormat>* GetSupportedFormats() const;
143
144 // Get the best capture format for the desired format. The best format is the
145 // same as one of the supported formats except that the frame interval may be
146 // different. If the application asks for 16x9 and the camera does not support
147 // 16x9 HD or the application asks for 16x10, we find the closest 4x3 and then
148 // crop; Otherwise, we find what the application asks for. Note that we assume
149 // that for HD, the desired format is always 16x9. The subclasses can override
150 // the default implementation.
151 // Parameters
152 // desired: the input desired format. If desired.fourcc is not kAnyFourcc,
153 // the best capture format has the exactly same fourcc. Otherwise,
154 // the best capture format uses a fourcc in GetPreferredFourccs().
155 // best_format: the output of the best capture format.
156 // Return false if there is no such a best format, that is, the desired format
157 // is not supported.
158 virtual bool GetBestCaptureFormat(const VideoFormat& desired,
159 VideoFormat* best_format);
160
161 // TODO(hellner): deprecate (make private) the Start API in favor of this one.
162 // Also remove CS_STARTING as it is implied by the return
163 // value of StartCapturing().
164 bool StartCapturing(const VideoFormat& capture_format);
165 // Start the video capturer with the specified capture format.
166 // Parameter
167 // capture_format: The caller got this parameter by either calling
168 // GetSupportedFormats() and selecting one of the supported
169 // or calling GetBestCaptureFormat().
170 // Return
171 // CS_STARTING: The capturer is trying to start. Success or failure will
172 // be notified via the |SignalStateChange| callback.
173 // CS_RUNNING: if the capturer is started and capturing.
174 // CS_PAUSED: Will never be returned.
175 // CS_FAILED: if the capturer failes to start..
176 // CS_NO_DEVICE: if the capturer has no device and fails to start.
177 virtual CaptureState Start(const VideoFormat& capture_format) = 0;
178 // Sets the desired aspect ratio. If the capturer is capturing at another
179 // aspect ratio it will crop the width or the height so that asked for
180 // aspect ratio is acheived. Note that ratio_w and ratio_h do not need to be
181 // relatively prime.
182 void UpdateAspectRatio(int ratio_w, int ratio_h);
183 void ClearAspectRatio();
184
185 // Get the current capture format, which is set by the Start() call.
186 // Note that the width and height of the captured frames may differ from the
187 // capture format. For example, the capture format is HD but the captured
188 // frames may be smaller than HD.
189 const VideoFormat* GetCaptureFormat() const {
190 return capture_format_.get();
191 }
192
193 // Pause the video capturer.
194 virtual bool Pause(bool paused);
195 // Stop the video capturer.
196 virtual void Stop() = 0;
197 // Check if the video capturer is running.
198 virtual bool IsRunning() = 0;
199 // Restart the video capturer with the new |capture_format|.
200 // Default implementation stops and starts the capturer.
201 virtual bool Restart(const VideoFormat& capture_format);
202 // TODO(thorcarpenter): This behavior of keeping the camera open just to emit
203 // black frames is a total hack and should be fixed.
204 // When muting, produce black frames then pause the camera.
205 // When unmuting, start the camera. Camera starts unmuted.
206 virtual bool MuteToBlackThenPause(bool muted);
207 virtual bool IsMuted() const {
208 return muted_;
209 }
210 CaptureState capture_state() const {
211 return capture_state_;
212 }
213
214 // Adds a video processor that will be applied on VideoFrames returned by
215 // |SignalVideoFrame|. Multiple video processors can be added. The video
216 // processors will be applied in the order they were added.
217 void AddVideoProcessor(VideoProcessor* video_processor);
218 // Removes the |video_processor| from the list of video processors or
219 // returns false.
220 bool RemoveVideoProcessor(VideoProcessor* video_processor);
221
222 // Returns true if the capturer is screencasting. This can be used to
223 // implement screencast specific behavior.
224 virtual bool IsScreencast() const = 0;
225
226 // Caps the VideoCapturer's format according to max_format. It can e.g. be
227 // used to prevent cameras from capturing at a resolution or framerate that
228 // the capturer is capable of but not performing satisfactorily at.
229 // The capping is an upper bound for each component of the capturing format.
230 // The fourcc component is ignored.
231 void ConstrainSupportedFormats(const VideoFormat& max_format);
232
233 void set_enable_camera_list(bool enable_camera_list) {
234 enable_camera_list_ = enable_camera_list;
235 }
236 bool enable_camera_list() {
237 return enable_camera_list_;
238 }
mallinath@webrtc.org1b15f422013-09-06 22:56:28 +0000239
240 // Enable scaling to ensure square pixels.
241 void set_square_pixel_aspect_ratio(bool square_pixel_aspect_ratio) {
242 square_pixel_aspect_ratio_ = square_pixel_aspect_ratio;
243 }
244 bool square_pixel_aspect_ratio() {
245 return square_pixel_aspect_ratio_;
246 }
247
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000248 // Signal all capture state changes that are not a direct result of calling
249 // Start().
250 sigslot::signal2<VideoCapturer*, CaptureState> SignalStateChange;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000251 // Frame callbacks are multithreaded to allow disconnect and connect to be
252 // called concurrently. It also ensures that it is safe to call disconnect
253 // at any time which is needed since the signal may be called from an
254 // unmarshalled thread owned by the VideoCapturer.
255 // Signal the captured frame to downstream.
256 sigslot::signal2<VideoCapturer*, const CapturedFrame*,
257 sigslot::multi_threaded_local> SignalFrameCaptured;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000258 // Signal the captured and possibly adapted frame to downstream consumers
259 // such as the encoder.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000260 sigslot::signal2<VideoCapturer*, const VideoFrame*,
261 sigslot::multi_threaded_local> SignalVideoFrame;
262
263 const VideoProcessors& video_processors() const { return video_processors_; }
264
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000265 // If 'screencast_max_pixels' is set greater than zero, screencasts will be
266 // scaled to be no larger than this value.
267 // If set to zero, the max pixels will be limited to
268 // Retina MacBookPro 15" resolution of 2880 x 1800.
269 // For high fps, maximum pixels limit is set based on common 24" monitor
270 // resolution of 2048 x 1280.
271 int screencast_max_pixels() const { return screencast_max_pixels_; }
272 void set_screencast_max_pixels(int p) {
273 screencast_max_pixels_ = talk_base::_max(0, p);
274 }
275
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000276 // If true, run video adaptation. By default, video adaptation is enabled
277 // and users must call video_adapter()->OnOutputFormatRequest()
278 // to receive frames.
279 bool enable_video_adapter() const { return enable_video_adapter_; }
280 void set_enable_video_adapter(bool enable_video_adapter) {
281 enable_video_adapter_ = enable_video_adapter;
282 }
283
284 CoordinatedVideoAdapter* video_adapter() { return &video_adapter_; }
285 const CoordinatedVideoAdapter* video_adapter() const {
286 return &video_adapter_;
287 }
288
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000289 protected:
290 // Callback attached to SignalFrameCaptured where SignalVideoFrames is called.
291 void OnFrameCaptured(VideoCapturer* video_capturer,
292 const CapturedFrame* captured_frame);
293 void SetCaptureState(CaptureState state);
294
295 // Marshals SignalStateChange onto thread_.
296 void OnMessage(talk_base::Message* message);
297
298 // subclasses override this virtual method to provide a vector of fourccs, in
299 // order of preference, that are expected by the media engine.
300 virtual bool GetPreferredFourccs(std::vector<uint32>* fourccs) = 0;
301
302 // mutators to set private attributes
303 void SetId(const std::string& id) {
304 id_ = id;
305 }
306
307 void SetCaptureFormat(const VideoFormat* format) {
308 capture_format_.reset(format ? new VideoFormat(*format) : NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000309 if (capture_format_) {
310 ASSERT(capture_format_->interval > 0 &&
311 "Capture format expected to have positive interval.");
312 // Video adapter really only cares about capture format interval.
313 video_adapter_.SetInputFormat(*capture_format_);
314 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000315 }
316
317 void SetSupportedFormats(const std::vector<VideoFormat>& formats);
318
319 private:
320 void Construct();
321 // Get the distance between the desired format and the supported format.
322 // Return the max distance if they mismatch. See the implementation for
323 // details.
324 int64 GetFormatDistance(const VideoFormat& desired,
325 const VideoFormat& supported);
326
327 // Convert captured frame to readable string for LOG messages.
328 std::string ToString(const CapturedFrame* frame) const;
329
330 // Applies all registered processors. If any of the processors signal that
331 // the frame should be dropped the return value will be false. Note that
332 // this frame should be dropped as it has not applied all processors.
333 bool ApplyProcessors(VideoFrame* video_frame);
334
335 // Updates filtered_supported_formats_ so that it contains the formats in
336 // supported_formats_ that fulfill all applied restrictions.
337 void UpdateFilteredSupportedFormats();
338 // Returns true if format doesn't fulfill all applied restrictions.
339 bool ShouldFilterFormat(const VideoFormat& format) const;
340
341 talk_base::Thread* thread_;
342 std::string id_;
343 CaptureState capture_state_;
344 talk_base::scoped_ptr<VideoFormat> capture_format_;
345 std::vector<VideoFormat> supported_formats_;
346 talk_base::scoped_ptr<VideoFormat> max_format_;
347 std::vector<VideoFormat> filtered_supported_formats_;
348
349 int ratio_w_; // View resolution. e.g. 1280 x 720.
350 int ratio_h_;
351 bool enable_camera_list_;
mallinath@webrtc.org1b15f422013-09-06 22:56:28 +0000352 bool square_pixel_aspect_ratio_; // Enable scaling to square pixels.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000353 int scaled_width_; // Current output size from ComputeScale.
354 int scaled_height_;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000355 int screencast_max_pixels_; // Downscale screencasts further if requested.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000356 bool muted_;
357 int black_frame_count_down_;
358
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000359 bool enable_video_adapter_;
360 CoordinatedVideoAdapter video_adapter_;
361
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000362 talk_base::CriticalSection crit_;
363 VideoProcessors video_processors_;
364
365 DISALLOW_COPY_AND_ASSIGN(VideoCapturer);
366};
367
368} // namespace cricket
369
370#endif // TALK_MEDIA_BASE_VIDEOCAPTURER_H_