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