Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(196)

Side by Side Diff: media/mp4/mp4_stream_parser.cc

Issue 10534172: Implement ISO BMFF support in Media Source (try 2). (Closed) Base URL: http://git.chromium.org/chromium/src.git@master
Patch Set: Created 8 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
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 #include "media/mp4/mp4_stream_parser.h"
6
7 #include "base/callback.h"
8 #include "base/logging.h"
9 #include "base/time.h"
10 #include "media/base/audio_decoder_config.h"
11 #include "media/base/stream_parser_buffer.h"
12 #include "media/base/video_decoder_config.h"
13 #include "media/mp4/box_definitions.h"
14 #include "media/mp4/box_reader.h"
15 #include "media/mp4/rcheck.h"
16
17 namespace media {
18 namespace mp4 {
19
20 MP4StreamParser::MP4StreamParser()
21 : state_(kWaitingForInit),
22 moof_head_(0),
23 mdat_tail_(0),
24 has_audio_(false),
25 has_video_(false) {
26 }
27
28 MP4StreamParser::~MP4StreamParser() {}
29
30 void MP4StreamParser::Init(const InitCB& init_cb,
31 const NewConfigCB& config_cb,
32 const NewBuffersCB& audio_cb,
33 const NewBuffersCB& video_cb,
34 const KeyNeededCB& key_needed_cb,
35 const NewMediaSegmentCB& new_segment_cb) {
36 DCHECK_EQ(state_, kWaitingForInit);
37 DCHECK(init_cb_.is_null());
38 DCHECK(!init_cb.is_null());
39 DCHECK(!config_cb.is_null());
40 DCHECK(!audio_cb.is_null() || !video_cb.is_null());
41 DCHECK(!key_needed_cb.is_null());
42
43 ChangeState(kParsingBoxes);
44 init_cb_ = init_cb;
45 config_cb_ = config_cb;
46 audio_cb_ = audio_cb;
47 video_cb_ = video_cb;
48 key_needed_cb_ = key_needed_cb;
49 new_segment_cb_ = new_segment_cb;
50 }
51
52 void MP4StreamParser::Flush() {
53 DCHECK_NE(state_, kWaitingForInit);
54
55 queue_.Reset();
56 moof_head_ = 0;
57 mdat_tail_ = 0;
58 }
59
60 bool MP4StreamParser::Parse(const uint8* buf, int size) {
61 DCHECK_NE(state_, kWaitingForInit);
62
63 if (state_ == kError)
64 return false;
65
66 queue_.Push(buf, size);
67
68 BufferQueue audio_buffers;
69 BufferQueue video_buffers;
70
71 bool result, err = false;
72
73 do {
74 if (state_ == kParsingBoxes) {
75 if (mdat_tail_ > queue_.head()) {
76 result = queue_.Trim(mdat_tail_);
77 } else {
78 result = ParseBox(&err);
79 }
80 } else {
81 DCHECK_EQ(kEmittingSamples, state_);
82 result = EnqueueSample(&audio_buffers, &video_buffers, &err);
83 if (result) {
84 int64 max_clear = runs_.GetMaxClearOffset() + moof_head_;
85 DCHECK(max_clear <= queue_.tail());
86 err = !(ReadMDATsUntil(max_clear) && queue_.Trim(max_clear));
87 }
88 }
89 } while (result && !err);
90
91 if (err) {
92 DLOG(ERROR) << "Unknown error while parsing MP4";
93 queue_.Reset();
94 moov_.reset();
95 ChangeState(kError);
96 return false;
97 }
98
99 if (!audio_buffers.empty() &&
100 (audio_cb_.is_null() || !audio_cb_.Run(audio_buffers)))
101 return false;
102 if (!video_buffers.empty() &&
103 (video_cb_.is_null() || !video_cb_.Run(video_buffers)))
104 return false;
105
106 return true;
107 }
108
109 bool MP4StreamParser::ParseBox(bool* err) {
110 const uint8* buf;
111 int size;
112 queue_.Peek(&buf, &size);
113 if (!size) return false;
114
115 scoped_ptr<BoxReader> reader(BoxReader::ReadTopLevelBox(buf, size, err));
116 if (reader.get() == NULL) return false;
117
118 if (reader->type() == FOURCC_MOOV) {
119 *err = !ParseMoov(reader.get());
120 } else if (reader->type() == FOURCC_MOOF) {
121 moof_head_ = queue_.head();
122 *err = !ParseMoof(reader.get());
123
124 // Set up first mdat offset for ParseMDATsUntil()
125 mdat_tail_ = queue_.head() + reader->size();
126 } else {
127 DVLOG(2) << "Skipping unrecognized top-level box: "
128 << FourCCToString(reader->type());
129 }
130
131 queue_.Pop(reader->size());
132 return !(*err);
133 }
134
135
136 bool MP4StreamParser::ParseMoov(BoxReader* reader) {
137 // TODO(strobe): Respect edit lists.
138 moov_.reset(new Movie);
139
140 RCHECK(moov_->Parse(reader));
141
142 has_audio_ = false;
143 has_video_ = false;
144 parameter_sets_inserted_ = false;
145
146 AudioDecoderConfig audio_config;
147 VideoDecoderConfig video_config;
148
149 for (std::vector<Track>::const_iterator track = moov_->tracks.begin();
150 track != moov_->tracks.end(); ++track) {
151 // TODO(strobe): Only the first audio and video track present in a file are
152 // used. (Track selection is better accomplished via Source IDs, though, so
153 // adding support for track selection within a stream is low-priority.)
154 const SampleDescription& samp_descr =
155 track->media.information.sample_table.description;
156 if (track->media.handler.type == kAudio && !audio_config.IsValidConfig()) {
157 RCHECK(!samp_descr.audio_entries.empty());
158 const AudioSampleEntry& entry = samp_descr.audio_entries[0];
159
160 // TODO(strobe): We accept all format values, pending clarification on
161 // the formats used for encrypted media (http://crbug.com/132351).
162 // RCHECK(entry.format == FOURCC_MP4A ||
163 // (entry.format == FOURCC_ENCA &&
164 // entry.sinf.format.format == FOURCC_MP4A));
165
166 const ChannelLayout layout =
167 AVC::ConvertAACChannelCountToChannelLayout(entry.channelcount);
168 audio_config.Initialize(kCodecAAC, entry.samplesize, layout,
169 entry.samplerate, NULL, 0, false);
170 has_audio_ = true;
171 audio_track_id_ = track->header.track_id;
172 }
173 if (track->media.handler.type == kVideo && !video_config.IsValidConfig()) {
174 RCHECK(!samp_descr.video_entries.empty());
175 const VideoSampleEntry& entry = samp_descr.video_entries[0];
176
177 // RCHECK(entry.format == FOURCC_AVC1 ||
178 // (entry.format == FOURCC_ENCV &&
179 // entry.sinf.format.format == FOURCC_AVC1));
180
181 // TODO(strobe): Recover correct crop box and pixel aspect ratio
182 video_config.Initialize(kCodecH264, H264PROFILE_MAIN, VideoFrame::YV12,
183 gfx::Size(entry.width, entry.height),
184 gfx::Rect(0, 0, entry.width, entry.height),
185 // Bogus duration used for framerate, since real
186 // framerate may be variable
187 1000, track->media.header.timescale,
188 1, 1,
189 // No decoder-specific buffer needed for AVC;
190 // SPS/PPS are embedded in the video stream
191 NULL, 0, false);
192 has_video_ = true;
193 video_track_id_ = track->header.track_id;
194
195 size_of_nalu_length_ = entry.avcc.length_size;
196 }
197 }
198
199 RCHECK(config_cb_.Run(audio_config, video_config));
200
201 base::TimeDelta duration;
202 if (moov_->extends.header.fragment_duration > 0) {
203 duration = TimeDeltaFromFrac(moov_->extends.header.fragment_duration,
204 moov_->header.timescale);
205 } else if (moov_->header.duration > 0) {
206 duration = TimeDeltaFromFrac(moov_->header.duration,
207 moov_->header.timescale);
208 } else {
209 duration = kInfiniteDuration();
210 }
211
212 init_cb_.Run(true, duration);
213 return true;
214 }
215
216 bool MP4StreamParser::ParseMoof(BoxReader* reader) {
217 RCHECK(moov_.get()); // Must already have initialization segment
218 MovieFragment moof;
219 RCHECK(moof.Parse(reader));
220 RCHECK(runs_.Init(*moov_, moof));
221 new_segment_cb_.Run(runs_.GetMinDecodeTimestamp());
222 ChangeState(kEmittingSamples);
223 return true;
224 }
225
226 bool MP4StreamParser::EnqueueSample(BufferQueue* audio_buffers,
227 BufferQueue* video_buffers,
228 bool* err) {
229 if (!runs_.RunValid()) {
230 ChangeState(kParsingBoxes);
231 return true;
232 }
233
234 if (!runs_.SampleValid()) {
235 runs_.AdvanceRun();
236 return true;
237 }
238
239 DCHECK(!(*err));
240
241 const uint8* buf;
242 int size;
243 queue_.Peek(&buf, &size);
244 if (!size) return false;
245
246 bool audio = has_audio_ && audio_track_id_ == runs_.track_id();
247 bool video = has_video_ && video_track_id_ == runs_.track_id();
248
249 // Skip this entire track if it's not one we're interested in
250 if (!audio && !video) runs_.AdvanceRun();
251
252 // Attempt to cache the auxiliary information first. Aux info is usually
253 // placed in a contiguous block before the sample data, rather than being
254 // interleaved. If we didn't cache it, this would require that we retain the
255 // start of the segment buffer while reading samples. Aux info is typically
256 // quite small compared to sample data, so this pattern is useful on
257 // memory-constrained devices where the source buffer consumes a substantial
258 // portion of the total system memory.
259 if (runs_.NeedsCENC()) {
260 queue_.PeekAt(runs_.cenc_offset() + moof_head_, &buf, &size);
261 return runs_.CacheCENC(buf, size);
262 }
263
264 queue_.PeekAt(runs_.offset() + moof_head_, &buf, &size);
265 if (size < runs_.size()) return false;
266
267 std::vector<uint8> frame_buf(buf, buf + runs_.size());
268 if (video) {
269 RCHECK(AVC::ConvertToAnnexB(size_of_nalu_length_, &frame_buf));
270 if (!parameter_sets_inserted_) {
271 const AVCDecoderConfigurationRecord* avc_config = NULL;
272 for (size_t t = 0; t < moov_->tracks.size(); t++) {
273 if (moov_->tracks[t].header.track_id == runs_.track_id()) {
274 avc_config = &moov_->tracks[t].media.information.
275 sample_table.description.video_entries[0].avcc;
276 break;
277 }
278 }
279 RCHECK(avc_config != NULL);
280 RCHECK(AVC::InsertParameterSets(*avc_config, &frame_buf));
281 parameter_sets_inserted_ = true;
282 }
283 }
284
285 scoped_refptr<StreamParserBuffer> stream_buf =
286 StreamParserBuffer::CopyFrom(&frame_buf[0], frame_buf.size(),
287 runs_.is_keyframe());
288
289 stream_buf->SetDuration(runs_.duration());
290 // We depend on the decoder performing frame reordering without reordering
291 // timestamps, and only provide the decode timestamp in the buffer.
292 stream_buf->SetTimestamp(runs_.dts());
293
294 DVLOG(3) << "Pushing frame: aud=" << audio
295 << ", key=" << runs_.is_keyframe()
296 << ", dur=" << runs_.duration().InMilliseconds()
297 << ", dts=" << runs_.dts().InMilliseconds()
298 << ", size=" << runs_.size();
299
300 if (audio) {
301 audio_buffers->push_back(stream_buf);
302 } else {
303 video_buffers->push_back(stream_buf);
304 }
305
306 runs_.AdvanceSample();
307 return true;
308 }
309
310 bool MP4StreamParser::ReadMDATsUntil(const int64 tgt_offset) {
311 DCHECK(tgt_offset <= queue_.tail());
312
313 while (mdat_tail_ < tgt_offset) {
314 const uint8* buf;
315 int size;
316 queue_.PeekAt(mdat_tail_, &buf, &size);
317
318 FourCC type;
319 int box_sz;
320 bool err;
321 if (!BoxReader::StartTopLevelBox(buf, size, &type, &box_sz, &err))
322 return false;
323
324 if (type != FOURCC_MDAT) {
325 DLOG(WARNING) << "Unexpected type while parsing MDATs: "
326 << FourCCToString(type);
327 }
328
329 mdat_tail_ += box_sz;
330 }
331
332 return true;
333 }
334
335 void MP4StreamParser::ChangeState(State new_state) {
336 DVLOG(2) << "Changing state: " << new_state;
337 state_ = new_state;
338 }
339
340 } // namespace mp4
341 } // namespace media
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698