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.
5 #include "media/formats/mp2t/mp2t_stream_parser.h"
8 #include "base/callback_helpers.h"
9 #include "base/stl_util.h"
10 #include "media/base/buffers.h"
11 #include "media/base/stream_parser_buffer.h"
12 #include "media/base/text_track_config.h"
13 #include "media/formats/mp2t/es_parser.h"
14 #include "media/formats/mp2t/es_parser_adts.h"
15 #include "media/formats/mp2t/es_parser_h264.h"
16 #include "media/formats/mp2t/es_parser_mpeg1audio.h"
17 #include "media/formats/mp2t/mp2t_common.h"
18 #include "media/formats/mp2t/ts_packet.h"
19 #include "media/formats/mp2t/ts_section.h"
20 #include "media/formats/mp2t/ts_section_pat.h"
21 #include "media/formats/mp2t/ts_section_pes.h"
22 #include "media/formats/mp2t/ts_section_pmt.h"
28 // ISO-13818.1 / ITU H.222 Table 2.34 "Stream type assignments"
29 kStreamTypeMpeg1Audio
= 0x3,
31 kStreamTypeAVC
= 0x1b,
43 PidState(int pid
, PidType pid_tyoe
,
44 scoped_ptr
<TsSection
> section_parser
);
46 // Extract the content of the TS packet and parse it.
47 // Return true if successful.
48 bool PushTsPacket(const TsPacket
& ts_packet
);
50 // Flush the PID state (possibly emitting some pending frames)
51 // and reset its state.
54 // Enable/disable the PID.
55 // Disabling a PID will reset its state and ignore any further incoming TS
59 bool IsEnabled() const;
61 PidType
pid_type() const { return pid_type_
; }
68 scoped_ptr
<TsSection
> section_parser_
;
72 int continuity_counter_
;
75 PidState::PidState(int pid
, PidType pid_type
,
76 scoped_ptr
<TsSection
> section_parser
)
79 section_parser_(section_parser
.Pass()),
81 continuity_counter_(-1) {
82 DCHECK(section_parser_
);
85 bool PidState::PushTsPacket(const TsPacket
& ts_packet
) {
86 DCHECK_EQ(ts_packet
.pid(), pid_
);
88 // The current PID is not part of the PID filter,
89 // just discard the incoming TS packet.
93 int expected_continuity_counter
= (continuity_counter_
+ 1) % 16;
94 if (continuity_counter_
>= 0 &&
95 ts_packet
.continuity_counter() != expected_continuity_counter
) {
96 DVLOG(1) << "TS discontinuity detected for pid: " << pid_
;
100 bool status
= section_parser_
->Parse(
101 ts_packet
.payload_unit_start_indicator(),
103 ts_packet
.payload_size());
105 // At the minimum, when parsing failed, auto reset the section parser.
106 // Components that use the StreamParser can take further action if needed.
108 DVLOG(1) << "Parsing failed for pid = " << pid_
;
115 void PidState::Flush() {
116 section_parser_
->Flush();
120 void PidState::Enable() {
124 void PidState::Disable() {
132 bool PidState::IsEnabled() const {
136 void PidState::ResetState() {
137 section_parser_
->Reset();
138 continuity_counter_
= -1;
141 Mp2tStreamParser::BufferQueueWithConfig::BufferQueueWithConfig(
143 const AudioDecoderConfig
& audio_cfg
,
144 const VideoDecoderConfig
& video_cfg
)
145 : is_config_sent(is_cfg_sent
),
146 audio_config(audio_cfg
),
147 video_config(video_cfg
) {
150 Mp2tStreamParser::BufferQueueWithConfig::~BufferQueueWithConfig() {
153 Mp2tStreamParser::Mp2tStreamParser(bool sbr_in_mimetype
)
154 : sbr_in_mimetype_(sbr_in_mimetype
),
155 selected_audio_pid_(-1),
156 selected_video_pid_(-1),
157 is_initialized_(false),
158 segment_started_(false) {
161 Mp2tStreamParser::~Mp2tStreamParser() {
162 STLDeleteValues(&pids_
);
165 void Mp2tStreamParser::Init(
166 const InitCB
& init_cb
,
167 const NewConfigCB
& config_cb
,
168 const NewBuffersCB
& new_buffers_cb
,
169 bool /* ignore_text_tracks */,
170 const EncryptedMediaInitDataCB
& encrypted_media_init_data_cb
,
171 const NewMediaSegmentCB
& new_segment_cb
,
172 const base::Closure
& end_of_segment_cb
,
173 const scoped_refptr
<MediaLog
>& media_log
) {
174 DCHECK(!is_initialized_
);
175 DCHECK(init_cb_
.is_null());
176 DCHECK(!init_cb
.is_null());
177 DCHECK(!config_cb
.is_null());
178 DCHECK(!new_buffers_cb
.is_null());
179 DCHECK(!encrypted_media_init_data_cb
.is_null());
180 DCHECK(!end_of_segment_cb
.is_null());
183 config_cb_
= config_cb
;
184 new_buffers_cb_
= new_buffers_cb
;
185 encrypted_media_init_data_cb_
= encrypted_media_init_data_cb
;
186 new_segment_cb_
= new_segment_cb
;
187 end_of_segment_cb_
= end_of_segment_cb
;
188 media_log_
= media_log
;
191 void Mp2tStreamParser::Flush() {
192 DVLOG(1) << "Mp2tStreamParser::Flush";
194 // Flush the buffers and reset the pids.
195 for (std::map
<int, PidState
*>::iterator it
= pids_
.begin();
196 it
!= pids_
.end(); ++it
) {
197 DVLOG(1) << "Flushing PID: " << it
->first
;
198 PidState
* pid_state
= it
->second
;
203 EmitRemainingBuffers();
204 buffer_queue_chain_
.clear();
206 // End of the segment.
207 // Note: does not need to invoke |end_of_segment_cb_| since flushing the
208 // stream parser already involves the end of the current segment.
209 segment_started_
= false;
211 // Remove any bytes left in the TS buffer.
212 // (i.e. any partial TS packet => less than 188 bytes).
213 ts_byte_queue_
.Reset();
215 // Reset the selected PIDs.
216 selected_audio_pid_
= -1;
217 selected_video_pid_
= -1;
219 // Reset the timestamp unroller.
220 timestamp_unroller_
.Reset();
223 bool Mp2tStreamParser::Parse(const uint8
* buf
, int size
) {
224 DVLOG(1) << "Mp2tStreamParser::Parse size=" << size
;
226 // Add the data to the parser state.
227 ts_byte_queue_
.Push(buf
, size
);
230 const uint8
* ts_buffer
;
232 ts_byte_queue_
.Peek(&ts_buffer
, &ts_buffer_size
);
233 if (ts_buffer_size
< TsPacket::kPacketSize
)
237 int skipped_bytes
= TsPacket::Sync(ts_buffer
, ts_buffer_size
);
238 if (skipped_bytes
> 0) {
239 DVLOG(1) << "Packet not aligned on a TS syncword:"
240 << " skipped_bytes=" << skipped_bytes
;
241 ts_byte_queue_
.Pop(skipped_bytes
);
245 // Parse the TS header, skipping 1 byte if the header is invalid.
246 scoped_ptr
<TsPacket
> ts_packet(TsPacket::Parse(ts_buffer
, ts_buffer_size
));
248 DVLOG(1) << "Error: invalid TS packet";
249 ts_byte_queue_
.Pop(1);
253 << "Processing PID=" << ts_packet
->pid()
254 << " start_unit=" << ts_packet
->payload_unit_start_indicator();
256 // Parse the section.
257 std::map
<int, PidState
*>::iterator it
= pids_
.find(ts_packet
->pid());
258 if (it
== pids_
.end() &&
259 ts_packet
->pid() == TsSection::kPidPat
) {
260 // Create the PAT state here if needed.
261 scoped_ptr
<TsSection
> pat_section_parser(
263 base::Bind(&Mp2tStreamParser::RegisterPmt
,
264 base::Unretained(this))));
265 scoped_ptr
<PidState
> pat_pid_state(
266 new PidState(ts_packet
->pid(), PidState::kPidPat
,
267 pat_section_parser
.Pass()));
268 pat_pid_state
->Enable();
270 std::pair
<int, PidState
*>(ts_packet
->pid(),
271 pat_pid_state
.release())).first
;
274 if (it
!= pids_
.end()) {
275 if (!it
->second
->PushTsPacket(*ts_packet
))
278 DVLOG(LOG_LEVEL_TS
) << "Ignoring TS packet for pid: " << ts_packet
->pid();
281 // Go to the next packet.
282 ts_byte_queue_
.Pop(TsPacket::kPacketSize
);
285 RCHECK(FinishInitializationIfNeeded());
287 // Emit the A/V buffers that kept accumulating during TS parsing.
288 return EmitRemainingBuffers();
291 void Mp2tStreamParser::RegisterPmt(int program_number
, int pmt_pid
) {
292 DVLOG(1) << "RegisterPmt:"
293 << " program_number=" << program_number
294 << " pmt_pid=" << pmt_pid
;
296 // Only one TS program is allowed. Ignore the incoming program map table,
297 // if there is already one registered.
298 for (std::map
<int, PidState
*>::iterator it
= pids_
.begin();
299 it
!= pids_
.end(); ++it
) {
300 PidState
* pid_state
= it
->second
;
301 if (pid_state
->pid_type() == PidState::kPidPmt
) {
302 DVLOG_IF(1, pmt_pid
!= it
->first
) << "More than one program is defined";
307 // Create the PMT state here if needed.
308 DVLOG(1) << "Create a new PMT parser";
309 scoped_ptr
<TsSection
> pmt_section_parser(
311 base::Bind(&Mp2tStreamParser::RegisterPes
,
312 base::Unretained(this), pmt_pid
)));
313 scoped_ptr
<PidState
> pmt_pid_state(
314 new PidState(pmt_pid
, PidState::kPidPmt
, pmt_section_parser
.Pass()));
315 pmt_pid_state
->Enable();
316 pids_
.insert(std::pair
<int, PidState
*>(pmt_pid
, pmt_pid_state
.release()));
319 void Mp2tStreamParser::RegisterPes(int pmt_pid
,
322 // TODO(damienv): check there is no mismatch if the entry already exists.
323 DVLOG(1) << "RegisterPes:"
324 << " pes_pid=" << pes_pid
325 << " stream_type=" << std::hex
<< stream_type
<< std::dec
;
326 std::map
<int, PidState
*>::iterator it
= pids_
.find(pes_pid
);
327 if (it
!= pids_
.end())
330 // Create a stream parser corresponding to the stream type.
331 bool is_audio
= false;
332 scoped_ptr
<EsParser
> es_parser
;
333 if (stream_type
== kStreamTypeAVC
) {
336 base::Bind(&Mp2tStreamParser::OnVideoConfigChanged
,
337 base::Unretained(this),
339 base::Bind(&Mp2tStreamParser::OnEmitVideoBuffer
,
340 base::Unretained(this),
342 } else if (stream_type
== kStreamTypeAAC
) {
345 base::Bind(&Mp2tStreamParser::OnAudioConfigChanged
,
346 base::Unretained(this),
348 base::Bind(&Mp2tStreamParser::OnEmitAudioBuffer
,
349 base::Unretained(this),
353 } else if (stream_type
== kStreamTypeMpeg1Audio
) {
354 es_parser
.reset(new EsParserMpeg1Audio(
355 base::Bind(&Mp2tStreamParser::OnAudioConfigChanged
,
356 base::Unretained(this), pes_pid
),
357 base::Bind(&Mp2tStreamParser::OnEmitAudioBuffer
, base::Unretained(this),
365 // Create the PES state here.
366 DVLOG(1) << "Create a new PES state";
367 scoped_ptr
<TsSection
> pes_section_parser(
368 new TsSectionPes(es_parser
.Pass(), ×tamp_unroller_
));
369 PidState::PidType pid_type
=
370 is_audio
? PidState::kPidAudioPes
: PidState::kPidVideoPes
;
371 scoped_ptr
<PidState
> pes_pid_state(
372 new PidState(pes_pid
, pid_type
, pes_section_parser
.Pass()));
373 pids_
.insert(std::pair
<int, PidState
*>(pes_pid
, pes_pid_state
.release()));
375 // A new PES pid has been added, the PID filter might change.
379 void Mp2tStreamParser::UpdatePidFilter() {
380 // Applies the HLS rule to select the default audio/video PIDs:
381 // select the audio/video streams with the lowest PID.
382 // TODO(damienv): this can be changed when the StreamParser interface
383 // supports multiple audio/video streams.
384 PidMap::iterator lowest_audio_pid
= pids_
.end();
385 PidMap::iterator lowest_video_pid
= pids_
.end();
386 for (PidMap::iterator it
= pids_
.begin(); it
!= pids_
.end(); ++it
) {
388 PidState
* pid_state
= it
->second
;
389 if (pid_state
->pid_type() == PidState::kPidAudioPes
&&
390 (lowest_audio_pid
== pids_
.end() || pid
< lowest_audio_pid
->first
))
391 lowest_audio_pid
= it
;
392 if (pid_state
->pid_type() == PidState::kPidVideoPes
&&
393 (lowest_video_pid
== pids_
.end() || pid
< lowest_video_pid
->first
))
394 lowest_video_pid
= it
;
397 // Enable both the lowest audio and video PIDs.
398 if (lowest_audio_pid
!= pids_
.end()) {
399 DVLOG(1) << "Enable audio pid: " << lowest_audio_pid
->first
;
400 lowest_audio_pid
->second
->Enable();
401 selected_audio_pid_
= lowest_audio_pid
->first
;
403 if (lowest_video_pid
!= pids_
.end()) {
404 DVLOG(1) << "Enable video pid: " << lowest_video_pid
->first
;
405 lowest_video_pid
->second
->Enable();
406 selected_video_pid_
= lowest_video_pid
->first
;
409 // Disable all the other audio and video PIDs.
410 for (PidMap::iterator it
= pids_
.begin(); it
!= pids_
.end(); ++it
) {
411 PidState
* pid_state
= it
->second
;
412 if (it
!= lowest_audio_pid
&& it
!= lowest_video_pid
&&
413 (pid_state
->pid_type() == PidState::kPidAudioPes
||
414 pid_state
->pid_type() == PidState::kPidVideoPes
))
415 pid_state
->Disable();
419 void Mp2tStreamParser::OnVideoConfigChanged(
421 const VideoDecoderConfig
& video_decoder_config
) {
422 DVLOG(1) << "OnVideoConfigChanged for pid=" << pes_pid
;
423 DCHECK_EQ(pes_pid
, selected_video_pid_
);
424 DCHECK(video_decoder_config
.IsValidConfig());
426 if (!buffer_queue_chain_
.empty() &&
427 !buffer_queue_chain_
.back().video_config
.IsValidConfig()) {
428 // No video has been received so far, can reuse the existing video queue.
429 DCHECK(buffer_queue_chain_
.back().video_queue
.empty());
430 buffer_queue_chain_
.back().video_config
= video_decoder_config
;
432 // Create a new entry in |buffer_queue_chain_| with the updated configs.
433 BufferQueueWithConfig
buffer_queue_with_config(
435 buffer_queue_chain_
.empty()
436 ? AudioDecoderConfig() : buffer_queue_chain_
.back().audio_config
,
437 video_decoder_config
);
438 buffer_queue_chain_
.push_back(buffer_queue_with_config
);
441 // Replace any non valid config with the 1st valid entry.
442 // This might happen if there was no available config before.
443 for (std::list
<BufferQueueWithConfig
>::iterator it
=
444 buffer_queue_chain_
.begin(); it
!= buffer_queue_chain_
.end(); ++it
) {
445 if (it
->video_config
.IsValidConfig())
447 it
->video_config
= video_decoder_config
;
451 void Mp2tStreamParser::OnAudioConfigChanged(
453 const AudioDecoderConfig
& audio_decoder_config
) {
454 DVLOG(1) << "OnAudioConfigChanged for pid=" << pes_pid
;
455 DCHECK_EQ(pes_pid
, selected_audio_pid_
);
456 DCHECK(audio_decoder_config
.IsValidConfig());
458 if (!buffer_queue_chain_
.empty() &&
459 !buffer_queue_chain_
.back().audio_config
.IsValidConfig()) {
460 // No audio has been received so far, can reuse the existing audio queue.
461 DCHECK(buffer_queue_chain_
.back().audio_queue
.empty());
462 buffer_queue_chain_
.back().audio_config
= audio_decoder_config
;
464 // Create a new entry in |buffer_queue_chain_| with the updated configs.
465 BufferQueueWithConfig
buffer_queue_with_config(
467 audio_decoder_config
,
468 buffer_queue_chain_
.empty()
469 ? VideoDecoderConfig() : buffer_queue_chain_
.back().video_config
);
470 buffer_queue_chain_
.push_back(buffer_queue_with_config
);
473 // Replace any non valid config with the 1st valid entry.
474 // This might happen if there was no available config before.
475 for (std::list
<BufferQueueWithConfig
>::iterator it
=
476 buffer_queue_chain_
.begin(); it
!= buffer_queue_chain_
.end(); ++it
) {
477 if (it
->audio_config
.IsValidConfig())
479 it
->audio_config
= audio_decoder_config
;
483 bool Mp2tStreamParser::FinishInitializationIfNeeded() {
484 // Nothing to be done if already initialized.
488 // Wait for more data to come to finish initialization.
489 if (buffer_queue_chain_
.empty())
492 // Wait for more data to come if one of the config is not available.
493 BufferQueueWithConfig
& queue_with_config
= buffer_queue_chain_
.front();
494 if (selected_audio_pid_
> 0 &&
495 !queue_with_config
.audio_config
.IsValidConfig())
497 if (selected_video_pid_
> 0 &&
498 !queue_with_config
.video_config
.IsValidConfig())
501 // Pass the config before invoking the initialization callback.
502 RCHECK(config_cb_
.Run(queue_with_config
.audio_config
,
503 queue_with_config
.video_config
,
504 TextTrackConfigMap()));
505 queue_with_config
.is_config_sent
= true;
507 // For Mpeg2 TS, the duration is not known.
508 DVLOG(1) << "Mpeg2TS stream parser initialization done";
509 base::ResetAndReturn(&init_cb_
).Run(InitParameters(kInfiniteDuration()));
510 is_initialized_
= true;
515 void Mp2tStreamParser::OnEmitAudioBuffer(
517 scoped_refptr
<StreamParserBuffer
> stream_parser_buffer
) {
518 DCHECK_EQ(pes_pid
, selected_audio_pid_
);
521 << "OnEmitAudioBuffer: "
523 << stream_parser_buffer
->data_size()
525 << stream_parser_buffer
->GetDecodeTimestamp().InMilliseconds()
527 << stream_parser_buffer
->timestamp().InMilliseconds()
529 << stream_parser_buffer
->duration().InMilliseconds();
531 // Ignore the incoming buffer if it is not associated with any config.
532 if (buffer_queue_chain_
.empty()) {
533 NOTREACHED() << "Cannot provide buffers before configs";
537 buffer_queue_chain_
.back().audio_queue
.push_back(stream_parser_buffer
);
540 void Mp2tStreamParser::OnEmitVideoBuffer(
542 scoped_refptr
<StreamParserBuffer
> stream_parser_buffer
) {
543 DCHECK_EQ(pes_pid
, selected_video_pid_
);
546 << "OnEmitVideoBuffer"
548 << stream_parser_buffer
->data_size()
550 << stream_parser_buffer
->GetDecodeTimestamp().InMilliseconds()
552 << stream_parser_buffer
->timestamp().InMilliseconds()
554 << stream_parser_buffer
->duration().InMilliseconds()
556 << stream_parser_buffer
->is_key_frame();
558 // Ignore the incoming buffer if it is not associated with any config.
559 if (buffer_queue_chain_
.empty()) {
560 NOTREACHED() << "Cannot provide buffers before configs";
564 buffer_queue_chain_
.back().video_queue
.push_back(stream_parser_buffer
);
567 bool Mp2tStreamParser::EmitRemainingBuffers() {
568 DVLOG(LOG_LEVEL_ES
) << "Mp2tStreamParser::EmitRemainingBuffers";
570 // No buffer should be sent until fully initialized.
571 if (!is_initialized_
)
574 if (buffer_queue_chain_
.empty())
577 // Keep track of the last audio and video config sent.
578 AudioDecoderConfig last_audio_config
=
579 buffer_queue_chain_
.back().audio_config
;
580 VideoDecoderConfig last_video_config
=
581 buffer_queue_chain_
.back().video_config
;
583 // Do not have all the configs, need more data.
584 if (selected_audio_pid_
>= 0 && !last_audio_config
.IsValidConfig())
586 if (selected_video_pid_
>= 0 && !last_video_config
.IsValidConfig())
590 while (!buffer_queue_chain_
.empty()) {
591 // Start a segment if needed.
592 if (!segment_started_
) {
593 DVLOG(1) << "Starting a new segment";
594 segment_started_
= true;
595 new_segment_cb_
.Run();
598 // Update the audio and video config if needed.
599 BufferQueueWithConfig
& queue_with_config
= buffer_queue_chain_
.front();
600 if (!queue_with_config
.is_config_sent
) {
601 if (!config_cb_
.Run(queue_with_config
.audio_config
,
602 queue_with_config
.video_config
,
603 TextTrackConfigMap()))
605 queue_with_config
.is_config_sent
= true;
609 TextBufferQueueMap empty_text_map
;
610 if (!queue_with_config
.audio_queue
.empty() ||
611 !queue_with_config
.video_queue
.empty()) {
612 if (!new_buffers_cb_
.Run(queue_with_config
.audio_queue
,
613 queue_with_config
.video_queue
,
619 buffer_queue_chain_
.pop_front();
622 // Push an empty queue with the last audio/video config
623 // so that buffers with the same config can be added later on.
624 BufferQueueWithConfig
queue_with_config(
625 true, last_audio_config
, last_video_config
);
626 buffer_queue_chain_
.push_back(queue_with_config
);