Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / content / common / gpu / media / vaapi_wrapper.h
blobd4c989d859219ad2197a7c9494a419c0928a4679
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.
4 //
5 // This file contains an implementation of VaapiWrapper, used by
6 // VaapiVideoDecodeAccelerator and VaapiH264Decoder for decode,
7 // and VaapiVideoEncodeAccelerator for encode, to interface
8 // with libva (VA-API library for hardware video codec).
10 #ifndef CONTENT_COMMON_GPU_MEDIA_VAAPI_WRAPPER_H_
11 #define CONTENT_COMMON_GPU_MEDIA_VAAPI_WRAPPER_H_
13 #include <set>
14 #include <vector>
16 #include "base/files/file.h"
17 #include "base/lazy_instance.h"
18 #include "base/memory/ref_counted.h"
19 #include "base/synchronization/lock.h"
20 #include "content/common/content_export.h"
21 #include "content/common/gpu/media/va_surface.h"
22 #include "media/base/video_decoder_config.h"
23 #include "media/base/video_frame.h"
24 #include "media/video/jpeg_decode_accelerator.h"
25 #include "media/video/video_decode_accelerator.h"
26 #include "media/video/video_encode_accelerator.h"
27 #include "third_party/libva/va/va.h"
28 #include "third_party/libva/va/va_vpp.h"
29 #include "ui/gfx/geometry/size.h"
30 #if defined(USE_X11)
31 #include "third_party/libva/va/va_x11.h"
32 #endif // USE_X11
34 namespace content {
36 // This class handles VA-API calls and ensures proper locking of VA-API calls
37 // to libva, the userspace shim to the HW codec driver. libva is not
38 // thread-safe, so we have to perform locking ourselves. This class is fully
39 // synchronous and its methods can be called from any thread and may wait on
40 // the va_lock_ while other, concurrent calls run.
42 // This class is responsible for managing VAAPI connection, contexts and state.
43 // It is also responsible for managing and freeing VABuffers (not VASurfaces),
44 // which are used to queue parameters and slice data to the HW codec,
45 // as well as underlying memory for VASurfaces themselves.
46 class CONTENT_EXPORT VaapiWrapper {
47 public:
48 enum CodecMode {
49 kDecode,
50 kEncode,
51 kCodecModeMax,
54 // Return an instance of VaapiWrapper initialized for |va_profile| and
55 // |mode|. |report_error_to_uma_cb| will be called independently from
56 // reporting errors to clients via method return values.
57 static scoped_ptr<VaapiWrapper> Create(
58 CodecMode mode,
59 VAProfile va_profile,
60 const base::Closure& report_error_to_uma_cb);
62 // Create VaapiWrapper for VideoCodecProfile. It maps VideoCodecProfile
63 // |profile| to VAProfile.
64 // |report_error_to_uma_cb| will be called independently from reporting
65 // errors to clients via method return values.
66 static scoped_ptr<VaapiWrapper> CreateForVideoCodec(
67 CodecMode mode,
68 media::VideoCodecProfile profile,
69 const base::Closure& report_error_to_uma_cb);
71 // Return the supported video encode profiles.
72 static media::VideoEncodeAccelerator::SupportedProfiles
73 GetSupportedEncodeProfiles();
75 // Return the supported video decode profiles.
76 static media::VideoDecodeAccelerator::SupportedProfiles
77 GetSupportedDecodeProfiles();
79 // Return true when JPEG decode is supported.
80 static bool IsJpegDecodeSupported();
82 ~VaapiWrapper();
84 // Create |num_surfaces| backing surfaces in driver for VASurfaces of
85 // |va_format|, each of size |size|. Returns true when successful, with the
86 // created IDs in |va_surfaces| to be managed and later wrapped in
87 // VASurfaces.
88 // The client must DestroySurfaces() each time before calling this method
89 // again to free the allocated surfaces first, but is not required to do so
90 // at destruction time, as this will be done automatically from
91 // the destructor.
92 bool CreateSurfaces(unsigned int va_format,
93 const gfx::Size& size,
94 size_t num_surfaces,
95 std::vector<VASurfaceID>* va_surfaces);
97 // Free all memory allocated in CreateSurfaces.
98 void DestroySurfaces();
100 // Create a VASurface of |va_format|, |size| and using |va_attribs|
101 // attributes. The ownership of the surface is transferred to the
102 // caller. It differs from surfaces created using CreateSurfaces(),
103 // where VaapiWrapper is the owner of the surfaces.
104 scoped_refptr<VASurface> CreateUnownedSurface(
105 unsigned int va_format,
106 const gfx::Size& size,
107 const std::vector<VASurfaceAttrib>& va_attribs);
109 // Submit parameters or slice data of |va_buffer_type|, copying them from
110 // |buffer| of size |size|, into HW codec. The data in |buffer| is no
111 // longer needed and can be freed after this method returns.
112 // Data submitted via this method awaits in the HW codec until
113 // ExecuteAndDestroyPendingBuffers() is called to execute or
114 // DestroyPendingBuffers() is used to cancel a pending job.
115 bool SubmitBuffer(VABufferType va_buffer_type, size_t size, void* buffer);
117 // Submit a VAEncMiscParameterBuffer of given |misc_param_type|, copying its
118 // data from |buffer| of size |size|, into HW codec. The data in |buffer| is
119 // no longer needed and can be freed after this method returns.
120 // Data submitted via this method awaits in the HW codec until
121 // ExecuteAndDestroyPendingBuffers() is called to execute or
122 // DestroyPendingBuffers() is used to cancel a pending job.
123 bool SubmitVAEncMiscParamBuffer(VAEncMiscParameterType misc_param_type,
124 size_t size,
125 void* buffer);
127 // Cancel and destroy all buffers queued to the HW codec via SubmitBuffer().
128 // Useful when a pending job is to be cancelled (on reset or error).
129 void DestroyPendingBuffers();
131 // Execute job in hardware on target |va_surface_id| and destroy pending
132 // buffers. Return false if Execute() fails.
133 bool ExecuteAndDestroyPendingBuffers(VASurfaceID va_surface_id);
135 #if defined(USE_X11)
136 // Put data from |va_surface_id| into |x_pixmap| of size
137 // |dest_size|, converting/scaling to it.
138 bool PutSurfaceIntoPixmap(VASurfaceID va_surface_id,
139 Pixmap x_pixmap,
140 gfx::Size dest_size);
141 #endif // USE_X11
143 // Get a VAImage from a VASurface and map it into memory. The size and format
144 // are derived from the surface. Use GetVaImage() instead if |format| or
145 // |size| are different from surface internal representation. The VAImage
146 // should be released using the ReturnVaImage function. Returns true when
147 // successful.
148 bool GetDerivedVaImage(VASurfaceID va_surface_id, VAImage* image, void** mem);
150 // Get a VAImage from a VASurface |va_surface_id| and map it into memory with
151 // given |format| and |size|. The output is |image| and the mapped memory is
152 // |mem|. If |format| doesn't equal to the internal format, the underlying
153 // implementation will do format conversion if supported. |size| should be
154 // smaller than or equal to the surface. If |size| is smaller, the image will
155 // be cropped. The VAImage should be released using the ReturnVaImage
156 // function. Returns true when successful.
157 bool GetVaImage(VASurfaceID va_surface_id,
158 VAImageFormat* format,
159 const gfx::Size& size,
160 VAImage* image,
161 void** mem);
163 // Release the VAImage (and the associated memory mapping) obtained from
164 // GetVaImage() or GetDerivedVaImage().
165 void ReturnVaImage(VAImage* image);
167 // Upload contents of |frame| into |va_surface_id| for encode.
168 bool UploadVideoFrameToSurface(const scoped_refptr<media::VideoFrame>& frame,
169 VASurfaceID va_surface_id);
171 // Create a buffer of |size| bytes to be used as encode output.
172 bool CreateCodedBuffer(size_t size, VABufferID* buffer_id);
174 // Download the contents of the buffer with given |buffer_id| into a buffer of
175 // size |target_size|, pointed to by |target_ptr|. The number of bytes
176 // downloaded will be returned in |coded_data_size|. |sync_surface_id| will
177 // be used as a sync point, i.e. it will have to become idle before starting
178 // the download. |sync_surface_id| should be the source surface passed
179 // to the encode job.
180 bool DownloadAndDestroyCodedBuffer(VABufferID buffer_id,
181 VASurfaceID sync_surface_id,
182 uint8* target_ptr,
183 size_t target_size,
184 size_t* coded_data_size);
186 // Destroy all previously-allocated (and not yet destroyed) coded buffers.
187 void DestroyCodedBuffers();
189 // Blits a VASurface |va_surface_id_src| into another VASurface
190 // |va_surface_id_dest| applying pixel format conversion and scaling
191 // if needed.
192 bool BlitSurface(VASurfaceID va_surface_id_src,
193 const gfx::Size& src_size,
194 VASurfaceID va_surface_id_dest,
195 const gfx::Size& dest_size);
197 // Initialize static data before sandbox is enabled.
198 static void PreSandboxInitialization();
200 private:
201 struct ProfileInfo {
202 VAProfile va_profile;
203 gfx::Size max_resolution;
206 class LazyProfileInfos {
207 public:
208 LazyProfileInfos();
209 ~LazyProfileInfos();
210 std::vector<ProfileInfo> GetSupportedProfileInfosForCodecMode(
211 CodecMode mode);
212 bool IsProfileSupported(CodecMode mode, VAProfile va_profile);
214 private:
215 std::vector<ProfileInfo> supported_profiles_[kCodecModeMax];
218 class VADisplayState {
219 public:
220 VADisplayState();
221 ~VADisplayState();
223 // |va_lock_| must be held on entry.
224 bool Initialize(VAStatus* status);
225 void Deinitialize(VAStatus* status);
227 base::Lock* va_lock() { return &va_lock_; }
228 VADisplay va_display() const { return va_display_; }
230 #if defined(USE_OZONE)
231 void SetDrmFd(base::PlatformFile fd);
232 #endif // USE_OZONE
234 private:
235 friend class base::LazyInstance<VADisplayState>;
237 // Returns true if the VAAPI version is less than the specified version.
238 bool VAAPIVersionLessThan(int major, int minor);
240 // Protected by |va_lock_|.
241 int refcount_;
243 // Libva is not thread safe, so we have to do locking for it ourselves.
244 // This lock is to be taken for the duration of all VA-API calls and for
245 // the entire job submission sequence in ExecuteAndDestroyPendingBuffers().
246 base::Lock va_lock_;
248 #if defined(USE_OZONE)
249 // Drm fd used to obtain access to the driver interface by VA.
250 base::ScopedFD drm_fd_;
251 #endif // USE_OZONE
253 // The VADisplay handle.
254 VADisplay va_display_;
256 // The VAAPI version.
257 int major_version_, minor_version_;
259 // True if vaInitialize has been called successfully.
260 bool va_initialized_;
263 VaapiWrapper();
265 bool Initialize(CodecMode mode, VAProfile va_profile);
266 void Deinitialize();
267 bool VaInitialize(const base::Closure& report_error_to_uma_cb);
268 bool GetSupportedVaProfiles(std::vector<VAProfile>* profiles);
270 // Check if |va_profile| supports |entrypoint| or not. |va_lock_| must be
271 // held on entry.
272 bool IsEntrypointSupported_Locked(VAProfile va_profile,
273 VAEntrypoint entrypoint);
275 // Return true if |va_profile| for |entrypoint| with |required_attribs| is
276 // supported. |va_lock_| must be held on entry.
277 bool AreAttribsSupported_Locked(
278 VAProfile va_profile,
279 VAEntrypoint entrypoint,
280 const std::vector<VAConfigAttrib>& required_attribs);
282 // Get maximum resolution for |va_profile| and |entrypoint| with
283 // |required_attribs|. If return value is true, |resolution| is the maximum
284 // resolution. |va_lock_| must be held on entry.
285 bool GetMaxResolution_Locked(
286 VAProfile va_profile,
287 VAEntrypoint entrypoint,
288 std::vector<VAConfigAttrib>& required_attribs,
289 gfx::Size* resolution);
291 // Destroys a |va_surface| created using CreateUnownedSurface.
292 void DestroyUnownedSurface(VASurfaceID va_surface_id);
294 // Initialize the video post processing context with the |size| of
295 // the input pictures to be processed.
296 bool InitializeVpp_Locked();
298 // Deinitialize the video post processing context.
299 void DeinitializeVpp();
301 // Execute pending job in hardware and destroy pending buffers. Return false
302 // if vaapi driver refuses to accept parameter or slice buffers submitted
303 // by client, or if execution fails in hardware.
304 bool Execute(VASurfaceID va_surface_id);
306 // Attempt to set render mode to "render to texture.". Failure is non-fatal.
307 void TryToSetVADisplayAttributeToLocalGPU();
309 // Get supported profile infos for |mode|.
310 std::vector<ProfileInfo> GetSupportedProfileInfosForCodecModeInternal(
311 CodecMode mode);
313 // Lazily initialize static data after sandbox is enabled. Return false on
314 // init failure.
315 static bool PostSandboxInitialization();
317 // Map VideoCodecProfile enum values to VaProfile values. This function
318 // includes a workaround for crbug.com/345569. If va_profile is h264 baseline
319 // and it is not supported, we try constrained baseline.
320 static VAProfile ProfileToVAProfile(media::VideoCodecProfile profile,
321 CodecMode mode);
323 // Pointer to VADisplayState's member |va_lock_|. Guaranteed to be valid for
324 // the lifetime of VaapiWrapper.
325 base::Lock* va_lock_;
327 // Allocated ids for VASurfaces.
328 std::vector<VASurfaceID> va_surface_ids_;
330 // Singleton instance of VADisplayState.
331 static base::LazyInstance<VADisplayState> va_display_state_;
333 // VA handles.
334 // All valid after successful Initialize() and until Deinitialize().
335 VADisplay va_display_;
336 VAConfigID va_config_id_;
337 // Created for the current set of va_surface_ids_ in CreateSurfaces() and
338 // valid until DestroySurfaces().
339 VAContextID va_context_id_;
341 // Data queued up for HW codec, to be committed on next execution.
342 std::vector<VABufferID> pending_slice_bufs_;
343 std::vector<VABufferID> pending_va_bufs_;
345 // Bitstream buffers for encode.
346 std::set<VABufferID> coded_buffers_;
348 // Called to report codec errors to UMA. Errors to clients are reported via
349 // return values from public methods.
350 base::Closure report_error_to_uma_cb_;
352 // VPP (Video Post Processing) context, this is used to convert
353 // pictures used by the decoder to RGBA pictures usable by GL or the
354 // display hardware.
355 VAConfigID va_vpp_config_id_;
356 VAContextID va_vpp_context_id_;
357 VABufferID va_vpp_buffer_id_;
359 // Singleton variable to store supported profile information for encode and
360 // decode.
361 static base::LazyInstance<LazyProfileInfos> profile_infos_;
363 DISALLOW_COPY_AND_ASSIGN(VaapiWrapper);
366 } // namespace content
368 #endif // CONTENT_COMMON_GPU_MEDIA_VAAPI_WRAPPER_H_