DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator
ts_writer.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_writer.h"
8 
9 #include <algorithm>
10 
11 #include "packager/base/logging.h"
12 #include "packager/media/base/audio_stream_info.h"
13 #include "packager/media/base/buffer_writer.h"
14 #include "packager/media/base/stream_info.h"
15 #include "packager/media/base/video_stream_info.h"
16 #include "packager/media/formats/mp2t/ts_packet_writer_util.h"
17 
18 namespace edash_packager {
19 namespace media {
20 namespace mp2t {
21 
22 namespace {
23 
24 // For all the pointer fields in the following PAT and PMTs, they are not really
25 // part of PAT or PMT but it's there so that TsPacket can point to a memory
26 // location that starts from pointer field.
27 const uint8_t kProgramAssociationTableId = 0x00;
28 
29 // This PAT can be used for both encrypted and clear.
30 const uint8_t kPat[] = {
31  0x00, // pointer field
32  kProgramAssociationTableId,
33  0xB0, // The last 2 '00' assumes that this PAT is not very long.
34  0x0D, // Length of the rest of this array.
35  0x00, 0x00, // Transport stream ID is 0.
36  0xC1, // version number 0, current next indicator 1.
37  0x00, // section number
38  0x00, // last section number
39  // program number -> PMT PID mapping.
40  0x00, 0x01, // program number is 1.
41  0xE0, // first 3 bits is reserved.
42  ProgramMapTableWriter::kPmtPid,
43  // CRC32.
44  0xF9, 0x62, 0xF5, 0x8B,
45 };
46 
47 const bool kHasPcr = true;
48 const bool kPayloadUnitStartIndicator = true;
49 
50 // This is the size of the first few fields in a TS packet, i.e. TS packet size
51 // without adaptation field or the payload.
52 const int kTsPacketHeaderSize = 4;
53 const int kTsPacketSize = 188;
54 const int kTsPacketMaximumPayloadSize =
55  kTsPacketSize - kTsPacketHeaderSize;
56 
57 const size_t kMaxPesPacketLengthValue = 0xFFFF;
58 
59 void WritePatToBuffer(const uint8_t* pat,
60  int pat_size,
61  ContinuityCounter* continuity_counter,
62  BufferWriter* writer) {
63  const int kPatPid = 0;
64  WritePayloadToBufferWriter(pat, pat_size, kPayloadUnitStartIndicator, kPatPid,
65  !kHasPcr, 0, continuity_counter, writer);
66 }
67 
68 // The only difference between writing PTS or DTS is the leading bits.
69 void WritePtsOrDts(uint8_t leading_bits,
70  uint64_t pts_or_dts,
71  BufferWriter* writer) {
72  // First byte has 3 MSB of PTS.
73  uint8_t first_byte =
74  leading_bits << 4 | (((pts_or_dts >> 30) & 0x07) << 1) | 1;
75  // Second byte has the next 8 bits of pts.
76  uint8_t second_byte = (pts_or_dts >> 22) & 0xFF;
77  // Third byte has the next 7 bits of pts followed by a marker bit.
78  uint8_t third_byte = (((pts_or_dts >> 15) & 0x7F) << 1) | 1;
79  // Fourth byte has the next 8 bits of pts.
80  uint8_t fourth_byte = ((pts_or_dts >> 7) & 0xFF);
81  // Fifth byte has the last 7 bits of pts followed by a marker bit.
82  uint8_t fifth_byte = ((pts_or_dts & 0x7F) << 1) | 1;
83  writer->AppendInt(first_byte);
84  writer->AppendInt(second_byte);
85  writer->AppendInt(third_byte);
86  writer->AppendInt(fourth_byte);
87  writer->AppendInt(fifth_byte);
88 }
89 
90 bool WritePesToFile(const PesPacket& pes,
91  ContinuityCounter* continuity_counter,
92  File* file) {
93  // The size of the length field.
94  const int kAdaptationFieldLengthSize = 1;
95  // The size of the flags field.
96  const int kAdaptationFieldHeaderSize = 1;
97  const int kPcrFieldSize = 6;
98  const int kTsPacketMaxPayloadWithPcr =
99  kTsPacketMaximumPayloadSize - kAdaptationFieldLengthSize -
100  kAdaptationFieldHeaderSize - kPcrFieldSize;
101  const uint64_t pcr_base = pes.has_dts() ? pes.dts() : pes.pts();
102  const int pid = ProgramMapTableWriter::kElementaryPid;
103 
104  // This writer will hold part of PES packet after PES_packet_length field.
105  BufferWriter pes_header_writer;
106  // The first bit must be '10' for PES with video or audio stream id. The other
107  // flags (bits) don't matter so they are 0.
108  pes_header_writer.AppendInt(static_cast<uint8_t>(0x80));
109  pes_header_writer.AppendInt(
110  static_cast<uint8_t>(static_cast<int>(pes.has_pts()) << 7 |
111  static_cast<int>(pes.has_dts()) << 6
112  // Other fields are all 0.
113  ));
114  uint8_t pes_header_data_length = 0;
115  if (pes.has_pts())
116  pes_header_data_length += 5;
117  if (pes.has_dts())
118  pes_header_data_length += 5;
119  pes_header_writer.AppendInt(pes_header_data_length);
120 
121  if (pes.has_pts() && pes.has_dts()) {
122  WritePtsOrDts(0x03, pes.pts(), &pes_header_writer);
123  WritePtsOrDts(0x01, pes.dts(), &pes_header_writer);
124  } else if (pes.has_pts()) {
125  WritePtsOrDts(0x02, pes.pts(), &pes_header_writer);
126  }
127 
128  // Put the first TS packet's payload into a buffer. This contains the PES
129  // packet's header.
130  BufferWriter first_ts_packet_buffer(kTsPacketSize);
131  first_ts_packet_buffer.AppendNBytes(static_cast<uint64_t>(0x000001), 3);
132  first_ts_packet_buffer.AppendInt(pes.stream_id());
133  const size_t pes_packet_length = pes.data().size() + pes_header_writer.Size();
134  first_ts_packet_buffer.AppendInt(static_cast<uint16_t>(
135  pes_packet_length > kMaxPesPacketLengthValue ? 0 : pes_packet_length));
136  first_ts_packet_buffer.AppendBuffer(pes_header_writer);
137 
138  const int available_payload =
139  kTsPacketMaxPayloadWithPcr - first_ts_packet_buffer.Size();
140  const int bytes_consumed =
141  std::min(static_cast<int>(pes.data().size()), available_payload);
142  first_ts_packet_buffer.AppendArray(pes.data().data(), bytes_consumed);
143 
144  BufferWriter output_writer;
145  WritePayloadToBufferWriter(first_ts_packet_buffer.Buffer(),
146  first_ts_packet_buffer.Size(),
147  kPayloadUnitStartIndicator, pid, kHasPcr, pcr_base,
148  continuity_counter, &output_writer);
149 
150  const size_t remaining_pes_data_size = pes.data().size() - bytes_consumed;
151  if (remaining_pes_data_size > 0) {
152  WritePayloadToBufferWriter(pes.data().data() + bytes_consumed,
153  remaining_pes_data_size,
154  !kPayloadUnitStartIndicator, pid, !kHasPcr, 0,
155  continuity_counter, &output_writer);
156  }
157  return output_writer.WriteToFile(file).ok();
158 }
159 
160 } // namespace
161 
162 TsWriter::TsWriter() {}
163 TsWriter::~TsWriter() {}
164 
165 bool TsWriter::Initialize(const StreamInfo& stream_info,
166  bool will_be_encrypted) {
167  const StreamType stream_type = stream_info.stream_type();
168  if (stream_type != StreamType::kStreamVideo &&
169  stream_type != StreamType::kStreamAudio) {
170  LOG(ERROR) << "TsWriter cannot handle stream type " << stream_type
171  << " yet.";
172  return false;
173  }
174 
175  if (stream_info.stream_type() == StreamType::kStreamVideo) {
176  const VideoStreamInfo& video_stream_info =
177  static_cast<const VideoStreamInfo&>(stream_info);
178  if (video_stream_info.codec() != VideoCodec::kCodecH264) {
179  LOG(ERROR) << "TsWriter cannot handle video codec "
180  << video_stream_info.codec() << " yet.";
181  return false;
182  }
183  pmt_writer_.reset(new H264ProgramMapTableWriter(&pmt_continuity_counter_));
184  } else {
185  DCHECK_EQ(stream_type, StreamType::kStreamAudio);
186  const AudioStreamInfo& audio_stream_info =
187  static_cast<const AudioStreamInfo&>(stream_info);
188  if (audio_stream_info.codec() != AudioCodec::kCodecAAC) {
189  LOG(ERROR) << "TsWriter cannot handle audio codec "
190  << audio_stream_info.codec() << " yet.";
191  return false;
192  }
193  pmt_writer_.reset(new AacProgramMapTableWriter(
194  audio_stream_info.extra_data(), &pmt_continuity_counter_));
195  }
196 
197  will_be_encrypted_ = will_be_encrypted;
198  return true;
199 }
200 
201 bool TsWriter::NewSegment(const std::string& file_name) {
202  if (current_file_) {
203  LOG(ERROR) << "File " << current_file_->file_name() << " still open.";
204  return false;
205  }
206  current_file_.reset(File::Open(file_name.c_str(), "w"));
207  if (!current_file_) {
208  LOG(ERROR) << "Failed to open file " << file_name;
209  return false;
210  }
211 
212  BufferWriter psi;
213  WritePatToBuffer(kPat, arraysize(kPat), &pat_continuity_counter_, &psi);
214  if (will_be_encrypted_ && !encrypted_) {
215  if (!pmt_writer_->ClearLeadSegmentPmt(&psi)) {
216  return false;
217  }
218  } else if (encrypted_) {
219  if (!pmt_writer_->EncryptedSegmentPmt(&psi)) {
220  return false;
221  }
222  } else {
223  if (!pmt_writer_->ClearSegmentPmt(&psi)) {
224  return false;
225  }
226  }
227 
228  if (!psi.WriteToFile(current_file_.get()).ok()) {
229  LOG(ERROR) << "Failed to write PSI to file.";
230  return false;
231  }
232 
233  return true;
234 }
235 
237  encrypted_ = true;
238 }
239 
241  return current_file_.release()->Close();
242 }
243 
244 bool TsWriter::AddPesPacket(scoped_ptr<PesPacket> pes_packet) {
245  DCHECK(current_file_);
246  if (!WritePesToFile(*pes_packet, &elementary_stream_continuity_counter_,
247  current_file_.get())) {
248  LOG(ERROR) << "Failed to write pes to file.";
249  return false;
250  }
251 
252  // No need to keep pes_packet around so not passing it anywhere.
253  return true;
254 }
255 
257  scoped_ptr<ProgramMapTableWriter> table_writer) {
258  pmt_writer_ = table_writer.Pass();
259 }
260 
261 } // namespace mp2t
262 } // namespace media
263 } // namespace edash_packager
Holds audio stream information.
Abstract class holds stream information.
Definition: stream_info.h:26
virtual bool Open()=0
Internal open. Should not be used directly.
void SetProgramMapTableWriterForTesting(scoped_ptr< ProgramMapTableWriter > table_writer)
Only for testing.
Definition: ts_writer.cc:256
virtual bool NewSegment(const std::string &file_name)
Definition: ts_writer.cc:201
virtual bool AddPesPacket(scoped_ptr< PesPacket > pes_packet)
Definition: ts_writer.cc:244
Holds video stream information.
virtual bool Initialize(const StreamInfo &stream_info, bool will_be_encrypted)
Definition: ts_writer.cc:165