Support for unpacked ARM packed relocations.
[chromium-blink-merge.git] / media / filters / ffmpeg_demuxer.h
blobca38f1b92294f345235e16be1d68f1144c74fc46
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.
5 // Implements the Demuxer interface using FFmpeg's libavformat. At this time
6 // will support demuxing any audio/video format thrown at it. The streams
7 // output mime types audio/x-ffmpeg and video/x-ffmpeg and include an integer
8 // key FFmpegCodecID which contains the CodecID enumeration value. The CodecIDs
9 // can be used to create and initialize the corresponding FFmpeg decoder.
11 // FFmpegDemuxer sets the duration of pipeline during initialization by using
12 // the duration of the longest audio/video stream.
14 // NOTE: since FFmpegDemuxer reads packets sequentially without seeking, media
15 // files with very large drift between audio/video streams may result in
16 // excessive memory consumption.
18 // When stopped, FFmpegDemuxer and FFmpegDemuxerStream release all callbacks
19 // and buffered packets. Reads from a stopped FFmpegDemuxerStream will not be
20 // replied to.
22 #ifndef MEDIA_FILTERS_FFMPEG_DEMUXER_H_
23 #define MEDIA_FILTERS_FFMPEG_DEMUXER_H_
25 #include <string>
26 #include <utility>
27 #include <vector>
29 #include "base/callback.h"
30 #include "base/gtest_prod_util.h"
31 #include "base/memory/scoped_vector.h"
32 #include "base/threading/thread.h"
33 #include "media/base/audio_decoder_config.h"
34 #include "media/base/decoder_buffer.h"
35 #include "media/base/decoder_buffer_queue.h"
36 #include "media/base/demuxer.h"
37 #include "media/base/pipeline.h"
38 #include "media/base/text_track_config.h"
39 #include "media/base/video_decoder_config.h"
40 #include "media/ffmpeg/ffmpeg_deleters.h"
41 #include "media/filters/blocking_url_protocol.h"
43 // FFmpeg forward declarations.
44 struct AVPacket;
45 struct AVRational;
46 struct AVStream;
48 namespace media {
50 class MediaLog;
51 class FFmpegDemuxer;
52 class FFmpegGlue;
53 class FFmpegH264ToAnnexBBitstreamConverter;
55 typedef scoped_ptr<AVPacket, ScopedPtrAVFreePacket> ScopedAVPacket;
57 class FFmpegDemuxerStream : public DemuxerStream {
58 public:
59 // Keeps a copy of |demuxer| and initializes itself using information inside
60 // |stream|. Both parameters must outlive |this|.
61 // |discard_negative_timestamps| tells the DemuxerStream that all packets with
62 // negative timestamps should be marked for post-decode discard. All decoded
63 // data before time zero will be discarded.
64 FFmpegDemuxerStream(FFmpegDemuxer* demuxer,
65 AVStream* stream,
66 bool discard_negative_timestamps);
67 virtual ~FFmpegDemuxerStream();
69 // Enqueues the given AVPacket. It is invalid to queue a |packet| after
70 // SetEndOfStream() has been called.
71 void EnqueuePacket(ScopedAVPacket packet);
73 // Enters the end of stream state. After delivering remaining queued buffers
74 // only end of stream buffers will be delivered.
75 void SetEndOfStream();
77 // Drops queued buffers and clears end of stream state.
78 void FlushBuffers();
80 // Empties the queues and ignores any additional calls to Read().
81 void Stop();
83 base::TimeDelta duration() const { return duration_; }
85 // DemuxerStream implementation.
86 virtual Type type() OVERRIDE;
87 virtual void Read(const ReadCB& read_cb) OVERRIDE;
88 virtual void EnableBitstreamConverter() OVERRIDE;
89 virtual bool SupportsConfigChanges() OVERRIDE;
90 virtual AudioDecoderConfig audio_decoder_config() OVERRIDE;
91 virtual VideoDecoderConfig video_decoder_config() OVERRIDE;
93 // Returns the range of buffered data in this stream.
94 Ranges<base::TimeDelta> GetBufferedRanges() const;
96 // Returns elapsed time based on the already queued packets.
97 // Used to determine stream duration when it's not known ahead of time.
98 base::TimeDelta GetElapsedTime() const;
100 // Returns true if this stream has capacity for additional data.
101 bool HasAvailableCapacity();
103 // Returns the total buffer size FFMpegDemuxerStream is holding onto.
104 size_t MemoryUsage() const;
106 TextKind GetTextKind() const;
108 // Returns the value associated with |key| in the metadata for the avstream.
109 // Returns an empty string if the key is not present.
110 std::string GetMetadata(const char* key) const;
112 private:
113 friend class FFmpegDemuxerTest;
115 // Runs |read_cb_| if present with the front of |buffer_queue_|, calling
116 // NotifyCapacityAvailable() if capacity is still available.
117 void SatisfyPendingRead();
119 // Converts an FFmpeg stream timestamp into a base::TimeDelta.
120 static base::TimeDelta ConvertStreamTimestamp(const AVRational& time_base,
121 int64 timestamp);
123 FFmpegDemuxer* demuxer_;
124 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
125 AVStream* stream_;
126 AudioDecoderConfig audio_config_;
127 VideoDecoderConfig video_config_;
128 Type type_;
129 base::TimeDelta duration_;
130 bool end_of_stream_;
131 base::TimeDelta last_packet_timestamp_;
132 Ranges<base::TimeDelta> buffered_ranges_;
134 DecoderBufferQueue buffer_queue_;
135 ReadCB read_cb_;
137 #if defined(USE_PROPRIETARY_CODECS)
138 scoped_ptr<FFmpegH264ToAnnexBBitstreamConverter> bitstream_converter_;
139 #endif
141 bool bitstream_converter_enabled_;
143 std::string encryption_key_id_;
144 const bool discard_negative_timestamps_;
146 DISALLOW_COPY_AND_ASSIGN(FFmpegDemuxerStream);
149 class MEDIA_EXPORT FFmpegDemuxer : public Demuxer {
150 public:
151 FFmpegDemuxer(const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
152 DataSource* data_source,
153 const NeedKeyCB& need_key_cb,
154 const scoped_refptr<MediaLog>& media_log);
155 virtual ~FFmpegDemuxer();
157 // Demuxer implementation.
158 virtual void Initialize(DemuxerHost* host,
159 const PipelineStatusCB& status_cb,
160 bool enable_text_tracks) OVERRIDE;
161 virtual void Stop(const base::Closure& callback) OVERRIDE;
162 virtual void Seek(base::TimeDelta time, const PipelineStatusCB& cb) OVERRIDE;
163 virtual DemuxerStream* GetStream(DemuxerStream::Type type) OVERRIDE;
164 virtual base::Time GetTimelineOffset() const OVERRIDE;
165 virtual Liveness GetLiveness() const OVERRIDE;
167 // Calls |need_key_cb_| with the initialization data encountered in the file.
168 void FireNeedKey(const std::string& init_data_type,
169 const std::string& encryption_key_id);
171 // Allow FFmpegDemuxerStream to notify us when there is updated information
172 // about capacity and what buffered data is available.
173 void NotifyCapacityAvailable();
174 void NotifyBufferingChanged();
176 // The lowest demuxed timestamp. DemuxerStream's must use this to adjust
177 // packet timestamps such that external clients see a zero-based timeline.
178 base::TimeDelta start_time() const { return start_time_; }
180 private:
181 // To allow tests access to privates.
182 friend class FFmpegDemuxerTest;
184 // FFmpeg callbacks during initialization.
185 void OnOpenContextDone(const PipelineStatusCB& status_cb, bool result);
186 void OnFindStreamInfoDone(const PipelineStatusCB& status_cb, int result);
188 // FFmpeg callbacks during seeking.
189 void OnSeekFrameDone(const PipelineStatusCB& cb, int result);
191 // FFmpeg callbacks during reading + helper method to initiate reads.
192 void ReadFrameIfNeeded();
193 void OnReadFrameDone(ScopedAVPacket packet, int result);
195 // DataSource callbacks during stopping.
196 void OnDataSourceStopped(const base::Closure& callback);
198 // Returns true iff any stream has additional capacity. Note that streams can
199 // go over capacity depending on how the file is muxed.
200 bool StreamsHaveAvailableCapacity();
202 // Returns true if the maximum allowed memory usage has been reached.
203 bool IsMaxMemoryUsageReached() const;
205 // Signal all FFmpegDemuxerStreams that the stream has ended.
206 void StreamHasEnded();
208 // Called by |url_protocol_| whenever |data_source_| returns a read error.
209 void OnDataSourceError();
211 // Returns the stream from |streams_| that matches |type| as an
212 // FFmpegDemuxerStream.
213 FFmpegDemuxerStream* GetFFmpegStream(DemuxerStream::Type type) const;
215 // Called after the streams have been collected from the media, to allow
216 // the text renderer to bind each text stream to the cue rendering engine.
217 void AddTextStreams();
219 DemuxerHost* host_;
221 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
223 // Thread on which all blocking FFmpeg operations are executed.
224 base::Thread blocking_thread_;
226 // Tracks if there's an outstanding av_read_frame() operation.
228 // TODO(scherkus): Allow more than one read in flight for higher read
229 // throughput using demuxer_bench to verify improvements.
230 bool pending_read_;
232 // Tracks if there's an outstanding av_seek_frame() operation. Used to discard
233 // results of pre-seek av_read_frame() operations.
234 bool pending_seek_;
236 // |streams_| mirrors the AVStream array in AVFormatContext. It contains
237 // FFmpegDemuxerStreams encapsluating AVStream objects at the same index.
239 // Since we only support a single audio and video stream, |streams_| will
240 // contain NULL entries for additional audio/video streams as well as for
241 // stream types that we do not currently support.
243 // Once initialized, operations on FFmpegDemuxerStreams should be carried out
244 // on the demuxer thread.
245 typedef ScopedVector<FFmpegDemuxerStream> StreamVector;
246 StreamVector streams_;
248 // Provides asynchronous IO to this demuxer. Consumed by |url_protocol_| to
249 // integrate with libavformat.
250 DataSource* data_source_;
252 scoped_refptr<MediaLog> media_log_;
254 // Derived bitrate after initialization has completed.
255 int bitrate_;
257 // The first timestamp of the audio or video stream, whichever is lower. This
258 // is used to adjust timestamps so that external consumers always see a zero
259 // based timeline.
260 base::TimeDelta start_time_;
262 // The index and start time of the preferred streams for seeking. Filled upon
263 // completion of OnFindStreamInfoDone(). Each info entry represents an index
264 // into |streams_| and the start time of that stream.
266 // Seek() will attempt to use |preferred_stream_for_seeking_| if the seek
267 // point occurs after its associated start time. Otherwise it will use
268 // |fallback_stream_for_seeking_|.
269 typedef std::pair<int, base::TimeDelta> StreamSeekInfo;
270 StreamSeekInfo preferred_stream_for_seeking_;
271 StreamSeekInfo fallback_stream_for_seeking_;
273 // The Time associated with timestamp 0. Set to a null
274 // time if the file doesn't have an association to Time.
275 base::Time timeline_offset_;
277 // Liveness of the stream.
278 Liveness liveness_;
280 // Whether text streams have been enabled for this demuxer.
281 bool text_enabled_;
283 // Set if we know duration of the audio stream. Used when processing end of
284 // stream -- at this moment we definitely know duration.
285 bool duration_known_;
287 // FFmpegURLProtocol implementation and corresponding glue bits.
288 scoped_ptr<BlockingUrlProtocol> url_protocol_;
289 scoped_ptr<FFmpegGlue> glue_;
291 const NeedKeyCB need_key_cb_;
293 // NOTE: Weak pointers must be invalidated before all other member variables.
294 base::WeakPtrFactory<FFmpegDemuxer> weak_factory_;
296 DISALLOW_COPY_AND_ASSIGN(FFmpegDemuxer);
299 } // namespace media
301 #endif // MEDIA_FILTERS_FFMPEG_DEMUXER_H_