1 // Copyright (c) 2012 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_DXVA_VIDEO_DECODE_ACCELERATOR_H_
6 #define CONTENT_COMMON_GPU_MEDIA_DXVA_VIDEO_DECODE_ACCELERATOR_H_
10 // Work around bug in this header by disabling the relevant warning for it.
11 // https://connect.microsoft.com/VisualStudio/feedback/details/911260/dxva2api-h-in-win8-sdk-triggers-c4201-with-w4
13 #pragma warning(disable:4201)
21 #include "base/compiler_specific.h"
22 #include "base/memory/linked_ptr.h"
23 #include "base/memory/weak_ptr.h"
24 #include "base/synchronization/lock.h"
25 #include "base/threading/non_thread_safe.h"
26 #include "base/threading/thread.h"
27 #include "base/win/scoped_comptr.h"
28 #include "content/common/content_export.h"
29 #include "media/video/video_decode_accelerator.h"
32 interface IDirect3DSurface9
;
38 typedef HRESULT (WINAPI
* CreateDXGIDeviceManager
)(
40 IMFDXGIDeviceManager
** device_manager
);
44 // Class to provide a DXVA 2.0 based accelerator using the Microsoft Media
45 // foundation APIs via the VideoDecodeAccelerator interface.
46 // This class lives on a single thread and DCHECKs that it is never accessed
48 class CONTENT_EXPORT DXVAVideoDecodeAccelerator
49 : public media::VideoDecodeAccelerator
{
52 kUninitialized
, // un-initialized.
53 kNormal
, // normal playing state.
54 kResetting
, // upon received Reset(), before ResetDone()
55 kStopped
, // upon output EOS received.
56 kFlushing
, // upon flush request received.
59 // Does not take ownership of |client| which must outlive |*this|.
60 explicit DXVAVideoDecodeAccelerator(
61 const base::Callback
<bool(void)>& make_context_current
,
62 gfx::GLContext
* gl_context
);
63 ~DXVAVideoDecodeAccelerator() override
;
65 // media::VideoDecodeAccelerator implementation.
66 bool Initialize(media::VideoCodecProfile profile
,
67 Client
* client
) override
;
68 void Decode(const media::BitstreamBuffer
& bitstream_buffer
) override
;
69 void AssignPictureBuffers(
70 const std::vector
<media::PictureBuffer
>& buffers
) override
;
71 void ReusePictureBuffer(int32 picture_buffer_id
) override
;
72 void Flush() override
;
73 void Reset() override
;
74 void Destroy() override
;
75 bool CanDecodeOnIOThread() override
;
76 GLenum
GetSurfaceInternalFormat() const override
;
78 static media::VideoDecodeAccelerator::SupportedProfiles
79 GetSupportedProfiles();
82 typedef void* EGLConfig
;
83 typedef void* EGLSurface
;
85 // Creates and initializes an instance of the D3D device and the
86 // corresponding device manager. The device manager instance is eventually
87 // passed to the IMFTransform interface implemented by the decoder.
88 bool CreateD3DDevManager();
90 // Creates and initializes an instance of the DX11 device and the
91 // corresponding device manager. The device manager instance is eventually
92 // passed to the IMFTransform interface implemented by the decoder.
93 bool CreateDX11DevManager();
95 // Creates, initializes and sets the media codec types for the decoder.
96 bool InitDecoder(media::VideoCodecProfile profile
);
98 // Validates whether the decoder supports hardware video acceleration.
99 bool CheckDecoderDxvaSupport();
101 // Returns information about the input and output streams. This includes
102 // alignment information, decoder support flags, minimum sample size, etc.
103 bool GetStreamsInfoAndBufferReqs();
105 // Registers the input and output media types on the decoder. This includes
106 // the expected input and output formats.
107 bool SetDecoderMediaTypes();
109 // Registers the input media type for the decoder.
110 bool SetDecoderInputMediaType();
112 // Registers the output media type for the decoder.
113 bool SetDecoderOutputMediaType(const GUID
& subtype
);
115 // Passes a command message to the decoder. This includes commands like
116 // start of stream, end of stream, flush, drain the decoder, etc.
117 bool SendMFTMessage(MFT_MESSAGE_TYPE msg
, int32 param
);
119 // The bulk of the decoding happens here. This function handles errors,
120 // format changes and processes decoded output.
123 // Invoked when we have a valid decoded output sample. Retrieves the D3D
124 // surface and maintains a copy of it which is passed eventually to the
125 // client when we have a picture buffer to copy the surface contents to.
126 bool ProcessOutputSample(IMFSample
* sample
);
128 // Processes pending output samples by copying them to available picture
130 void ProcessPendingSamples();
132 // Helper function to notify the accelerator client about the error.
133 void StopOnError(media::VideoDecodeAccelerator::Error error
);
135 // Transitions the decoder to the uninitialized state. The decoder will stop
136 // accepting requests in this state.
139 // Notifies the client that the input buffer identifed by input_buffer_id has
141 void NotifyInputBufferRead(int input_buffer_id
);
143 // Notifies the client that the decoder was flushed.
144 void NotifyFlushDone();
146 // Notifies the client that the decoder was reset.
147 void NotifyResetDone();
149 // Requests picture buffers from the client.
150 void RequestPictureBuffers(int width
, int height
);
152 // Notifies the client about the availability of a picture.
153 void NotifyPictureReady(int picture_buffer_id
,
154 int input_buffer_id
);
156 // Sends pending input buffer processed acks to the client if we don't have
157 // output samples waiting to be processed.
158 void NotifyInputBuffersDropped();
160 // Decodes pending input buffers.
161 void DecodePendingInputBuffers();
163 // Helper for handling the Flush operation.
164 void FlushInternal();
166 // Helper for handling the Decode operation.
167 void DecodeInternal(const base::win::ScopedComPtr
<IMFSample
>& input_sample
);
169 // Handles mid stream resolution changes.
170 void HandleResolutionChanged(int width
, int height
);
172 struct DXVAPictureBuffer
;
173 typedef std::map
<int32
, linked_ptr
<DXVAPictureBuffer
> > OutputBuffers
;
175 // Tells the client to dismiss the stale picture buffers passed in.
176 void DismissStaleBuffers();
178 // Called after the client indicates we can recycle a stale picture buffer.
179 void DeferredDismissStaleBuffer(int32 picture_buffer_id
);
181 // Sets the state of the decoder. Called from the main thread and the decoder
182 // thread. The state is changed on the main thread.
183 void SetState(State state
);
185 // Gets the state of the decoder. Can be called from the main thread and
186 // the decoder thread. Thread safe.
189 // Worker function for the Decoder Reset functionality. Executes on the
190 // decoder thread and queues tasks on the main thread as needed.
193 // Starts the thread used for decoding.
194 void StartDecoderThread();
196 // Returns if we have output samples waiting to be processed. We only
197 // allow one output sample to be present in the output queue at any given
199 bool OutputSamplesPresent();
201 // Copies the source surface |src_surface| to the destination |dest_surface|.
202 // The copying is done on the decoder thread.
203 void CopySurface(IDirect3DSurface9
* src_surface
,
204 IDirect3DSurface9
* dest_surface
,
205 int picture_buffer_id
,
206 int input_buffer_id
);
208 // This is a notification that the source surface |src_surface| was copied to
209 // the destination |dest_surface|. Received on the main thread.
210 void CopySurfaceComplete(IDirect3DSurface9
* src_surface
,
211 IDirect3DSurface9
* dest_surface
,
212 int picture_buffer_id
,
213 int input_buffer_id
);
215 // Copies the source texture |src_texture| to the destination |dest_texture|.
216 // The copying is done on the decoder thread. The |video_frame| parameter
217 // is the sample containing the frame to be copied.
218 void CopyTexture(ID3D11Texture2D
* src_texture
,
219 ID3D11Texture2D
* dest_texture
,
220 IMFSample
* video_frame
,
221 int picture_buffer_id
,
222 int input_buffer_id
);
224 // Flushes the decoder device to ensure that the decoded surface is copied
225 // to the target surface. |iterations| helps to maintain an upper limit on
226 // the number of times we try to complete the flush operation.
227 void FlushDecoder(int iterations
,
228 IDirect3DSurface9
* src_surface
,
229 IDirect3DSurface9
* dest_surface
,
230 int picture_buffer_id
,
231 int input_buffer_id
);
233 // Initializes the DX11 Video format converter media types.
234 // Returns true on success.
235 bool InitializeDX11VideoFormatConverterMediaType(int width
, int height
);
237 // Returns the output video frame dimensions (width, height).
238 // |sample| :- This is the output sample containing the video frame.
239 // |width| :- The width is returned here.
240 // |height| :- The height is returned here.
241 // Returns true on success.
242 bool GetVideoFrameDimensions(IMFSample
* sample
, int* width
, int* height
);
244 // To expose client callbacks from VideoDecodeAccelerator.
245 media::VideoDecodeAccelerator::Client
* client_
;
247 base::win::ScopedComPtr
<IMFTransform
> decoder_
;
248 base::win::ScopedComPtr
<IMFTransform
> video_format_converter_mft_
;
250 base::win::ScopedComPtr
<IDirect3D9Ex
> d3d9_
;
251 base::win::ScopedComPtr
<IDirect3DDevice9Ex
> d3d9_device_ex_
;
252 base::win::ScopedComPtr
<IDirect3DDeviceManager9
> device_manager_
;
253 base::win::ScopedComPtr
<IDirect3DQuery9
> query_
;
255 base::win::ScopedComPtr
<ID3D11DeviceContext
> d3d11_device_context_
;
256 base::win::ScopedComPtr
<ID3D11Device
> d3d11_device_
;
257 base::win::ScopedComPtr
<IMFDXGIDeviceManager
> d3d11_device_manager_
;
258 base::win::ScopedComPtr
<ID3D11Query
> d3d11_query_
;
260 // Ideally the reset token would be a stack variable which is used while
261 // creating the device manager. However it seems that the device manager
262 // holds onto the token and attempts to access it if the underlying device
264 // TODO(ananta): This needs to be verified.
265 uint32 dev_manager_reset_token_
;
267 // Reset token for the DX11 device manager.
268 uint32 dx11_dev_manager_reset_token_
;
270 uint32 dx11_dev_manager_reset_token_format_conversion_
;
272 // The EGL config to use for decoded frames.
273 EGLConfig egl_config_
;
275 // Current state of the decoder.
276 volatile State state_
;
278 MFT_INPUT_STREAM_INFO input_stream_info_
;
279 MFT_OUTPUT_STREAM_INFO output_stream_info_
;
281 // Contains information about a decoded sample.
282 struct PendingSampleInfo
{
283 PendingSampleInfo(int32 buffer_id
, IMFSample
* sample
);
284 ~PendingSampleInfo();
286 int32 input_buffer_id
;
288 // The target picture buffer id where the frame would be copied to.
290 int picture_buffer_id
;
292 base::win::ScopedComPtr
<IMFSample
> output_sample
;
295 typedef std::list
<PendingSampleInfo
> PendingOutputSamples
;
297 // List of decoded output samples. Protected by |decoder_lock_|.
298 PendingOutputSamples pending_output_samples_
;
300 // This map maintains the picture buffers passed the client for decoding.
301 // The key is the picture buffer id.
302 OutputBuffers output_picture_buffers_
;
304 // After a resolution change there may be a few output buffers which have yet
305 // to be displayed so they cannot be dismissed immediately. We move them from
306 // |output_picture_buffers_| to this map so they may be dismissed once they
308 OutputBuffers stale_output_picture_buffers_
;
310 // Set to true if we requested picture slots from the client.
311 bool pictures_requested_
;
313 // Counter which holds the number of input packets before a successful
315 int inputs_before_decode_
;
317 // Set to true when the drain message is sent to the decoder during a flush
318 // operation. Used to ensure the message is only sent once after
319 // |pending_input_buffers_| is drained. Protected by |decoder_lock_|.
320 bool sent_drain_message_
;
322 // List of input samples waiting to be processed.
323 typedef std::list
<base::win::ScopedComPtr
<IMFSample
>> PendingInputs
;
324 PendingInputs pending_input_buffers_
;
326 // Callback to set the correct gl context.
327 base::Callback
<bool(void)> make_context_current_
;
329 // Which codec we are decoding with hardware acceleration.
330 media::VideoCodec codec_
;
331 // Thread on which the decoder operations like passing input frames,
332 // getting output frames are performed. One instance of this thread
333 // is created per decoder instance.
334 base::Thread decoder_thread_
;
336 // Task runner to be used for posting tasks to the decoder thread.
337 scoped_refptr
<base::SingleThreadTaskRunner
> decoder_thread_task_runner_
;
339 // Task runner to be used for posting tasks to the main thread.
340 scoped_refptr
<base::SingleThreadTaskRunner
> main_thread_task_runner_
;
342 // Used to synchronize access between the decoder thread and the main thread.
343 base::Lock decoder_lock_
;
345 // Disallow rebinding WeakReference ownership to a different thread by
346 // keeping a persistent reference. This avoids problems with the
347 // thread safety of reaching into this class from multiple threads to
349 base::WeakPtr
<DXVAVideoDecodeAccelerator
> weak_ptr_
;
351 // Set to true if we are in the context of a Flush operation. Used to prevent
352 // multiple flush done notifications being sent out.
355 // Defaults to false. Indicates if we should use D3D or DX11 interfaces for
359 // Set to true if the DX11 video format converter input media types need to
360 // be initialized. Defaults to true.
361 bool dx11_video_format_converter_media_type_needs_init_
;
363 // The GLContext to be used by the decoder.
364 scoped_refptr
<gfx::GLContext
> gl_context_
;
366 // WeakPtrFactory for posting tasks back to |this|.
367 base::WeakPtrFactory
<DXVAVideoDecodeAccelerator
> weak_this_factory_
;
369 // Function pointer for the MFCreateDXGIDeviceManager API.
370 static CreateDXGIDeviceManager create_dxgi_device_manager_
;
373 } // namespace content
375 #endif // CONTENT_COMMON_GPU_MEDIA_DXVA_VIDEO_DECODE_ACCELERATOR_H_