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 "media/formats/mp2t/ts_section_pes.h"
6
7#include "base/logging.h"
8#include "base/strings/string_number_conversions.h"
9#include "media/base/bit_reader.h"
10#include "media/base/buffers.h"
11#include "media/formats/mp2t/es_parser.h"
12#include "media/formats/mp2t/mp2t_common.h"
13#include "media/formats/mp2t/timestamp_unroller.h"
14
15static const int kPesStartCode = 0x000001;
16
17static bool IsTimestampSectionValid(int64 timestamp_section) {
18  // |pts_section| has 40 bits:
19  // - starting with either '0010' or '0011' or '0001'
20  // - and ending with a marker bit.
21  // See ITU H.222 standard - PES section.
22
23  // Verify that all the marker bits are set to one.
24  return ((timestamp_section & 0x1) != 0) &&
25         ((timestamp_section & 0x10000) != 0) &&
26         ((timestamp_section & 0x100000000) != 0);
27}
28
29static int64 ConvertTimestampSectionToTimestamp(int64 timestamp_section) {
30  return (((timestamp_section >> 33) & 0x7) << 30) |
31         (((timestamp_section >> 17) & 0x7fff) << 15) |
32         (((timestamp_section >> 1) & 0x7fff) << 0);
33}
34
35namespace media {
36namespace mp2t {
37
38TsSectionPes::TsSectionPes(scoped_ptr<EsParser> es_parser,
39                           TimestampUnroller* timestamp_unroller)
40  : es_parser_(es_parser.release()),
41    wait_for_pusi_(true),
42    timestamp_unroller_(timestamp_unroller) {
43  DCHECK(es_parser_);
44  DCHECK(timestamp_unroller_);
45}
46
47TsSectionPes::~TsSectionPes() {
48}
49
50bool TsSectionPes::Parse(bool payload_unit_start_indicator,
51                             const uint8* buf, int size) {
52  // Ignore partial PES.
53  if (wait_for_pusi_ && !payload_unit_start_indicator)
54    return true;
55
56  bool parse_result = true;
57  if (payload_unit_start_indicator) {
58    // Try emitting a packet since we might have a pending PES packet
59    // with an undefined size.
60    // In this case, a unit is emitted when the next unit is coming.
61    int raw_pes_size;
62    const uint8* raw_pes;
63    pes_byte_queue_.Peek(&raw_pes, &raw_pes_size);
64    if (raw_pes_size > 0)
65      parse_result = Emit(true);
66
67    // Reset the state.
68    ResetPesState();
69
70    // Update the state.
71    wait_for_pusi_ = false;
72  }
73
74  // Add the data to the parser state.
75  if (size > 0)
76    pes_byte_queue_.Push(buf, size);
77
78  // Try emitting the current PES packet.
79  return (parse_result && Emit(false));
80}
81
82void TsSectionPes::Flush() {
83  // Try emitting a packet since we might have a pending PES packet
84  // with an undefined size.
85  Emit(true);
86
87  // Flush the underlying ES parser.
88  es_parser_->Flush();
89}
90
91void TsSectionPes::Reset() {
92  ResetPesState();
93  es_parser_->Reset();
94}
95
96bool TsSectionPes::Emit(bool emit_for_unknown_size) {
97  int raw_pes_size;
98  const uint8* raw_pes;
99  pes_byte_queue_.Peek(&raw_pes, &raw_pes_size);
100
101  // A PES should be at least 6 bytes.
102  // Wait for more data to come if not enough bytes.
103  if (raw_pes_size < 6)
104    return true;
105
106  // Check whether we have enough data to start parsing.
107  int pes_packet_length =
108      (static_cast<int>(raw_pes[4]) << 8) |
109      (static_cast<int>(raw_pes[5]));
110  if ((pes_packet_length == 0 && !emit_for_unknown_size) ||
111      (pes_packet_length != 0 && raw_pes_size < pes_packet_length + 6)) {
112    // Wait for more data to come either because:
113    // - there are not enough bytes,
114    // - or the PES size is unknown and the "force emit" flag is not set.
115    //   (PES size might be unknown for video PES packet).
116    return true;
117  }
118  DVLOG(LOG_LEVEL_PES) << "pes_packet_length=" << pes_packet_length;
119
120  // Parse the packet.
121  bool parse_result = ParseInternal(raw_pes, raw_pes_size);
122
123  // Reset the state.
124  ResetPesState();
125
126  return parse_result;
127}
128
129bool TsSectionPes::ParseInternal(const uint8* raw_pes, int raw_pes_size) {
130  BitReader bit_reader(raw_pes, raw_pes_size);
131
132  // Read up to the pes_packet_length (6 bytes).
133  int packet_start_code_prefix;
134  int stream_id;
135  int pes_packet_length;
136  RCHECK(bit_reader.ReadBits(24, &packet_start_code_prefix));
137  RCHECK(bit_reader.ReadBits(8, &stream_id));
138  RCHECK(bit_reader.ReadBits(16, &pes_packet_length));
139
140  RCHECK(packet_start_code_prefix == kPesStartCode);
141  DVLOG(LOG_LEVEL_PES) << "stream_id=" << std::hex << stream_id << std::dec;
142  if (pes_packet_length == 0)
143    pes_packet_length = bit_reader.bits_available() / 8;
144
145  // Ignore the PES for unknown stream IDs.
146  // See ITU H.222 Table 2-22 "Stream_id assignments"
147  bool is_audio_stream_id = ((stream_id & 0xe0) == 0xc0);
148  bool is_video_stream_id = ((stream_id & 0xf0) == 0xe0);
149  if (!is_audio_stream_id && !is_video_stream_id)
150    return true;
151
152  // Read up to "pes_header_data_length".
153  int dummy_2;
154  int PES_scrambling_control;
155  int PES_priority;
156  int data_alignment_indicator;
157  int copyright;
158  int original_or_copy;
159  int pts_dts_flags;
160  int escr_flag;
161  int es_rate_flag;
162  int dsm_trick_mode_flag;
163  int additional_copy_info_flag;
164  int pes_crc_flag;
165  int pes_extension_flag;
166  int pes_header_data_length;
167  RCHECK(bit_reader.ReadBits(2, &dummy_2));
168  RCHECK(dummy_2 == 0x2);
169  RCHECK(bit_reader.ReadBits(2, &PES_scrambling_control));
170  RCHECK(bit_reader.ReadBits(1, &PES_priority));
171  RCHECK(bit_reader.ReadBits(1, &data_alignment_indicator));
172  RCHECK(bit_reader.ReadBits(1, &copyright));
173  RCHECK(bit_reader.ReadBits(1, &original_or_copy));
174  RCHECK(bit_reader.ReadBits(2, &pts_dts_flags));
175  RCHECK(bit_reader.ReadBits(1, &escr_flag));
176  RCHECK(bit_reader.ReadBits(1, &es_rate_flag));
177  RCHECK(bit_reader.ReadBits(1, &dsm_trick_mode_flag));
178  RCHECK(bit_reader.ReadBits(1, &additional_copy_info_flag));
179  RCHECK(bit_reader.ReadBits(1, &pes_crc_flag));
180  RCHECK(bit_reader.ReadBits(1, &pes_extension_flag));
181  RCHECK(bit_reader.ReadBits(8, &pes_header_data_length));
182  int pes_header_start_size = bit_reader.bits_available() / 8;
183
184  // Compute the size and the offset of the ES payload.
185  // "6" for the 6 bytes read before and including |pes_packet_length|.
186  // "3" for the 3 bytes read before and including |pes_header_data_length|.
187  int es_size = pes_packet_length - 3 - pes_header_data_length;
188  int es_offset = 6 + 3 + pes_header_data_length;
189  RCHECK(es_size >= 0);
190  RCHECK(es_offset + es_size <= raw_pes_size);
191
192  // Read the timing information section.
193  bool is_pts_valid = false;
194  bool is_dts_valid = false;
195  int64 pts_section = 0;
196  int64 dts_section = 0;
197  if (pts_dts_flags == 0x2) {
198    RCHECK(bit_reader.ReadBits(40, &pts_section));
199    RCHECK((((pts_section >> 36) & 0xf) == 0x2) &&
200           IsTimestampSectionValid(pts_section));
201    is_pts_valid = true;
202  }
203  if (pts_dts_flags == 0x3) {
204    RCHECK(bit_reader.ReadBits(40, &pts_section));
205    RCHECK(bit_reader.ReadBits(40, &dts_section));
206    RCHECK((((pts_section >> 36) & 0xf) == 0x3) &&
207           IsTimestampSectionValid(pts_section));
208    RCHECK((((dts_section >> 36) & 0xf) == 0x1) &&
209           IsTimestampSectionValid(dts_section));
210    is_pts_valid = true;
211    is_dts_valid = true;
212  }
213
214  // Convert and unroll the timestamps.
215  base::TimeDelta media_pts(kNoTimestamp());
216  DecodeTimestamp media_dts(kNoDecodeTimestamp());
217  if (is_pts_valid) {
218    int64 pts = timestamp_unroller_->GetUnrolledTimestamp(
219        ConvertTimestampSectionToTimestamp(pts_section));
220    media_pts = base::TimeDelta::FromMicroseconds((1000 * pts) / 90);
221  }
222  if (is_dts_valid) {
223    int64 dts = timestamp_unroller_->GetUnrolledTimestamp(
224        ConvertTimestampSectionToTimestamp(dts_section));
225    media_dts = DecodeTimestamp::FromMicroseconds((1000 * dts) / 90);
226  }
227
228  // Discard the rest of the PES packet header.
229  // TODO(damienv): check if some info of the PES packet header are useful.
230  DCHECK_EQ(bit_reader.bits_available() % 8, 0);
231  int pes_header_remaining_size = pes_header_data_length -
232      (pes_header_start_size - bit_reader.bits_available() / 8);
233  RCHECK(pes_header_remaining_size >= 0);
234
235  // Read the PES packet.
236  DVLOG(LOG_LEVEL_PES)
237      << "Emit a reassembled PES:"
238      << " size=" << es_size
239      << " pts=" << media_pts.InMilliseconds()
240      << " dts=" << media_dts.InMilliseconds()
241      << " data_alignment_indicator=" << data_alignment_indicator;
242  return es_parser_->Parse(&raw_pes[es_offset], es_size, media_pts, media_dts);
243}
244
245void TsSectionPes::ResetPesState() {
246  pes_byte_queue_.Reset();
247  wait_for_pusi_ = true;
248}
249
250}  // namespace mp2t
251}  // namespace media
252