Shaka Packager SDK
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/audio_stream_info.h"
12 #include "packager/media/base/muxer_util.h"
13 #include "packager/media/base/video_stream_info.h"
14 #include "packager/media/event/muxer_listener.h"
15 #include "packager/media/formats/mp2t/pes_packet.h"
16 #include "packager/media/formats/mp2t/program_map_table_writer.h"
17 #include "packager/status.h"
18 
19 namespace shaka {
20 namespace media {
21 namespace mp2t {
22 
23 namespace {
24 const double kTsTimescale = 90000;
25 
26 bool IsAudioCodec(Codec codec) {
27  return codec >= kCodecAudio && codec < kCodecAudioMaxPlusOne;
28 }
29 
30 bool IsVideoCodec(Codec codec) {
31  return codec >= kCodecVideo && codec < kCodecVideoMaxPlusOne;
32 }
33 
34 } // namespace
35 
37  : muxer_options_(options),
38  listener_(listener),
39  transport_stream_timestamp_offset_(
40  options.transport_stream_timestamp_offset_ms * kTsTimescale / 1000),
41  pes_packet_generator_(
42  new PesPacketGenerator(transport_stream_timestamp_offset_)) {}
43 
44 TsSegmenter::~TsSegmenter() {}
45 
47  if (muxer_options_.segment_template.empty())
48  return Status(error::MUXER_FAILURE, "Segment template not specified.");
49  if (!pes_packet_generator_->Initialize(stream_info)) {
50  return Status(error::MUXER_FAILURE,
51  "Failed to initialize PesPacketGenerator.");
52  }
53 
54  const StreamType stream_type = stream_info.stream_type();
55  if (stream_type != StreamType::kStreamVideo &&
56  stream_type != StreamType::kStreamAudio) {
57  LOG(ERROR) << "TsWriter cannot handle stream type " << stream_type
58  << " yet.";
59  return Status(error::MUXER_FAILURE, "Unsupported stream type.");
60  }
61 
62  codec_ = stream_info.codec();
63  if (stream_type == StreamType::kStreamAudio)
64  audio_codec_config_ = stream_info.codec_config();
65 
66  timescale_scale_ = kTsTimescale / stream_info.time_scale();
67  return Status::OK;
68 }
69 
71  return Status::OK;
72 }
73 
75  if (!ts_writer_) {
76  std::unique_ptr<ProgramMapTableWriter> pmt_writer;
77  if (codec_ == kCodecAC3) {
78  // https://goo.gl/N7Tvqi MPEG-2 Stream Encryption Format for HTTP Live
79  // Streaming 2.3.2.2 AC-3 Setup: For AC-3, the setup_data in the
80  // audio_setup_information is the first 10 bytes of the audio data (the
81  // syncframe()).
82  // For unencrypted AC3, the setup_data is not used, so what is in there
83  // does not matter.
84  const size_t kSetupDataSize = 10u;
85  if (sample.data_size() < kSetupDataSize) {
86  LOG(ERROR) << "Sample is too small for AC3: " << sample.data_size();
87  return Status(error::MUXER_FAILURE, "Sample is too small for AC3.");
88  }
89  const std::vector<uint8_t> setup_data(sample.data(),
90  sample.data() + kSetupDataSize);
91  pmt_writer.reset(new AudioProgramMapTableWriter(codec_, setup_data));
92  } else if (IsAudioCodec(codec_)) {
93  pmt_writer.reset(
94  new AudioProgramMapTableWriter(codec_, audio_codec_config_));
95  } else {
96  DCHECK(IsVideoCodec(codec_));
97  pmt_writer.reset(new VideoProgramMapTableWriter(codec_));
98  }
99  ts_writer_.reset(new TsWriter(std::move(pmt_writer)));
100  }
101 
102  if (sample.is_encrypted())
103  ts_writer_->SignalEncrypted();
104 
105  if (!ts_writer_file_opened_ && !sample.is_key_frame())
106  LOG(WARNING) << "A segment will start with a non key frame.";
107 
108  if (!pes_packet_generator_->PushSample(sample)) {
109  return Status(error::MUXER_FAILURE,
110  "Failed to add sample to PesPacketGenerator.");
111  }
112  return WritePesPacketsToFile();
113 }
114 
115 void TsSegmenter::InjectTsWriterForTesting(std::unique_ptr<TsWriter> writer) {
116  ts_writer_ = std::move(writer);
117 }
118 
120  std::unique_ptr<PesPacketGenerator> generator) {
121  pes_packet_generator_ = std::move(generator);
122 }
123 
125  ts_writer_file_opened_ = value;
126 }
127 
128 Status TsSegmenter::OpenNewSegmentIfClosed(uint32_t next_pts) {
129  if (ts_writer_file_opened_)
130  return Status::OK;
131  const std::string segment_name =
132  GetSegmentName(muxer_options_.segment_template, next_pts,
133  segment_number_++, muxer_options_.bandwidth);
134  if (!ts_writer_->NewSegment(segment_name))
135  return Status(error::MUXER_FAILURE, "Failed to initilize TsPacketWriter.");
136  current_segment_path_ = segment_name;
137  ts_writer_file_opened_ = true;
138  return Status::OK;
139 }
140 
141 Status TsSegmenter::WritePesPacketsToFile() {
142  while (pes_packet_generator_->NumberOfReadyPesPackets() > 0u) {
143  std::unique_ptr<PesPacket> pes_packet =
144  pes_packet_generator_->GetNextPesPacket();
145 
146  Status status = OpenNewSegmentIfClosed(pes_packet->pts());
147  if (!status.ok())
148  return status;
149 
150  if (listener_ && IsVideoCodec(codec_) && pes_packet->is_key_frame()) {
151  base::Optional<uint64_t> start_pos = ts_writer_->GetFilePosition();
152 
153  const int64_t timestamp = pes_packet->pts();
154  if (!ts_writer_->AddPesPacket(std::move(pes_packet)))
155  return Status(error::MUXER_FAILURE, "Failed to add PES packet.");
156 
157  base::Optional<uint64_t> end_pos = ts_writer_->GetFilePosition();
158  if (!start_pos || !end_pos) {
159  return Status(error::MUXER_FAILURE,
160  "Failed to get file position in WritePesPacketsToFile.");
161  }
162  listener_->OnKeyFrame(timestamp, *start_pos, *end_pos - *start_pos);
163  } else {
164  if (!ts_writer_->AddPesPacket(std::move(pes_packet)))
165  return Status(error::MUXER_FAILURE, "Failed to add PES packet.");
166  }
167  }
168  return Status::OK;
169 }
170 
171 Status TsSegmenter::FinalizeSegment(uint64_t start_timestamp,
172  uint64_t duration) {
173  if (!pes_packet_generator_->Flush()) {
174  return Status(error::MUXER_FAILURE,
175  "Failed to flush PesPacketGenerator.");
176  }
177  Status status = WritePesPacketsToFile();
178  if (!status.ok())
179  return status;
180 
181  // This method may be called from Finalize() so ts_writer_file_opened_ could
182  // be false.
183  if (ts_writer_file_opened_) {
184  if (!ts_writer_->FinalizeSegment()) {
185  return Status(error::MUXER_FAILURE, "Failed to finalize TsWriter.");
186  }
187  if (listener_) {
188  const int64_t file_size =
189  File::GetFileSize(current_segment_path_.c_str());
190  listener_->OnNewSegment(current_segment_path_,
191  start_timestamp * timescale_scale_ +
192  transport_stream_timestamp_offset_,
193  duration * timescale_scale_, file_size);
194  }
195  ts_writer_file_opened_ = false;
196  }
197  current_segment_path_.clear();
198  return Status::OK;
199 }
200 
201 } // namespace mp2t
202 } // namespace media
203 } // namespace shaka
Abstract class holds stream information.
Definition: stream_info.h:62
ProgramMapTableWriter for video codecs.
Status Initialize(const StreamInfo &stream_info)
Definition: ts_segmenter.cc:46
All the methods that are virtual are virtual for mocking.
static int64_t GetFileSize(const char *file_name)
Definition: file.cc:207
This structure contains the list of configuration options for Muxer.
Definition: muxer_options.h:20
Status AddSample(const MediaSample &sample)
Definition: ts_segmenter.cc:74
ProgramMapTableWriter for video codecs.
TsSegmenter(const MuxerOptions &options, MuxerListener *listener)
Definition: ts_segmenter.cc:36
void InjectPesPacketGeneratorForTesting(std::unique_ptr< PesPacketGenerator > generator)
Only for testing.
void SetTsWriterFileOpenedForTesting(bool value)
Only for testing.
void InjectTsWriterForTesting(std::unique_ptr< TsWriter > writer)
Only for testing.
virtual void OnNewSegment(const std::string &segment_name, int64_t start_time, int64_t duration, uint64_t segment_file_size)=0
Class to hold a media sample.
Definition: media_sample.h:22
Status FinalizeSegment(uint64_t start_timestamp, uint64_t duration)
virtual void OnKeyFrame(int64_t timestamp, uint64_t start_byte_offset, uint64_t size)=0