Home | History | Annotate | Download | only in vda
      1 // Copyright 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 VideoDecodeAccelerator
      6 // that utilizes hardware video decoders, which expose Video4Linux 2 API
      7 // (http://linuxtv.org/downloads/v4l-dvb-apis/).
      8 // Note: ported from Chromium commit head: 85fdf90
      9 // Note: image processor is not ported.
     10 
     11 #ifndef MEDIA_GPU_V4L2_VIDEO_DECODE_ACCELERATOR_H_
     12 #define MEDIA_GPU_V4L2_VIDEO_DECODE_ACCELERATOR_H_
     13 
     14 #include <stddef.h>
     15 #include <stdint.h>
     16 
     17 #include <list>
     18 #include <memory>
     19 #include <queue>
     20 #include <vector>
     21 
     22 #include "base/callback_forward.h"
     23 #include "base/macros.h"
     24 #include "base/memory/linked_ptr.h"
     25 #include "base/memory/ref_counted.h"
     26 #include "base/synchronization/waitable_event.h"
     27 #include "base/threading/thread.h"
     28 #include "picture.h"
     29 #include "size.h"
     30 #include "v4l2_device.h"
     31 #include "video_decode_accelerator.h"
     32 
     33 namespace media {
     34 
     35 class H264Parser;
     36 
     37 // This class handles video accelerators directly through a V4L2 device exported
     38 // by the hardware blocks.
     39 //
     40 // The threading model of this class is driven by the fact that it needs to
     41 // interface two fundamentally different event queues -- the one Chromium
     42 // provides through MessageLoop, and the one driven by the V4L2 devices which
     43 // is waited on with epoll().  There are three threads involved in this class:
     44 //
     45 // * The child thread, which is the main GPU process thread which calls the
     46 //   VideoDecodeAccelerator entry points.  Calls from this thread
     47 //   generally do not block (with the exception of Initialize() and Destroy()).
     48 //   They post tasks to the decoder_thread_, which actually services the task
     49 //   and calls back when complete through the
     50 //   VideoDecodeAccelerator::Client interface.
     51 // * The decoder_thread_, owned by this class.  It services API tasks, through
     52 //   the *Task() routines, as well as V4L2 device events, through
     53 //   ServiceDeviceTask().  Almost all state modification is done on this thread
     54 //   (this doesn't include buffer (re)allocation sequence, see below).
     55 // * The device_poll_thread_, owned by this class.  All it does is epoll() on
     56 //   the V4L2 in DevicePollTask() and schedule a ServiceDeviceTask() on the
     57 //   decoder_thread_ when something interesting happens.
     58 //   TODO(sheu): replace this thread with an TYPE_IO decoder_thread_.
     59 //
     60 // Note that this class has (almost) no locks, apart from the pictures_assigned_
     61 // WaitableEvent. Everything (apart from buffer (re)allocation) is serviced on
     62 // the decoder_thread_, so there are no synchronization issues.
     63 // ... well, there are, but it's a matter of getting messages posted in the
     64 // right order, not fiddling with locks.
     65 // Buffer creation is a two-step process that is serviced partially on the
     66 // Child thread, because we need to wait for the client to provide textures
     67 // for the buffers we allocate. We cannot keep the decoder thread running while
     68 // the client allocates Pictures for us, because we need to REQBUFS first to get
     69 // the required number of output buffers from the device and that cannot be done
     70 // unless we free the previous set of buffers, leaving the decoding in a
     71 // inoperable state for the duration of the wait for Pictures. So to prevent
     72 // subtle races (esp. if we get Reset() in the meantime), we block the decoder
     73 // thread while we wait for AssignPictureBuffers from the client.
     74 //
     75 // V4L2VideoDecodeAccelerator may use image processor to convert the output.
     76 // There are three cases:
     77 // Flush: V4L2VDA should wait until image processor returns all processed
     78 //   frames.
     79 // Reset: V4L2VDA doesn't need to wait for image processor. When image processor
     80 //   returns an old frame, drop it.
     81 // Resolution change: V4L2VDA destroy image processor when destroying output
     82 //   buffrers. We cannot drop any frame during resolution change. So V4L2VDA
     83 //   should destroy output buffers after image processor returns all the frames.
     84 class V4L2VideoDecodeAccelerator
     85     : public VideoDecodeAccelerator {
     86  public:
     87   V4L2VideoDecodeAccelerator(
     88       const scoped_refptr<V4L2Device>& device);
     89   ~V4L2VideoDecodeAccelerator() override;
     90 
     91   // VideoDecodeAccelerator implementation.
     92   // Note: Initialize() and Destroy() are synchronous.
     93   bool Initialize(const Config& config, Client* client) override;
     94   void Decode(const BitstreamBuffer& bitstream_buffer) override;
     95   void AssignPictureBuffers(const std::vector<PictureBuffer>& buffers) override;
     96   void ImportBufferForPicture(
     97       int32_t picture_buffer_id,
     98       VideoPixelFormat pixel_format,
     99       const NativePixmapHandle& native_pixmap_handle) override;
    100   void ReusePictureBuffer(int32_t picture_buffer_id) override;
    101   void Flush() override;
    102   void Reset() override;
    103   void Destroy() override;
    104   bool TryToSetupDecodeOnSeparateThread(
    105       const base::WeakPtr<Client>& decode_client,
    106       const scoped_refptr<base::SingleThreadTaskRunner>& decode_task_runner)
    107       override;
    108 
    109   static VideoDecodeAccelerator::SupportedProfiles GetSupportedProfiles();
    110 
    111  private:
    112   // These are rather subjectively tuned.
    113   enum {
    114     kInputBufferCount = 8,
    115     // TODO(posciak): determine input buffer size based on level limits.
    116     // See http://crbug.com/255116.
    117     // Input bitstream buffer size for up to 1080p streams.
    118     kInputBufferMaxSizeFor1080p = 1024 * 1024,
    119     // Input bitstream buffer size for up to 4k streams.
    120     kInputBufferMaxSizeFor4k = 4 * kInputBufferMaxSizeFor1080p,
    121     // This is originally from media/base/limits.h in Chromium.
    122     kMaxVideoFrames = 4,
    123     // Number of output buffers to use for each VDA stage above what's required
    124     // by the decoder (e.g. DPB size, in H264).  We need
    125     // limits::kMaxVideoFrames to fill up the GpuVideoDecode pipeline,
    126     // and +1 for a frame in transit.
    127     kDpbOutputBufferExtraCount = kMaxVideoFrames + 1,
    128     // Number of extra output buffers if image processor is used.
    129     kDpbOutputBufferExtraCountForImageProcessor = 1,
    130   };
    131 
    132   // Internal state of the decoder.
    133   enum State {
    134     kUninitialized,  // Initialize() not yet called.
    135     kInitialized,    // Initialize() returned true; ready to start decoding.
    136     kDecoding,       // DecodeBufferInitial() successful; decoding frames.
    137     kResetting,      // Presently resetting.
    138     // Performing resolution change and waiting for image processor to return
    139     // all frames.
    140     kChangingResolution,
    141     // Requested new PictureBuffers via ProvidePictureBuffers(), awaiting
    142     // AssignPictureBuffers().
    143     kAwaitingPictureBuffers,
    144     kError,  // Error in kDecoding state.
    145   };
    146 
    147   enum OutputRecordState {
    148     kFree,         // Ready to be queued to the device.
    149     kAtDevice,     // Held by device.
    150     kAtProcessor,  // Held by image processor.
    151     kAtClient,     // Held by client of V4L2VideoDecodeAccelerator.
    152   };
    153 
    154   enum BufferId {
    155     kFlushBufferId = -2  // Buffer id for flush buffer, queued by FlushTask().
    156   };
    157 
    158   // Auto-destruction reference for BitstreamBuffer, for message-passing from
    159   // Decode() to DecodeTask().
    160   struct BitstreamBufferRef;
    161 
    162   // Record for decoded pictures that can be sent to PictureReady.
    163   struct PictureRecord {
    164     PictureRecord(bool cleared, const Picture& picture);
    165     ~PictureRecord();
    166     bool cleared;     // Whether the texture is cleared and safe to render from.
    167     Picture picture;  // The decoded picture.
    168   };
    169 
    170   // Record for input buffers.
    171   struct InputRecord {
    172     InputRecord();
    173     ~InputRecord();
    174     bool at_device;    // held by device.
    175     void* address;     // mmap() address.
    176     size_t length;     // mmap() length.
    177     off_t bytes_used;  // bytes filled in the mmap() segment.
    178     int32_t input_id;  // triggering input_id as given to Decode().
    179   };
    180 
    181   // Record for output buffers.
    182   struct OutputRecord {
    183     OutputRecord();
    184     OutputRecord(OutputRecord&&) = default;
    185     ~OutputRecord();
    186     OutputRecordState state;
    187     int32_t picture_id;     // picture buffer id as returned to PictureReady().
    188     bool cleared;           // Whether the texture is cleared and safe to render
    189                             // from. See TextureManager for details.
    190     // Output fds of the processor. Used only when OutputMode is IMPORT.
    191     std::vector<base::ScopedFD> processor_output_fds;
    192   };
    193 
    194   //
    195   // Decoding tasks, to be run on decode_thread_.
    196   //
    197 
    198   // Task to finish initialization on decoder_thread_.
    199   void InitializeTask();
    200 
    201   // Enqueue a BitstreamBuffer to decode.  This will enqueue a buffer to the
    202   // decoder_input_queue_, then queue a DecodeBufferTask() to actually decode
    203   // the buffer.
    204   void DecodeTask(const BitstreamBuffer& bitstream_buffer);
    205 
    206   // Decode from the buffers queued in decoder_input_queue_.  Calls
    207   // DecodeBufferInitial() or DecodeBufferContinue() as appropriate.
    208   void DecodeBufferTask();
    209   // Advance to the next fragment that begins a frame.
    210   bool AdvanceFrameFragment(const uint8_t* data, size_t size, size_t* endpos);
    211   // Schedule another DecodeBufferTask() if we're behind.
    212   void ScheduleDecodeBufferTaskIfNeeded();
    213 
    214   // Return true if we should continue to schedule DecodeBufferTask()s after
    215   // completion.  Store the amount of input actually consumed in |endpos|.
    216   bool DecodeBufferInitial(const void* data, size_t size, size_t* endpos);
    217   bool DecodeBufferContinue(const void* data, size_t size);
    218 
    219   // Accumulate data for the next frame to decode.  May return false in
    220   // non-error conditions; for example when pipeline is full and should be
    221   // retried later.
    222   bool AppendToInputFrame(const void* data, size_t size);
    223   // Flush data for one decoded frame.
    224   bool FlushInputFrame();
    225 
    226   // Allocate V4L2 buffers and assign them to |buffers| provided by the client
    227   // via AssignPictureBuffers() on decoder thread.
    228   void AssignPictureBuffersTask(const std::vector<PictureBuffer>& buffers);
    229 
    230   // Use buffer backed by dmabuf file descriptors in |dmabuf_fds| for the
    231   // OutputRecord associated with |picture_buffer_id|, taking ownership of the
    232   // file descriptors.
    233   void ImportBufferForPictureTask(int32_t picture_buffer_id,
    234                                   std::vector<base::ScopedFD> dmabuf_fds);
    235 
    236   // Service I/O on the V4L2 devices.  This task should only be scheduled from
    237   // DevicePollTask().  If |event_pending| is true, one or more events
    238   // on file descriptor are pending.
    239   void ServiceDeviceTask(bool event_pending);
    240   // Handle the various device queues.
    241   void Enqueue();
    242   void Dequeue();
    243   // Dequeue one input buffer. Return true if success.
    244   bool DequeueInputBuffer();
    245   // Dequeue one output buffer. Return true if success.
    246   bool DequeueOutputBuffer();
    247 
    248   // Return true if there is a resolution change event pending.
    249   bool DequeueResolutionChangeEvent();
    250 
    251   // Enqueue a buffer on the corresponding queue.
    252   bool EnqueueInputRecord();
    253   bool EnqueueOutputRecord();
    254 
    255   // Process a ReusePictureBuffer() API call.  The API call create an EGLSync
    256   // object on the main (GPU process) thread; we will record this object so we
    257   // can wait on it before reusing the buffer.
    258   void ReusePictureBufferTask(int32_t picture_buffer_id);
    259 
    260   // Flush() task.  Child thread should not submit any more buffers until it
    261   // receives the NotifyFlushDone callback.  This task will schedule an empty
    262   // BitstreamBufferRef (with input_id == kFlushBufferId) to perform the flush.
    263   void FlushTask();
    264   // Notify the client of a flush completion, if required.  This should be
    265   // called any time a relevant queue could potentially be emptied: see
    266   // function definition.
    267   void NotifyFlushDoneIfNeeded();
    268   // Returns true if VIDIOC_DECODER_CMD is supported.
    269   bool IsDecoderCmdSupported();
    270   // Send V4L2_DEC_CMD_START to the driver. Return true if success.
    271   bool SendDecoderCmdStop();
    272 
    273   // Reset() task.  Drop all input buffers. If V4L2VDA is not doing resolution
    274   // change or waiting picture buffers, call FinishReset.
    275   void ResetTask();
    276   // This will schedule a ResetDoneTask() that will send the NotifyResetDone
    277   // callback, then set the decoder state to kResetting so that all intervening
    278   // tasks will drain.
    279   void FinishReset();
    280   void ResetDoneTask();
    281 
    282   // Device destruction task.
    283   void DestroyTask();
    284 
    285   // Start |device_poll_thread_|.
    286   bool StartDevicePoll();
    287 
    288   // Stop |device_poll_thread_|.
    289   bool StopDevicePoll();
    290 
    291   bool StopInputStream();
    292   bool StopOutputStream();
    293 
    294   void StartResolutionChange();
    295   void FinishResolutionChange();
    296 
    297   // Try to get output format and visible size, detected after parsing the
    298   // beginning of the stream. Sets |again| to true if more parsing is needed.
    299   // |visible_size| could be nullptr and ignored.
    300   bool GetFormatInfo(struct v4l2_format* format,
    301                      Size* visible_size,
    302                      bool* again);
    303   // Create output buffers for the given |format| and |visible_size|.
    304   bool CreateBuffersForFormat(const struct v4l2_format& format,
    305                               const Size& visible_size);
    306 
    307   // Try to get |visible_size|. Return visible size, or, if querying it is not
    308   // supported or produces invalid size, return |coded_size| instead.
    309   Size GetVisibleSize(const Size& coded_size);
    310 
    311   //
    312   // Device tasks, to be run on device_poll_thread_.
    313   //
    314 
    315   // The device task.
    316   void DevicePollTask(bool poll_device);
    317 
    318   //
    319   // Safe from any thread.
    320   //
    321 
    322   // Error notification (using PostTask() to child thread, if necessary).
    323   void NotifyError(Error error);
    324 
    325   // Set the decoder_state_ to kError and notify the client (if necessary).
    326   void SetErrorState(Error error);
    327 
    328   //
    329   // Other utility functions.  Called on decoder_thread_, unless
    330   // decoder_thread_ is not yet started, in which case the child thread can call
    331   // these (e.g. in Initialize() or Destroy()).
    332   //
    333 
    334   // Create the buffers we need.
    335   bool CreateInputBuffers();
    336   bool CreateOutputBuffers();
    337 
    338   // Destroy buffers.
    339   void DestroyInputBuffers();
    340   // In contrast to DestroyInputBuffers, which is called only on destruction,
    341   // we call DestroyOutputBuffers also during playback, on resolution change.
    342   // Even if anything fails along the way, we still want to go on and clean
    343   // up as much as possible, so return false if this happens, so that the
    344   // caller can error out on resolution change.
    345   bool DestroyOutputBuffers();
    346 
    347   // Set input and output formats before starting decode.
    348   bool SetupFormats();
    349 
    350   //
    351   // Methods run on child thread.
    352   //
    353 
    354   // Send decoded pictures to PictureReady.
    355   void SendPictureReady();
    356 
    357   // Callback that indicates a picture has been cleared.
    358   void PictureCleared();
    359 
    360   // Our original calling task runner for the child thread.
    361   scoped_refptr<base::SingleThreadTaskRunner> child_task_runner_;
    362 
    363   // Task runner Decode() and PictureReady() run on.
    364   scoped_refptr<base::SingleThreadTaskRunner> decode_task_runner_;
    365 
    366   // WeakPtr<> pointing to |this| for use in posting tasks from the decoder or
    367   // device worker threads back to the child thread.  Because the worker threads
    368   // are members of this class, any task running on those threads is guaranteed
    369   // that this object is still alive.  As a result, tasks posted from the child
    370   // thread to the decoder or device thread should use base::Unretained(this),
    371   // and tasks posted the other way should use |weak_this_|.
    372   base::WeakPtr<V4L2VideoDecodeAccelerator> weak_this_;
    373 
    374   // To expose client callbacks from VideoDecodeAccelerator.
    375   // NOTE: all calls to these objects *MUST* be executed on
    376   // child_task_runner_.
    377   std::unique_ptr<base::WeakPtrFactory<Client>> client_ptr_factory_;
    378   base::WeakPtr<Client> client_;
    379   // Callbacks to |decode_client_| must be executed on |decode_task_runner_|.
    380   base::WeakPtr<Client> decode_client_;
    381 
    382   //
    383   // Decoder state, owned and operated by decoder_thread_.
    384   // Before decoder_thread_ has started, the decoder state is managed by
    385   // the child (main) thread.  After decoder_thread_ has started, the decoder
    386   // thread should be the only one managing these.
    387   //
    388 
    389   // This thread services tasks posted from the VDA API entry points by the
    390   // child thread and device service callbacks posted from the device thread.
    391   base::Thread decoder_thread_;
    392   // Decoder state machine state.
    393   State decoder_state_;
    394 
    395   Config::OutputMode output_mode_;
    396 
    397   // BitstreamBuffer we're presently reading.
    398   std::unique_ptr<BitstreamBufferRef> decoder_current_bitstream_buffer_;
    399   // The V4L2Device this class is operating upon.
    400   scoped_refptr<V4L2Device> device_;
    401   // FlushTask() and ResetTask() should not affect buffers that have been
    402   // queued afterwards.  For flushing or resetting the pipeline then, we will
    403   // delay these buffers until after the flush or reset completes.
    404   int decoder_delay_bitstream_buffer_id_;
    405   // Input buffer we're presently filling.
    406   int decoder_current_input_buffer_;
    407   // We track the number of buffer decode tasks we have scheduled, since each
    408   // task execution should complete one buffer.  If we fall behind (due to
    409   // resource backpressure, etc.), we'll have to schedule more to catch up.
    410   int decoder_decode_buffer_tasks_scheduled_;
    411   // Picture buffers held by the client.
    412   int decoder_frames_at_client_;
    413 
    414   // Are we flushing?
    415   bool decoder_flushing_;
    416   // True if VIDIOC_DECODER_CMD is supported.
    417   bool decoder_cmd_supported_;
    418   // True if flushing is waiting for last output buffer. After
    419   // VIDIOC_DECODER_CMD is sent to the driver, this flag will be set to true to
    420   // wait for the last output buffer. When this flag is true, flush done will
    421   // not be sent. After an output buffer that has the flag V4L2_BUF_FLAG_LAST is
    422   // received, this is set to false.
    423   bool flush_awaiting_last_output_buffer_;
    424 
    425   // Got a reset request while we were performing resolution change or waiting
    426   // picture buffers.
    427   bool reset_pending_;
    428   // Input queue for decoder_thread_: BitstreamBuffers in.
    429   std::queue<linked_ptr<BitstreamBufferRef>> decoder_input_queue_;
    430   // For H264 decode, hardware requires that we send it frame-sized chunks.
    431   // We'll need to parse the stream.
    432   std::unique_ptr<H264Parser> decoder_h264_parser_;
    433   // Set if the decoder has a pending incomplete frame in an input buffer.
    434   bool decoder_partial_frame_pending_;
    435 
    436   //
    437   // Hardware state and associated queues.  Since decoder_thread_ services
    438   // the hardware, decoder_thread_ owns these too.
    439   // output_buffer_map_, free_output_buffers_ and output_planes_count_ are an
    440   // exception during the buffer (re)allocation sequence, when the
    441   // decoder_thread_ is blocked briefly while the Child thread manipulates
    442   // them.
    443   //
    444 
    445   // Completed decode buffers.
    446   std::queue<int> input_ready_queue_;
    447 
    448   // Input buffer state.
    449   bool input_streamon_;
    450   // Input buffers enqueued to device.
    451   int input_buffer_queued_count_;
    452   // Input buffers ready to use, as a LIFO since we don't care about ordering.
    453   std::vector<int> free_input_buffers_;
    454   // Mapping of int index to input buffer record.
    455   std::vector<InputRecord> input_buffer_map_;
    456 
    457   // Output buffer state.
    458   bool output_streamon_;
    459   // Output buffers enqueued to device.
    460   int output_buffer_queued_count_;
    461   // Output buffers ready to use, as a FIFO since we want oldest-first to hide
    462   // synchronization latency with GL.
    463   std::list<int> free_output_buffers_;
    464   // Mapping of int index to output buffer record.
    465   std::vector<OutputRecord> output_buffer_map_;
    466   // Required size of DPB for decoding.
    467   int output_dpb_size_;
    468 
    469   // Number of planes (i.e. separate memory buffers) for output.
    470   size_t output_planes_count_;
    471 
    472   // Pictures that are ready but not sent to PictureReady yet.
    473   std::queue<PictureRecord> pending_picture_ready_;
    474 
    475   // The number of pictures that are sent to PictureReady and will be cleared.
    476   int picture_clearing_count_;
    477 
    478   // Output picture coded size.
    479   Size coded_size_;
    480 
    481   // Output picture visible size.
    482   Size visible_size_;
    483 
    484   //
    485   // The device polling thread handles notifications of V4L2 device changes.
    486   //
    487 
    488   // The thread.
    489   base::Thread device_poll_thread_;
    490 
    491   //
    492   // Other state, held by the child (main) thread.
    493   //
    494 
    495   // The codec we'll be decoding for.
    496   VideoCodecProfile video_profile_;
    497   // Chosen input format for video_profile_.
    498   uint32_t input_format_fourcc_;
    499   // Chosen output format.
    500   uint32_t output_format_fourcc_;
    501 
    502   // Input format V4L2 fourccs this class supports.
    503   static const uint32_t supported_input_fourccs_[];
    504 
    505   // The WeakPtrFactory for |weak_this_|.
    506   base::WeakPtrFactory<V4L2VideoDecodeAccelerator> weak_this_factory_;
    507 
    508   DISALLOW_COPY_AND_ASSIGN(V4L2VideoDecodeAccelerator);
    509 };
    510 
    511 }  // namespace media
    512 
    513 #endif  // MEDIA_GPU_V4L2_VIDEO_DECODE_ACCELERATOR_H_
    514