GPU workaround to simulate Out of Memory errors with large textures
[chromium-blink-merge.git] / content / common / gpu / media / v4l2_video_decode_accelerator.h
blobfbb973e05cbbf1f3075e2b0fc508fe7675f61692
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/).
9 #ifndef CONTENT_COMMON_GPU_MEDIA_V4L2_VIDEO_DECODE_ACCELERATOR_H_
10 #define CONTENT_COMMON_GPU_MEDIA_V4L2_VIDEO_DECODE_ACCELERATOR_H_
12 #include <queue>
13 #include <vector>
15 #include "base/callback_forward.h"
16 #include "base/memory/linked_ptr.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/synchronization/waitable_event.h"
20 #include "base/threading/thread.h"
21 #include "content/common/content_export.h"
22 #include "content/common/gpu/media/v4l2_device.h"
23 #include "media/base/limits.h"
24 #include "media/base/video_decoder_config.h"
25 #include "media/video/picture.h"
26 #include "media/video/video_decode_accelerator.h"
27 #include "ui/gfx/geometry/size.h"
28 #include "ui/gl/gl_bindings.h"
30 namespace base {
31 class MessageLoopProxy;
32 } // namespace base
34 namespace media {
35 class H264Parser;
36 } // namespace media
38 namespace content {
39 // This class handles video accelerators directly through a V4L2 device exported
40 // by the hardware blocks.
42 // The threading model of this class is driven by the fact that it needs to
43 // interface two fundamentally different event queues -- the one Chromium
44 // provides through MessageLoop, and the one driven by the V4L2 devices which
45 // is waited on with epoll(). There are three threads involved in this class:
47 // * The child thread, which is the main GPU process thread which calls the
48 // media::VideoDecodeAccelerator entry points. Calls from this thread
49 // generally do not block (with the exception of Initialize() and Destroy()).
50 // They post tasks to the decoder_thread_, which actually services the task
51 // and calls back when complete through the
52 // media::VideoDecodeAccelerator::Client interface.
53 // * The decoder_thread_, owned by this class. It services API tasks, through
54 // the *Task() routines, as well as V4L2 device events, through
55 // ServiceDeviceTask(). Almost all state modification is done on this thread
56 // (this doesn't include buffer (re)allocation sequence, see below).
57 // * The device_poll_thread_, owned by this class. All it does is epoll() on
58 // the V4L2 in DevicePollTask() and schedule a ServiceDeviceTask() on the
59 // decoder_thread_ when something interesting happens.
60 // TODO(sheu): replace this thread with an TYPE_IO decoder_thread_.
62 // Note that this class has (almost) no locks, apart from the pictures_assigned_
63 // WaitableEvent. Everything (apart from buffer (re)allocation) is serviced on
64 // the decoder_thread_, so there are no synchronization issues.
65 // ... well, there are, but it's a matter of getting messages posted in the
66 // right order, not fiddling with locks.
67 // Buffer creation is a two-step process that is serviced partially on the
68 // Child thread, because we need to wait for the client to provide textures
69 // for the buffers we allocate. We cannot keep the decoder thread running while
70 // the client allocates Pictures for us, because we need to REQBUFS first to get
71 // the required number of output buffers from the device and that cannot be done
72 // unless we free the previous set of buffers, leaving the decoding in a
73 // inoperable state for the duration of the wait for Pictures. So to prevent
74 // subtle races (esp. if we get Reset() in the meantime), we block the decoder
75 // thread while we wait for AssignPictureBuffers from the client.
76 class CONTENT_EXPORT V4L2VideoDecodeAccelerator
77 : public media::VideoDecodeAccelerator {
78 public:
79 V4L2VideoDecodeAccelerator(
80 EGLDisplay egl_display,
81 EGLContext egl_context,
82 const base::WeakPtr<Client>& io_client_,
83 const base::Callback<bool(void)>& make_context_current,
84 const scoped_refptr<V4L2Device>& device,
85 const scoped_refptr<base::MessageLoopProxy>& io_message_loop_proxy);
86 ~V4L2VideoDecodeAccelerator() override;
88 // media::VideoDecodeAccelerator implementation.
89 // Note: Initialize() and Destroy() are synchronous.
90 bool Initialize(media::VideoCodecProfile profile,
91 Client* client) override;
92 void Decode(const media::BitstreamBuffer& bitstream_buffer) override;
93 void AssignPictureBuffers(
94 const std::vector<media::PictureBuffer>& buffers) override;
95 void ReusePictureBuffer(int32 picture_buffer_id) override;
96 void Flush() override;
97 void Reset() override;
98 void Destroy() override;
99 bool CanDecodeOnIOThread() override;
101 private:
102 // These are rather subjectively tuned.
103 enum {
104 kInputBufferCount = 8,
105 // TODO(posciak): determine input buffer size based on level limits.
106 // See http://crbug.com/255116.
107 // Input bitstream buffer size for up to 1080p streams.
108 kInputBufferMaxSizeFor1080p = 1024 * 1024,
109 // Input bitstream buffer size for up to 4k streams.
110 kInputBufferMaxSizeFor4k = 4 * kInputBufferMaxSizeFor1080p,
111 // Number of output buffers to use for each VDA stage above what's required
112 // by the decoder (e.g. DPB size, in H264). We need
113 // media::limits::kMaxVideoFrames to fill up the GpuVideoDecode pipeline,
114 // and +1 for a frame in transit.
115 kDpbOutputBufferExtraCount = media::limits::kMaxVideoFrames + 1,
118 // Internal state of the decoder.
119 enum State {
120 kUninitialized, // Initialize() not yet called.
121 kInitialized, // Initialize() returned true; ready to start decoding.
122 kDecoding, // DecodeBufferInitial() successful; decoding frames.
123 kResetting, // Presently resetting.
124 kAfterReset, // After Reset(), ready to start decoding again.
125 kChangingResolution, // Performing resolution change, all remaining
126 // pre-change frames decoded and processed.
127 kError, // Error in kDecoding state.
130 enum BufferId {
131 kFlushBufferId = -2 // Buffer id for flush buffer, queued by FlushTask().
134 // Auto-destruction reference for BitstreamBuffer, for message-passing from
135 // Decode() to DecodeTask().
136 struct BitstreamBufferRef;
138 // Auto-destruction reference for EGLSync (for message-passing).
139 struct EGLSyncKHRRef;
141 // Record for decoded pictures that can be sent to PictureReady.
142 struct PictureRecord;
144 // Record for input buffers.
145 struct InputRecord {
146 InputRecord();
147 ~InputRecord();
148 bool at_device; // held by device.
149 void* address; // mmap() address.
150 size_t length; // mmap() length.
151 off_t bytes_used; // bytes filled in the mmap() segment.
152 int32 input_id; // triggering input_id as given to Decode().
155 // Record for output buffers.
156 struct OutputRecord {
157 OutputRecord();
158 ~OutputRecord();
159 bool at_device; // held by device.
160 bool at_client; // held by client.
161 EGLImageKHR egl_image; // EGLImageKHR for the output buffer.
162 EGLSyncKHR egl_sync; // sync the compositor's use of the EGLImage.
163 int32 picture_id; // picture buffer id as returned to PictureReady().
164 bool cleared; // Whether the texture is cleared and safe to render
165 // from. See TextureManager for details.
169 // Decoding tasks, to be run on decode_thread_.
172 // Enqueue a BitstreamBuffer to decode. This will enqueue a buffer to the
173 // decoder_input_queue_, then queue a DecodeBufferTask() to actually decode
174 // the buffer.
175 void DecodeTask(const media::BitstreamBuffer& bitstream_buffer);
177 // Decode from the buffers queued in decoder_input_queue_. Calls
178 // DecodeBufferInitial() or DecodeBufferContinue() as appropriate.
179 void DecodeBufferTask();
180 // Advance to the next fragment that begins a frame.
181 bool AdvanceFrameFragment(const uint8* data, size_t size, size_t* endpos);
182 // Schedule another DecodeBufferTask() if we're behind.
183 void ScheduleDecodeBufferTaskIfNeeded();
185 // Return true if we should continue to schedule DecodeBufferTask()s after
186 // completion. Store the amount of input actually consumed in |endpos|.
187 bool DecodeBufferInitial(const void* data, size_t size, size_t* endpos);
188 bool DecodeBufferContinue(const void* data, size_t size);
190 // Accumulate data for the next frame to decode. May return false in
191 // non-error conditions; for example when pipeline is full and should be
192 // retried later.
193 bool AppendToInputFrame(const void* data, size_t size);
194 // Flush data for one decoded frame.
195 bool FlushInputFrame();
197 // Service I/O on the V4L2 devices. This task should only be scheduled from
198 // DevicePollTask(). If |event_pending| is true, one or more events
199 // on file descriptor are pending.
200 void ServiceDeviceTask(bool event_pending);
201 // Handle the various device queues.
202 void Enqueue();
203 void Dequeue();
204 // Handle incoming events.
205 void DequeueEvents();
206 // Enqueue a buffer on the corresponding queue.
207 bool EnqueueInputRecord();
208 bool EnqueueOutputRecord();
210 // Process a ReusePictureBuffer() API call. The API call create an EGLSync
211 // object on the main (GPU process) thread; we will record this object so we
212 // can wait on it before reusing the buffer.
213 void ReusePictureBufferTask(int32 picture_buffer_id,
214 scoped_ptr<EGLSyncKHRRef> egl_sync_ref);
216 // Flush() task. Child thread should not submit any more buffers until it
217 // receives the NotifyFlushDone callback. This task will schedule an empty
218 // BitstreamBufferRef (with input_id == kFlushBufferId) to perform the flush.
219 void FlushTask();
220 // Notify the client of a flush completion, if required. This should be
221 // called any time a relevant queue could potentially be emptied: see
222 // function definition.
223 void NotifyFlushDoneIfNeeded();
225 // Reset() task. This task will schedule a ResetDoneTask() that will send
226 // the NotifyResetDone callback, then set the decoder state to kResetting so
227 // that all intervening tasks will drain.
228 void ResetTask();
229 // ResetDoneTask() will set the decoder state back to kAfterReset, so
230 // subsequent decoding can continue.
231 void ResetDoneTask();
233 // Device destruction task.
234 void DestroyTask();
236 // Attempt to start/stop device_poll_thread_.
237 bool StartDevicePoll();
238 // If |keep_input_state| is true, don't reset input state; used during
239 // resolution change.
240 bool StopDevicePoll(bool keep_input_state);
242 void StartResolutionChangeIfNeeded();
243 void FinishResolutionChange();
245 // Try to get output format and visible size, detected after parsing the
246 // beginning of the stream. Sets |again| to true if more parsing is needed.
247 // |visible_size| could be nullptr and ignored.
248 bool GetFormatInfo(struct v4l2_format* format,
249 gfx::Size* visible_size,
250 bool* again);
251 // Create output buffers for the given |format| and |visible_size|.
252 bool CreateBuffersForFormat(const struct v4l2_format& format,
253 const gfx::Size& visible_size);
255 // Try to get |visible_size|. Return visible size, or, if querying it is not
256 // supported or produces invalid size, return |coded_size| instead.
257 gfx::Size GetVisibleSize(const gfx::Size& coded_size);
260 // Device tasks, to be run on device_poll_thread_.
263 // The device task.
264 void DevicePollTask(bool poll_device);
267 // Safe from any thread.
270 // Error notification (using PostTask() to child thread, if necessary).
271 void NotifyError(Error error);
273 // Set the decoder_state_ to kError and notify the client (if necessary).
274 void SetErrorState(Error error);
277 // Other utility functions. Called on decoder_thread_, unless
278 // decoder_thread_ is not yet started, in which case the child thread can call
279 // these (e.g. in Initialize() or Destroy()).
282 // Create the buffers we need.
283 bool CreateInputBuffers();
284 bool CreateOutputBuffers();
286 // Set input and output formats before starting decode.
287 bool SetupFormats();
290 // Methods run on child thread.
293 // Destroy buffers.
294 void DestroyInputBuffers();
295 // In contrast to DestroyInputBuffers, which is called only from destructor,
296 // we call DestroyOutputBuffers also during playback, on resolution change.
297 // Even if anything fails along the way, we still want to go on and clean
298 // up as much as possible, so return false if this happens, so that the
299 // caller can error out on resolution change.
300 bool DestroyOutputBuffers();
301 void ResolutionChangeDestroyBuffers();
303 // Send decoded pictures to PictureReady.
304 void SendPictureReady();
306 // Callback that indicates a picture has been cleared.
307 void PictureCleared();
309 // This method determines whether a resolution change event processing
310 // is indeed required by returning true iff:
311 // - width or height of the new format is different than previous format; or
312 // - V4L2_CID_MIN_BUFFERS_FOR_CAPTURE has changed.
313 bool IsResolutionChangeNecessary();
315 // Our original calling message loop for the child thread.
316 scoped_refptr<base::MessageLoopProxy> child_message_loop_proxy_;
318 // Message loop of the IO thread.
319 scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_;
321 // WeakPtr<> pointing to |this| for use in posting tasks from the decoder or
322 // device worker threads back to the child thread. Because the worker threads
323 // are members of this class, any task running on those threads is guaranteed
324 // that this object is still alive. As a result, tasks posted from the child
325 // thread to the decoder or device thread should use base::Unretained(this),
326 // and tasks posted the other way should use |weak_this_|.
327 base::WeakPtr<V4L2VideoDecodeAccelerator> weak_this_;
329 // To expose client callbacks from VideoDecodeAccelerator.
330 // NOTE: all calls to these objects *MUST* be executed on
331 // child_message_loop_proxy_.
332 scoped_ptr<base::WeakPtrFactory<Client> > client_ptr_factory_;
333 base::WeakPtr<Client> client_;
334 // Callbacks to |io_client_| must be executed on |io_message_loop_proxy_|.
335 base::WeakPtr<Client> io_client_;
338 // Decoder state, owned and operated by decoder_thread_.
339 // Before decoder_thread_ has started, the decoder state is managed by
340 // the child (main) thread. After decoder_thread_ has started, the decoder
341 // thread should be the only one managing these.
344 // This thread services tasks posted from the VDA API entry points by the
345 // child thread and device service callbacks posted from the device thread.
346 base::Thread decoder_thread_;
347 // Decoder state machine state.
348 State decoder_state_;
349 // BitstreamBuffer we're presently reading.
350 scoped_ptr<BitstreamBufferRef> decoder_current_bitstream_buffer_;
351 // The V4L2Device this class is operating upon.
352 scoped_refptr<V4L2Device> device_;
353 // FlushTask() and ResetTask() should not affect buffers that have been
354 // queued afterwards. For flushing or resetting the pipeline then, we will
355 // delay these buffers until after the flush or reset completes.
356 int decoder_delay_bitstream_buffer_id_;
357 // Input buffer we're presently filling.
358 int decoder_current_input_buffer_;
359 // We track the number of buffer decode tasks we have scheduled, since each
360 // task execution should complete one buffer. If we fall behind (due to
361 // resource backpressure, etc.), we'll have to schedule more to catch up.
362 int decoder_decode_buffer_tasks_scheduled_;
363 // Picture buffers held by the client.
364 int decoder_frames_at_client_;
365 // Are we flushing?
366 bool decoder_flushing_;
367 // Got a notification from driver that it reached resolution change point
368 // in the stream.
369 bool resolution_change_pending_;
370 // Got a reset request while we were performing resolution change.
371 bool resolution_change_reset_pending_;
372 // Input queue for decoder_thread_: BitstreamBuffers in.
373 std::queue<linked_ptr<BitstreamBufferRef> > decoder_input_queue_;
374 // For H264 decode, hardware requires that we send it frame-sized chunks.
375 // We'll need to parse the stream.
376 scoped_ptr<media::H264Parser> decoder_h264_parser_;
377 // Set if the decoder has a pending incomplete frame in an input buffer.
378 bool decoder_partial_frame_pending_;
381 // Hardware state and associated queues. Since decoder_thread_ services
382 // the hardware, decoder_thread_ owns these too.
383 // output_buffer_map_, free_output_buffers_ and output_planes_count_ are an
384 // exception during the buffer (re)allocation sequence, when the
385 // decoder_thread_ is blocked briefly while the Child thread manipulates
386 // them.
389 // Completed decode buffers.
390 std::queue<int> input_ready_queue_;
392 // Input buffer state.
393 bool input_streamon_;
394 // Input buffers enqueued to device.
395 int input_buffer_queued_count_;
396 // Input buffers ready to use, as a LIFO since we don't care about ordering.
397 std::vector<int> free_input_buffers_;
398 // Mapping of int index to input buffer record.
399 std::vector<InputRecord> input_buffer_map_;
401 // Output buffer state.
402 bool output_streamon_;
403 // Output buffers enqueued to device.
404 int output_buffer_queued_count_;
405 // Output buffers ready to use, as a FIFO since we want oldest-first to hide
406 // synchronization latency with GL.
407 std::queue<int> free_output_buffers_;
408 // Mapping of int index to output buffer record.
409 std::vector<OutputRecord> output_buffer_map_;
410 // Required size of DPB for decoding.
411 int output_dpb_size_;
413 // Number of planes (i.e. separate memory buffers) for output.
414 size_t output_planes_count_;
416 // Pictures that are ready but not sent to PictureReady yet.
417 std::queue<PictureRecord> pending_picture_ready_;
419 // The number of pictures that are sent to PictureReady and will be cleared.
420 int picture_clearing_count_;
422 // Used by the decoder thread to wait for AssignPictureBuffers to arrive
423 // to avoid races with potential Reset requests.
424 base::WaitableEvent pictures_assigned_;
426 // Output picture coded size.
427 gfx::Size coded_size_;
429 // Output picture visible size.
430 gfx::Size visible_size_;
433 // The device polling thread handles notifications of V4L2 device changes.
436 // The thread.
437 base::Thread device_poll_thread_;
440 // Other state, held by the child (main) thread.
443 // Make our context current before running any EGL entry points.
444 base::Callback<bool(void)> make_context_current_;
446 // EGL state
447 EGLDisplay egl_display_;
448 EGLContext egl_context_;
450 // The codec we'll be decoding for.
451 media::VideoCodecProfile video_profile_;
452 // Chosen output format.
453 uint32_t output_format_fourcc_;
455 // The WeakPtrFactory for |weak_this_|.
456 base::WeakPtrFactory<V4L2VideoDecodeAccelerator> weak_this_factory_;
458 DISALLOW_COPY_AND_ASSIGN(V4L2VideoDecodeAccelerator);
461 } // namespace content
463 #endif // CONTENT_COMMON_GPU_MEDIA_V4L2_VIDEO_DECODE_ACCELERATOR_H_