Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / content / common / gpu / media / vaapi_video_encode_accelerator.h
blobc70f26fb7c287aec97167993c10f5dbce3b29d3a
1 // Copyright 2014 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 CONTENT_COMMON_GPU_MEDIA_VAAPI_VIDEO_ENCODE_ACCELERATOR_H_
6 #define CONTENT_COMMON_GPU_MEDIA_VAAPI_VIDEO_ENCODE_ACCELERATOR_H_
8 #include <list>
9 #include <queue>
11 #include "base/memory/linked_ptr.h"
12 #include "base/threading/thread.h"
13 #include "content/common/content_export.h"
14 #include "content/common/gpu/media/h264_dpb.h"
15 #include "content/common/gpu/media/va_surface.h"
16 #include "content/common/gpu/media/vaapi_wrapper.h"
17 #include "media/filters/h264_bitstream_buffer.h"
18 #include "media/video/video_encode_accelerator.h"
20 namespace content {
22 // A VideoEncodeAccelerator implementation that uses VA-API
23 // (http://www.freedesktop.org/wiki/Software/vaapi) for HW-accelerated
24 // video encode.
25 class CONTENT_EXPORT VaapiVideoEncodeAccelerator
26 : public media::VideoEncodeAccelerator {
27 public:
28 VaapiVideoEncodeAccelerator();
29 ~VaapiVideoEncodeAccelerator() override;
31 // media::VideoEncodeAccelerator implementation.
32 media::VideoEncodeAccelerator::SupportedProfiles GetSupportedProfiles()
33 override;
34 bool Initialize(media::VideoPixelFormat format,
35 const gfx::Size& input_visible_size,
36 media::VideoCodecProfile output_profile,
37 uint32 initial_bitrate,
38 Client* client) override;
39 void Encode(const scoped_refptr<media::VideoFrame>& frame,
40 bool force_keyframe) override;
41 void UseOutputBitstreamBuffer(const media::BitstreamBuffer& buffer) override;
42 void RequestEncodingParametersChange(uint32 bitrate,
43 uint32 framerate) override;
44 void Destroy() override;
46 private:
47 // Reference picture list.
48 typedef std::list<scoped_refptr<VASurface> > RefPicList;
50 // Encode job for one frame. Created when an input frame is awaiting and
51 // enough resources are available to proceed. Once the job is prepared and
52 // submitted to the hardware, it awaits on the submitted_encode_jobs_ queue
53 // for an output bitstream buffer to become available. Once one is ready,
54 // the encoded bytes are downloaded to it and job resources are released
55 // and become available for reuse.
56 struct EncodeJob {
57 // Input surface for video frame data.
58 scoped_refptr<VASurface> input_surface;
59 // Surface for a reconstructed picture, which is used for reference
60 // for subsequent frames.
61 scoped_refptr<VASurface> recon_surface;
62 // Buffer that will contain output bitstream for this frame.
63 VABufferID coded_buffer;
64 // Reference surfaces required to encode this picture. We keep references
65 // to them here, because we may discard some of them from ref_pic_list*
66 // before the HW job is done.
67 RefPicList reference_surfaces;
68 // True if this job will produce a keyframe. Used to report
69 // to BitstreamBufferReady().
70 bool keyframe;
72 EncodeJob();
73 ~EncodeJob();
76 // Encoder state.
77 enum State {
78 kUninitialized,
79 kEncoding,
80 kError,
83 // Holds input frames coming from the client ready to be encoded.
84 struct InputFrameRef;
85 // Holds output buffers coming from the client ready to be filled.
86 struct BitstreamBufferRef;
88 // Tasks for each of the VEA interface calls to be executed on the
89 // encoder thread.
90 void InitializeTask();
91 void EncodeTask(const scoped_refptr<media::VideoFrame>& frame,
92 bool force_keyframe);
93 void UseOutputBitstreamBufferTask(scoped_ptr<BitstreamBufferRef> buffer_ref);
94 void RequestEncodingParametersChangeTask(uint32 bitrate, uint32 framerate);
95 void DestroyTask();
97 // Prepare and schedule an encode job if we have an input to encode
98 // and enough resources to proceed.
99 void EncodeFrameTask();
101 // Fill current_sps_/current_pps_ with current values.
102 void UpdateSPS();
103 void UpdatePPS();
104 void UpdateRates(uint32 bitrate, uint32 framerate);
106 // Generate packed SPS and PPS in packed_sps_/packed_pps_, using
107 // values in current_sps_/current_pps_.
108 void GeneratePackedSPS();
109 void GeneratePackedPPS();
111 // Check if we have sufficient resources for a new encode job, claim them and
112 // fill current_encode_job_ with them.
113 // Return false if we cannot start a new job yet, true otherwise.
114 bool PrepareNextJob();
116 // Begin a new frame, making it a keyframe if |force_keyframe| is true,
117 // updating current_pic_.
118 void BeginFrame(bool force_keyframe);
120 // End current frame, updating reference picture lists and storing current
121 // job in the jobs awaiting completion on submitted_encode_jobs_.
122 void EndFrame();
124 // Submit parameters for the current frame to the hardware.
125 bool SubmitFrameParameters();
126 // Submit keyframe headers to the hardware if the current frame is a keyframe.
127 bool SubmitHeadersIfNeeded();
129 // Upload image data from |frame| to the input surface for current job.
130 bool UploadFrame(const scoped_refptr<media::VideoFrame>& frame);
132 // Execute encode in hardware. This does not block and will return before
133 // the job is finished.
134 bool ExecuteEncode();
136 // Callback that returns a no longer used VASurfaceID to
137 // available_va_surface_ids_ for reuse.
138 void RecycleVASurfaceID(VASurfaceID va_surface_id);
140 // Tries to return a bitstream buffer if both a submitted job awaits to
141 // be completed and we have bitstream buffers from the client available
142 // to download the encoded data to.
143 void TryToReturnBitstreamBuffer();
145 // Puts the encoder into en error state and notifies client about the error.
146 void NotifyError(Error error);
148 // Sets the encoder state on the correct thread.
149 void SetState(State state);
151 // VaapiWrapper is the owner of all HW resources (surfaces and buffers)
152 // and will free them on destruction.
153 scoped_ptr<VaapiWrapper> vaapi_wrapper_;
155 // Input profile and sizes.
156 media::VideoCodecProfile profile_;
157 gfx::Size visible_size_;
158 gfx::Size coded_size_; // Macroblock-aligned.
159 // Width/height in macroblocks.
160 unsigned int mb_width_;
161 unsigned int mb_height_;
163 // Maximum size of the reference list 0.
164 unsigned int max_ref_idx_l0_size_;
166 // Initial QP.
167 unsigned int qp_;
169 // IDR frame period.
170 unsigned int idr_period_;
171 // I frame period.
172 unsigned int i_period_;
173 // IP period, i.e. how often do we need to have either an I or a P frame in
174 // the stream. Period of 1 means we can have no B frames.
175 unsigned int ip_period_;
177 // Size in bytes required for input bitstream buffers.
178 size_t output_buffer_byte_size_;
180 // All of the members below must be accessed on the encoder_thread_,
181 // while it is running.
183 // Encoder state. Encode tasks will only run in kEncoding state.
184 State state_;
186 // frame_num to be used for the next frame.
187 unsigned int frame_num_;
188 // idr_pic_id to be used for the next frame.
189 unsigned int idr_pic_id_;
191 // Current bitrate in bps.
192 unsigned int bitrate_;
193 // Current fps.
194 unsigned int framerate_;
195 // CPB size in bits, i.e. bitrate in kbps * window size in ms/1000.
196 unsigned int cpb_size_;
197 // True if the parameters have changed and we need to submit a keyframe
198 // with updated parameters.
199 bool encoding_parameters_changed_;
201 // Job currently being prepared for encode.
202 scoped_ptr<EncodeJob> current_encode_job_;
204 // Current SPS, PPS and their packed versions. Packed versions are their NALUs
205 // in AnnexB format *without* emulation prevention three-byte sequences
206 // (those will be added by the driver).
207 media::H264SPS current_sps_;
208 media::H264BitstreamBuffer packed_sps_;
209 media::H264PPS current_pps_;
210 media::H264BitstreamBuffer packed_pps_;
212 // Picture currently being prepared for encode.
213 scoped_refptr<H264Picture> current_pic_;
215 // VA surfaces available for reuse.
216 std::vector<VASurfaceID> available_va_surface_ids_;
218 // VA buffers for coded frames.
219 std::vector<VABufferID> available_va_buffer_ids_;
221 // Currently active reference surfaces.
222 RefPicList ref_pic_list0_;
224 // Callback via which finished VA surfaces are returned to us.
225 VASurface::ReleaseCB va_surface_release_cb_;
227 // VideoFrames passed from the client, waiting to be encoded.
228 std::queue<linked_ptr<InputFrameRef> > encoder_input_queue_;
230 // BitstreamBuffers mapped, ready to be filled.
231 std::queue<linked_ptr<BitstreamBufferRef> > available_bitstream_buffers_;
233 // Jobs submitted for encode, awaiting bitstream buffers to become available.
234 std::queue<linked_ptr<EncodeJob> > submitted_encode_jobs_;
236 // Encoder thread. All tasks are executed on it.
237 base::Thread encoder_thread_;
238 scoped_refptr<base::SingleThreadTaskRunner> encoder_thread_task_runner_;
240 const scoped_refptr<base::SingleThreadTaskRunner> child_task_runner_;
242 // To expose client callbacks from VideoEncodeAccelerator.
243 // NOTE: all calls to these objects *MUST* be executed on
244 // child_task_runner_.
245 scoped_ptr<base::WeakPtrFactory<Client> > client_ptr_factory_;
246 base::WeakPtr<Client> client_;
248 // WeakPtr to post from the encoder thread back to the ChildThread, as it may
249 // outlive this. Posting from the ChildThread using base::Unretained(this)
250 // to the encoder thread is safe, because |this| always outlives the encoder
251 // thread (it's a member of this class).
252 base::WeakPtr<VaapiVideoEncodeAccelerator> weak_this_;
253 base::WeakPtrFactory<VaapiVideoEncodeAccelerator> weak_this_ptr_factory_;
255 DISALLOW_COPY_AND_ASSIGN(VaapiVideoEncodeAccelerator);
258 } // namespace content
260 #endif // CONTENT_COMMON_GPU_MEDIA_VAAPI_VIDEO_ENCODE_ACCELERATOR_H_