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_
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"
32 class SingleThreadTaskRunner
;
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
{
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.
55 const scoped_refptr
<base::SingleThreadTaskRunner
>& task_runner
,
56 VideoRendererSink
* sink
,
57 ScopedVector
<VideoDecoder
> decoders
,
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;
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
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
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.
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
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_
;
178 // Used for accessing data members.
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.
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
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_|.
212 // | Decoders initialized
215 // kFlushed <------------------ kFlushing
216 // | StartPlayingFrom() ^
219 // `---------> kPlaying --------'
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.
238 BufferingState buffering_state_
;
240 // Playback operation callbacks.
241 base::Closure flush_cb_
;
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.
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
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.
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
);
300 #endif // MEDIA_RENDERERS_VIDEO_RENDERER_IMPL_H_