DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator
segmenter.cc
1 // Copyright 2015 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/webm/segmenter.h"
8 
9 #include "packager/base/time/time.h"
10 #include "packager/media/base/audio_stream_info.h"
11 #include "packager/media/base/media_handler.h"
12 #include "packager/media/base/media_sample.h"
13 #include "packager/media/base/muxer_options.h"
14 #include "packager/media/base/muxer_util.h"
15 #include "packager/media/base/stream_info.h"
16 #include "packager/media/base/video_stream_info.h"
17 #include "packager/media/codecs/vp_codec_configuration_record.h"
18 #include "packager/media/event/muxer_listener.h"
19 #include "packager/media/event/progress_listener.h"
20 #include "packager/third_party/libwebm/src/mkvmuxerutil.hpp"
21 #include "packager/third_party/libwebm/src/webmids.hpp"
22 #include "packager/version/version.h"
23 
24 namespace shaka {
25 namespace media {
26 namespace webm {
27 namespace {
28 int64_t kTimecodeScale = 1000000;
29 int64_t kSecondsToNs = 1000000000L;
30 } // namespace
31 
32 Segmenter::Segmenter(const MuxerOptions& options) : options_(options) {}
33 
34 Segmenter::~Segmenter() {}
35 
37  ProgressListener* progress_listener,
38  MuxerListener* muxer_listener,
39  KeySource* encryption_key_source,
40  uint32_t max_sd_pixels,
41  uint32_t max_hd_pixels,
42  uint32_t max_uhd1_pixels,
43  double clear_lead_in_seconds) {
44  muxer_listener_ = muxer_listener;
45  info_ = info;
46  clear_lead_ = clear_lead_in_seconds;
47 
48  // Use media duration as progress target.
49  progress_target_ = info_->duration();
50  progress_listener_ = progress_listener;
51 
52  segment_info_.Init();
53  segment_info_.set_timecode_scale(kTimecodeScale);
54 
55  const std::string version = GetPackagerVersion();
56  if (!version.empty()) {
57  segment_info_.set_writing_app(
58  (GetPackagerProjectUrl() + " version " + version).c_str());
59  }
60 
61  if (options().segment_template.empty()) {
62  // Set an initial duration so the duration element is written; will be
63  // overwritten at the end. This works because this is a float and floats
64  // are always the same size.
65  segment_info_.set_duration(1);
66  }
67 
68  Status status;
69  if (encryption_key_source) {
70  status = InitializeEncryptor(encryption_key_source,
71  max_sd_pixels,
72  max_hd_pixels,
73  max_uhd1_pixels);
74  if (!status.ok())
75  return status;
76  }
77 
78  // Create the track info.
79  switch (info_->stream_type()) {
80  case kStreamVideo:
81  status = CreateVideoTrack(static_cast<VideoStreamInfo*>(info_));
82  break;
83  case kStreamAudio:
84  status = CreateAudioTrack(static_cast<AudioStreamInfo*>(info_));
85  break;
86  default:
87  NOTIMPLEMENTED() << "Not implemented for stream type: "
88  << info_->stream_type();
89  status = Status(error::UNIMPLEMENTED, "Not implemented for stream type");
90  }
91  if (!status.ok())
92  return status;
93 
94  return DoInitialize();
95 }
96 
98  uint64_t duration =
99  prev_sample_->pts() - first_timestamp_ + prev_sample_->duration();
100  segment_info_.set_duration(FromBMFFTimescale(duration));
101  return DoFinalize();
102 }
103 
104 Status Segmenter::AddSample(std::shared_ptr<MediaSample> sample) {
105  if (sample_duration_ == 0) {
106  first_timestamp_ = sample->pts();
107  sample_duration_ = sample->duration();
108  if (muxer_listener_)
109  muxer_listener_->OnSampleDurationReady(sample_duration_);
110  }
111 
112  UpdateProgress(sample->duration());
113 
114  // This writes frames in a delay. Meaning that the previous frame is written
115  // on this call to AddSample. The current frame is stored until the next
116  // call. This is done to determine which frame is the last in a Cluster.
117  // This first block determines if this is a new Cluster and writes the
118  // previous frame first before creating the new Cluster.
119 
120  Status status;
121  if (new_segment_ || new_subsegment_) {
122  status = NewSegment(sample->pts(), new_subsegment_);
123  } else {
124  status = WriteFrame(false /* write_duration */);
125  }
126  if (!status.ok())
127  return status;
128 
129  // Encrypt the frame.
130  if (encryptor_) {
131  // Don't enable encryption in the middle of a segment, i.e. only at the
132  // first frame of a segment.
133  if (new_segment_ && !enable_encryption_) {
134  if (sample->pts() - first_timestamp_ >=
135  clear_lead_ * info_->time_scale()) {
136  enable_encryption_ = true;
137  if (muxer_listener_)
138  muxer_listener_->OnEncryptionStart();
139  }
140  }
141 
142  status = encryptor_->EncryptFrame(sample, enable_encryption_);
143  if (!status.ok()) {
144  LOG(ERROR) << "Error encrypting frame.";
145  return status;
146  }
147  }
148 
149  new_subsegment_ = false;
150  new_segment_ = false;
151  prev_sample_ = sample;
152  return Status::OK;
153 }
154 
155 Status Segmenter::FinalizeSegment(uint64_t start_timescale,
156  uint64_t duration_timescale,
157  bool is_subsegment) {
158  if (is_subsegment)
159  new_subsegment_ = true;
160  else
161  new_segment_ = true;
162  return WriteFrame(true /* write duration */);
163 }
164 
165 float Segmenter::GetDuration() const {
166  return static_cast<float>(segment_info_.duration()) *
167  segment_info_.timecode_scale() / kSecondsToNs;
168 }
169 
170 uint64_t Segmenter::FromBMFFTimescale(uint64_t time_timescale) {
171  // Convert the time from BMFF time_code to WebM timecode scale.
172  const int64_t time_ns =
173  kSecondsToNs * time_timescale / info_->time_scale();
174  return time_ns / segment_info_.timecode_scale();
175 }
176 
177 uint64_t Segmenter::FromWebMTimecode(uint64_t time_webm_timecode) {
178  // Convert the time to BMFF time_code from WebM timecode scale.
179  const int64_t time_ns = time_webm_timecode * segment_info_.timecode_scale();
180  return time_ns * info_->time_scale() / kSecondsToNs;
181 }
182 
183 Status Segmenter::WriteSegmentHeader(uint64_t file_size, MkvWriter* writer) {
184  Status error_status(error::FILE_FAILURE, "Error writing segment header.");
185 
186  if (!WriteEbmlHeader(writer))
187  return error_status;
188 
189  if (WriteID(writer, mkvmuxer::kMkvSegment) != 0)
190  return error_status;
191 
192  const uint64_t segment_size_size = 8;
193  segment_payload_pos_ = writer->Position() + segment_size_size;
194  if (file_size > 0) {
195  // We want the size of the segment element, so subtract the header.
196  if (WriteUIntSize(writer, file_size - segment_payload_pos_,
197  segment_size_size) != 0)
198  return error_status;
199  if (!seek_head_.Write(writer))
200  return error_status;
201  } else {
202  if (SerializeInt(writer, mkvmuxer::kEbmlUnknownValue, segment_size_size) !=
203  0)
204  return error_status;
205  // We don't know the header size, so write a placeholder.
206  if (!seek_head_.WriteVoid(writer))
207  return error_status;
208  }
209 
210  seek_head_.set_info_pos(writer->Position() - segment_payload_pos_);
211  if (!segment_info_.Write(writer))
212  return error_status;
213 
214  seek_head_.set_tracks_pos(writer->Position() - segment_payload_pos_);
215  if (!tracks_.Write(writer))
216  return error_status;
217 
218  return Status::OK;
219 }
220 
221 Status Segmenter::SetCluster(uint64_t start_webm_timecode,
222  uint64_t position,
223  MkvWriter* writer) {
224  const uint64_t scale = segment_info_.timecode_scale();
225  cluster_.reset(new mkvmuxer::Cluster(start_webm_timecode, position, scale));
226  cluster_->Init(writer);
227  return Status::OK;
228 }
229 
230 void Segmenter::UpdateProgress(uint64_t progress) {
231  accumulated_progress_ += progress;
232  if (!progress_listener_ || progress_target_ == 0)
233  return;
234  // It might happen that accumulated progress exceeds progress_target due to
235  // computation errors, e.g. rounding error. Cap it so it never reports > 100%
236  // progress.
237  if (accumulated_progress_ >= progress_target_) {
238  progress_listener_->OnProgress(1.0);
239  } else {
240  progress_listener_->OnProgress(static_cast<double>(accumulated_progress_) /
241  progress_target_);
242  }
243 }
244 
245 Status Segmenter::CreateVideoTrack(VideoStreamInfo* info) {
246  // The seed is only used to create a UID which we overwrite later.
247  unsigned int seed = 0;
248  mkvmuxer::VideoTrack* track = new mkvmuxer::VideoTrack(&seed);
249  if (!track)
250  return Status(error::INTERNAL_ERROR, "Failed to create video track.");
251 
252  if (info->codec() == kCodecVP8) {
253  track->set_codec_id(mkvmuxer::Tracks::kVp8CodecId);
254  } else if (info->codec() == kCodecVP9) {
255  track->set_codec_id(mkvmuxer::Tracks::kVp9CodecId);
256 
257  // The |StreamInfo::codec_config| field is stored using the MP4 format; we
258  // need to convert it to the WebM format.
259  VPCodecConfigurationRecord vp_config;
260  if (!vp_config.ParseMP4(info->codec_config())) {
261  return Status(error::INTERNAL_ERROR,
262  "Unable to parse VP9 codec configuration");
263  }
264 
265  std::vector<uint8_t> codec_config;
266  vp_config.WriteWebM(&codec_config);
267  if (!track->SetCodecPrivate(codec_config.data(), codec_config.size())) {
268  return Status(error::INTERNAL_ERROR,
269  "Private codec data required for VP9 streams");
270  }
271  } else {
272  LOG(ERROR) << "Only VP8 and VP9 video codecs are supported.";
273  return Status(error::UNIMPLEMENTED,
274  "Only VP8 and VP9 video codecs are supported.");
275  }
276 
277  track->set_uid(info->track_id());
278  if (!info->language().empty())
279  track->set_language(info->language().c_str());
280  track->set_type(mkvmuxer::Tracks::kVideo);
281  track->set_width(info->width());
282  track->set_height(info->height());
283  track->set_display_height(info->height());
284  track->set_display_width(info->width() * info->pixel_width() /
285  info->pixel_height());
286 
287  if (encryptor_)
288  encryptor_->AddTrackInfo(track);
289 
290  tracks_.AddTrack(track, info->track_id());
291  track_id_ = track->number();
292  return Status::OK;
293 }
294 
295 Status Segmenter::CreateAudioTrack(AudioStreamInfo* info) {
296  // The seed is only used to create a UID which we overwrite later.
297  unsigned int seed = 0;
298  mkvmuxer::AudioTrack* track = new mkvmuxer::AudioTrack(&seed);
299  if (!track)
300  return Status(error::INTERNAL_ERROR, "Failed to create audio track.");
301 
302  if (info->codec() == kCodecOpus) {
303  track->set_codec_id(mkvmuxer::Tracks::kOpusCodecId);
304  } else if (info->codec() == kCodecVorbis) {
305  track->set_codec_id(mkvmuxer::Tracks::kVorbisCodecId);
306  } else {
307  LOG(ERROR) << "Only Vorbis and Opus audio codec is supported.";
308  return Status(error::UNIMPLEMENTED,
309  "Only Vorbis and Opus audio codecs are supported.");
310  }
311  if (!track->SetCodecPrivate(info->codec_config().data(),
312  info->codec_config().size())) {
313  return Status(error::INTERNAL_ERROR,
314  "Private codec data required for audio streams");
315  }
316 
317  track->set_uid(info->track_id());
318  if (!info->language().empty())
319  track->set_language(info->language().c_str());
320  track->set_type(mkvmuxer::Tracks::kAudio);
321  track->set_sample_rate(info->sampling_frequency());
322  track->set_channels(info->num_channels());
323  track->set_seek_pre_roll(info->seek_preroll_ns());
324  track->set_codec_delay(info->codec_delay_ns());
325 
326  if (encryptor_)
327  encryptor_->AddTrackInfo(track);
328 
329  tracks_.AddTrack(track, info->track_id());
330  track_id_ = track->number();
331  return Status::OK;
332 }
333 
334 Status Segmenter::InitializeEncryptor(KeySource* key_source,
335  uint32_t max_sd_pixels,
336  uint32_t max_hd_pixels,
337  uint32_t max_uhd1_pixels) {
338  encryptor_.reset(new Encryptor());
339  const KeySource::TrackType track_type =
340  GetTrackTypeForEncryption(*info_, max_sd_pixels, max_hd_pixels,
341  max_uhd1_pixels);
342  if (track_type == KeySource::TrackType::TRACK_TYPE_UNKNOWN)
343  return Status::OK;
344  return encryptor_->Initialize(muxer_listener_, track_type, info_->codec(),
345  key_source, options_.webm_subsample_encryption);
346 }
347 
348 Status Segmenter::WriteFrame(bool write_duration) {
349  // Create a frame manually so we can create non-SimpleBlock frames. This
350  // is required to allow the frame duration to be added. If the duration
351  // is not set, then a SimpleBlock will still be written.
352  mkvmuxer::Frame frame;
353 
354  if (!frame.Init(prev_sample_->data(), prev_sample_->data_size())) {
355  return Status(error::MUXER_FAILURE,
356  "Error adding sample to segment: Frame::Init failed");
357  }
358 
359  if (write_duration) {
360  const uint64_t duration_ns =
361  prev_sample_->duration() * kSecondsToNs / info_->time_scale();
362  frame.set_duration(duration_ns);
363  }
364  frame.set_is_key(prev_sample_->is_key_frame());
365  frame.set_timestamp(prev_sample_->pts() * kSecondsToNs / info_->time_scale());
366  frame.set_track_number(track_id_);
367 
368  if (prev_sample_->side_data_size() > 0) {
369  uint64_t block_add_id;
370  // First 8 bytes of side_data is the BlockAddID element's value, which is
371  // done to mimic ffmpeg behavior. See webm_cluster_parser.cc for details.
372  CHECK_GT(prev_sample_->side_data_size(), sizeof(block_add_id));
373  memcpy(&block_add_id, prev_sample_->side_data(), sizeof(block_add_id));
374  if (!frame.AddAdditionalData(
375  prev_sample_->side_data() + sizeof(block_add_id),
376  prev_sample_->side_data_size() - sizeof(block_add_id),
377  block_add_id)) {
378  return Status(
379  error::MUXER_FAILURE,
380  "Error adding sample to segment: Frame::AddAditionalData Failed");
381  }
382  }
383 
384  if (!prev_sample_->is_key_frame() && !frame.CanBeSimpleBlock()) {
385  const int64_t timestamp_ns =
386  reference_frame_timestamp_ * kSecondsToNs / info_->time_scale();
387  frame.set_reference_block_timestamp(timestamp_ns);
388  }
389 
390  // GetRelativeTimecode will return -1 if the relative timecode is too large
391  // to fit in the frame.
392  if (cluster_->GetRelativeTimecode(frame.timestamp() /
393  cluster_->timecode_scale()) < 0) {
394  const double segment_duration =
395  static_cast<double>(frame.timestamp()) / kSecondsToNs;
396  LOG(ERROR) << "Error adding sample to segment: segment too large, "
397  << segment_duration << " seconds.";
398  return Status(error::MUXER_FAILURE,
399  "Error adding sample to segment: segment too large");
400  }
401 
402  if (!cluster_->AddFrame(&frame)) {
403  return Status(error::MUXER_FAILURE,
404  "Error adding sample to segment: Cluster::AddFrame failed");
405  }
406 
407  // A reference frame is needed for non-keyframes. Having a reference to the
408  // previous block is good enough.
409  // See libwebm Segment::AddGenericFrame
410  reference_frame_timestamp_ = prev_sample_->pts();
411  return Status::OK;
412 }
413 
414 } // namespace webm
415 } // namespace media
416 } // namespace shaka
Abstract class holds stream information.
Definition: stream_info.h:60
void UpdateProgress(uint64_t progress)
Update segmentation progress using ProgressListener.
Definition: segmenter.cc:412
virtual void OnSampleDurationReady(uint32_t sample_duration)=0
Class for parsing or writing VP codec configuration record.
virtual void OnEncryptionStart()=0
Status AddSample(size_t stream_id, std::shared_ptr< MediaSample > sample)
Definition: segmenter.cc:311
This class listens to progress updates events.
mkvmuxer::int64 Position() const override
Definition: mkv_writer.cc:71
void WriteWebM(std::vector< uint8_t > *data) const
An implementation of IMkvWriter using our File type.
Definition: mkv_writer.h:21
bool ParseMP4(const std::vector< uint8_t > &data)
Status Initialize(const std::vector< std::shared_ptr< StreamInfo >> &streams, MuxerListener *muxer_listener, ProgressListener *progress_listener, KeySource *encryption_key_source, uint32_t max_sd_pixels, uint32_t max_hd_pixels, uint32_t max_uhd1_pixels, double clear_lead_in_seconds, double crypto_period_duration_in_seconds, FourCC protection_scheme)
Definition: segmenter.cc:164
virtual void OnProgress(double progress)=0
KeySource is responsible for encryption key acquisition.
Definition: key_source.h:30
Status FinalizeSegment(size_t stream_id, bool is_subsegment)
Definition: segmenter.cc:336
double GetDuration() const
Definition: segmenter.cc:403
Holds video stream information.