DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs 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/stream_info.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 #include "packager/third_party/libwebm/src/mkvmuxerutil.hpp"
19 #include "packager/third_party/libwebm/src/webmids.hpp"
20 
21 namespace edash_packager {
22 namespace media {
23 namespace webm {
24 namespace {
25 int64_t kTimecodeScale = 1000000;
26 int64_t kSecondsToNs = 1000000000L;
27 } // namespace
28 
29 Segmenter::Segmenter(const MuxerOptions& options)
30  : reference_frame_timestamp_(0),
31  options_(options),
32  info_(NULL),
33  muxer_listener_(NULL),
34  progress_listener_(NULL),
35  progress_target_(0),
36  accumulated_progress_(0),
37  first_timestamp_(0),
38  sample_duration_(0),
39  segment_payload_pos_(0),
40  cluster_length_sec_(0),
41  segment_length_sec_(0),
42  track_id_(0) {}
43 
44 Segmenter::~Segmenter() {}
45 
46 Status Segmenter::Initialize(scoped_ptr<MkvWriter> writer,
47  StreamInfo* info,
48  ProgressListener* progress_listener,
49  MuxerListener* muxer_listener,
50  KeySource* encryption_key_source,
51  uint32_t max_sd_pixels,
52  double clear_lead_in_seconds) {
53  muxer_listener_ = muxer_listener;
54  info_ = info;
55  clear_lead_ = clear_lead_in_seconds;
56 
57  // Use media duration as progress target.
58  progress_target_ = info_->duration();
59  progress_listener_ = progress_listener;
60 
61  const std::string version_string =
62  "https://github.com/google/edash-packager version " +
63  options().packager_version_string;
64 
65  segment_info_.Init();
66  segment_info_.set_timecode_scale(kTimecodeScale);
67  segment_info_.set_writing_app(version_string.c_str());
68  if (options().single_segment) {
69  // Set an initial duration so the duration element is written; will be
70  // overwritten at the end. This works because this is a float and floats
71  // are always the same size.
72  segment_info_.set_duration(1);
73  }
74 
75  Status status;
76  if (encryption_key_source) {
77  status = InitializeEncryptor(encryption_key_source, max_sd_pixels);
78  if (!status.ok())
79  return status;
80  }
81 
82  // Create the track info.
83  switch (info_->stream_type()) {
84  case kStreamVideo:
85  status = CreateVideoTrack(static_cast<VideoStreamInfo*>(info_));
86  break;
87  case kStreamAudio:
88  status = CreateAudioTrack(static_cast<AudioStreamInfo*>(info_));
89  break;
90  default:
91  NOTIMPLEMENTED() << "Not implemented for stream type: "
92  << info_->stream_type();
93  status = Status(error::UNIMPLEMENTED, "Not implemented for stream type");
94  }
95  if (!status.ok())
96  return status;
97 
98  return DoInitialize(writer.Pass());
99 }
100 
102  Status status = WriteFrame(true /* write_duration */);
103  if (!status.ok())
104  return status;
105 
106  uint64_t duration =
107  prev_sample_->pts() - first_timestamp_ + prev_sample_->duration();
108  segment_info_.set_duration(FromBMFFTimescale(duration));
109  return DoFinalize();
110 }
111 
112 Status Segmenter::AddSample(scoped_refptr<MediaSample> sample) {
113  if (sample_duration_ == 0) {
114  first_timestamp_ = sample->pts();
115  sample_duration_ = sample->duration();
116  if (muxer_listener_)
117  muxer_listener_->OnSampleDurationReady(sample_duration_);
118  }
119 
120  UpdateProgress(sample->duration());
121 
122  // This writes frames in a delay. Meaning that the previous frame is written
123  // on this call to AddSample. The current frame is stored until the next
124  // call. This is done to determine which frame is the last in a Cluster.
125  // This first block determines if this is a new Cluster and writes the
126  // previous frame first before creating the new Cluster.
127 
128  Status status;
129  bool wrote_frame = false;
130  if (!cluster_) {
131  status = NewSegment(sample->pts());
132  // First frame, so no previous frame to write.
133  wrote_frame = true;
134  } else if (segment_length_sec_ >= options_.segment_duration) {
135  if (sample->is_key_frame() || !options_.segment_sap_aligned) {
136  status = WriteFrame(true /* write_duration */);
137  status.Update(NewSegment(sample->pts()));
138  segment_length_sec_ = 0;
139  cluster_length_sec_ = 0;
140  wrote_frame = true;
141  }
142  } else if (cluster_length_sec_ >= options_.fragment_duration) {
143  if (sample->is_key_frame() || !options_.fragment_sap_aligned) {
144  status = WriteFrame(true /* write_duration */);
145  status.Update(NewSubsegment(sample->pts()));
146  cluster_length_sec_ = 0;
147  wrote_frame = true;
148  }
149  }
150  if (!wrote_frame) {
151  status = WriteFrame(false /* write_duration */);
152  }
153  if (!status.ok())
154  return status;
155 
156  // Encrypt the frame.
157  if (encryptor_) {
158  const bool encrypt_frame =
159  static_cast<double>(sample->pts() - first_timestamp_) /
160  info_->time_scale() >=
161  clear_lead_;
162  status = encryptor_->EncryptFrame(sample, encrypt_frame);
163  if (!status.ok()) {
164  LOG(ERROR) << "Error encrypting frame.";
165  return status;
166  }
167  }
168 
169 
170  // Add the sample to the durations even though we have not written the frame
171  // yet. This is needed to make sure we split Clusters at the correct point.
172  // These are only used in this method.
173  const double duration_sec =
174  static_cast<double>(sample->duration()) / info_->time_scale();
175  cluster_length_sec_ += duration_sec;
176  segment_length_sec_ += duration_sec;
177 
178  prev_sample_ = sample;
179  return Status::OK;
180 }
181 
182 float Segmenter::GetDuration() const {
183  return static_cast<float>(segment_info_.duration()) *
184  segment_info_.timecode_scale() / kSecondsToNs;
185 }
186 
187 uint64_t Segmenter::FromBMFFTimescale(uint64_t time_timescale) {
188  // Convert the time from BMFF time_code to WebM timecode scale.
189  const int64_t time_ns =
190  kSecondsToNs * time_timescale / info_->time_scale();
191  return time_ns / segment_info_.timecode_scale();
192 }
193 
194 uint64_t Segmenter::FromWebMTimecode(uint64_t time_webm_timecode) {
195  // Convert the time to BMFF time_code from WebM timecode scale.
196  const int64_t time_ns = time_webm_timecode * segment_info_.timecode_scale();
197  return time_ns * info_->time_scale() / kSecondsToNs;
198 }
199 
200 Status Segmenter::WriteSegmentHeader(uint64_t file_size, MkvWriter* writer) {
201  Status error_status(error::FILE_FAILURE, "Error writing segment header.");
202 
203  if (!WriteEbmlHeader(writer))
204  return error_status;
205 
206  if (WriteID(writer, mkvmuxer::kMkvSegment) != 0)
207  return error_status;
208 
209  const uint64_t segment_size_size = 8;
210  segment_payload_pos_ = writer->Position() + segment_size_size;
211  if (file_size > 0) {
212  // We want the size of the segment element, so subtract the header.
213  if (WriteUIntSize(writer, file_size - segment_payload_pos_,
214  segment_size_size) != 0)
215  return error_status;
216  if (!seek_head_.Write(writer))
217  return error_status;
218  } else {
219  if (SerializeInt(writer, mkvmuxer::kEbmlUnknownValue, segment_size_size) !=
220  0)
221  return error_status;
222  // We don't know the header size, so write a placeholder.
223  if (!seek_head_.WriteVoid(writer))
224  return error_status;
225  }
226 
227  if (!segment_info_.Write(writer))
228  return error_status;
229 
230  if (!tracks_.Write(writer))
231  return error_status;
232 
233  return Status::OK;
234 }
235 
236 Status Segmenter::SetCluster(uint64_t start_webm_timecode,
237  uint64_t position,
238  MkvWriter* writer) {
239  const uint64_t scale = segment_info_.timecode_scale();
240  cluster_.reset(new mkvmuxer::Cluster(start_webm_timecode, position, scale));
241  cluster_->Init(writer);
242  return Status::OK;
243 }
244 
245 void Segmenter::UpdateProgress(uint64_t progress) {
246  accumulated_progress_ += progress;
247  if (!progress_listener_ || progress_target_ == 0)
248  return;
249  // It might happen that accumulated progress exceeds progress_target due to
250  // computation errors, e.g. rounding error. Cap it so it never reports > 100%
251  // progress.
252  if (accumulated_progress_ >= progress_target_) {
253  progress_listener_->OnProgress(1.0);
254  } else {
255  progress_listener_->OnProgress(static_cast<double>(accumulated_progress_) /
256  progress_target_);
257  }
258 }
259 
260 Status Segmenter::CreateVideoTrack(VideoStreamInfo* info) {
261  // The seed is only used to create a UID which we overwrite later.
262  unsigned int seed = 0;
263  mkvmuxer::VideoTrack* track = new mkvmuxer::VideoTrack(&seed);
264  if (!track)
265  return Status(error::INTERNAL_ERROR, "Failed to create video track.");
266 
267  if (info->codec() == kCodecVP8) {
268  track->set_codec_id(mkvmuxer::Tracks::kVp8CodecId);
269  } else if (info->codec() == kCodecVP9) {
270  track->set_codec_id(mkvmuxer::Tracks::kVp9CodecId);
271  } else {
272  LOG(ERROR) << "Only VP8 and VP9 video codec is 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->extra_data().data(),
312  info->extra_data().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 
324  if (encryptor_)
325  encryptor_->AddTrackInfo(track);
326 
327  tracks_.AddTrack(track, info->track_id());
328  track_id_ = track->number();
329  return Status::OK;
330 }
331 
332 Status Segmenter::InitializeEncryptor(KeySource* key_source,
333  uint32_t max_sd_pixels) {
334  encryptor_.reset(new Encryptor());
335  switch (info_->stream_type()) {
336  case kStreamVideo: {
337  VideoStreamInfo* video_info = static_cast<VideoStreamInfo*>(info_);
338  uint32_t pixels = video_info->width() * video_info->height();
339  KeySource::TrackType type = (pixels > max_sd_pixels)
340  ? KeySource::TRACK_TYPE_HD
341  : KeySource::TRACK_TYPE_SD;
342  return encryptor_->Initialize(muxer_listener_, type, key_source);
343  }
344  case kStreamAudio:
345  return encryptor_->Initialize(
346  muxer_listener_, KeySource::TrackType::TRACK_TYPE_AUDIO, key_source);
347  default:
348  // Other streams are not encrypted.
349  return Status::OK;
350  }
351 }
352 
353 Status Segmenter::WriteFrame(bool write_duration) {
354  // Create a frame manually so we can create non-SimpleBlock frames. This
355  // is required to allow the frame duration to be added. If the duration
356  // is not set, then a SimpleBlock will still be written.
357  mkvmuxer::Frame frame;
358 
359  if (!frame.Init(prev_sample_->data(), prev_sample_->data_size())) {
360  return Status(error::MUXER_FAILURE,
361  "Error adding sample to segment: Frame::Init failed");
362  }
363 
364  if (write_duration) {
365  const uint64_t duration_ns =
366  prev_sample_->duration() * kSecondsToNs / info_->time_scale();
367  frame.set_duration(duration_ns);
368  }
369  frame.set_is_key(prev_sample_->is_key_frame());
370  frame.set_timestamp(prev_sample_->pts() * kSecondsToNs / info_->time_scale());
371  frame.set_track_number(track_id_);
372 
373  if (prev_sample_->side_data_size() > 0) {
374  uint64_t block_add_id;
375  // First 8 bytes of side_data is the BlockAddID element's value, which is
376  // done to mimic ffmpeg behavior. See webm_cluster_parser.cc for details.
377  CHECK_GT(prev_sample_->side_data_size(), sizeof(block_add_id));
378  memcpy(&block_add_id, prev_sample_->side_data(), sizeof(block_add_id));
379  if (!frame.AddAdditionalData(
380  prev_sample_->side_data() + sizeof(block_add_id),
381  prev_sample_->side_data_size() - sizeof(block_add_id),
382  block_add_id)) {
383  return Status(
384  error::MUXER_FAILURE,
385  "Error adding sample to segment: Frame::AddAditionalData Failed");
386  }
387  }
388 
389  if (!prev_sample_->is_key_frame() && !frame.CanBeSimpleBlock()) {
390  const int64_t timestamp_ns =
391  reference_frame_timestamp_ * kSecondsToNs / info_->time_scale();
392  frame.set_reference_block_timestamp(timestamp_ns);
393  }
394 
395  // GetRelativeTimecode will return -1 if the relative timecode is too large
396  // to fit in the frame.
397  if (cluster_->GetRelativeTimecode(frame.timestamp() /
398  cluster_->timecode_scale()) < 0) {
399  const double segment_duration =
400  static_cast<double>(frame.timestamp()) / kSecondsToNs;
401  LOG(ERROR) << "Error adding sample to segment: segment too large, "
402  << segment_duration << " seconds.";
403  return Status(error::MUXER_FAILURE,
404  "Error adding sample to segment: segment too large");
405  }
406 
407  if (!cluster_->AddFrame(&frame)) {
408  return Status(error::MUXER_FAILURE,
409  "Error adding sample to segment: Cluster::AddFrame failed");
410  }
411 
412  // A reference frame is needed for non-keyframes. Having a reference to the
413  // previous block is good enough.
414  // See libwebm Segment::AddGenericFrame
415  reference_frame_timestamp_ = prev_sample_->pts();
416  return Status::OK;
417 }
418 
419 } // namespace webm
420 } // namespace media
421 } // namespace edash_packager
An implementation of IMkvWriter using our File type.
Definition: mkv_writer.h:21
mkvmuxer::int64 Position() const override
Definition: mkv_writer.cc:63
Abstract class holds stream information.
Definition: stream_info.h:26
std::string packager_version_string
Specify the version string to be embedded in the output files.
Definition: muxer_options.h:71
This class listens to progress updates events.
Status AddSample(const MediaStream *stream, scoped_refptr< MediaSample > sample)
Definition: segmenter.cc:259
KeySource is responsible for encryption key acquisition.
Definition: key_source.h:33
virtual void OnProgress(double progress)=0
void UpdateProgress(uint64_t progress)
Update segmentation progress using ProgressListener.
Definition: segmenter.cc:326
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)
Definition: segmenter.cc:124
Holds video stream information.
virtual void OnSampleDurationReady(uint32_t sample_duration)=0