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