Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / content / common / gpu / media / vaapi_video_decode_accelerator.h
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.
4 //
5 // This file contains an implementation of VideoDecoderAccelerator
6 // that utilizes hardware video decoder present on Intel CPUs.
7
8 #ifndef CONTENT_COMMON_GPU_MEDIA_VAAPI_VIDEO_DECODE_ACCELERATOR_H_
9 #define CONTENT_COMMON_GPU_MEDIA_VAAPI_VIDEO_DECODE_ACCELERATOR_H_
10
11 #if defined(USE_OZONE)
12 #include <wayland-client.h>
13 #endif
14 #include <list>
15 #include <map>
16 #include <queue>
17 #include <utility>
18 #include <vector>
19
20 #include "base/logging.h"
21 #include "base/memory/linked_ptr.h"
22 #include "base/memory/shared_memory.h"
23 #include "base/memory/weak_ptr.h"
24 #include "base/message_loop/message_loop.h"
25 #include "base/synchronization/condition_variable.h"
26 #include "base/synchronization/lock.h"
27 #include "base/threading/non_thread_safe.h"
28 #include "base/threading/thread.h"
29 #include "content/common/content_export.h"
30 #include "content/common/gpu/media/vaapi_h264_decoder.h"
31 #include "content/common/gpu/media/vaapi_wrapper.h"
32 #include "content/common/gpu/media/video_decode_accelerator_impl.h"
33 #include "media/base/bitstream_buffer.h"
34 #include "media/video/picture.h"
35 #include "media/video/video_decode_accelerator.h"
36 #include "ui/gl/gl_bindings.h"
37
38 namespace content {
39
40 // Class to provide video decode acceleration for Intel systems with hardware
41 // support for it, and on which libva is available.
42 // Decoding tasks are performed in a separate decoding thread.
43 //
44 // Threading/life-cycle: this object is created & destroyed on the GPU
45 // ChildThread.  A few methods on it are called on the decoder thread which is
46 // stopped during |this->Destroy()|, so any tasks posted to the decoder thread
47 // can assume |*this| is still alive.  See |weak_this_| below for more details.
48 class CONTENT_EXPORT VaapiVideoDecodeAccelerator
49     : public VideoDecodeAcceleratorImpl {
50  public:
51 #if defined(USE_OZONE)
52   VaapiVideoDecodeAccelerator(
53       const base::Callback<bool(void)>& make_context_current); //NOLINT
54 #else
55   VaapiVideoDecodeAccelerator(
56       Display* x_display,
57       const base::Callback<bool(void)>& make_context_current);
58 #endif
59   virtual ~VaapiVideoDecodeAccelerator();
60
61   // media::VideoDecodeAccelerator implementation.
62   virtual bool Initialize(media::VideoCodecProfile profile,
63                           Client* client) OVERRIDE;
64   virtual void Decode(const media::BitstreamBuffer& bitstream_buffer) OVERRIDE;
65   virtual void AssignPictureBuffers(
66       const std::vector<media::PictureBuffer>& buffers) OVERRIDE;
67   virtual void ReusePictureBuffer(int32 picture_buffer_id) OVERRIDE;
68   virtual void Flush() OVERRIDE;
69   virtual void Reset() OVERRIDE;
70   virtual void Destroy() OVERRIDE;
71
72 private:
73   // Notify the client that an error has occurred and decoding cannot continue.
74   void NotifyError(Error error);
75
76   // Map the received input buffer into this process' address space and
77   // queue it for decode.
78   void MapAndQueueNewInputBuffer(
79       const media::BitstreamBuffer& bitstream_buffer);
80
81   // Get a new input buffer from the queue and set it up in decoder. This will
82   // sleep if no input buffers are available. Return true if a new buffer has
83   // been set up, false if an early exit has been requested (due to initiated
84   // reset/flush/destroy).
85   bool GetInputBuffer_Locked();
86
87   // Signal the client that the current buffer has been read and can be
88   // returned. Will also release the mapping.
89   void ReturnCurrInputBuffer_Locked();
90
91   // Pass one or more output buffers to the decoder. This will sleep
92   // if no buffers are available. Return true if buffers have been set up or
93   // false if an early exit has been requested (due to initiated
94   // reset/flush/destroy).
95   bool FeedDecoderWithOutputSurfaces_Locked();
96
97   // Continue decoding given input buffers and sleep waiting for input/output
98   // as needed. Will exit if a new set of surfaces or reset/flush/destroy
99   // is requested.
100   void DecodeTask();
101
102   // Scheduled after receiving a flush request and executed after the current
103   // decoding task finishes decoding pending inputs. Makes the decoder return
104   // all remaining output pictures and puts it in an idle state, ready
105   // to resume if needed and schedules a FinishFlush.
106   void FlushTask();
107
108   // Scheduled by the FlushTask after decoder is flushed to put VAVDA into idle
109   // state and notify the client that flushing has been finished.
110   void FinishFlush();
111
112   // Scheduled after receiving a reset request and executed after the current
113   // decoding task finishes decoding the current frame. Puts the decoder into
114   // an idle state, ready to resume if needed, discarding decoded but not yet
115   // outputted pictures (decoder keeps ownership of their associated picture
116   // buffers). Schedules a FinishReset afterwards.
117   void ResetTask();
118
119   // Scheduled by ResetTask after it's done putting VAVDA into an idle state.
120   // Drops remaining input buffers and notifies the client that reset has been
121   // finished.
122   void FinishReset();
123
124   // Helper for Destroy(), doing all the actual work except for deleting self.
125   void Cleanup();
126
127   // Get a usable framebuffer configuration for use in binding textures
128   // or return false on failure.
129   bool InitializeFBConfig();
130
131   // Callback for the decoder to execute when it wants us to output given
132   // |va_surface|.
133   void SurfaceReady(int32 input_id, const scoped_refptr<VASurface>& va_surface);
134
135   // Represents a texture bound to an X Pixmap for output purposes.
136   class TFPPicture;
137
138   // Callback to be executed once we have a |va_surface| to be output and
139   // an available |tfp_picture| to use for output.
140   // Puts contents of |va_surface| into given |tfp_picture|, releases the
141   // surface and passes the resulting picture to client for output.
142   void OutputPicture(const scoped_refptr<VASurface>& va_surface,
143                      int32 input_id,
144                      TFPPicture* tfp_picture);
145
146   // Try to OutputPicture() if we have both a ready surface and picture.
147   void TryOutputSurface();
148
149   // Called when a VASurface is no longer in use by the decoder or is not being
150   // synced/waiting to be synced to a picture. Returns it to available surfaces
151   // pool.
152   void RecycleVASurfaceID(VASurfaceID va_surface_id);
153
154   // Initiate wait cycle for surfaces to be released before we release them
155   // and allocate new ones, as requested by the decoder.
156   void InitiateSurfaceSetChange(size_t num_pics, gfx::Size size);
157   // Check if the surfaces have been released or post ourselves for later.
158   void TryFinishSurfaceSetChange();
159
160 #if defined(USE_OZONE)
161   wl_display* wl_display_;
162   base::Callback<bool(void)> make_context_current_; //NOLINT
163 #else
164   // Client-provided X/GLX state.
165   Display* x_display_;
166   base::Callback<bool(void)> make_context_current_;
167   GLXFBConfig fb_config_;
168 #endif
169
170   // VAVDA state.
171   enum State {
172     // Initialize() not called yet or failed.
173     kUninitialized,
174     // DecodeTask running.
175     kDecoding,
176     // Resetting, waiting for decoder to finish current task and cleanup.
177     kResetting,
178     // Flushing, waiting for decoder to finish current task and cleanup.
179     kFlushing,
180     // Idle, decoder in state ready to start/resume decoding.
181     kIdle,
182     // Destroying, waiting for the decoder to finish current task.
183     kDestroying,
184   };
185
186   // Protects input buffer and surface queues and state_.
187   base::Lock lock_;
188   State state_;
189
190   // An input buffer awaiting consumption, provided by the client.
191   struct InputBuffer {
192     InputBuffer();
193     ~InputBuffer();
194
195     int32 id;
196     size_t size;
197     scoped_ptr<base::SharedMemory> shm;
198   };
199
200   // Queue for incoming input buffers.
201   typedef std::queue<linked_ptr<InputBuffer> > InputBuffers;
202   InputBuffers input_buffers_;
203   // Signalled when input buffers are queued onto the input_buffers_ queue.
204   base::ConditionVariable input_ready_;
205
206   // Current input buffer at decoder.
207   linked_ptr<InputBuffer> curr_input_buffer_;
208
209   // Queue for incoming output buffers (texture ids).
210   typedef std::queue<int32> OutputBuffers;
211   OutputBuffers output_buffers_;
212
213   typedef std::map<int32, linked_ptr<TFPPicture> > TFPPictures;
214   // All allocated TFPPictures, regardless of their current state. TFPPictures
215   // are allocated once and destroyed at the end of decode.
216   TFPPictures tfp_pictures_;
217
218   // Return a TFPPicture associated with given client-provided id.
219   TFPPicture* TFPPictureById(int32 picture_buffer_id);
220
221   // VA Surfaces no longer in use that can be passed back to the decoder for
222   // reuse, once it requests them.
223   std::list<VASurfaceID> available_va_surfaces_;
224   // Signalled when output surfaces are queued onto the available_va_surfaces_
225   // queue.
226   base::ConditionVariable surfaces_available_;
227
228   // Pending output requests from the decoder. When it indicates that we should
229   // output a surface and we have an available TFPPicture (i.e. texture) ready
230   // to use, we'll execute the callback passing the TFPPicture. The callback
231   // will put the contents of the surface into the picture and return it to
232   // the client, releasing the surface as well.
233   // If we don't have any available TFPPictures at the time when the decoder
234   // requests output, we'll store the request on pending_output_cbs_ queue for
235   // later and run it once the client gives us more textures
236   // via ReusePictureBuffer().
237   typedef base::Callback<void(TFPPicture*)> OutputCB;
238   std::queue<OutputCB> pending_output_cbs_;
239
240   // ChildThread's message loop
241   base::MessageLoop* message_loop_;
242
243   // WeakPtr<> pointing to |this| for use in posting tasks from the decoder
244   // thread back to the ChildThread.  Because the decoder thread is a member of
245   // this class, any task running on the decoder thread is guaranteed that this
246   // object is still alive.  As a result, tasks posted from ChildThread to
247   // decoder thread should use base::Unretained(this), and tasks posted from the
248   // decoder thread to the ChildThread should use |weak_this_|.
249   base::WeakPtr<VaapiVideoDecodeAccelerator> weak_this_;
250
251   // Callback used when creating VASurface objects.
252   VASurface::ReleaseCB va_surface_release_cb_;
253
254   // To expose client callbacks from VideoDecodeAccelerator.
255   // NOTE: all calls to these objects *MUST* be executed on message_loop_.
256   scoped_ptr<base::WeakPtrFactory<Client> > client_ptr_factory_;
257   base::WeakPtr<Client> client_;
258
259   scoped_ptr<VaapiWrapper> vaapi_wrapper_;
260
261   // Comes after vaapi_wrapper_ to ensure its destructor is executed before
262   // vaapi_wrapper_ is destroyed.
263   scoped_ptr<VaapiH264Decoder> decoder_;
264   base::Thread decoder_thread_;
265   // Use this to post tasks to |decoder_thread_| instead of
266   // |decoder_thread_.message_loop()| because the latter will be NULL once
267   // |decoder_thread_.Stop()| returns.
268   scoped_refptr<base::MessageLoopProxy> decoder_thread_proxy_;
269
270   int num_frames_at_client_;
271   int num_stream_bufs_at_decoder_;
272
273   // Whether we are waiting for any pending_output_cbs_ to be run before
274   // NotifyingFlushDone.
275   bool finish_flush_pending_;
276
277   // Decoder requested a new surface set and we are waiting for all the surfaces
278   // to be returned before we can free them.
279   bool awaiting_va_surfaces_recycle_;
280
281   // Last requested number/resolution of output picture buffers.
282   size_t requested_num_pics_;
283   gfx::Size requested_pic_size_;
284
285   // The WeakPtrFactory for |weak_this_|.
286   base::WeakPtrFactory<VaapiVideoDecodeAccelerator> weak_this_factory_;
287
288   DISALLOW_COPY_AND_ASSIGN(VaapiVideoDecodeAccelerator);
289 };
290
291 }  // namespace content
292
293 #endif  // CONTENT_COMMON_GPU_MEDIA_VAAPI_VIDEO_DECODE_ACCELERATOR_H_