DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs Enumerator
es_parser_h264.cc
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 #include "packager/media/formats/mp2t/es_parser_h264.h"
6 
7 #include <stdint.h>
8 
9 #include "packager/base/logging.h"
10 #include "packager/base/numerics/safe_conversions.h"
11 #include "packager/media/base/media_sample.h"
12 #include "packager/media/base/offset_byte_queue.h"
13 #include "packager/media/base/timestamp.h"
14 #include "packager/media/base/video_stream_info.h"
15 #include "packager/media/filters/avc_decoder_configuration.h"
16 #include "packager/media/filters/h264_byte_to_unit_stream_converter.h"
17 #include "packager/media/filters/h264_parser.h"
18 #include "packager/media/formats/mp2t/mp2t_common.h"
19 
20 namespace edash_packager {
21 namespace media {
22 namespace mp2t {
23 
24 namespace {
25 
26 // An AUD NALU is at least 4 bytes:
27 // 3 bytes for the start code + 1 byte for the NALU type.
28 const int kMinAUDSize = 4;
29 
30 } // anonymous namespace
31 
32 EsParserH264::EsParserH264(uint32_t pid,
33  const NewStreamInfoCB& new_stream_info_cb,
34  const EmitSampleCB& emit_sample_cb)
35  : EsParser(pid),
36  new_stream_info_cb_(new_stream_info_cb),
37  emit_sample_cb_(emit_sample_cb),
38  es_queue_(new media::OffsetByteQueue()),
39  h264_parser_(new H264Parser()),
40  current_access_unit_pos_(0),
41  next_access_unit_pos_(0),
42  stream_converter_(new H264ByteToUnitStreamConverter),
43  decoder_config_check_pending_(false),
44  pending_sample_duration_(0),
45  waiting_for_key_frame_(true) {
46 }
47 
48 EsParserH264::~EsParserH264() {
49 }
50 
51 bool EsParserH264::Parse(const uint8_t* buf,
52  int size,
53  int64_t pts,
54  int64_t dts) {
55  // Note: Parse is invoked each time a PES packet has been reassembled.
56  // Unfortunately, a PES packet does not necessarily map
57  // to an h264 access unit, although the HLS recommendation is to use one PES
58  // for each access unit (but this is just a recommendation and some streams
59  // do not comply with this recommendation).
60 
61  // HLS recommendation: "In AVC video, you should have both a DTS and a
62  // PTS in each PES header".
63  // However, some streams do not comply with this recommendation.
64  DVLOG_IF(1, pts == kNoTimestamp) << "Each video PES should have a PTS";
65  if (pts != kNoTimestamp) {
66  TimingDesc timing_desc;
67  timing_desc.pts = pts;
68  timing_desc.dts = (dts != kNoTimestamp) ? dts : pts;
69 
70  // Link the end of the byte queue with the incoming timing descriptor.
71  timing_desc_list_.push_back(
72  std::pair<int64_t, TimingDesc>(es_queue_->tail(), timing_desc));
73  }
74 
75  // Add the incoming bytes to the ES queue.
76  es_queue_->Push(buf, size);
77  return ParseInternal();
78 }
79 
80 void EsParserH264::Flush() {
81  DVLOG(1) << "EsParserH264::Flush";
82 
83  if (FindAUD(&current_access_unit_pos_)) {
84  // Simulate an additional AUD to force emitting the last access unit
85  // which is assumed to be complete at this point.
86  uint8_t aud[] = {0x00, 0x00, 0x01, 0x09};
87  es_queue_->Push(aud, sizeof(aud));
88  ParseInternal();
89  }
90 
91  if (pending_sample_) {
92  // Flush pending sample.
93  DCHECK(pending_sample_duration_);
94  pending_sample_->set_duration(pending_sample_duration_);
95  emit_sample_cb_.Run(pid(), pending_sample_);
96  pending_sample_ = scoped_refptr<MediaSample>();
97  }
98 }
99 
100 void EsParserH264::Reset() {
101  DVLOG(1) << "EsParserH264::Reset";
102  es_queue_.reset(new media::OffsetByteQueue());
103  h264_parser_.reset(new H264Parser());
104  current_access_unit_pos_ = 0;
105  next_access_unit_pos_ = 0;
106  timing_desc_list_.clear();
107  last_video_decoder_config_ = scoped_refptr<StreamInfo>();
108  decoder_config_check_pending_ = false;
109  pending_sample_ = scoped_refptr<MediaSample>();
110  pending_sample_duration_ = 0;
111  waiting_for_key_frame_ = true;
112 }
113 
114 bool EsParserH264::FindAUD(int64_t* stream_pos) {
115  while (true) {
116  const uint8_t* es;
117  int size;
118  es_queue_->PeekAt(*stream_pos, &es, &size);
119 
120  // Find a start code and move the stream to the start code parser position.
121  off_t start_code_offset;
122  off_t start_code_size;
123  bool start_code_found = H264Parser::FindStartCode(
124  es, size, &start_code_offset, &start_code_size);
125  *stream_pos += start_code_offset;
126 
127  // No H264 start code found or NALU type not available yet.
128  if (!start_code_found || start_code_offset + start_code_size >= size)
129  return false;
130 
131  // Exit the parser loop when an AUD is found.
132  // Note: NALU header for an AUD:
133  // - nal_ref_idc must be 0
134  // - nal_unit_type must be H264NALU::kAUD
135  if (es[start_code_offset + start_code_size] == H264NALU::kAUD)
136  break;
137 
138  // The current NALU is not an AUD, skip the start code
139  // and continue parsing the stream.
140  *stream_pos += start_code_size;
141  }
142 
143  return true;
144 }
145 
146 bool EsParserH264::ParseInternal() {
147  DCHECK_LE(es_queue_->head(), current_access_unit_pos_);
148  DCHECK_LE(current_access_unit_pos_, next_access_unit_pos_);
149  DCHECK_LE(next_access_unit_pos_, es_queue_->tail());
150 
151  // Find the next AUD located at or after |current_access_unit_pos_|. This is
152  // needed since initially |current_access_unit_pos_| might not point to
153  // an AUD.
154  // Discard all the data before the updated |current_access_unit_pos_|
155  // since it won't be used again.
156  bool aud_found = FindAUD(&current_access_unit_pos_);
157  es_queue_->Trim(current_access_unit_pos_);
158  if (next_access_unit_pos_ < current_access_unit_pos_)
159  next_access_unit_pos_ = current_access_unit_pos_;
160 
161  // Resume parsing later if no AUD was found.
162  if (!aud_found)
163  return true;
164 
165  // Find the next AUD to make sure we have a complete access unit.
166  if (next_access_unit_pos_ < current_access_unit_pos_ + kMinAUDSize) {
167  next_access_unit_pos_ = current_access_unit_pos_ + kMinAUDSize;
168  DCHECK_LE(next_access_unit_pos_, es_queue_->tail());
169  }
170  if (!FindAUD(&next_access_unit_pos_))
171  return true;
172 
173  // At this point, we know we have a full access unit.
174  bool is_key_frame = false;
175  int pps_id_for_access_unit = -1;
176 
177  const uint8_t* es;
178  int size;
179  es_queue_->PeekAt(current_access_unit_pos_, &es, &size);
180  int access_unit_size = base::checked_cast<int, int64_t>(
181  next_access_unit_pos_ - current_access_unit_pos_);
182  DCHECK_LE(access_unit_size, size);
183  h264_parser_->SetStream(es, access_unit_size);
184 
185  while (true) {
186  bool is_eos = false;
187  H264NALU nalu;
188  switch (h264_parser_->AdvanceToNextNALU(&nalu)) {
189  case H264Parser::kOk:
190  break;
191  case H264Parser::kInvalidStream:
192  case H264Parser::kUnsupportedStream:
193  return false;
194  case H264Parser::kEOStream:
195  is_eos = true;
196  break;
197  }
198  if (is_eos)
199  break;
200 
201  switch (nalu.nal_unit_type) {
202  case H264NALU::kAUD: {
203  DVLOG(LOG_LEVEL_ES) << "NALU: AUD";
204  break;
205  }
206  case H264NALU::kSPS: {
207  DVLOG(LOG_LEVEL_ES) << "NALU: SPS";
208  int sps_id;
209  if (h264_parser_->ParseSPS(&sps_id) != H264Parser::kOk)
210  return false;
211  decoder_config_check_pending_ = true;
212  break;
213  }
214  case H264NALU::kPPS: {
215  DVLOG(LOG_LEVEL_ES) << "NALU: PPS";
216  int pps_id;
217  if (h264_parser_->ParsePPS(&pps_id) != H264Parser::kOk) {
218  // Allow PPS parsing to fail if waiting for SPS.
219  if (last_video_decoder_config_)
220  return false;
221  } else {
222  decoder_config_check_pending_ = true;
223  }
224  break;
225  }
226  case H264NALU::kIDRSlice:
227  case H264NALU::kNonIDRSlice: {
228  is_key_frame = (nalu.nal_unit_type == H264NALU::kIDRSlice);
229  DVLOG(LOG_LEVEL_ES) << "NALU: slice IDR=" << is_key_frame;
230  H264SliceHeader shdr;
231  if (h264_parser_->ParseSliceHeader(nalu, &shdr) != H264Parser::kOk) {
232  // Only accept an invalid SPS/PPS at the beginning when the stream
233  // does not necessarily start with an SPS/PPS/IDR.
234  if (last_video_decoder_config_)
235  return false;
236  } else {
237  pps_id_for_access_unit = shdr.pic_parameter_set_id;
238  }
239  break;
240  }
241  default: {
242  DVLOG(LOG_LEVEL_ES) << "NALU: " << nalu.nal_unit_type;
243  }
244  }
245  }
246 
247  if (waiting_for_key_frame_) {
248  waiting_for_key_frame_ = !is_key_frame;
249  }
250  if (!waiting_for_key_frame_) {
251  // Emit a frame and move the stream to the next AUD position.
252  RCHECK(EmitFrame(current_access_unit_pos_, access_unit_size,
253  is_key_frame, pps_id_for_access_unit));
254  }
255  current_access_unit_pos_ = next_access_unit_pos_;
256  es_queue_->Trim(current_access_unit_pos_);
257 
258  return true;
259 }
260 
261 bool EsParserH264::EmitFrame(int64_t access_unit_pos,
262  int access_unit_size,
263  bool is_key_frame,
264  int pps_id) {
265  // Get the access unit timing info.
266  TimingDesc current_timing_desc = {kNoTimestamp, kNoTimestamp};
267  while (!timing_desc_list_.empty() &&
268  timing_desc_list_.front().first <= access_unit_pos) {
269  current_timing_desc = timing_desc_list_.front().second;
270  timing_desc_list_.pop_front();
271  }
272  if (current_timing_desc.pts == kNoTimestamp)
273  return false;
274 
275  // Emit a frame.
276  DVLOG(LOG_LEVEL_ES) << "Emit frame: stream_pos=" << current_access_unit_pos_
277  << " size=" << access_unit_size;
278  int es_size;
279  const uint8_t* es;
280  es_queue_->PeekAt(current_access_unit_pos_, &es, &es_size);
281  CHECK_GE(es_size, access_unit_size);
282 
283  // Convert frame to unit stream format.
284  std::vector<uint8_t> converted_frame;
285  if (!stream_converter_->ConvertByteStreamToNalUnitStream(
286  es, access_unit_size, &converted_frame)) {
287  DLOG(ERROR) << "Failure to convert video frame to unit stream format.";
288  return false;
289  }
290 
291  if (decoder_config_check_pending_) {
292  // Update the video decoder configuration if needed.
293  const H264PPS* pps = h264_parser_->GetPPS(pps_id);
294  if (!pps) {
295  // Only accept an invalid PPS at the beginning when the stream
296  // does not necessarily start with an SPS/PPS/IDR.
297  // In this case, the initial frames are conveyed to the upper layer with
298  // an invalid VideoDecoderConfig and it's up to the upper layer
299  // to process this kind of frame accordingly.
300  if (last_video_decoder_config_)
301  return false;
302  } else {
303  const H264SPS* sps = h264_parser_->GetSPS(pps->seq_parameter_set_id);
304  if (!sps)
305  return false;
306  RCHECK(UpdateVideoDecoderConfig(sps));
307  decoder_config_check_pending_ = false;
308  }
309  }
310 
311  // Create the media sample, emitting always the previous sample after
312  // calculating its duration.
313  scoped_refptr<MediaSample> media_sample = MediaSample::CopyFrom(
314  converted_frame.data(), converted_frame.size(), is_key_frame);
315  media_sample->set_dts(current_timing_desc.dts);
316  media_sample->set_pts(current_timing_desc.pts);
317  if (pending_sample_) {
318  DCHECK_GT(media_sample->dts(), pending_sample_->dts());
319  pending_sample_duration_ = media_sample->dts() - pending_sample_->dts();
320  pending_sample_->set_duration(pending_sample_duration_);
321  emit_sample_cb_.Run(pid(), pending_sample_);
322  }
323  pending_sample_ = media_sample;
324 
325  return true;
326 }
327 
328 bool EsParserH264::UpdateVideoDecoderConfig(const H264SPS* sps) {
329  std::vector<uint8_t> decoder_config_record;
330  if (!stream_converter_->GetAVCDecoderConfigurationRecord(
331  &decoder_config_record)) {
332  DLOG(ERROR) << "Failure to construct an AVCDecoderConfigurationRecord";
333  return false;
334  }
335 
336  if (last_video_decoder_config_) {
337  if (last_video_decoder_config_->extra_data() != decoder_config_record) {
338  // Video configuration has changed. Issue warning.
339  // TODO(tinskip): Check the nature of the configuration change. Only
340  // minor configuration changes (such as frame ordering) can be handled
341  // gracefully by decoders without notification. Major changes (such as
342  // video resolution changes) should be treated as errors.
343  LOG(WARNING) << "H.264 decoder configuration has changed.";
344  last_video_decoder_config_->set_extra_data(decoder_config_record);
345  }
346  return true;
347  }
348 
349  uint32_t coded_width = 0;
350  uint32_t coded_height = 0;
351  uint32_t pixel_width = 0;
352  uint32_t pixel_height = 0;
353  if (!ExtractResolutionFromSps(*sps, &coded_width, &coded_height, &pixel_width,
354  &pixel_height)) {
355  LOG(ERROR) << "Failed to parse SPS.";
356  return false;
357  }
358 
359  last_video_decoder_config_ = scoped_refptr<StreamInfo>(
360  new VideoStreamInfo(
361  pid(),
362  kMpeg2Timescale,
363  kInfiniteDuration,
364  kCodecH264,
365  AVCDecoderConfiguration::GetCodecString(decoder_config_record[1],
366  decoder_config_record[2],
367  decoder_config_record[3]),
368  std::string(),
369  coded_width,
370  coded_height,
371  pixel_width,
372  pixel_height,
373  0,
374  H264ByteToUnitStreamConverter::kUnitStreamNaluLengthSize,
375  decoder_config_record.data(),
376  decoder_config_record.size(),
377  false));
378  DVLOG(1) << "Profile IDC: " << sps->profile_idc;
379  DVLOG(1) << "Level IDC: " << sps->level_idc;
380  DVLOG(1) << "log2_max_frame_num_minus4: " << sps->log2_max_frame_num_minus4;
381 
382  // Video config notification.
383  new_stream_info_cb_.Run(last_video_decoder_config_);
384 
385  return true;
386 }
387 
388 } // namespace mp2t
389 } // namespace media
390 } // namespace edash_packager
static scoped_refptr< MediaSample > CopyFrom(const uint8_t *data, size_t size, bool is_key_frame)
Definition: media_sample.cc:47