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