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