DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator
mp2t_media_parser.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/mp2t_media_parser.h"
6 
7 #include <memory>
8 #include "packager/base/bind.h"
9 #include "packager/media/base/media_sample.h"
10 #include "packager/media/base/stream_info.h"
11 #include "packager/media/formats/mp2t/es_parser.h"
12 #include "packager/media/formats/mp2t/es_parser_adts.h"
13 #include "packager/media/formats/mp2t/es_parser_h264.h"
14 #include "packager/media/formats/mp2t/es_parser_h265.h"
15 #include "packager/media/formats/mp2t/mp2t_common.h"
16 #include "packager/media/formats/mp2t/ts_packet.h"
17 #include "packager/media/formats/mp2t/ts_section.h"
18 #include "packager/media/formats/mp2t/ts_section_pat.h"
19 #include "packager/media/formats/mp2t/ts_section_pes.h"
20 #include "packager/media/formats/mp2t/ts_section_pmt.h"
21 
22 namespace shaka {
23 namespace media {
24 namespace mp2t {
25 
26 enum StreamType {
27  // ISO-13818.1 / ITU H.222 Table 2.34 "Stream type assignments"
28  kStreamTypeMpeg1Audio = 0x3,
29  kStreamTypeAAC = 0xf,
30  kStreamTypeAVC = 0x1b,
31  kStreamTypeHEVC = 0x24,
32 };
33 
34 class PidState {
35  public:
36  enum PidType {
37  kPidPat,
38  kPidPmt,
39  kPidAudioPes,
40  kPidVideoPes,
41  };
42 
43  PidState(int pid,
44  PidType pid_type,
45  std::unique_ptr<TsSection> section_parser);
46 
47  // Extract the content of the TS packet and parse it.
48  // Return true if successful.
49  bool PushTsPacket(const TsPacket& ts_packet);
50 
51  // Flush the PID state (possibly emitting some pending frames)
52  // and reset its state.
53  void Flush();
54 
55  // Enable/disable the PID.
56  // Disabling a PID will reset its state and ignore any further incoming TS
57  // packets.
58  void Enable();
59  void Disable();
60  bool IsEnabled() const;
61 
62  PidType pid_type() const { return pid_type_; }
63 
64  std::shared_ptr<StreamInfo>& config() { return config_; }
65  void set_config(const std::shared_ptr<StreamInfo>& config) {
66  config_ = config;
67  }
68 
69  SampleQueue& sample_queue() { return sample_queue_; }
70 
71  private:
72  void ResetState();
73 
74  int pid_;
75  PidType pid_type_;
76  std::unique_ptr<TsSection> section_parser_;
77 
78  bool enable_;
79  int continuity_counter_;
80  std::shared_ptr<StreamInfo> config_;
81  SampleQueue sample_queue_;
82 };
83 
84 PidState::PidState(int pid,
85  PidType pid_type,
86  std::unique_ptr<TsSection> section_parser)
87  : pid_(pid),
88  pid_type_(pid_type),
89  section_parser_(std::move(section_parser)),
90  enable_(false),
91  continuity_counter_(-1) {
92  DCHECK(section_parser_);
93 }
94 
95 bool PidState::PushTsPacket(const TsPacket& ts_packet) {
96  DCHECK_EQ(ts_packet.pid(), pid_);
97 
98  // The current PID is not part of the PID filter,
99  // just discard the incoming TS packet.
100  if (!enable_)
101  return true;
102 
103  int expected_continuity_counter = (continuity_counter_ + 1) % 16;
104  if (continuity_counter_ >= 0 &&
105  ts_packet.continuity_counter() != expected_continuity_counter) {
106  DVLOG(1) << "TS discontinuity detected for pid: " << pid_;
107  // TODO(tinskip): Handle discontinuity better.
108  return false;
109  }
110 
111  bool status = section_parser_->Parse(
112  ts_packet.payload_unit_start_indicator(),
113  ts_packet.payload(),
114  ts_packet.payload_size());
115 
116  // At the minimum, when parsing failed, auto reset the section parser.
117  // Components that use the Mp2tMediaParser can take further action if needed.
118  if (!status) {
119  DVLOG(1) << "Parsing failed for pid = " << pid_;
120  ResetState();
121  }
122 
123  return status;
124 }
125 
126 void PidState::Flush() {
127  section_parser_->Flush();
128  ResetState();
129 }
130 
131 void PidState::Enable() {
132  enable_ = true;
133 }
134 
135 void PidState::Disable() {
136  if (!enable_)
137  return;
138 
139  ResetState();
140  enable_ = false;
141 }
142 
143 bool PidState::IsEnabled() const {
144  return enable_;
145 }
146 
147 void PidState::ResetState() {
148  section_parser_->Reset();
149  continuity_counter_ = -1;
150 }
151 
152 Mp2tMediaParser::Mp2tMediaParser()
153  : sbr_in_mimetype_(false),
154  is_initialized_(false) {
155 }
156 
157 Mp2tMediaParser::~Mp2tMediaParser() {}
158 
160  const InitCB& init_cb,
161  const NewSampleCB& new_sample_cb,
162  KeySource* decryption_key_source) {
163  DCHECK(!is_initialized_);
164  DCHECK(init_cb_.is_null());
165  DCHECK(!init_cb.is_null());
166  DCHECK(!new_sample_cb.is_null());
167 
168  init_cb_ = init_cb;
169  new_sample_cb_ = new_sample_cb;
170 }
171 
173  DVLOG(1) << "Mp2tMediaParser::Flush";
174 
175  // Flush the buffers and reset the pids.
176  for (const auto& pair : pids_) {
177  DVLOG(1) << "Flushing PID: " << pair.first;
178  PidState* pid_state = pair.second.get();
179  pid_state->Flush();
180  }
181  bool result = EmitRemainingSamples();
182  pids_.clear();
183 
184  // Remove any bytes left in the TS buffer.
185  // (i.e. any partial TS packet => less than 188 bytes).
186  ts_byte_queue_.Reset();
187  return result;
188 }
189 
190 bool Mp2tMediaParser::Parse(const uint8_t* buf, int size) {
191  DVLOG(1) << "Mp2tMediaParser::Parse size=" << size;
192 
193  // Add the data to the parser state.
194  ts_byte_queue_.Push(buf, size);
195 
196  while (true) {
197  const uint8_t* ts_buffer;
198  int ts_buffer_size;
199  ts_byte_queue_.Peek(&ts_buffer, &ts_buffer_size);
200  if (ts_buffer_size < TsPacket::kPacketSize)
201  break;
202 
203  // Synchronization.
204  int skipped_bytes = TsPacket::Sync(ts_buffer, ts_buffer_size);
205  if (skipped_bytes > 0) {
206  DVLOG(1) << "Packet not aligned on a TS syncword:"
207  << " skipped_bytes=" << skipped_bytes;
208  ts_byte_queue_.Pop(skipped_bytes);
209  continue;
210  }
211 
212  // Parse the TS header, skipping 1 byte if the header is invalid.
213  std::unique_ptr<TsPacket> ts_packet(
214  TsPacket::Parse(ts_buffer, ts_buffer_size));
215  if (!ts_packet) {
216  DVLOG(1) << "Error: invalid TS packet";
217  ts_byte_queue_.Pop(1);
218  continue;
219  }
220  DVLOG(LOG_LEVEL_TS)
221  << "Processing PID=" << ts_packet->pid()
222  << " start_unit=" << ts_packet->payload_unit_start_indicator();
223 
224  // Parse the section.
225  std::map<int, std::unique_ptr<PidState>>::iterator it =
226  pids_.find(ts_packet->pid());
227  if (it == pids_.end() &&
228  ts_packet->pid() == TsSection::kPidPat) {
229  // Create the PAT state here if needed.
230  std::unique_ptr<TsSection> pat_section_parser(new TsSectionPat(
231  base::Bind(&Mp2tMediaParser::RegisterPmt, base::Unretained(this))));
232  std::unique_ptr<PidState> pat_pid_state(new PidState(
233  ts_packet->pid(), PidState::kPidPat, std::move(pat_section_parser)));
234  pat_pid_state->Enable();
235  it = pids_
236  .insert(std::pair<int, std::unique_ptr<PidState>>(
237  ts_packet->pid(), std::move(pat_pid_state)))
238  .first;
239  }
240 
241  if (it != pids_.end()) {
242  if (!it->second->PushTsPacket(*ts_packet))
243  return false;
244  } else {
245  DVLOG(LOG_LEVEL_TS) << "Ignoring TS packet for pid: " << ts_packet->pid();
246  }
247 
248  // Go to the next packet.
249  ts_byte_queue_.Pop(TsPacket::kPacketSize);
250  }
251 
252  // Emit the A/V buffers that kept accumulating during TS parsing.
253  return EmitRemainingSamples();
254 }
255 
256 void Mp2tMediaParser::RegisterPmt(int program_number, int pmt_pid) {
257  DVLOG(1) << "RegisterPmt:"
258  << " program_number=" << program_number
259  << " pmt_pid=" << pmt_pid;
260 
261  // Only one TS program is allowed. Ignore the incoming program map table,
262  // if there is already one registered.
263  for (const auto& pair : pids_) {
264  if (pair.second->pid_type() == PidState::kPidPmt) {
265  DVLOG_IF(1, pmt_pid != pair.first) << "More than one program is defined";
266  return;
267  }
268  }
269 
270  // Create the PMT state here if needed.
271  DVLOG(1) << "Create a new PMT parser";
272  std::unique_ptr<TsSection> pmt_section_parser(new TsSectionPmt(base::Bind(
273  &Mp2tMediaParser::RegisterPes, base::Unretained(this), pmt_pid)));
274  std::unique_ptr<PidState> pmt_pid_state(
275  new PidState(pmt_pid, PidState::kPidPmt, std::move(pmt_section_parser)));
276  pmt_pid_state->Enable();
277  pids_.insert(std::pair<int, std::unique_ptr<PidState>>(
278  pmt_pid, std::move(pmt_pid_state)));
279 }
280 
281 void Mp2tMediaParser::RegisterPes(int pmt_pid,
282  int pes_pid,
283  int stream_type) {
284  DVLOG(1) << "RegisterPes:"
285  << " pes_pid=" << pes_pid
286  << " stream_type=" << std::hex << stream_type << std::dec;
287  std::map<int, std::unique_ptr<PidState>>::iterator it = pids_.find(pes_pid);
288  if (it != pids_.end())
289  return;
290 
291  // Create a stream parser corresponding to the stream type.
292  bool is_audio = false;
293  std::unique_ptr<EsParser> es_parser;
294  if (stream_type == kStreamTypeAVC) {
295  es_parser.reset(
296  new EsParserH264(
297  pes_pid,
298  base::Bind(&Mp2tMediaParser::OnNewStreamInfo,
299  base::Unretained(this)),
300  base::Bind(&Mp2tMediaParser::OnEmitSample,
301  base::Unretained(this))));
302  } else if (stream_type == kStreamTypeHEVC) {
303  es_parser.reset(
304  new EsParserH265(
305  pes_pid,
306  base::Bind(&Mp2tMediaParser::OnNewStreamInfo,
307  base::Unretained(this)),
308  base::Bind(&Mp2tMediaParser::OnEmitSample,
309  base::Unretained(this))));
310  } else if (stream_type == kStreamTypeAAC) {
311  es_parser.reset(
312  new EsParserAdts(
313  pes_pid,
314  base::Bind(&Mp2tMediaParser::OnNewStreamInfo,
315  base::Unretained(this)),
316  base::Bind(&Mp2tMediaParser::OnEmitSample,
317  base::Unretained(this)),
318  sbr_in_mimetype_));
319  is_audio = true;
320  } else {
321  LOG(WARNING) << "Ignore unsupported stream type 0x" << std::hex
322  << stream_type << std::dec;
323  return;
324  }
325 
326  // Create the PES state here.
327  DVLOG(1) << "Create a new PES state";
328  std::unique_ptr<TsSection> pes_section_parser(
329  new TsSectionPes(std::move(es_parser)));
330  PidState::PidType pid_type =
331  is_audio ? PidState::kPidAudioPes : PidState::kPidVideoPes;
332  std::unique_ptr<PidState> pes_pid_state(
333  new PidState(pes_pid, pid_type, std::move(pes_section_parser)));
334  pes_pid_state->Enable();
335  pids_.insert(std::pair<int, std::unique_ptr<PidState>>(
336  pes_pid, std::move(pes_pid_state)));
337 }
338 
339 void Mp2tMediaParser::OnNewStreamInfo(
340  const std::shared_ptr<StreamInfo>& new_stream_info) {
341  DCHECK(new_stream_info);
342  DVLOG(1) << "OnVideoConfigChanged for pid=" << new_stream_info->track_id();
343 
344  PidMap::iterator pid_state = pids_.find(new_stream_info->track_id());
345  if (pid_state == pids_.end()) {
346  LOG(ERROR) << "PID State for new stream not found (pid = "
347  << new_stream_info->track_id() << ").";
348  return;
349  }
350 
351  // Set the stream configuration information for the PID.
352  pid_state->second->set_config(new_stream_info);
353 
354  // Finish initialization if all streams have configs.
355  FinishInitializationIfNeeded();
356 }
357 
358 bool Mp2tMediaParser::FinishInitializationIfNeeded() {
359  // Nothing to be done if already initialized.
360  if (is_initialized_)
361  return true;
362 
363  // Wait for more data to come to finish initialization.
364  if (pids_.empty())
365  return true;
366 
367  std::vector<std::shared_ptr<StreamInfo>> all_stream_info;
368  uint32_t num_es(0);
369  for (PidMap::const_iterator iter = pids_.begin(); iter != pids_.end();
370  ++iter) {
371  if (((iter->second->pid_type() == PidState::kPidAudioPes) ||
372  (iter->second->pid_type() == PidState::kPidVideoPes))) {
373  ++num_es;
374  if (iter->second->config())
375  all_stream_info.push_back(iter->second->config());
376  }
377  }
378  if (num_es && (all_stream_info.size() == num_es)) {
379  // All stream configurations have been received. Initialization can
380  // be completed.
381  init_cb_.Run(all_stream_info);
382  DVLOG(1) << "Mpeg2TS stream parser initialization done";
383  is_initialized_ = true;
384  }
385  return true;
386 }
387 
388 void Mp2tMediaParser::OnEmitSample(
389  uint32_t pes_pid,
390  const std::shared_ptr<MediaSample>& new_sample) {
391  DCHECK(new_sample);
392  DVLOG(LOG_LEVEL_ES)
393  << "OnEmitSample: "
394  << " pid="
395  << pes_pid
396  << " size="
397  << new_sample->data_size()
398  << " dts="
399  << new_sample->dts()
400  << " pts="
401  << new_sample->pts();
402 
403  // Add the sample to the appropriate PID sample queue.
404  PidMap::iterator pid_state = pids_.find(pes_pid);
405  if (pid_state == pids_.end()) {
406  LOG(ERROR) << "PID State for new sample not found (pid = "
407  << pes_pid << ").";
408  return;
409  }
410  pid_state->second->sample_queue().push_back(new_sample);
411 }
412 
413 bool Mp2tMediaParser::EmitRemainingSamples() {
414  DVLOG(LOG_LEVEL_ES) << "Mp2tMediaParser::EmitRemainingBuffers";
415 
416  // No buffer should be sent until fully initialized.
417  if (!is_initialized_)
418  return true;
419 
420  // Buffer emission.
421  for (PidMap::const_iterator pid_iter = pids_.begin(); pid_iter != pids_.end();
422  ++pid_iter) {
423  SampleQueue& sample_queue = pid_iter->second->sample_queue();
424  for (SampleQueue::iterator sample_iter = sample_queue.begin();
425  sample_iter != sample_queue.end();
426  ++sample_iter) {
427  if (!new_sample_cb_.Run(pid_iter->first, *sample_iter)) {
428  // Error processing sample. Propagate error condition.
429  return false;
430  }
431  }
432  sample_queue.clear();
433  }
434 
435  return true;
436 }
437 
438 } // namespace mp2t
439 } // namespace media
440 } // namespace shaka
void Init(const InitCB &init_cb, const NewSampleCB &new_sample_cb, KeySource *decryption_key_source) override
bool Flush() override WARN_UNUSED_RESULT
KeySource is responsible for encryption key acquisition.
Definition: key_source.h:45
bool Parse(const uint8_t *buf, int size) override WARN_UNUSED_RESULT