• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifndef VIDEO_DECODE_ACCELERATOR_H_
6 #define VIDEO_DECODE_ACCELERATOR_H_
7 
8 #include <vector>
9 
10 #include "base/file_descriptor_posix.h"
11 #include "base/memory/ref_counted.h"
12 #include "base/memory/weak_ptr.h"
13 
14 #include "bitstream_buffer.h"
15 #include "picture.h"
16 #include "size.h"
17 #include "video_codecs.h"
18 #include "video_pixel_format.h"
19 
20 namespace base {
21 class SingleThreadTaskRunner;
22 }
23 
24 namespace media {
25 
26 // Video decoder interface.
27 // This interface is extended by the various components that ultimately
28 // implement the backend of PPB_VideoDecoder_Dev.
29 class VideoDecodeAccelerator {
30  public:
31   // Specification of a decoding profile supported by an decoder.
32   // |max_resolution| and |min_resolution| are inclusive.
33   struct SupportedProfile {
34     SupportedProfile();
35     ~SupportedProfile();
36     VideoCodecProfile profile;
37     Size max_resolution;
38     Size min_resolution;
39     bool encrypted_only;
40   };
41   using SupportedProfiles = std::vector<SupportedProfile>;
42 
43   struct Capabilities {
44     Capabilities();
45     Capabilities(const Capabilities& other);
46     ~Capabilities();
47 
48     std::string AsHumanReadableString() const;
49 
50     // Flags that can be associated with a VDA.
51     enum Flags {
52       NO_FLAGS = 0,
53 
54       // Normally, the VDA is required to be able to provide all PictureBuffers
55       // to the client via PictureReady(), even if the client does not return
56       // any of them via ReusePictureBuffer().  The client is only required to
57       // return PictureBuffers when it holds all of them, if it wants to get
58       // more decoded output.  See VideoDecoder::CanReadWithoutStalling for
59       // more context.
60       // If this flag is set, then the VDA does not make this guarantee.  The
61       // client must return PictureBuffers to be sure that new frames will be
62       // provided via PictureReady.
63       NEEDS_ALL_PICTURE_BUFFERS_TO_DECODE = 1 << 0,
64 
65       // Whether the VDA supports being configured with an output surface for
66       // it to render frames to. For example, SurfaceViews on Android.
67       SUPPORTS_EXTERNAL_OUTPUT_SURFACE = 1 << 1,
68 
69       // If set, the VDA will use deferred initialization if the config
70       // indicates that the client supports it as well.  Refer to
71       // NotifyInitializationComplete for more details.
72       SUPPORTS_DEFERRED_INITIALIZATION = 1 << 2,
73 
74       // If set, video frames will have COPY_REQUIRED flag which will cause
75       // an extra texture copy during composition.
76       REQUIRES_TEXTURE_COPY = 1 << 3,
77 
78       // Whether the VDA supports encrypted streams or not.
79       SUPPORTS_ENCRYPTED_STREAMS = 1 << 4,
80 
81       // If set the decoder does not require a restart in order to switch to
82       // using an external output surface.
83       SUPPORTS_SET_EXTERNAL_OUTPUT_SURFACE = 1 << 5,
84     };
85 
86     SupportedProfiles supported_profiles;
87     uint32_t flags;
88   };
89 
90   // Enumeration of potential errors generated by the API.
91   // Note: Keep these in sync with PP_VideoDecodeError_Dev. Also do not
92   // rearrange, reuse or remove values as they are used for gathering UMA
93   // statistics.
94   enum Error {
95     // An operation was attempted during an incompatible decoder state.
96     ILLEGAL_STATE = 1,
97     // Invalid argument was passed to an API method.
98     INVALID_ARGUMENT,
99     // Encoded input is unreadable.
100     UNREADABLE_INPUT,
101     // A failure occurred at the browser layer or one of its dependencies.
102     // Examples of such failures include GPU hardware failures, GPU driver
103     // failures, GPU library failures, browser programming errors, and so on.
104     PLATFORM_FAILURE,
105     // Largest used enum. This should be adjusted when new errors are added.
106     ERROR_MAX = PLATFORM_FAILURE,
107   };
108 
109   // Config structure contains parameters required for the VDA initialization.
110   struct Config {
111     // Specifies the allocation and handling mode for output PictureBuffers.
112     // When set to ALLOCATE, the VDA is expected to allocate backing memory
113     // for PictureBuffers at the time of AssignPictureBuffers() call.
114     // When set to IMPORT, the VDA will not allocate, but after receiving
115     // AssignPictureBuffers() call, it will expect a call to
116     // ImportBufferForPicture() for each PictureBuffer before use.
117     enum class OutputMode {
118       ALLOCATE,
119       IMPORT,
120     };
121 
122     Config();
123     Config(const Config& config);
124 
125     explicit Config(VideoCodecProfile profile);
126 
127     ~Config();
128 
129     std::string AsHumanReadableString() const;
130 
131     // The video codec and profile.
132     VideoCodecProfile profile = VIDEO_CODEC_PROFILE_UNKNOWN;
133 
134     // Whether the client supports deferred initialization.
135     bool is_deferred_initialization_allowed = false;
136 
137     // Coded size of the video frame hint, subject to change.
138     Size initial_expected_coded_size = Size(320, 240);
139 
140     OutputMode output_mode = OutputMode::ALLOCATE;
141 
142     // The list of picture buffer formats that the client knows how to use. An
143     // empty list means any format is supported.
144     std::vector<VideoPixelFormat> supported_output_formats;
145 
146     // The H264 SPS and PPS configuration data. Not all clients populate these
147     // fields, so they should be parsed from the bitstream instead, if required.
148     // Each SPS and PPS is prefixed with the Annex B framing bytes: 0, 0, 0, 1.
149     std::vector<uint8_t> sps;
150     std::vector<uint8_t> pps;
151   };
152 
153   // Interface for collaborating with picture interface to provide memory for
154   // output picture and blitting them. These callbacks will not be made unless
155   // Initialize() has returned successfully.
156   // This interface is extended by the various layers that relay messages back
157   // to the plugin, through the PPP_VideoDecoder_Dev interface the plugin
158   // implements.
159   class Client {
160    public:
161     // Notify the client that deferred initialization has completed successfully
162     // or not.  This is required if and only if deferred initialization is
163     // supported by the VDA (see Capabilities), and it is supported by the
164     // client (see Config::is_deferred_initialization_allowed), and the initial
165     // call to VDA::Initialize returns true.
166     // The default implementation is a NOTREACHED, since deferred initialization
167     // is not supported by default.
168     virtual void NotifyInitializationComplete(bool success);
169 
170     // Callback to tell client how many and what size of buffers to provide.
171     // Note that the actual count provided through AssignPictureBuffers() can be
172     // larger than the value requested.
173     // |format| indicates what format the decoded frames will be produced in
174     // by the VDA, or PIXEL_FORMAT_UNKNOWN if the underlying platform handles
175     // this transparently.
176     virtual void ProvidePictureBuffers(uint32_t requested_num_of_buffers,
177                                        VideoPixelFormat format,
178                                        const Size& dimensions) = 0;
179 
180     // Callback to dismiss picture buffer that was assigned earlier.
181     virtual void DismissPictureBuffer(int32_t picture_buffer_id) = 0;
182 
183     // Callback to deliver decoded pictures ready to be displayed.
184     virtual void PictureReady(const Picture& picture) = 0;
185 
186     // Callback to notify that decoded has decoded the end of the current
187     // bitstream buffer.
188     virtual void NotifyEndOfBitstreamBuffer(int32_t bitstream_buffer_id) = 0;
189 
190     // Flush completion callback.
191     virtual void NotifyFlushDone() = 0;
192 
193     // Reset completion callback.
194     virtual void NotifyResetDone() = 0;
195 
196     // Callback to notify about decoding errors. Note that errors in
197     // Initialize() will not be reported here, but will instead be indicated by
198     // a false return value there.
199     virtual void NotifyError(Error error) = 0;
200 
201    protected:
~Client()202     virtual ~Client() {}
203   };
204 
205   // Video decoder functions.
206 
207   // Initializes the video decoder with specific configuration.  Called once per
208   // decoder construction.  This call is synchronous and returns true iff
209   // initialization is successful, unless deferred initialization is used.
210   //
211   // By default, deferred initialization is not used.  However, if Config::
212   // is_deferred_initialization_allowed is set by the client, and if
213   // Capabilities::Flags::SUPPORTS_DEFERRED_INITIALIZATION is set by the VDA,
214   // and if VDA::Initialize returns true, then the client can expect a call to
215   // NotifyInitializationComplete with the actual success / failure of
216   // initialization.  Note that a return value of false from VDA::Initialize
217   // indicates that initialization definitely failed, and no callback is needed.
218   //
219   // For encrypted video, only deferred initialization is supported and |config|
220   // must contain a valid |cdm_id|.
221   //
222   // Parameters:
223   //  |config| contains the initialization parameters.
224   //  |client| is the client of this video decoder. Does not take ownership of
225   //  |client| which must be valid until Destroy() is called.
226   virtual bool Initialize(const Config& config, Client* client) = 0;
227 
228   // Decodes given bitstream buffer that contains at most one frame.  Once
229   // decoder is done with processing |bitstream_buffer| it will call
230   // NotifyEndOfBitstreamBuffer() with the bitstream buffer id.
231   // Parameters:
232   //  |bitstream_buffer| is the input bitstream that is sent for decoding.
233   virtual void Decode(const BitstreamBuffer& bitstream_buffer) = 0;
234 
235   // Assigns a set of texture-backed picture buffers to the video decoder.
236   //
237   // Ownership of each picture buffer remains with the client, but the client
238   // is not allowed to deallocate the buffer before the DismissPictureBuffer
239   // callback has been initiated for a given buffer.
240   //
241   // Parameters:
242   //  |buffers| contains the allocated picture buffers for the output.  Note
243   //  that the count of buffers may be larger than the count requested through
244   //  the call to Client::ProvidePictureBuffers().
245   virtual void AssignPictureBuffers(
246       const std::vector<PictureBuffer>& buffers) = 0;
247 
248   // Imports |dmabuf_fds| as backing memory for picture buffer
249   // associated with |picture_buffer_id|. This can only be be used if the VDA
250   // has been Initialize()d with config.output_mode = IMPORT, and should be
251   // preceded by a call to AssignPictureBuffers() to set up the number of
252   // PictureBuffers and their details.
253   // After this call, the VDA becomes the owner of those file descriptors,
254   // and is responsible for closing it after use, also on import failure.
255   virtual void ImportBufferForPicture(
256       int32_t picture_buffer_id,
257       const std::vector<base::FileDescriptor>& dmabuf_fds);
258 
259   // Sends picture buffers to be reused by the decoder. This needs to be called
260   // for each buffer that has been processed so that decoder may know onto which
261   // picture buffers it can write the output to.
262   //
263   // Parameters:
264   //  |picture_buffer_id| id of the picture buffer that is to be reused.
265   virtual void ReusePictureBuffer(int32_t picture_buffer_id) = 0;
266 
267   // Flushes the decoder: all pending inputs will be decoded and pictures handed
268   // back to the client, followed by NotifyFlushDone() being called on the
269   // client.  Can be used to implement "end of stream" notification.
270   virtual void Flush() = 0;
271 
272   // Resets the decoder: all pending inputs are dropped immediately and the
273   // decoder returned to a state ready for further Decode()s, followed by
274   // NotifyResetDone() being called on the client.  Can be used to implement
275   // "seek". After Flush is called, it is OK to call Reset before receiving
276   // NotifyFlushDone() and VDA should cancel the flush. Note NotifyFlushDone()
277   // may be on the way to the client. If client gets NotifyFlushDone(), it
278   // should be before NotifyResetDone().
279   virtual void Reset() = 0;
280 
281   // Destroys the decoder: all pending inputs are dropped immediately and the
282   // component is freed.  This call may asynchornously free system resources,
283   // but its client-visible effects are synchronous.  After this method returns
284   // no more callbacks will be made on the client.  Deletes |this|
285   // unconditionally, so make sure to drop all pointers to it!
286   virtual void Destroy() = 0;
287 
288   // TO BE CALLED IN THE SAME PROCESS AS THE VDA IMPLEMENTATION ONLY.
289   //
290   // A decode "task" is a sequence that includes a Decode() call from Client,
291   // as well as corresponding callbacks to return the input BitstreamBuffer
292   // after use, and the resulting output Picture(s).
293   //
294   // If the Client can support running these three calls on a separate thread,
295   // it may call this method to try to set up the VDA implementation to do so.
296   // If the VDA can support this as well, return true, otherwise return false.
297   // If true is returned, the client may submit each Decode() call (but no other
298   // calls) on |decode_task_runner|, and should then expect that
299   // NotifyEndOfBitstreamBuffer() and PictureReady() callbacks may come on
300   // |decode_task_runner| as well, called on |decode_client|, instead of client
301   // provided to Initialize().
302   //
303   // This method may be called at any time.
304   //
305   // NOTE 1: some callbacks may still have to come on the main thread and the
306   // Client should handle both callbacks coming on main and |decode_task_runner|
307   // thread.
308   //
309   // NOTE 2: VDA implementations of Decode() must return as soon as possible and
310   // never block, as |decode_task_runner| may be a latency critical thread
311   // (such as the GPU IO thread).
312   //
313   // One application of this is offloading the GPU Child thread. In general,
314   // calls to VDA in GPU process have to be done on the GPU Child thread, as
315   // they may require GL context to be current. However, some VDAs may be able
316   // to run decode operations without GL context, which helps reduce latency and
317   // offloads the GPU Child thread.
318   virtual bool TryToSetupDecodeOnSeparateThread(
319       const base::WeakPtr<Client>& decode_client,
320       const scoped_refptr<base::SingleThreadTaskRunner>& decode_task_runner);
321 
322  protected:
323   // Do not delete directly; use Destroy() or own it with a scoped_ptr, which
324   // will Destroy() it properly by default.
325   virtual ~VideoDecodeAccelerator();
326 };
327 
328 }  // namespace media
329 
330 namespace std {
331 
332 // Specialize std::default_delete so that
333 // std::unique_ptr<VideoDecodeAccelerator> uses "Destroy()" instead of trying to
334 // use the destructor.
335 template <>
336 struct default_delete<media::VideoDecodeAccelerator> {
337   void operator()(media::VideoDecodeAccelerator* vda) const;
338 };
339 
340 }  // namespace std
341 
342 #endif  // VIDEO_DECODE_ACCELERATOR_H_
343