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