DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator
ts_segmenter.cc
1 // Copyright 2016 Google Inc. All rights reserved.
2 //
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file or at
5 // https://developers.google.com/open-source/licenses/bsd
6 
7 #include "packager/media/formats/mp2t/ts_segmenter.h"
8 
9 #include <memory>
10 
11 #include "packager/media/base/aes_encryptor.h"
12 #include "packager/media/base/key_source.h"
13 #include "packager/media/base/muxer_util.h"
14 #include "packager/media/base/status.h"
15 #include "packager/media/base/video_stream_info.h"
16 #include "packager/media/event/muxer_listener.h"
17 #include "packager/media/event/progress_listener.h"
18 
19 namespace shaka {
20 namespace media {
21 namespace mp2t {
22 
23 namespace {
24 const double kTsTimescale = 90000;
25 } // namespace
26 
28  : muxer_options_(options),
29  listener_(listener),
30  ts_writer_(new TsWriter()),
31  pes_packet_generator_(new PesPacketGenerator()) {}
32 TsSegmenter::~TsSegmenter() {}
33 
35  KeySource* encryption_key_source,
36  uint32_t max_sd_pixels,
37  double clear_lead_in_seconds) {
38  if (muxer_options_.segment_template.empty())
39  return Status(error::MUXER_FAILURE, "Segment template not specified.");
40  if (!ts_writer_->Initialize(stream_info))
41  return Status(error::MUXER_FAILURE, "Failed to initialize TsWriter.");
42  if (!pes_packet_generator_->Initialize(stream_info)) {
43  return Status(error::MUXER_FAILURE,
44  "Failed to initialize PesPacketGenerator.");
45  }
46 
47  if (encryption_key_source) {
48  scoped_ptr<EncryptionKey> encryption_key(new EncryptionKey());
49  const KeySource::TrackType type =
50  GetTrackTypeForEncryption(stream_info, max_sd_pixels);
51  Status status = encryption_key_source->GetKey(type, encryption_key.get());
52 
53  if (encryption_key->iv.empty()) {
54  if (!AesCryptor::GenerateRandomIv(FOURCC_cbcs, &encryption_key->iv)) {
55  return Status(error::INTERNAL_ERROR, "Failed to generate random iv.");
56  }
57  }
58  if (!status.ok())
59  return status;
60  encryption_key_ = encryption_key.Pass();
61  clear_lead_in_seconds_ = clear_lead_in_seconds;
62  status = NotifyEncrypted();
63  if (!status.ok())
64  return status;
65  }
66 
67  timescale_scale_ = kTsTimescale / stream_info.time_scale();
68  return Status::OK;
69 }
70 
72  return Flush();
73 }
74 
75 // First checks whether the sample is a key frame. If so and the segment has
76 // passed the segment duration, then flush the generator and write all the data
77 // to file.
78 Status TsSegmenter::AddSample(scoped_refptr<MediaSample> sample) {
79  const bool passed_segment_duration =
80  current_segment_total_sample_duration_ > muxer_options_.segment_duration;
81  if (sample->is_key_frame() && passed_segment_duration) {
82  Status status = Flush();
83  if (!status.ok())
84  return status;
85  }
86 
87  if (!ts_writer_file_opened_ && !sample->is_key_frame())
88  LOG(WARNING) << "A segment will start with a non key frame.";
89 
90  if (!pes_packet_generator_->PushSample(sample)) {
91  return Status(error::MUXER_FAILURE,
92  "Failed to add sample to PesPacketGenerator.");
93  }
94 
95  const double scaled_sample_duration = sample->duration() * timescale_scale_;
96  current_segment_total_sample_duration_ +=
97  scaled_sample_duration / kTsTimescale;
98 
99  return WritePesPacketsToFile();
100 }
101 
102 void TsSegmenter::InjectTsWriterForTesting(scoped_ptr<TsWriter> writer) {
103  ts_writer_ = writer.Pass();
104 }
105 
107  scoped_ptr<PesPacketGenerator> generator) {
108  pes_packet_generator_ = generator.Pass();
109 }
110 
112  ts_writer_file_opened_ = value;
113 }
114 
115 Status TsSegmenter::OpenNewSegmentIfClosed(uint32_t next_pts) {
116  if (ts_writer_file_opened_)
117  return Status::OK;
118  const std::string segment_name =
119  GetSegmentName(muxer_options_.segment_template, next_pts,
120  segment_number_++, muxer_options_.bandwidth);
121  if (!ts_writer_->NewSegment(segment_name))
122  return Status(error::MUXER_FAILURE, "Failed to initilize TsPacketWriter.");
123  current_segment_start_time_ = next_pts;
124  current_segment_path_ = segment_name;
125  ts_writer_file_opened_ = true;
126  return Status::OK;
127 }
128 
129 Status TsSegmenter::WritePesPacketsToFile() {
130  while (pes_packet_generator_->NumberOfReadyPesPackets() > 0u) {
131  scoped_ptr<PesPacket> pes_packet =
132  pes_packet_generator_->GetNextPesPacket();
133 
134  Status status = OpenNewSegmentIfClosed(pes_packet->pts());
135  if (!status.ok())
136  return status;
137 
138  if (!ts_writer_->AddPesPacket(pes_packet.Pass()))
139  return Status(error::MUXER_FAILURE, "Failed to add PES packet.");
140  }
141  return Status::OK;
142 }
143 
144 Status TsSegmenter::Flush() {
145  if (!pes_packet_generator_->Flush()) {
146  return Status(error::MUXER_FAILURE,
147  "Failed to flush PesPacketGenerator.");
148  }
149  Status status = WritePesPacketsToFile();
150  if (!status.ok())
151  return status;
152 
153  // This method may be called from Finalize() so ts_writer_file_opened_ could
154  // be false.
155  if (ts_writer_file_opened_) {
156  if (!ts_writer_->FinalizeSegment()) {
157  return Status(error::MUXER_FAILURE, "Failed to finalize TsWriter.");
158  }
159  if (listener_) {
160  const int64_t file_size =
161  File::GetFileSize(current_segment_path_.c_str());
162  listener_->OnNewSegment(
163  current_segment_path_, current_segment_start_time_,
164  current_segment_total_sample_duration_ * kTsTimescale, file_size);
165  }
166  ts_writer_file_opened_ = false;
167  total_duration_in_seconds_ += current_segment_total_sample_duration_;
168  }
169  current_segment_total_sample_duration_ = 0.0;
170  current_segment_start_time_ = 0;
171  current_segment_path_.clear();
172  return NotifyEncrypted();
173 }
174 
175 Status TsSegmenter::NotifyEncrypted() {
176  if (encryption_key_ && total_duration_in_seconds_ >= clear_lead_in_seconds_) {
177  if (listener_) {
178  // For now this only happens once, so send true.
179  const bool kIsInitialEncryptionInfo = true;
180  listener_->OnEncryptionInfoReady(
181  kIsInitialEncryptionInfo, FOURCC_cbcs, encryption_key_->key_id,
182  encryption_key_->iv, encryption_key_->key_system_info);
183  }
184 
185  if (!pes_packet_generator_->SetEncryptionKey(encryption_key_.Pass()))
186  return Status(error::INTERNAL_ERROR, "Failed to set encryption key.");
187  ts_writer_->SignalEncypted();
188  }
189  return Status::OK;
190 }
191 
192 } // namespace mp2t
193 } // namespace media
194 } // namespace shaka
virtual void OnNewSegment(const std::string &segment_name, uint64_t start_time, uint64_t duration, uint64_t segment_file_size)=0
virtual void OnEncryptionInfoReady(bool is_initial_encryption_info, FourCC protection_scheme, const std::vector< uint8_t > &key_id, const std::vector< uint8_t > &iv, const std::vector< ProtectionSystemSpecificInfo > &key_system_info)=0
Abstract class holds stream information.
Definition: stream_info.h:26
Status AddSample(scoped_refptr< MediaSample > sample)
Definition: ts_segmenter.cc:78
This structure contains the list of configuration options for Muxer.
Definition: muxer_options.h:18
virtual Status GetKey(TrackType track_type, EncryptionKey *key)=0
void InjectTsWriterForTesting(scoped_ptr< TsWriter > writer)
Only for testing.
TsSegmenter(const MuxerOptions &options, MuxerListener *listener)
Definition: ts_segmenter.cc:27
static bool GenerateRandomIv(FourCC protection_scheme, std::vector< uint8_t > *iv)
Definition: aes_cryptor.cc:109
void SetTsWriterFileOpenedForTesting(bool value)
Only for testing.
void InjectPesPacketGeneratorForTesting(scoped_ptr< PesPacketGenerator > generator)
Only for testing.
static int64_t GetFileSize(const char *file_name)
Definition: file.cc:175
KeySource is responsible for encryption key acquisition.
Definition: key_source.h:31
Status Initialize(const StreamInfo &stream_info, KeySource *encryption_key_source, uint32_t max_sd_pixels, double clear_lead_in_seconds)
Definition: ts_segmenter.cc:34