Shaka Packager SDK
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends
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  if (!audio_header->Parse(cur_buf, raw_es_size - offset))
63  continue;
64 
65  // Check whether there is another frame |size| apart from the current one.
66  const size_t remaining_size = static_cast<size_t>(raw_es_size - offset);
67  const int kSyncWordSize = 2;
68  if (remaining_size >= audio_header->GetFrameSize() + kSyncWordSize &&
69  !audio_header->IsSyncWord(&cur_buf[audio_header->GetFrameSize()])) {
70  continue;
71  }
72 
73  *new_pos = offset;
74  return true;
75  }
76 
77  *new_pos = max_offset;
78  return false;
79 }
80 
81 EsParserAudio::EsParserAudio(uint32_t pid,
82  TsStreamType stream_type,
83  const NewStreamInfoCB& new_stream_info_cb,
84  const EmitSampleCB& emit_sample_cb,
85  bool sbr_in_mimetype)
86  : EsParser(pid),
87  stream_type_(stream_type),
88  new_stream_info_cb_(new_stream_info_cb),
89  emit_sample_cb_(emit_sample_cb),
90  sbr_in_mimetype_(sbr_in_mimetype) {
91  if (stream_type == TsStreamType::kAc3) {
92  audio_header_.reset(new Ac3Header);
93  } else {
94  DCHECK_EQ(stream_type, TsStreamType::kAdtsAac);
95  audio_header_.reset(new AdtsHeader);
96  }
97 }
98 
99 EsParserAudio::~EsParserAudio() {}
100 
101 bool EsParserAudio::Parse(const uint8_t* buf,
102  int size,
103  int64_t pts,
104  int64_t dts) {
105  int raw_es_size;
106  const uint8_t* raw_es;
107 
108  // The incoming PTS applies to the access unit that comes just after
109  // the beginning of |buf|.
110  if (pts != kNoTimestamp) {
111  es_byte_queue_.Peek(&raw_es, &raw_es_size);
112  pts_list_.push_back(EsPts(raw_es_size, pts));
113  }
114 
115  // Copy the input data to the ES buffer.
116  es_byte_queue_.Push(buf, static_cast<int>(size));
117  es_byte_queue_.Peek(&raw_es, &raw_es_size);
118 
119  // Look for every frame in the ES buffer starting at offset = 0
120  int es_position = 0;
121  while (LookForSyncWord(raw_es, raw_es_size, es_position, &es_position,
122  audio_header_.get())) {
123  const uint8_t* frame_ptr = raw_es + es_position;
124  DVLOG(LOG_LEVEL_ES) << "syncword @ pos=" << es_position
125  << " frame_size=" << audio_header_->GetFrameSize();
126  DVLOG(LOG_LEVEL_ES) << "header: "
127  << base::HexEncode(frame_ptr,
128  audio_header_->GetHeaderSize());
129 
130  // Do not process the frame if this one is a partial frame.
131  int remaining_size = raw_es_size - es_position;
132  if (static_cast<int>(audio_header_->GetFrameSize()) > remaining_size)
133  break;
134 
135  // Update the audio configuration if needed.
136  if (!UpdateAudioConfiguration(*audio_header_))
137  return false;
138 
139  // Get the PTS & the duration of this access unit.
140  while (!pts_list_.empty() && pts_list_.front().first <= es_position) {
141  audio_timestamp_helper_->SetBaseTimestamp(pts_list_.front().second);
142  pts_list_.pop_front();
143  }
144 
145  int64_t current_pts = audio_timestamp_helper_->GetTimestamp();
146  int64_t frame_duration = audio_timestamp_helper_->GetFrameDuration(
147  audio_header_->GetSamplesPerFrame());
148 
149  // Emit an audio frame.
150  bool is_key_frame = true;
151 
152  std::shared_ptr<MediaSample> sample = MediaSample::CopyFrom(
153  frame_ptr + audio_header_->GetHeaderSize(),
154  audio_header_->GetFrameSize() - audio_header_->GetHeaderSize(),
155  is_key_frame);
156  sample->set_pts(current_pts);
157  sample->set_dts(current_pts);
158  sample->set_duration(frame_duration);
159  emit_sample_cb_.Run(pid(), sample);
160 
161  // Update the PTS of the next frame.
162  audio_timestamp_helper_->AddFrames(audio_header_->GetSamplesPerFrame());
163 
164  // Skip the current frame.
165  es_position += static_cast<int>(audio_header_->GetFrameSize());
166  }
167 
168  // Discard all the bytes that have been processed.
169  DiscardEs(es_position);
170 
171  return true;
172 }
173 
174 void EsParserAudio::Flush() {}
175 
176 void EsParserAudio::Reset() {
177  es_byte_queue_.Reset();
178  pts_list_.clear();
179  last_audio_decoder_config_ = std::shared_ptr<AudioStreamInfo>();
180 }
181 
182 bool EsParserAudio::UpdateAudioConfiguration(const AudioHeader& audio_header) {
183  const uint8_t kAacSampleSizeBits(16);
184 
185  std::vector<uint8_t> audio_specific_config;
186  audio_header.GetAudioSpecificConfig(&audio_specific_config);
187 
188  if (last_audio_decoder_config_) {
189  // Verify that the audio decoder config has not changed.
190  if (last_audio_decoder_config_->codec_config() == audio_specific_config) {
191  // Audio configuration has not changed.
192  return true;
193  }
194  NOTIMPLEMENTED() << "Varying audio configurations are not supported.";
195  return false;
196  }
197 
198  // The following code is written according to ISO 14496 Part 3 Table 1.11 and
199  // Table 1.22. (Table 1.11 refers to the capping to 48000, Table 1.22 refers
200  // to SBR doubling the AAC sample rate.)
201  int samples_per_second = audio_header.GetSamplingFrequency();
202  // TODO(kqyang): Review if it makes sense to have |sbr_in_mimetype_| in
203  // es_parser.
204  int extended_samples_per_second =
205  sbr_in_mimetype_ ? std::min(2 * samples_per_second, 48000)
206  : samples_per_second;
207 
208  const Codec codec =
209  stream_type_ == TsStreamType::kAc3 ? kCodecAC3 : kCodecAAC;
210  last_audio_decoder_config_ = std::make_shared<AudioStreamInfo>(
211  pid(), kMpeg2Timescale, kInfiniteDuration, codec,
212  AudioStreamInfo::GetCodecString(codec, audio_header.GetObjectType()),
213  audio_specific_config.data(), audio_specific_config.size(),
214  kAacSampleSizeBits, audio_header.GetNumChannels(),
215  extended_samples_per_second, 0 /* seek preroll */, 0 /* codec delay */,
216  0 /* max bitrate */, 0 /* avg bitrate */, std::string(), false);
217 
218  DVLOG(1) << "Sampling frequency: " << samples_per_second;
219  DVLOG(1) << "Extended sampling frequency: " << extended_samples_per_second;
220  DVLOG(1) << "Channel config: "
221  << static_cast<int>(audio_header.GetNumChannels());
222  DVLOG(1) << "Object type: " << static_cast<int>(audio_header.GetObjectType());
223  // Reset the timestamp helper to use a new sampling frequency.
224  if (audio_timestamp_helper_) {
225  int64_t base_timestamp = audio_timestamp_helper_->GetTimestamp();
226  audio_timestamp_helper_.reset(
227  new AudioTimestampHelper(kMpeg2Timescale, samples_per_second));
228  audio_timestamp_helper_->SetBaseTimestamp(base_timestamp);
229  } else {
230  audio_timestamp_helper_.reset(
231  new AudioTimestampHelper(kMpeg2Timescale, extended_samples_per_second));
232  }
233 
234  // Audio config notification.
235  new_stream_info_cb_.Run(last_audio_decoder_config_);
236 
237  return true;
238 }
239 
240 void EsParserAudio::DiscardEs(int nbytes) {
241  DCHECK_GE(nbytes, 0);
242  if (nbytes <= 0)
243  return;
244 
245  // Adjust the ES position of each PTS.
246  for (EsPtsList::iterator it = pts_list_.begin(); it != pts_list_.end(); ++it)
247  it->first -= nbytes;
248 
249  // Discard |nbytes| of ES.
250  es_byte_queue_.Pop(nbytes);
251 }
252 
253 } // namespace mp2t
254 } // namespace media
255 } // 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
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:42