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  const std::string version_string =
58  "https://github.com/google/edash-packager version " +
59  options().packager_version_string;
60 
61  segment_info_.Init();
62  segment_info_.set_timecode_scale(kTimecodeScale);
63  segment_info_.set_writing_app(version_string.c_str());
64  if (options().single_segment) {
65  // Set an initial duration so the duration element is written; will be
66  // overwritten at the end.
67  segment_info_.set_duration(1);
68  }
69 
70  // Create the track info.
71  Status status;
72  switch (info_->stream_type()) {
73  case kStreamVideo:
74  status = CreateVideoTrack(static_cast<VideoStreamInfo*>(info_));
75  break;
76  case kStreamAudio:
77  status = CreateAudioTrack(static_cast<AudioStreamInfo*>(info_));
78  break;
79  default:
80  NOTIMPLEMENTED() << "Not implemented for stream type: "
81  << info_->stream_type();
82  status = Status(error::UNIMPLEMENTED, "Not implemented for stream type");
83  }
84  if (!status.ok())
85  return status;
86 
87  return DoInitialize(writer.Pass());
88 }
89 
91  segment_info_.set_duration(FromBMFFTimescale(total_duration_));
92  return DoFinalize();
93 }
94 
95 Status Segmenter::AddSample(scoped_refptr<MediaSample> sample) {
96  if (sample_duration_ == 0) {
97  sample_duration_ = sample->duration();
98  if (muxer_listener_)
99  muxer_listener_->OnSampleDurationReady(sample_duration_);
100  }
101 
102  UpdateProgress(sample->duration());
103 
104  // Create a new cluster if needed.
105  Status status;
106  if (!cluster_) {
107  status = NewSegment(sample->pts());
108  } else if (segment_length_sec_ >= options_.segment_duration) {
109  if (sample->is_key_frame() || !options_.segment_sap_aligned) {
110  status = NewSegment(sample->pts());
111  segment_length_sec_ = 0;
112  cluster_length_sec_ = 0;
113  }
114  } else if (cluster_length_sec_ >= options_.fragment_duration) {
115  if (sample->is_key_frame() || !options_.fragment_sap_aligned) {
116  status = NewSubsegment(sample->pts());
117  cluster_length_sec_ = 0;
118  }
119  }
120  if (!status.ok())
121  return status;
122 
123  const int64_t time_ns =
124  sample->pts() * kSecondsToNs / info_->time_scale();
125  bool addframe_result;
126  if (sample->side_data_size() > 0) {
127  uint64_t block_add_id;
128  // First 8 bytes of side_data is the BlockAddID element's value, which is
129  // done to mimic ffmpeg behavior. See webm_cluster_parser.cc for details.
130  CHECK_GT(sample->side_data_size(), sizeof(block_add_id));
131  memcpy(&block_add_id, sample->side_data(), sizeof(block_add_id));
132  addframe_result = cluster_->AddFrameWithAdditional(
133  sample->data(), sample->data_size(),
134  sample->side_data() + sizeof(block_add_id),
135  sample->side_data_size() - sizeof(block_add_id), block_add_id,
136  track_id_, time_ns, sample->is_key_frame());
137  } else {
138  addframe_result =
139  cluster_->AddFrame(sample->data(), sample->data_size(), track_id_,
140  time_ns, sample->is_key_frame());
141  }
142  if (!addframe_result) {
143  LOG(ERROR) << "Error adding sample to segment.";
144  return Status(error::FILE_FAILURE, "Error adding sample to segment.");
145  }
146 
147  const double duration_sec =
148  static_cast<double>(sample->duration()) / info_->time_scale();
149  cluster_length_sec_ += duration_sec;
150  segment_length_sec_ += duration_sec;
151  total_duration_ += sample->duration();
152 
153  return Status::OK;
154 }
155 
156 float Segmenter::GetDuration() const {
157  return static_cast<float>(segment_info_.duration()) *
158  segment_info_.timecode_scale() / kSecondsToNs;
159 }
160 
161 uint64_t Segmenter::FromBMFFTimescale(uint64_t time_timescale) {
162  // Convert the time from BMFF time_code to WebM timecode scale.
163  const int64_t time_ns =
164  kSecondsToNs * time_timescale / info_->time_scale();
165  return time_ns / segment_info_.timecode_scale();
166 }
167 
168 uint64_t Segmenter::FromWebMTimecode(uint64_t time_webm_timecode) {
169  // Convert the time to BMFF time_code from WebM timecode scale.
170  const int64_t time_ns = time_webm_timecode * segment_info_.timecode_scale();
171  return time_ns * info_->time_scale() / kSecondsToNs;
172 }
173 
174 Status Segmenter::WriteSegmentHeader(uint64_t file_size, MkvWriter* writer) {
175  Status error_status(error::FILE_FAILURE, "Error writing segment header.");
176 
177  if (!WriteEbmlHeader(writer))
178  return error_status;
179 
180  if (WriteID(writer, mkvmuxer::kMkvSegment) != 0)
181  return error_status;
182 
183  const uint64_t segment_size_size = 8;
184  segment_payload_pos_ = writer->Position() + segment_size_size;
185  if (file_size > 0) {
186  // We want the size of the segment element, so subtract the header.
187  if (WriteUIntSize(writer, file_size - segment_payload_pos_,
188  segment_size_size) != 0)
189  return error_status;
190  if (!seek_head_.Write(writer))
191  return error_status;
192  } else {
193  if (SerializeInt(writer, mkvmuxer::kEbmlUnknownValue, segment_size_size) !=
194  0)
195  return error_status;
196  // We don't know the header size, so write a placeholder.
197  if (!seek_head_.WriteVoid(writer))
198  return error_status;
199  }
200 
201  if (!segment_info_.Write(writer))
202  return error_status;
203 
204  if (!tracks_.Write(writer))
205  return error_status;
206 
207  return Status::OK;
208 }
209 
210 Status Segmenter::SetCluster(uint64_t start_webm_timecode,
211  uint64_t position,
212  MkvWriter* writer) {
213  const uint64_t scale = segment_info_.timecode_scale();
214  cluster_.reset(new mkvmuxer::Cluster(start_webm_timecode, position, scale));
215  cluster_->Init(writer);
216  return Status::OK;
217 }
218 
219 void Segmenter::UpdateProgress(uint64_t progress) {
220  accumulated_progress_ += progress;
221  if (!progress_listener_ || progress_target_ == 0)
222  return;
223  // It might happen that accumulated progress exceeds progress_target due to
224  // computation errors, e.g. rounding error. Cap it so it never reports > 100%
225  // progress.
226  if (accumulated_progress_ >= progress_target_) {
227  progress_listener_->OnProgress(1.0);
228  } else {
229  progress_listener_->OnProgress(static_cast<double>(accumulated_progress_) /
230  progress_target_);
231  }
232 }
233 
234 Status Segmenter::CreateVideoTrack(VideoStreamInfo* info) {
235  // The seed is only used to create a UID which we overwrite later.
236  unsigned int seed = 0;
237  mkvmuxer::VideoTrack* track = new mkvmuxer::VideoTrack(&seed);
238  if (!track)
239  return Status(error::INTERNAL_ERROR, "Failed to create video track.");
240 
241  if (info->codec() == kCodecVP8) {
242  track->set_codec_id(mkvmuxer::Tracks::kVp8CodecId);
243  } else if (info->codec() == kCodecVP9) {
244  track->set_codec_id(mkvmuxer::Tracks::kVp9CodecId);
245  } else {
246  LOG(ERROR) << "Only VP8 and VP9 video codec is supported.";
247  return Status(error::UNIMPLEMENTED,
248  "Only VP8 and VP9 video codecs are supported.");
249  }
250 
251  track->set_uid(info->track_id());
252  if (!info->language().empty())
253  track->set_language(info->language().c_str());
254  track->set_type(mkvmuxer::Tracks::kVideo);
255  track->set_width(info->width());
256  track->set_height(info->height());
257  track->set_display_height(info->height());
258  track->set_display_width(info->width() * info->pixel_width() /
259  info->pixel_height());
260 
261  tracks_.AddTrack(track, info->track_id());
262  track_id_ = track->number();
263  return Status::OK;
264 }
265 
266 Status Segmenter::CreateAudioTrack(AudioStreamInfo* info) {
267  // The seed is only used to create a UID which we overwrite later.
268  unsigned int seed = 0;
269  mkvmuxer::AudioTrack* track = new mkvmuxer::AudioTrack(&seed);
270  if (!track)
271  return Status(error::INTERNAL_ERROR, "Failed to create audio track.");
272 
273  if (info->codec() == kCodecOpus) {
274  track->set_codec_id(mkvmuxer::Tracks::kOpusCodecId);
275  } else if (info->codec() == kCodecVorbis) {
276  track->set_codec_id(mkvmuxer::Tracks::kVorbisCodecId);
277  } else {
278  LOG(ERROR) << "Only Vorbis and Opus audio codec is supported.";
279  return Status(error::UNIMPLEMENTED,
280  "Only Vorbis and Opus audio codecs are supported.");
281  }
282  if (!track->SetCodecPrivate(info->extra_data().data(),
283  info->extra_data().size())) {
284  return Status(error::INTERNAL_ERROR,
285  "Private codec data required for audio streams");
286  }
287 
288  track->set_uid(info->track_id());
289  if (!info->language().empty())
290  track->set_language(info->language().c_str());
291  track->set_type(mkvmuxer::Tracks::kAudio);
292  track->set_sample_rate(info->sampling_frequency());
293  track->set_channels(info->num_channels());
294 
295  tracks_.AddTrack(track, info->track_id());
296  track_id_ = track->number();
297  return Status::OK;
298 }
299 
300 } // namespace webm
301 } // namespace media
302 } // 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:277
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:344
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