Gallery: change size of crop overlay to cover entire window.
[chromium-blink-merge.git] / media / renderers / video_renderer_impl.h
blob6f0884b2d24bab279b2d026deda27e3e1b3e0d11
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef MEDIA_RENDERERS_VIDEO_RENDERER_IMPL_H_
6 #define MEDIA_RENDERERS_VIDEO_RENDERER_IMPL_H_
8 #include <deque>
10 #include "base/memory/ref_counted.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/memory/scoped_vector.h"
13 #include "base/memory/weak_ptr.h"
14 #include "base/synchronization/condition_variable.h"
15 #include "base/synchronization/lock.h"
16 #include "base/threading/platform_thread.h"
17 #include "base/timer/timer.h"
18 #include "media/base/decryptor.h"
19 #include "media/base/demuxer_stream.h"
20 #include "media/base/media_log.h"
21 #include "media/base/pipeline_status.h"
22 #include "media/base/video_decoder.h"
23 #include "media/base/video_frame.h"
24 #include "media/base/video_renderer.h"
25 #include "media/base/video_renderer_sink.h"
26 #include "media/filters/decoder_stream.h"
27 #include "media/filters/video_renderer_algorithm.h"
28 #include "media/renderers/gpu_video_accelerator_factories.h"
29 #include "media/video/gpu_memory_buffer_video_frame_pool.h"
31 namespace base {
32 class SingleThreadTaskRunner;
33 class TickClock;
36 namespace media {
38 // VideoRendererImpl creates its own thread for the sole purpose of timing frame
39 // presentation. It handles reading from the VideoFrameStream and stores the
40 // results in a queue of decoded frames and executing a callback when a frame is
41 // ready for rendering.
42 class MEDIA_EXPORT VideoRendererImpl
43 : public VideoRenderer,
44 public NON_EXPORTED_BASE(VideoRendererSink::RenderCallback),
45 public base::PlatformThread::Delegate {
46 public:
47 // |decoders| contains the VideoDecoders to use when initializing.
49 // Implementors should avoid doing any sort of heavy work in this method and
50 // instead post a task to a common/worker thread to handle rendering. Slowing
51 // down the video thread may result in losing synchronization with audio.
53 // Setting |drop_frames_| to true causes the renderer to drop expired frames.
54 VideoRendererImpl(
55 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
56 VideoRendererSink* sink,
57 ScopedVector<VideoDecoder> decoders,
58 bool drop_frames,
59 const scoped_refptr<GpuVideoAcceleratorFactories>& gpu_factories,
60 const scoped_refptr<MediaLog>& media_log);
61 ~VideoRendererImpl() override;
63 // VideoRenderer implementation.
64 void Initialize(DemuxerStream* stream,
65 const PipelineStatusCB& init_cb,
66 const SetDecryptorReadyCB& set_decryptor_ready_cb,
67 const StatisticsCB& statistics_cb,
68 const BufferingStateCB& buffering_state_cb,
69 const base::Closure& ended_cb,
70 const PipelineStatusCB& error_cb,
71 const TimeSource::WallClockTimeCB& wall_clock_time_cb,
72 const base::Closure& waiting_for_decryption_key_cb) override;
73 void Flush(const base::Closure& callback) override;
74 void StartPlayingFrom(base::TimeDelta timestamp) override;
75 void OnTimeStateChanged(bool time_progressing) override;
77 // PlatformThread::Delegate implementation.
78 void ThreadMain() override;
80 void SetTickClockForTesting(scoped_ptr<base::TickClock> tick_clock);
82 // VideoRendererSink::RenderCallback implementation.
83 scoped_refptr<VideoFrame> Render(base::TimeTicks deadline_min,
84 base::TimeTicks deadline_max,
85 bool background_rendering) override;
86 void OnFrameDropped() override;
88 void disable_new_video_renderer_for_testing() {
89 use_new_video_renderering_path_ = false;
92 private:
93 // Creates a dedicated |thread_| for video rendering.
94 void CreateVideoThread();
96 // Callback for |video_frame_stream_| initialization.
97 void OnVideoFrameStreamInitialized(bool success);
99 // Callback for |video_frame_stream_| to deliver decoded video frames and
100 // report video decoding status.
101 void FrameReady(VideoFrameStream::Status status,
102 const scoped_refptr<VideoFrame>& frame);
104 // Helper method for adding a frame to |ready_frames_|.
105 void AddReadyFrame_Locked(const scoped_refptr<VideoFrame>& frame);
107 // Helper method that schedules an asynchronous read from the
108 // |video_frame_stream_| as long as there isn't a pending read and we have
109 // capacity.
110 void AttemptRead();
111 void AttemptRead_Locked();
113 // Called when VideoFrameStream::Reset() completes.
114 void OnVideoFrameStreamResetDone();
116 // Runs |paint_cb_| with the next frame from |ready_frames_|.
118 // A read is scheduled to replace the frame.
119 void PaintNextReadyFrame_Locked();
121 // Drops the next frame from |ready_frames_| and runs |statistics_cb_|.
123 // A read is scheduled to replace the frame.
124 void DropNextReadyFrame_Locked();
126 // Returns true if the renderer has enough data for playback purposes.
127 // Note that having enough data may be due to reaching end of stream.
128 bool HaveEnoughData_Locked();
129 void TransitionToHaveEnough_Locked();
130 void TransitionToHaveNothing();
132 // Runs |statistics_cb_| with |frames_decoded_| and |frames_dropped_|, resets
133 // them to 0, and then waits on |frame_available_| for up to the
134 // |wait_duration|.
135 void UpdateStatsAndWait_Locked(base::TimeDelta wait_duration);
137 // Called after we've painted the first frame. If |time_progressing_| is
138 // false it Stop() on |sink_|.
139 void MaybeStopSinkAfterFirstPaint();
141 // Returns true if there is no more room for additional buffered frames.
142 bool HaveReachedBufferingCap();
144 // Starts or stops |sink_| respectively. Do not call while |lock_| is held.
145 void StartSink();
146 void StopSink();
148 // Fires |ended_cb_| if there are no remaining usable frames and
149 // |received_end_of_stream_| is true. Sets |rendered_end_of_stream_| if it
150 // does so.
152 // When called from the media thread, |time_progressing| should reflect the
153 // value of |time_progressing_|. When called from Render() on the sink
154 // callback thread, the inverse of |render_first_frame_and_stop_| should be
155 // used as a proxy for |time_progressing_|.
157 // Returns algorithm_->EffectiveFramesQueued().
158 size_t MaybeFireEndedCallback_Locked(bool time_progressing);
160 // Helper method for converting a single media timestamp to wall clock time.
161 base::TimeTicks ConvertMediaTimestamp(base::TimeDelta media_timestamp);
163 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
165 // Enables the use of VideoRendererAlgorithm and VideoRendererSink for frame
166 // rendering instead of using a thread in a sleep-loop. Set via the command
167 // line flag kEnableNewVideoRenderer or via test methods.
168 bool use_new_video_renderering_path_;
170 // Sink which calls into VideoRendererImpl via Render() for video frames. Do
171 // not call any methods on the sink while |lock_| is held or the two threads
172 // might deadlock. Do not call Start() or Stop() on the sink directly, use
173 // StartSink() and StopSink() to ensure background rendering is started. Only
174 // access these values on |task_runner_|.
175 VideoRendererSink* const sink_;
176 bool sink_started_;
178 // Used for accessing data members.
179 base::Lock lock_;
181 // Provides video frames to VideoRendererImpl.
182 scoped_ptr<VideoFrameStream> video_frame_stream_;
184 // Pool of GpuMemoryBuffers and resources used to create hardware frames.
185 scoped_ptr<GpuMemoryBufferVideoFramePool> gpu_memory_buffer_pool_;
187 // Flag indicating low-delay mode.
188 bool low_delay_;
190 // Queue of incoming frames yet to be painted.
191 typedef std::deque<scoped_refptr<VideoFrame>> VideoFrameQueue;
192 VideoFrameQueue ready_frames_;
194 // Keeps track of whether we received the end of stream buffer and finished
195 // rendering.
196 bool received_end_of_stream_;
197 bool rendered_end_of_stream_;
199 // Used to signal |thread_| as frames are added to |frames_|. Rule of thumb:
200 // always check |state_| to see if it was set to STOPPED after waking up!
201 base::ConditionVariable frame_available_;
203 // Important detail: being in kPlaying doesn't imply that video is being
204 // rendered. Rather, it means that the renderer is ready to go. The actual
205 // rendering of video is controlled by time advancing via |get_time_cb_|.
207 // kUninitialized
208 // | Initialize()
209 // |
210 // V
211 // kInitializing
212 // | Decoders initialized
213 // |
214 // V Decoders reset
215 // kFlushed <------------------ kFlushing
216 // | StartPlayingFrom() ^
217 // | |
218 // | | Flush()
219 // `---------> kPlaying --------'
220 enum State {
221 kUninitialized,
222 kInitializing,
223 kFlushing,
224 kFlushed,
225 kPlaying
227 State state_;
229 // Video thread handle.
230 base::PlatformThreadHandle thread_;
232 // Keep track of the outstanding read on the VideoFrameStream. Flushing can
233 // only complete once the read has completed.
234 bool pending_read_;
236 bool drop_frames_;
238 BufferingState buffering_state_;
240 // Playback operation callbacks.
241 base::Closure flush_cb_;
243 // Event callbacks.
244 PipelineStatusCB init_cb_;
245 StatisticsCB statistics_cb_;
246 BufferingStateCB buffering_state_cb_;
247 base::Closure ended_cb_;
248 PipelineStatusCB error_cb_;
249 TimeSource::WallClockTimeCB wall_clock_time_cb_;
251 base::TimeDelta start_timestamp_;
253 // Embedder callback for notifying a new frame is available for painting.
254 PaintCB paint_cb_;
256 // The wallclock times of the last frame removed from the |ready_frames_|
257 // queue, either for calling |paint_cb_| or for dropping. Set to null during
258 // flushing.
259 base::TimeTicks last_media_time_;
261 // Equivalent to |last_media_time_| + the estimated duration of the frame.
262 base::TimeTicks latest_possible_paint_time_;
264 // Keeps track of the number of frames decoded and dropped since the
265 // last call to |statistics_cb_|. These must be accessed under lock.
266 int frames_decoded_;
267 int frames_dropped_;
269 bool is_shutting_down_;
271 scoped_ptr<base::TickClock> tick_clock_;
273 // Algorithm for selecting which frame to render; manages frames and all
274 // timing related information.
275 scoped_ptr<VideoRendererAlgorithm> algorithm_;
277 // Indicates that Render() was called with |background_rendering| set to true,
278 // so we've entered a background rendering mode where dropped frames are not
279 // counted. Must be accessed under |lock_| once |sink_| is started.
280 bool was_background_rendering_;
282 // Indicates whether or not media time is currently progressing or not. Must
283 // only be accessed from |task_runner_|.
284 bool time_progressing_;
286 // Indicates that Render() should only render the first frame and then request
287 // that the sink be stopped. |posted_maybe_stop_after_first_paint_| is used
288 // to avoid repeated task posts.
289 bool render_first_frame_and_stop_;
290 bool posted_maybe_stop_after_first_paint_;
292 // NOTE: Weak pointers must be invalidated before all other member variables.
293 base::WeakPtrFactory<VideoRendererImpl> weak_factory_;
295 DISALLOW_COPY_AND_ASSIGN(VideoRendererImpl);
298 } // namespace media
300 #endif // MEDIA_RENDERERS_VIDEO_RENDERER_IMPL_H_