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