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  : options_(options),
31  info_(NULL),
32  muxer_listener_(NULL),
33  progress_listener_(NULL),
34  progress_target_(0),
35  accumulated_progress_(0),
36  total_duration_(0),
37  sample_duration_(0),
38  segment_payload_pos_(0),
39  cluster_length_sec_(0),
40  segment_length_sec_(0),
41  track_id_(0) {}
42 
43 Segmenter::~Segmenter() {}
44 
45 Status Segmenter::Initialize(scoped_ptr<MkvWriter> writer,
46  StreamInfo* info,
47  ProgressListener* progress_listener,
48  MuxerListener* muxer_listener,
49  KeySource* encryption_key_source) {
50  muxer_listener_ = muxer_listener;
51  info_ = info;
52 
53  // Use media duration as progress target.
54  progress_target_ = info_->duration();
55  progress_listener_ = progress_listener;
56 
57  segment_info_.Init();
58  segment_info_.set_timecode_scale(kTimecodeScale);
59  if (options().single_segment) {
60  // Set an initial duration so the duration element is written; will be
61  // overwritten at the end.
62  segment_info_.set_duration(1);
63  }
64 
65  // Create the track info.
66  Status status;
67  switch (info_->stream_type()) {
68  case kStreamVideo:
69  status = CreateVideoTrack(static_cast<VideoStreamInfo*>(info_));
70  break;
71  case kStreamAudio:
72  status = CreateAudioTrack(static_cast<AudioStreamInfo*>(info_));
73  break;
74  default:
75  NOTIMPLEMENTED() << "Not implemented for stream type: "
76  << info_->stream_type();
77  status = Status(error::UNIMPLEMENTED, "Not implemented for stream type");
78  }
79  if (!status.ok())
80  return status;
81 
82  return DoInitialize(writer.Pass());
83 }
84 
86  segment_info_.set_duration(FromBMFFTimescale(total_duration_));
87  return DoFinalize();
88 }
89 
90 Status Segmenter::AddSample(scoped_refptr<MediaSample> sample) {
91  if (sample_duration_ == 0) {
92  sample_duration_ = sample->duration();
93  if (muxer_listener_)
94  muxer_listener_->OnSampleDurationReady(sample_duration_);
95  }
96 
97  UpdateProgress(sample->duration());
98 
99  // Create a new cluster if needed.
100  Status status;
101  if (!cluster_) {
102  status = NewSegment(sample->pts());
103  } else if (segment_length_sec_ >= options_.segment_duration) {
104  if (sample->is_key_frame() || !options_.segment_sap_aligned) {
105  status = NewSegment(sample->pts());
106  segment_length_sec_ = 0;
107  cluster_length_sec_ = 0;
108  }
109  } else if (cluster_length_sec_ >= options_.fragment_duration) {
110  if (sample->is_key_frame() || !options_.fragment_sap_aligned) {
111  status = NewSubsegment(sample->pts());
112  cluster_length_sec_ = 0;
113  }
114  }
115  if (!status.ok())
116  return status;
117 
118  const int64_t time_ns =
119  sample->pts() * kSecondsToNs / info_->time_scale();
120  if (!cluster_->AddFrame(sample->data(), sample->data_size(), track_id_,
121  time_ns, sample->is_key_frame())) {
122  LOG(ERROR) << "Error adding sample to segment.";
123  return Status(error::FILE_FAILURE, "Error adding sample to segment.");
124  }
125  const double duration_sec =
126  static_cast<double>(sample->duration()) / info_->time_scale();
127  cluster_length_sec_ += duration_sec;
128  segment_length_sec_ += duration_sec;
129  total_duration_ += sample->duration();
130 
131  return Status::OK;
132 }
133 
134 float Segmenter::GetDuration() const {
135  return static_cast<float>(segment_info_.duration()) *
136  segment_info_.timecode_scale() / kSecondsToNs;
137 }
138 
139 uint64_t Segmenter::FromBMFFTimescale(uint64_t time_timescale) {
140  // Convert the time from BMFF time_code to WebM timecode scale.
141  const int64_t time_ns =
142  kSecondsToNs * time_timescale / info_->time_scale();
143  return time_ns / segment_info_.timecode_scale();
144 }
145 
146 uint64_t Segmenter::FromWebMTimecode(uint64_t time_webm_timecode) {
147  // Convert the time to BMFF time_code from WebM timecode scale.
148  const int64_t time_ns = time_webm_timecode * segment_info_.timecode_scale();
149  return time_ns * info_->time_scale() / kSecondsToNs;
150 }
151 
152 Status Segmenter::WriteSegmentHeader(uint64_t file_size, MkvWriter* writer) {
153  Status error_status(error::FILE_FAILURE, "Error writing segment header.");
154 
155  if (!WriteEbmlHeader(writer))
156  return error_status;
157 
158  if (WriteID(writer, mkvmuxer::kMkvSegment) != 0)
159  return error_status;
160 
161  const uint64_t segment_size_size = 8;
162  segment_payload_pos_ = writer->Position() + segment_size_size;
163  if (file_size > 0) {
164  // We want the size of the segment element, so subtract the header.
165  if (WriteUIntSize(writer, file_size - segment_payload_pos_,
166  segment_size_size) != 0)
167  return error_status;
168  if (!seek_head_.Write(writer))
169  return error_status;
170  } else {
171  if (SerializeInt(writer, mkvmuxer::kEbmlUnknownValue, segment_size_size) !=
172  0)
173  return error_status;
174  // We don't know the header size, so write a placeholder.
175  if (!seek_head_.WriteVoid(writer))
176  return error_status;
177  }
178 
179  if (!segment_info_.Write(writer))
180  return error_status;
181 
182  if (!tracks_.Write(writer))
183  return error_status;
184 
185  return Status::OK;
186 }
187 
188 Status Segmenter::SetCluster(uint64_t start_webm_timecode,
189  uint64_t position,
190  MkvWriter* writer) {
191  const uint64_t scale = segment_info_.timecode_scale();
192  cluster_.reset(new mkvmuxer::Cluster(start_webm_timecode, position, scale));
193  cluster_->Init(writer);
194  return Status::OK;
195 }
196 
197 void Segmenter::UpdateProgress(uint64_t progress) {
198  accumulated_progress_ += progress;
199  if (!progress_listener_ || progress_target_ == 0)
200  return;
201  // It might happen that accumulated progress exceeds progress_target due to
202  // computation errors, e.g. rounding error. Cap it so it never reports > 100%
203  // progress.
204  if (accumulated_progress_ >= progress_target_) {
205  progress_listener_->OnProgress(1.0);
206  } else {
207  progress_listener_->OnProgress(static_cast<double>(accumulated_progress_) /
208  progress_target_);
209  }
210 }
211 
212 Status Segmenter::CreateVideoTrack(VideoStreamInfo* info) {
213  // The seed is only used to create a UID which we overwrite later.
214  unsigned int seed = 0;
215  mkvmuxer::VideoTrack* track = new mkvmuxer::VideoTrack(&seed);
216  if (!track)
217  return Status(error::INTERNAL_ERROR, "Failed to create video track.");
218 
219  if (info->codec() == kCodecVP8) {
220  track->set_codec_id(mkvmuxer::Tracks::kVp8CodecId);
221  } else if (info->codec() == kCodecVP9) {
222  track->set_codec_id(mkvmuxer::Tracks::kVp9CodecId);
223  } else {
224  LOG(ERROR) << "Only VP8 and VP9 video codec is supported.";
225  return Status(error::UNIMPLEMENTED,
226  "Only VP8 and VP9 video codecs are supported.");
227  }
228 
229  track->set_uid(info->track_id());
230  track->set_type(mkvmuxer::Tracks::kVideo);
231  track->set_width(info->width());
232  track->set_height(info->height());
233  track->set_display_height(info->height());
234  track->set_display_width(info->width() * info->pixel_width() /
235  info->pixel_height());
236  track->set_language(info->language().c_str());
237 
238  tracks_.AddTrack(track, info->track_id());
239  track_id_ = track->number();
240  return Status::OK;
241 }
242 
243 Status Segmenter::CreateAudioTrack(AudioStreamInfo* info) {
244  // The seed is only used to create a UID which we overwrite later.
245  unsigned int seed = 0;
246  mkvmuxer::AudioTrack* track = new mkvmuxer::AudioTrack(&seed);
247  if (!track)
248  return Status(error::INTERNAL_ERROR, "Failed to create audio track.");
249 
250  if (info->codec() == kCodecOpus) {
251  track->set_codec_id(mkvmuxer::Tracks::kOpusCodecId);
252  } else if (info->codec() == kCodecVorbis) {
253  track->set_codec_id(mkvmuxer::Tracks::kVorbisCodecId);
254  } else {
255  LOG(ERROR) << "Only Vorbis and Opus audio codec is supported.";
256  return Status(error::UNIMPLEMENTED,
257  "Only Vorbis and Opus audio codecs are supported.");
258  }
259 
260  track->set_uid(info->track_id());
261  track->set_language(info->language().c_str());
262  track->set_type(mkvmuxer::Tracks::kAudio);
263  track->set_sample_rate(info->sampling_frequency());
264  track->set_channels(info->num_channels());
265 
266  tracks_.AddTrack(track, info->track_id());
267  track_id_ = track->number();
268  return Status::OK;
269 }
270 
271 } // namespace webm
272 } // namespace media
273 } // 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
This class listens to progress updates events.
Status AddSample(const MediaStream *stream, scoped_refptr< MediaSample > sample)
Definition: segmenter.cc:270
KeySource is responsible for encryption key acquisition.
Definition: key_source.h:29
virtual void OnProgress(double progress)=0
void UpdateProgress(uint64_t progress)
Update segmentation progress using ProgressListener.
Definition: segmenter.cc:337
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:140
Holds video stream information.
virtual void OnSampleDurationReady(uint32_t sample_duration)=0