Shaka Packager SDK
Loading...
Searching...
No Matches
es_parser_h26x.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_h26x.h>
6
7#include <cstddef>
8#include <cstdint>
9#include <memory>
10#include <utility>
11#include <vector>
12
13#include <absl/log/check.h>
14#include <absl/log/log.h>
15
16#include <packager/media/base/media_sample.h>
17#include <packager/media/base/offset_byte_queue.h>
18#include <packager/media/base/timestamp.h>
19#include <packager/media/codecs/h26x_byte_to_unit_stream_converter.h>
20#include <packager/media/codecs/nalu_reader.h>
21#include <packager/media/formats/mp2t/es_parser.h>
22#include <packager/media/formats/mp2t/mp2t_common.h>
23
24namespace shaka {
25namespace media {
26namespace mp2t {
27
28namespace {
29
30const int kStartCodeSize = 3;
31const int kH264NaluHeaderSize = 1;
32const int kH265NaluHeaderSize = 2;
33
34} // namespace
35
36EsParserH26x::EsParserH26x(
37 Nalu::CodecType type,
38 std::unique_ptr<H26xByteToUnitStreamConverter> stream_converter,
39 uint32_t pid,
40 const EmitSampleCB& emit_sample_cb)
41 : EsParser(pid),
42 emit_sample_cb_(emit_sample_cb),
43 type_(type),
44 es_queue_(new media::OffsetByteQueue()),
45 stream_converter_(std::move(stream_converter)) {}
46
47EsParserH26x::~EsParserH26x() {}
48
49bool EsParserH26x::Parse(const uint8_t* buf,
50 int size,
51 int64_t pts,
52 int64_t dts) {
53 // Note: Parse is invoked each time a PES packet has been reassembled.
54 // Unfortunately, a PES packet does not necessarily map
55 // to an h264/h265 access unit, although the HLS recommendation is to use one
56 // PES for each access unit (but this is just a recommendation and some
57 // streams do not comply with this recommendation).
58
59 // HLS recommendation: "In AVC video, you should have both a DTS and a
60 // PTS in each PES header".
61 // However, some streams do not comply with this recommendation.
62 if (pts == kNoTimestamp) {
63 DVLOG(1) << "Each video PES should have a PTS";
64 } else {
65 TimingDesc timing_desc;
66 timing_desc.pts = pts;
67 timing_desc.dts = (dts != kNoTimestamp) ? dts : pts;
68
69 // Link the end of the byte queue with the incoming timing descriptor.
70 timing_desc_list_.push_back(
71 std::pair<int64_t, TimingDesc>(es_queue_->tail(), timing_desc));
72
73 // Warns if there are a large number of cached timestamps, which should be 1
74 // or 2 if everythings works as expected.
75 const size_t kWarningSize =
76 24; // An arbitrary number (it is 1 second for a fps of 24).
77 LOG_IF(WARNING, timing_desc_list_.size() >= kWarningSize)
78 << "Unusually large number of cached timestamps ("
79 << timing_desc_list_.size() << ").";
80 }
81
82 // Add the incoming bytes to the ES queue.
83 es_queue_->Push(buf, size);
84 return ParseInternal();
85}
86
87bool EsParserH26x::Flush() {
88 DVLOG(1) << "EsParserH26x::Flush";
89
90 // Simulate two additional AUDs to force emitting the last access unit
91 // which is assumed to be complete at this point.
92 // Two AUDs are needed because the exact size of a NAL unit can only be
93 // determined after seeing the next NAL unit, so we need a second AUD to
94 // finish the parsing of the first AUD.
95 if (type_ == Nalu::kH264) {
96 const uint8_t aud[] = {0x00, 0x00, 0x01, 0x09, 0x00, 0x00, 0x01, 0x09};
97 es_queue_->Push(aud, sizeof(aud));
98 } else {
99 DCHECK_EQ(Nalu::kH265, type_);
100 const uint8_t aud[] = {0x00, 0x00, 0x01, 0x46, 0x01,
101 0x00, 0x00, 0x01, 0x46, 0x01};
102 es_queue_->Push(aud, sizeof(aud));
103 }
104
105 RCHECK(ParseInternal());
106
107 if (pending_sample_) {
108 // Flush pending sample.
109 if (!pending_sample_duration_) {
110 pending_sample_duration_ =
111 CalculateSampleDuration(pending_sample_pps_id_);
112 }
113 pending_sample_->set_duration(pending_sample_duration_);
114 emit_sample_cb_(std::move(pending_sample_));
115 }
116 return true;
117}
118
119void EsParserH26x::Reset() {
120 es_queue_.reset(new media::OffsetByteQueue());
121 current_search_position_ = 0;
122 current_access_unit_position_ = 0;
123 current_video_slice_info_.valid = false;
124 next_access_unit_position_set_ = false;
125 next_access_unit_position_ = 0;
126 current_nalu_info_.reset();
127 timing_desc_list_.clear();
128 pending_sample_ = std::shared_ptr<MediaSample>();
129 pending_sample_duration_ = 0;
130 waiting_for_key_frame_ = true;
131}
132
133bool EsParserH26x::SearchForNalu(uint64_t* position, Nalu* nalu) {
134 const uint8_t* es;
135 int es_size;
136 es_queue_->PeekAt(current_search_position_, &es, &es_size);
137
138 // Find a start code.
139 uint64_t start_code_offset;
140 uint8_t start_code_size;
141 const bool start_code_found = NaluReader::FindStartCode(
142 es, es_size, &start_code_offset, &start_code_size);
143
144 if (!start_code_found) {
145 // We didn't find a start code, so we don't have to search this data again.
146 if (es_size > kStartCodeSize)
147 current_search_position_ += es_size - kStartCodeSize;
148 return false;
149 }
150
151 // Ensure the next NAL unit is a real NAL unit.
152 const uint8_t* next_nalu_ptr = es + start_code_offset + start_code_size;
153 // This size is likely inaccurate, this is just to get the header info.
154 const int64_t next_nalu_size = es_size - start_code_offset - start_code_size;
155 if (next_nalu_size <
156 (type_ == Nalu::kH264 ? kH264NaluHeaderSize : kH265NaluHeaderSize)) {
157 // There was not enough data, wait for more.
158 return false;
159 }
160
161 // Update search position for next nalu.
162 current_search_position_ += start_code_offset + start_code_size;
163
164 // |next_nalu_info_| is made global intentionally to avoid repetitive memory
165 // allocation which could create memory fragments.
166 if (!next_nalu_info_)
167 next_nalu_info_.reset(new NaluInfo);
168 if (!next_nalu_info_->nalu.Initialize(type_, next_nalu_ptr, next_nalu_size)) {
169 // This NAL unit is invalid, skip it and search again.
170 return SearchForNalu(position, nalu);
171 }
172 next_nalu_info_->position = current_search_position_ - start_code_size;
173 next_nalu_info_->start_code_size = start_code_size;
174
175 const bool current_nalu_set = current_nalu_info_ ? true : false;
176 if (current_nalu_info_) {
177 // Starting position for the nalu including start code.
178 *position = current_nalu_info_->position;
179 // Update the NALU because the data pointer may have been invalidated.
180 const uint8_t* current_nalu_ptr =
181 next_nalu_ptr +
182 (current_nalu_info_->position + current_nalu_info_->start_code_size) -
183 current_search_position_;
184 const uint64_t current_nalu_size = next_nalu_info_->position -
185 current_nalu_info_->position -
186 current_nalu_info_->start_code_size;
187 CHECK(nalu->Initialize(type_, current_nalu_ptr, current_nalu_size));
188 }
189 current_nalu_info_.swap(next_nalu_info_);
190 return current_nalu_set ? true : SearchForNalu(position, nalu);
191}
192
193bool EsParserH26x::ParseInternal() {
194 uint64_t position;
195 Nalu nalu;
196 VideoSliceInfo video_slice_info;
197 while (SearchForNalu(&position, &nalu)) {
198 // ITU H.264 sec. 7.4.1.2.3
199 // H264: The first of the NAL units with |can_start_access_unit() == true|
200 // after the last VCL NAL unit of a primary coded picture specifies the
201 // start of a new access unit.
202 // ITU H.265 sec. 7.4.2.4.4
203 // H265: The first of the NAL units with |can_start_access_unit() == true|
204 // after the last VCL NAL unit preceding firstBlPicNalUnit (the first
205 // VCL NAL unit of a coded picture with nuh_layer_id equal to 0), if
206 // any, specifies the start of a new access unit.
207 if (nalu.can_start_access_unit()) {
208 if (!next_access_unit_position_set_) {
209 next_access_unit_position_set_ = true;
210 next_access_unit_position_ = position;
211 }
212 RCHECK(ProcessNalu(nalu, &video_slice_info));
213 if (nalu.is_vcl() && !video_slice_info.valid) {
214 // This could happen only if decoder config is not available yet. Drop
215 // this frame.
216 DCHECK(!current_video_slice_info_.valid);
217 next_access_unit_position_set_ = false;
218 continue;
219 }
220 } else if (nalu.is_vcl()) {
221 // This isn't the first VCL NAL unit. Next access unit should start after
222 // this NAL unit.
223 next_access_unit_position_set_ = false;
224 continue;
225 }
226
227 // AUD shall be the first NAL unit if present. There shall be at most one
228 // AUD in any access unit. We can emit the current access unit which shall
229 // not contain the AUD.
230 if (nalu.is_aud()) {
231 RCHECK(EmitCurrentAccessUnit());
232 continue;
233 }
234
235 // We can only determine if the current access unit ends after seeing
236 // another VCL NAL unit.
237 if (!video_slice_info.valid)
238 continue;
239
240 // Check if it is the first VCL NAL unit of a primary coded picture. It is
241 // always true for H265 as nuh_layer_id shall be == 0 at this point.
242 bool is_first_vcl_nalu = true;
243 if (type_ == Nalu::kH264) {
244 if (current_video_slice_info_.valid) {
245 // ITU H.264 sec. 7.4.1.2.4 Detection of the first VCL NAL unit of a
246 // primary coded picture. Only pps_id and frame_num are checked here.
247 is_first_vcl_nalu =
248 video_slice_info.frame_num != current_video_slice_info_.frame_num ||
249 video_slice_info.pps_id != current_video_slice_info_.pps_id;
250 }
251 }
252 if (!is_first_vcl_nalu) {
253 // This isn't the first VCL NAL unit. Next access unit should start after
254 // this NAL unit.
255 next_access_unit_position_set_ = false;
256 continue;
257 }
258
259 DCHECK(next_access_unit_position_set_);
260 RCHECK(EmitCurrentAccessUnit());
261
262 // Delete the data we have already processed.
263 es_queue_->Trim(next_access_unit_position_);
264
265 current_access_unit_position_ = next_access_unit_position_;
266 current_video_slice_info_ = video_slice_info;
267 next_access_unit_position_set_ = false;
268 }
269 return true;
270}
271
272bool EsParserH26x::EmitCurrentAccessUnit() {
273 if (current_video_slice_info_.valid) {
274 if (current_video_slice_info_.is_key_frame)
275 waiting_for_key_frame_ = false;
276 if (!waiting_for_key_frame_) {
277 RCHECK(
278 EmitFrame(current_access_unit_position_,
279 next_access_unit_position_ - current_access_unit_position_,
280 current_video_slice_info_.is_key_frame,
281 current_video_slice_info_.pps_id));
282 }
283 current_video_slice_info_.valid = false;
284 }
285 return true;
286}
287
288bool EsParserH26x::EmitFrame(int64_t access_unit_pos,
289 int access_unit_size,
290 bool is_key_frame,
291 int pps_id) {
292 // Get the access unit timing info.
293 TimingDesc current_timing_desc = {kNoTimestamp, kNoTimestamp};
294 while (!timing_desc_list_.empty() &&
295 timing_desc_list_.front().first <= access_unit_pos) {
296 current_timing_desc = timing_desc_list_.front().second;
297 timing_desc_list_.pop_front();
298 }
299 if (current_timing_desc.pts == kNoTimestamp)
300 return false;
301
302 // Emit a frame.
303 DVLOG(LOG_LEVEL_ES) << "Emit frame: stream_pos=" << access_unit_pos
304 << " size=" << access_unit_size << " pts "
305 << current_timing_desc.pts << " timing_desc_list size "
306 << timing_desc_list_.size();
307 int es_size;
308 const uint8_t* es;
309 es_queue_->PeekAt(access_unit_pos, &es, &es_size);
310
311 // Convert frame to unit stream format.
312 std::vector<uint8_t> converted_frame;
313 if (!stream_converter_->ConvertByteStreamToNalUnitStream(es, access_unit_size,
314 &converted_frame)) {
315 DLOG(ERROR) << "Failure to convert video frame to unit stream format.";
316 return false;
317 }
318
319 // Update the video decoder configuration if needed.
320 RCHECK(UpdateVideoDecoderConfig(pps_id));
321
322 // Create the media sample, emitting always the previous sample after
323 // calculating its duration.
324 std::shared_ptr<MediaSample> media_sample = MediaSample::CopyFrom(
325 converted_frame.data(), converted_frame.size(), is_key_frame);
326 media_sample->set_dts(current_timing_desc.dts);
327 media_sample->set_pts(current_timing_desc.pts);
328 if (pending_sample_) {
329 if (media_sample->dts() <= pending_sample_->dts()) {
330 LOG(WARNING) << "[MPEG-2 TS] PID " << pid() << " dts "
331 << media_sample->dts()
332 << " less than or equal to previous dts "
333 << pending_sample_->dts();
334 // Keep the sample but adjust the sample duration to a very small value,
335 // in case that the sample is still needed for the decoding afterwards.
336 const int64_t kArbitrarySmallDuration = 0.001 * kMpeg2Timescale; // 1ms.
337 pending_sample_->set_duration(kArbitrarySmallDuration);
338 } else {
339 int64_t sample_duration = media_sample->dts() - pending_sample_->dts();
340 pending_sample_->set_duration(sample_duration);
341
342 const int kArbitraryGapScale = 10;
343 if (pending_sample_duration_ &&
344 sample_duration > kArbitraryGapScale * pending_sample_duration_) {
345 LOG(WARNING) << "[MPEG-2 TS] PID " << pid() << " Possible GAP at dts "
346 << pending_sample_->dts() << " with next sample at dts "
347 << media_sample->dts() << " (difference "
348 << sample_duration << ")";
349 }
350
351 pending_sample_duration_ = sample_duration;
352 }
353 emit_sample_cb_(std::move(pending_sample_));
354 }
355 pending_sample_ = media_sample;
356 pending_sample_pps_id_ = pps_id;
357
358 return true;
359}
360
361} // namespace mp2t
362} // namespace media
363} // namespace shaka
All the methods that are virtual are virtual for mocking.