Shaka Packager SDK
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends
es_parser_adts.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_adts.h"
6 
7 #include <stdint.h>
8 
9 #include <algorithm>
10 #include <list>
11 
12 #include "packager/base/logging.h"
13 #include "packager/base/strings/string_number_conversions.h"
14 #include "packager/media/base/audio_timestamp_helper.h"
15 #include "packager/media/base/bit_reader.h"
16 #include "packager/media/base/media_sample.h"
17 #include "packager/media/base/timestamp.h"
18 #include "packager/media/formats/mp2t/adts_header.h"
19 #include "packager/media/formats/mp2t/mp2t_common.h"
20 #include "packager/media/formats/mpeg/adts_constants.h"
21 
22 namespace shaka {
23 namespace media {
24 
25 // Return true if buf corresponds to an ADTS syncword.
26 // |buf| size must be at least 2.
27 static bool isAdtsSyncWord(const uint8_t* buf) {
28  return (buf[0] == 0xff) && ((buf[1] & 0xf6) == 0xf0);
29 }
30 
31 // Look for an ADTS syncword.
32 // |new_pos| returns
33 // - either the byte position of the ADTS frame (if found)
34 // - or the byte position of 1st byte that was not processed (if not found).
35 // In every case, the returned value in |new_pos| is such that new_pos >= pos
36 // |frame_sz| returns the size of the ADTS frame (if found).
37 // Return whether a syncword was found.
38 static bool LookForSyncWord(const uint8_t* raw_es,
39  int raw_es_size,
40  int pos,
41  int* new_pos,
42  int* frame_sz) {
43  DCHECK_GE(pos, 0);
44  DCHECK_LE(pos, raw_es_size);
45 
46  int max_offset = raw_es_size - kAdtsHeaderMinSize;
47  if (pos >= max_offset) {
48  // Do not change the position if:
49  // - max_offset < 0: not enough bytes to get a full header
50  // Since pos >= 0, this is a subcase of the next condition.
51  // - pos >= max_offset: might be the case after reading one full frame,
52  // |pos| is then incremented by the frame size and might then point
53  // to the end of the buffer.
54  *new_pos = pos;
55  return false;
56  }
57 
58  for (int offset = pos; offset < max_offset; offset++) {
59  const uint8_t* cur_buf = &raw_es[offset];
60 
61  if (!isAdtsSyncWord(cur_buf))
62  // The first 12 bits must be 1.
63  // The layer field (2 bits) must be set to 0.
64  continue;
65 
66  int frame_size = static_cast<int>(
67  mp2t::AdtsHeader::GetAdtsFrameSize(cur_buf, kAdtsHeaderMinSize));
68  if (frame_size < kAdtsHeaderMinSize) {
69  // Too short to be an ADTS frame.
70  continue;
71  }
72 
73  // Check whether there is another frame
74  // |size| apart from the current one.
75  int remaining_size = raw_es_size - offset;
76  if (remaining_size >= frame_size + 2 &&
77  !isAdtsSyncWord(&cur_buf[frame_size])) {
78  continue;
79  }
80 
81  *new_pos = offset;
82  *frame_sz = frame_size;
83  return true;
84  }
85 
86  *new_pos = max_offset;
87  return false;
88 }
89 
90 namespace mp2t {
91 
92 EsParserAdts::EsParserAdts(uint32_t pid,
93  const NewStreamInfoCB& new_stream_info_cb,
94  const EmitSampleCB& emit_sample_cb,
95  bool sbr_in_mimetype)
96  : EsParser(pid),
97  new_stream_info_cb_(new_stream_info_cb),
98  emit_sample_cb_(emit_sample_cb),
99  sbr_in_mimetype_(sbr_in_mimetype) {
100 }
101 
102 EsParserAdts::~EsParserAdts() {
103 }
104 
105 bool EsParserAdts::Parse(const uint8_t* buf,
106  int size,
107  int64_t pts,
108  int64_t dts) {
109  int raw_es_size;
110  const uint8_t* raw_es;
111 
112  // The incoming PTS applies to the access unit that comes just after
113  // the beginning of |buf|.
114  if (pts != kNoTimestamp) {
115  es_byte_queue_.Peek(&raw_es, &raw_es_size);
116  pts_list_.push_back(EsPts(raw_es_size, pts));
117  }
118 
119  // Copy the input data to the ES buffer.
120  es_byte_queue_.Push(buf, static_cast<int>(size));
121  es_byte_queue_.Peek(&raw_es, &raw_es_size);
122 
123  // Look for every ADTS frame in the ES buffer starting at offset = 0
124  int es_position = 0;
125  int frame_size;
126  while (LookForSyncWord(raw_es, raw_es_size, es_position,
127  &es_position, &frame_size)) {
128  const uint8_t* frame_ptr = raw_es + es_position;
129  DVLOG(LOG_LEVEL_ES)
130  << "ADTS syncword @ pos=" << es_position
131  << " frame_size=" << frame_size;
132  DVLOG(LOG_LEVEL_ES)
133  << "ADTS header: "
134  << base::HexEncode(frame_ptr, kAdtsHeaderMinSize);
135 
136  // Do not process the frame if this one is a partial frame.
137  int remaining_size = raw_es_size - es_position;
138  if (frame_size > remaining_size)
139  break;
140 
141  size_t header_size = AdtsHeader::GetAdtsHeaderSize(frame_ptr, frame_size);
142 
143  // Update the audio configuration if needed.
144  DCHECK_GE(frame_size, kAdtsHeaderMinSize);
145  if (!UpdateAudioConfiguration(frame_ptr, frame_size))
146  return false;
147 
148  // Get the PTS & the duration of this access unit.
149  while (!pts_list_.empty() &&
150  pts_list_.front().first <= es_position) {
151  audio_timestamp_helper_->SetBaseTimestamp(pts_list_.front().second);
152  pts_list_.pop_front();
153  }
154 
155  int64_t current_pts = audio_timestamp_helper_->GetTimestamp();
156  int64_t frame_duration =
157  audio_timestamp_helper_->GetFrameDuration(kSamplesPerAACFrame);
158 
159  // Emit an audio frame.
160  bool is_key_frame = true;
161 
162  std::shared_ptr<MediaSample> sample = MediaSample::CopyFrom(
163  frame_ptr + header_size, frame_size - header_size, is_key_frame);
164  sample->set_pts(current_pts);
165  sample->set_dts(current_pts);
166  sample->set_duration(frame_duration);
167  emit_sample_cb_.Run(pid(), sample);
168 
169  // Update the PTS of the next frame.
170  audio_timestamp_helper_->AddFrames(kSamplesPerAACFrame);
171 
172  // Skip the current frame.
173  es_position += frame_size;
174  }
175 
176  // Discard all the bytes that have been processed.
177  DiscardEs(es_position);
178 
179  return true;
180 }
181 
182 void EsParserAdts::Flush() {
183 }
184 
185 void EsParserAdts::Reset() {
186  es_byte_queue_.Reset();
187  pts_list_.clear();
188  last_audio_decoder_config_ = std::shared_ptr<AudioStreamInfo>();
189 }
190 
191 bool EsParserAdts::UpdateAudioConfiguration(const uint8_t* adts_frame,
192  size_t adts_frame_size) {
193  const uint8_t kAacSampleSizeBits(16);
194 
195  AdtsHeader adts_header;
196  if (!adts_header.Parse(adts_frame, adts_frame_size)) {
197  LOG(ERROR) << "Error parsing ADTS frame header.";
198  return false;
199  }
200  std::vector<uint8_t> audio_specific_config;
201  if (!adts_header.GetAudioSpecificConfig(&audio_specific_config))
202  return false;
203 
204  if (last_audio_decoder_config_) {
205  // Verify that the audio decoder config has not changed.
206  if (last_audio_decoder_config_->codec_config() == audio_specific_config) {
207  // Audio configuration has not changed.
208  return true;
209  }
210  NOTIMPLEMENTED() << "Varying audio configurations are not supported.";
211  return false;
212  }
213 
214  // The following code is written according to ISO 14496 Part 3 Table 1.11 and
215  // Table 1.22. (Table 1.11 refers to the capping to 48000, Table 1.22 refers
216  // to SBR doubling the AAC sample rate.)
217  int samples_per_second = adts_header.GetSamplingFrequency();
218  int extended_samples_per_second = sbr_in_mimetype_
219  ? std::min(2 * samples_per_second, 48000)
220  : samples_per_second;
221 
222  last_audio_decoder_config_ = std::make_shared<AudioStreamInfo>(
223  pid(), kMpeg2Timescale, kInfiniteDuration, kCodecAAC,
224  AudioStreamInfo::GetCodecString(kCodecAAC, adts_header.GetObjectType()),
225  audio_specific_config.data(), audio_specific_config.size(),
226  kAacSampleSizeBits, adts_header.GetNumChannels(),
227  extended_samples_per_second, 0 /* seek preroll */, 0 /* codec delay */,
228  0 /* max bitrate */, 0 /* avg bitrate */, std::string(), false);
229 
230  DVLOG(1) << "Sampling frequency: " << samples_per_second;
231  DVLOG(1) << "Extended sampling frequency: " << extended_samples_per_second;
232  DVLOG(1) << "Channel config: " << adts_header.GetNumChannels();
233  DVLOG(1) << "Object type: " << adts_header.GetObjectType();
234  // Reset the timestamp helper to use a new sampling frequency.
235  if (audio_timestamp_helper_) {
236  int64_t base_timestamp = audio_timestamp_helper_->GetTimestamp();
237  audio_timestamp_helper_.reset(
238  new AudioTimestampHelper(kMpeg2Timescale, samples_per_second));
239  audio_timestamp_helper_->SetBaseTimestamp(base_timestamp);
240  } else {
241  audio_timestamp_helper_.reset(
242  new AudioTimestampHelper(kMpeg2Timescale, extended_samples_per_second));
243  }
244 
245  // Audio config notification.
246  new_stream_info_cb_.Run(last_audio_decoder_config_);
247 
248  return true;
249 }
250 
251 void EsParserAdts::DiscardEs(int nbytes) {
252  DCHECK_GE(nbytes, 0);
253  if (nbytes <= 0)
254  return;
255 
256  // Adjust the ES position of each PTS.
257  for (EsPtsList::iterator it = pts_list_.begin(); it != pts_list_.end(); ++it)
258  it->first -= nbytes;
259 
260  // Discard |nbytes| of ES.
261  es_byte_queue_.Pop(nbytes);
262 }
263 
264 } // namespace mp2t
265 } // namespace media
266 } // namespace shaka
void Push(const uint8_t *data, int size)
Append new bytes to the end of the queue.
Definition: byte_queue.cc:29
void Pop(int count)
Definition: byte_queue.cc:70
static size_t GetAdtsFrameSize(const uint8_t *data, size_t num_bytes)
Definition: adts_header.cc:23
void Reset()
Reset the queue to the empty state.
Definition: byte_queue.cc:24
void Peek(const uint8_t **data, int *size) const
Definition: byte_queue.cc:63
static std::string GetCodecString(Codec codec, uint8_t audio_object_type)
static std::shared_ptr< MediaSample > CopyFrom(const uint8_t *data, size_t size, bool is_key_frame)
Definition: media_sample.cc:45
static size_t GetAdtsHeaderSize(const uint8_t *data, size_t num_bytes)
Definition: adts_header.cc:31