Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / content / renderer / media / rtc_video_decoder.h
1 // Copyright 2013 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 CONTENT_RENDERER_MEDIA_RTC_VIDEO_DECODER_H_
6 #define CONTENT_RENDERER_MEDIA_RTC_VIDEO_DECODER_H_
7
8 #include <deque>
9 #include <list>
10 #include <map>
11 #include <set>
12 #include <utility>
13
14 #include "base/basictypes.h"
15 #include "base/gtest_prod_util.h"
16 #include "base/memory/weak_ptr.h"
17 #include "base/synchronization/lock.h"
18 #include "base/threading/thread.h"
19 #include "content/common/content_export.h"
20 #include "media/base/bitstream_buffer.h"
21 #include "media/base/video_decoder.h"
22 #include "media/video/picture.h"
23 #include "media/video/video_decode_accelerator.h"
24 #include "third_party/webrtc/modules/video_coding/codecs/interface/video_codec_interface.h"
25
26 namespace base {
27 class WaitableEvent;
28 class MessageLoopProxy;
29 };
30
31 namespace gpu {
32 struct MailboxHolder;
33 }
34
35 namespace media {
36 class DecoderBuffer;
37 class GpuVideoAcceleratorFactories;
38 }
39
40 namespace content {
41
42 // This class uses hardware accelerated video decoder to decode video for
43 // WebRTC. |vda_message_loop_| is the message loop proxy of the media thread,
44 // which VDA::Client methods run on. webrtc::VideoDecoder methods run on WebRTC
45 // DecodingThread or Chrome_libJingle_WorkerThread, which are trampolined to
46 // |vda_message_loop_|. Decode() is non-blocking and queues the buffers. Decoded
47 // frames are delivered to WebRTC on |vda_message_loop_|.
48 class CONTENT_EXPORT RTCVideoDecoder
49     : NON_EXPORTED_BASE(public webrtc::VideoDecoder),
50       public media::VideoDecodeAccelerator::Client {
51  public:
52   virtual ~RTCVideoDecoder();
53
54   // Creates a RTCVideoDecoder. Returns NULL if failed. The video decoder will
55   // run on the message loop of |factories|.
56   static scoped_ptr<RTCVideoDecoder> Create(
57       webrtc::VideoCodecType type,
58       const scoped_refptr<media::GpuVideoAcceleratorFactories>& factories);
59
60   // webrtc::VideoDecoder implementation.
61   // Called on WebRTC DecodingThread.
62   virtual int32_t InitDecode(const webrtc::VideoCodec* codecSettings,
63                              int32_t numberOfCores) OVERRIDE;
64   // Called on WebRTC DecodingThread.
65   virtual int32_t Decode(
66       const webrtc::EncodedImage& inputImage,
67       bool missingFrames,
68       const webrtc::RTPFragmentationHeader* fragmentation,
69       const webrtc::CodecSpecificInfo* codecSpecificInfo = NULL,
70       int64_t renderTimeMs = -1) OVERRIDE;
71   // Called on WebRTC DecodingThread.
72   virtual int32_t RegisterDecodeCompleteCallback(
73       webrtc::DecodedImageCallback* callback) OVERRIDE;
74   // Called on Chrome_libJingle_WorkerThread. The child thread is blocked while
75   // this runs.
76   virtual int32_t Release() OVERRIDE;
77   // Called on Chrome_libJingle_WorkerThread. The child thread is blocked while
78   // this runs.
79   virtual int32_t Reset() OVERRIDE;
80
81   // VideoDecodeAccelerator::Client implementation.
82   virtual void NotifyInitializeDone() OVERRIDE;
83   virtual void ProvidePictureBuffers(uint32 count,
84                                      const gfx::Size& size,
85                                      uint32 texture_target) OVERRIDE;
86   virtual void DismissPictureBuffer(int32 id) OVERRIDE;
87   virtual void PictureReady(const media::Picture& picture) OVERRIDE;
88   virtual void NotifyEndOfBitstreamBuffer(int32 id) OVERRIDE;
89   virtual void NotifyFlushDone() OVERRIDE;
90   virtual void NotifyResetDone() OVERRIDE;
91   virtual void NotifyError(media::VideoDecodeAccelerator::Error error) OVERRIDE;
92
93  private:
94   class SHMBuffer;
95   // Metadata of a bitstream buffer.
96   struct BufferData {
97     BufferData(int32 bitstream_buffer_id,
98                uint32_t timestamp,
99                int width,
100                int height,
101                size_t size);
102     BufferData();
103     ~BufferData();
104     int32 bitstream_buffer_id;
105     uint32_t timestamp;  // in 90KHz
106     uint32_t width;
107     uint32_t height;
108     size_t size;  // buffer size
109   };
110
111   FRIEND_TEST_ALL_PREFIXES(RTCVideoDecoderTest, IsBufferAfterReset);
112   FRIEND_TEST_ALL_PREFIXES(RTCVideoDecoderTest, IsFirstBufferAfterReset);
113
114   // The meessage loop of |factories| will be saved to |vda_task_runner_|.
115   RTCVideoDecoder(
116       const scoped_refptr<media::GpuVideoAcceleratorFactories>& factories);
117
118   // Requests a buffer to be decoded by VDA.
119   void RequestBufferDecode();
120
121   bool CanMoreDecodeWorkBeDone();
122
123   // Returns true if bitstream buffer id |id_buffer| comes after |id_reset|.
124   // This handles the wraparound.
125   bool IsBufferAfterReset(int32 id_buffer, int32 id_reset);
126
127   // Returns true if bitstream buffer |id_buffer| is the first buffer after
128   // |id_reset|.
129   bool IsFirstBufferAfterReset(int32 id_buffer, int32 id_reset);
130
131   // Saves a WebRTC buffer in |decode_buffers_| for decode.
132   void SaveToDecodeBuffers_Locked(const webrtc::EncodedImage& input_image,
133                                   scoped_ptr<SHMBuffer> shm_buffer,
134                                   const BufferData& buffer_data);
135
136   // Saves a WebRTC buffer in |pending_buffers_| waiting for SHM available.
137   // Returns true on success.
138   bool SaveToPendingBuffers_Locked(const webrtc::EncodedImage& input_image,
139                                    const BufferData& buffer_data);
140
141   // Gets SHM and moves pending buffers to decode buffers.
142   void MovePendingBuffersToDecodeBuffers();
143
144   scoped_refptr<media::VideoFrame> CreateVideoFrame(
145       const media::Picture& picture,
146       const media::PictureBuffer& pb,
147       uint32_t timestamp,
148       uint32_t width,
149       uint32_t height,
150       size_t size);
151
152   // Resets VDA.
153   void ResetInternal();
154
155   // Tells VDA that a picture buffer can be recycled.
156   void ReusePictureBuffer(int64 picture_buffer_id,
157                           scoped_ptr<gpu::MailboxHolder> mailbox_holder);
158
159   // Create |vda_| on |vda_loop_proxy_|.
160   void CreateVDA(media::VideoCodecProfile profile, base::WaitableEvent* waiter);
161
162   void DestroyTextures();
163   void DestroyVDA();
164
165   // Gets a shared-memory segment of at least |min_size| bytes from
166   // |available_shm_segments_|. Returns NULL if there is no buffer or the
167   // buffer is not big enough.
168   scoped_ptr<SHMBuffer> GetSHM_Locked(size_t min_size);
169
170   // Returns a shared-memory segment to the available pool.
171   void PutSHM_Locked(scoped_ptr<SHMBuffer> shm_buffer);
172
173   // Allocates |number| shared memory of at least |min_size| bytes.
174   void CreateSHM(int number, size_t min_size);
175
176   // Stores the buffer metadata to |input_buffer_data_|.
177   void RecordBufferData(const BufferData& buffer_data);
178   // Gets the buffer metadata from |input_buffer_data_|.
179   void GetBufferData(int32 bitstream_buffer_id,
180                      uint32_t* timestamp,
181                      uint32_t* width,
182                      uint32_t* height,
183                      size_t* size);
184
185   // Records the result of InitDecode to UMA and returns |status|.
186   int32_t RecordInitDecodeUMA(int32_t status);
187
188   enum State {
189     UNINITIALIZED,  // The decoder has not initialized.
190     INITIALIZED,    // The decoder has initialized.
191     RESETTING,      // The decoder is being reset.
192     DECODE_ERROR,   // Decoding error happened.
193   };
194
195   static const int32 ID_LAST;     // maximum bitstream buffer id
196   static const int32 ID_HALF;     // half of the maximum bitstream buffer id
197   static const int32 ID_INVALID;  // indicates Reset or Release never occurred
198
199   // The hardware video decoder.
200   scoped_ptr<media::VideoDecodeAccelerator> vda_;
201
202   // The size of the incoming video frames.
203   gfx::Size frame_size_;
204
205   // Weak pointer to this, which can be dereferenced only on |vda_task_runner_|.
206   base::WeakPtr<RTCVideoDecoder> weak_this_;
207
208   scoped_refptr<media::GpuVideoAcceleratorFactories> factories_;
209
210   // The task runner to run callbacks on. This is from |factories_|.
211   scoped_refptr<base::SingleThreadTaskRunner> vda_task_runner_;
212
213   // The texture target used for decoded pictures.
214   uint32 decoder_texture_target_;
215
216   // Metadata of the buffers that have been sent for decode.
217   std::list<BufferData> input_buffer_data_;
218
219   // A map from bitstream buffer IDs to bitstream buffers that are being
220   // processed by VDA. The map owns SHM buffers.
221   std::map<int32, SHMBuffer*> bitstream_buffers_in_decoder_;
222
223   // A map from picture buffer IDs to texture-backed picture buffers.
224   std::map<int32, media::PictureBuffer> assigned_picture_buffers_;
225
226   // Picture buffers that are dismissed but not deleted yet.
227   std::map<int32, media::PictureBuffer> dismissed_picture_buffers_;
228
229   // PictureBuffers given to us by VDA via PictureReady, which we sent forward
230   // as VideoFrames to be rendered via read_cb_, and which will be returned
231   // to us via ReusePictureBuffer.
232   std::set<int32> picture_buffers_at_display_;
233
234   // The id that will be given to the next picture buffer.
235   int32 next_picture_buffer_id_;
236
237   // Protects |state_|, |decode_complete_callback_| , |num_shm_buffers_|,
238   // |available_shm_segments_|, |pending_buffers_|, |decode_buffers_|,
239   // |next_bitstream_buffer_id_| and |reset_bitstream_buffer_id_|.
240   base::Lock lock_;
241
242   // The state of RTCVideoDecoder. Guarded by |lock_|.
243   State state_;
244
245   // Guarded by |lock_|.
246   webrtc::DecodedImageCallback* decode_complete_callback_;
247
248   // Total number of allocated SHM buffers. Guarded by |lock_|.
249   int num_shm_buffers_;
250
251   // Shared-memory buffer pool.  Since allocating SHM segments requires a
252   // round-trip to the browser process, we keep allocation out of the
253   // steady-state of the decoder. The vector owns SHM buffers. Guarded by
254   // |lock_|.
255   std::vector<SHMBuffer*> available_shm_segments_;
256
257   // A queue storing WebRTC encoding images (and their metadata) that are
258   // waiting for the shared memory. Guarded by |lock_|.
259   std::deque<std::pair<webrtc::EncodedImage, BufferData> > pending_buffers_;
260
261   // A queue storing buffers (and their metadata) that will be sent to VDA for
262   // decode. The queue owns SHM buffers. Guarded by |lock_|.
263   std::deque<std::pair<SHMBuffer*, BufferData> > decode_buffers_;
264
265   // The id that will be given to the next bitstream buffer. Guarded by |lock_|.
266   int32 next_bitstream_buffer_id_;
267
268   // A buffer that has an id less than this should be dropped because Reset or
269   // Release has been called. Guarded by |lock_|.
270   int32 reset_bitstream_buffer_id_;
271
272   // Factory used to populate |weak_this_|. Must be destroyed, or invalidated,
273   // on |vda_loop_proxy_|.
274   base::WeakPtrFactory<RTCVideoDecoder> weak_factory_;
275
276   DISALLOW_COPY_AND_ASSIGN(RTCVideoDecoder);
277 };
278
279 }  // namespace content
280
281 #endif  // CONTENT_RENDERER_MEDIA_RTC_VIDEO_DECODER_H_