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