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