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