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