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
>& media_task_runner
,
56 const scoped_refptr
<base::TaskRunner
>& worker_task_runner
,
57 VideoRendererSink
* sink
,
58 ScopedVector
<VideoDecoder
> decoders
,
60 const scoped_refptr
<GpuVideoAcceleratorFactories
>& gpu_factories
,
61 const scoped_refptr
<MediaLog
>& media_log
);
62 ~VideoRendererImpl() override
;
64 // VideoRenderer implementation.
65 void Initialize(DemuxerStream
* stream
,
66 const PipelineStatusCB
& init_cb
,
67 const SetDecryptorReadyCB
& set_decryptor_ready_cb
,
68 const StatisticsCB
& statistics_cb
,
69 const BufferingStateCB
& buffering_state_cb
,
70 const base::Closure
& ended_cb
,
71 const PipelineStatusCB
& error_cb
,
72 const TimeSource::WallClockTimeCB
& wall_clock_time_cb
,
73 const base::Closure
& waiting_for_decryption_key_cb
) override
;
74 void Flush(const base::Closure
& callback
) override
;
75 void StartPlayingFrom(base::TimeDelta timestamp
) override
;
76 void OnTimeStateChanged(bool time_progressing
) override
;
78 // PlatformThread::Delegate implementation.
79 void ThreadMain() override
;
81 void SetTickClockForTesting(scoped_ptr
<base::TickClock
> tick_clock
);
82 void SetGpuMemoryBufferVideoForTesting(
83 scoped_ptr
<GpuMemoryBufferVideoFramePool
> gpu_memory_buffer_pool
);
85 // VideoRendererSink::RenderCallback implementation.
86 scoped_refptr
<VideoFrame
> Render(base::TimeTicks deadline_min
,
87 base::TimeTicks deadline_max
,
88 bool background_rendering
) override
;
89 void OnFrameDropped() override
;
91 void disable_new_video_renderer_for_testing() {
92 use_new_video_renderering_path_
= false;
96 // Creates a dedicated |thread_| for video rendering.
97 void CreateVideoThread();
99 // Callback for |video_frame_stream_| initialization.
100 void OnVideoFrameStreamInitialized(bool success
);
102 // Callback for |video_frame_stream_| to deliver decoded video frames and
103 // report video decoding status. If a frame is available the planes will be
104 // copied asynchronously and FrameReady will be called once finished copying.
105 void FrameReadyForCopyingToGpuMemoryBuffers(
106 VideoFrameStream::Status status
,
107 const scoped_refptr
<VideoFrame
>& frame
);
109 // Callback for |video_frame_stream_| to deliver decoded video frames and
110 // report video decoding status.
111 void FrameReady(uint32_t sequence_token
,
112 VideoFrameStream::Status status
,
113 const scoped_refptr
<VideoFrame
>& frame
);
115 // Helper method for adding a frame to |ready_frames_|.
116 void AddReadyFrame_Locked(const scoped_refptr
<VideoFrame
>& frame
);
118 // Helper method that schedules an asynchronous read from the
119 // |video_frame_stream_| as long as there isn't a pending read and we have
122 void AttemptRead_Locked();
124 // Called when VideoFrameStream::Reset() completes.
125 void OnVideoFrameStreamResetDone();
127 // Runs |paint_cb_| with the next frame from |ready_frames_|.
129 // A read is scheduled to replace the frame.
130 void PaintNextReadyFrame_Locked();
132 // Drops the next frame from |ready_frames_| and runs |statistics_cb_|.
134 // A read is scheduled to replace the frame.
135 void DropNextReadyFrame_Locked();
137 // Returns true if the renderer has enough data for playback purposes.
138 // Note that having enough data may be due to reaching end of stream.
139 bool HaveEnoughData_Locked();
140 void TransitionToHaveEnough_Locked();
141 void TransitionToHaveNothing();
143 // Runs |statistics_cb_| with |frames_decoded_| and |frames_dropped_|, resets
144 // them to 0, and then waits on |frame_available_| for up to the
146 void UpdateStatsAndWait_Locked(base::TimeDelta wait_duration
);
148 // Called after we've painted the first frame. If |time_progressing_| is
149 // false it Stop() on |sink_|.
150 void MaybeStopSinkAfterFirstPaint();
152 // Returns true if there is no more room for additional buffered frames.
153 bool HaveReachedBufferingCap();
155 // Starts or stops |sink_| respectively. Do not call while |lock_| is held.
159 // Fires |ended_cb_| if there are no remaining usable frames and
160 // |received_end_of_stream_| is true. Sets |rendered_end_of_stream_| if it
163 // When called from the media thread, |time_progressing| should reflect the
164 // value of |time_progressing_|. When called from Render() on the sink
165 // callback thread, the inverse of |render_first_frame_and_stop_| should be
166 // used as a proxy for |time_progressing_|.
168 // Returns algorithm_->EffectiveFramesQueued().
169 size_t MaybeFireEndedCallback_Locked(bool time_progressing
);
171 // Helper method for converting a single media timestamp to wall clock time.
172 base::TimeTicks
ConvertMediaTimestamp(base::TimeDelta media_timestamp
);
174 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner_
;
176 // Enables the use of VideoRendererAlgorithm and VideoRendererSink for frame
177 // rendering instead of using a thread in a sleep-loop. Set via the command
178 // line flag kEnableNewVideoRenderer or via test methods.
179 bool use_new_video_renderering_path_
;
181 // Sink which calls into VideoRendererImpl via Render() for video frames. Do
182 // not call any methods on the sink while |lock_| is held or the two threads
183 // might deadlock. Do not call Start() or Stop() on the sink directly, use
184 // StartSink() and StopSink() to ensure background rendering is started. Only
185 // access these values on |task_runner_|.
186 VideoRendererSink
* const sink_
;
189 // Used for accessing data members.
192 // Provides video frames to VideoRendererImpl.
193 scoped_ptr
<VideoFrameStream
> video_frame_stream_
;
195 // Pool of GpuMemoryBuffers and resources used to create hardware frames.
196 scoped_ptr
<GpuMemoryBufferVideoFramePool
> gpu_memory_buffer_pool_
;
198 scoped_refptr
<MediaLog
> media_log_
;
200 // Flag indicating low-delay mode.
203 // Queue of incoming frames yet to be painted.
204 typedef std::deque
<scoped_refptr
<VideoFrame
>> VideoFrameQueue
;
205 VideoFrameQueue ready_frames_
;
207 // Keeps track of whether we received the end of stream buffer and finished
209 bool received_end_of_stream_
;
210 bool rendered_end_of_stream_
;
212 // Used to signal |thread_| as frames are added to |frames_|. Rule of thumb:
213 // always check |state_| to see if it was set to STOPPED after waking up!
214 base::ConditionVariable frame_available_
;
216 // Important detail: being in kPlaying doesn't imply that video is being
217 // rendered. Rather, it means that the renderer is ready to go. The actual
218 // rendering of video is controlled by time advancing via |get_time_cb_|.
225 // | Decoders initialized
228 // kFlushed <------------------ kFlushing
229 // | StartPlayingFrom() ^
232 // `---------> kPlaying --------'
242 // An integer that represents how many times the video frame stream has been
243 // reset. This is useful when doing video frame copies asynchronously since we
244 // want to discard video frames that might be received after the stream has
246 uint32_t sequence_token_
;
247 // Video thread handle.
248 base::PlatformThreadHandle thread_
;
250 // Keep track of the outstanding read on the VideoFrameStream. Flushing can
251 // only complete once the read has completed.
256 BufferingState buffering_state_
;
258 // Playback operation callbacks.
259 base::Closure flush_cb_
;
262 PipelineStatusCB init_cb_
;
263 StatisticsCB statistics_cb_
;
264 BufferingStateCB buffering_state_cb_
;
265 base::Closure ended_cb_
;
266 PipelineStatusCB error_cb_
;
267 TimeSource::WallClockTimeCB wall_clock_time_cb_
;
269 base::TimeDelta start_timestamp_
;
271 // Embedder callback for notifying a new frame is available for painting.
274 // The wallclock times of the last frame removed from the |ready_frames_|
275 // queue, either for calling |paint_cb_| or for dropping. Set to null during
277 base::TimeTicks last_media_time_
;
279 // Equivalent to |last_media_time_| + the estimated duration of the frame.
280 base::TimeTicks latest_possible_paint_time_
;
282 // Keeps track of the number of frames decoded and dropped since the
283 // last call to |statistics_cb_|. These must be accessed under lock.
287 bool is_shutting_down_
;
289 scoped_ptr
<base::TickClock
> tick_clock_
;
291 // Algorithm for selecting which frame to render; manages frames and all
292 // timing related information.
293 scoped_ptr
<VideoRendererAlgorithm
> algorithm_
;
295 // Indicates that Render() was called with |background_rendering| set to true,
296 // so we've entered a background rendering mode where dropped frames are not
297 // counted. Must be accessed under |lock_| once |sink_| is started.
298 bool was_background_rendering_
;
300 // Indicates whether or not media time is currently progressing or not. Must
301 // only be accessed from |task_runner_|.
302 bool time_progressing_
;
304 // Indicates that Render() should only render the first frame and then request
305 // that the sink be stopped. |posted_maybe_stop_after_first_paint_| is used
306 // to avoid repeated task posts.
307 bool render_first_frame_and_stop_
;
308 bool posted_maybe_stop_after_first_paint_
;
310 // NOTE: Weak pointers must be invalidated before all other member variables.
311 base::WeakPtrFactory
<VideoRendererImpl
> weak_factory_
;
313 DISALLOW_COPY_AND_ASSIGN(VideoRendererImpl
);
318 #endif // MEDIA_RENDERERS_VIDEO_RENDERER_IMPL_H_