7 #include <packager/mpd/base/representation.h>
11 #include <absl/flags/declare.h>
12 #include <absl/log/check.h>
13 #include <absl/log/log.h>
14 #include <absl/strings/str_format.h>
16 #include <packager/file.h>
17 #include <packager/macros/logging.h>
18 #include <packager/media/base/muxer_util.h>
19 #include <packager/mpd/base/mpd_options.h>
20 #include <packager/mpd/base/mpd_utils.h>
21 #include <packager/mpd/base/xml/xml_node.h>
26 std::string GetMimeType(
const std::string& prefix,
27 MediaInfo::ContainerType container_type) {
28 switch (container_type) {
29 case MediaInfo::CONTAINER_MP4:
30 return prefix +
"/mp4";
31 case MediaInfo::CONTAINER_MPEG2_TS:
33 return prefix +
"/MP2T";
34 case MediaInfo::CONTAINER_WEBM:
35 return prefix +
"/webm";
41 LOG(ERROR) <<
"Unrecognized container type: " << container_type;
48 bool HasRequiredVideoFields(
const MediaInfo_VideoInfo& video_info) {
49 if (!video_info.has_height() || !video_info.has_width()) {
51 <<
"Width and height are required fields for generating a valid MPD.";
56 LOG_IF(WARNING, !video_info.has_time_scale())
57 <<
"Video info does not contain timescale required for "
58 "calculating framerate. @frameRate is required for DASH IOP.";
59 LOG_IF(WARNING, !video_info.has_pixel_width())
60 <<
"Video info does not contain pixel_width to calculate the sample "
61 "aspect ratio required for DASH IOP.";
62 LOG_IF(WARNING, !video_info.has_pixel_height())
63 <<
"Video info does not contain pixel_height to calculate the sample "
64 "aspect ratio required for DASH IOP.";
68 int32_t GetTimeScale(
const MediaInfo& media_info) {
69 if (media_info.has_reference_time_scale()) {
70 return media_info.reference_time_scale();
73 if (media_info.has_video_info()) {
74 return media_info.video_info().time_scale();
77 if (media_info.has_audio_info()) {
78 return media_info.audio_info().time_scale();
81 LOG(WARNING) <<
"No timescale specified, using 1 as timescale.";
88 const MediaInfo& media_info,
91 std::unique_ptr<RepresentationStateChangeListener> state_change_listener)
92 : media_info_(media_info),
94 mpd_options_(mpd_options),
95 state_change_listener_(std::move(state_change_listener)),
96 allow_approximate_segment_timeline_(
99 media_info.segment_template().find(
"$Time") == std::string::npos &&
100 mpd_options_.mpd_params.allow_approximate_segment_timeline) {}
104 std::unique_ptr<RepresentationStateChangeListener> state_change_listener)
106 representation.mpd_options_,
108 std::move(state_change_listener)) {
109 mime_type_ = representation.mime_type_;
110 codecs_ = representation.codecs_;
113 Representation::~Representation() {}
116 if (!AtLeastOneTrue(media_info_.has_video_info(),
117 media_info_.has_audio_info(),
118 media_info_.has_text_info())) {
122 LOG(ERROR) <<
"Representation needs one of video, audio, or text.";
126 if (MoreThanOneTrue(media_info_.has_video_info(),
127 media_info_.has_audio_info(),
128 media_info_.has_text_info())) {
129 LOG(ERROR) <<
"Only one of VideoInfo, AudioInfo, or TextInfo can be set.";
133 if (media_info_.container_type() == MediaInfo::CONTAINER_UNKNOWN) {
134 LOG(ERROR) <<
"'container_type' in MediaInfo cannot be CONTAINER_UNKNOWN.";
138 if (media_info_.has_video_info()) {
139 mime_type_ = GetVideoMimeType();
140 if (!HasRequiredVideoFields(media_info_.video_info())) {
141 LOG(ERROR) <<
"Missing required fields to create a video Representation.";
144 }
else if (media_info_.has_audio_info()) {
145 mime_type_ = GetAudioMimeType();
146 }
else if (media_info_.has_text_info()) {
147 mime_type_ = GetTextMimeType();
150 if (mime_type_.empty())
153 codecs_ = GetCodecs(media_info_);
154 supplemental_codecs_ = GetSupplementalCodecs(media_info_);
155 supplemental_profiles_ = GetSupplementalProfiles(media_info_);
161 content_protection_elements_.push_back(content_protection_element);
162 RemoveDuplicateAttributes(&content_protection_elements_.back());
166 const std::string& pssh) {
167 UpdateContentProtectionPsshHelper(drm_uuid, pssh,
168 &content_protection_elements_);
174 int64_t segment_number) {
175 if (start_time == 0 && duration == 0) {
176 LOG(WARNING) <<
"Got segment with start_time and duration == 0. Ignoring.";
187 if (state_change_listener_)
188 state_change_listener_->OnNewSegmentForRepresentation(start_time, duration);
190 AddSegmentInfo(start_time, duration, segment_number);
197 if (!mpd_options_.mpd_params.low_latency_dash_mode) {
198 current_buffer_depth_ += segment_infos_.back().duration;
200 bandwidth_estimator_.
AddBlock(size,
static_cast<double>(duration) /
201 media_info_.reference_time_scale());
206 if (!mpd_options_.mpd_params.low_latency_dash_mode) {
208 <<
"UpdateCompletedSegment is only applicable to low latency mode.";
212 UpdateSegmentInfo(duration);
214 current_buffer_depth_ += segment_infos_.back().duration;
217 size,
static_cast<double>(duration) / media_info_.reference_time_scale());
223 if (media_info_.has_audio_info() || media_info_.has_video_info())
224 frame_duration_ = frame_duration;
226 if (media_info_.has_video_info()) {
227 media_info_.mutable_video_info()->set_frame_duration(frame_duration);
228 if (state_change_listener_) {
229 state_change_listener_->OnSetFrameRateForRepresentation(
230 frame_duration, media_info_.video_info().time_scale());
236 int64_t sd = mpd_options_.mpd_params.target_segment_duration *
237 media_info_.reference_time_scale();
240 media_info_.set_segment_duration(sd);
254 if (!HasRequiredMediaInfoFields()) {
255 LOG(ERROR) <<
"MediaInfo missing required fields.";
259 const uint64_t bandwidth = media_info_.has_bandwidth()
260 ? media_info_.bandwidth()
261 : bandwidth_estimator_.
Max();
263 DCHECK(!(HasVODOnlyFields(media_info_) && HasLiveOnlyFields(media_info_)));
267 if (!representation.
SetId(id_) ||
275 if (!supplemental_codecs_.empty() && !supplemental_profiles_.empty()) {
277 supplemental_codecs_) ||
279 supplemental_profiles_)) {
280 LOG(ERROR) <<
"Failed to add supplemental codecs/profiles to "
281 "Representation XML.";
285 const bool has_video_info = media_info_.has_video_info();
286 const bool has_audio_info = media_info_.has_audio_info();
288 if (has_video_info &&
290 media_info_.video_info(),
291 !(output_suppression_flags_ & kSuppressWidth),
292 !(output_suppression_flags_ & kSuppressHeight),
293 !(output_suppression_flags_ & kSuppressFrameRate))) {
294 LOG(ERROR) <<
"Failed to add video info to Representation XML.";
298 if (has_audio_info &&
299 !representation.
AddAudioInfo(media_info_.audio_info())) {
300 LOG(ERROR) <<
"Failed to add audio info to Representation XML.";
304 if (!representation.AddContentProtectionElements(
305 content_protection_elements_)) {
309 if (HasVODOnlyFields(media_info_) &&
311 media_info_, mpd_options_.mpd_params.use_segment_list,
312 mpd_options_.mpd_params.target_segment_duration)) {
313 LOG(ERROR) <<
"Failed to add VOD info.";
317 if (HasLiveOnlyFields(media_info_) &&
319 media_info_, segment_infos_,
320 mpd_options_.mpd_params.low_latency_dash_mode)) {
321 LOG(ERROR) <<
"Failed to add Live info.";
327 output_suppression_flags_ = 0;
328 return representation;
332 output_suppression_flags_ |= flag;
336 double presentation_time_offset) {
337 int64_t pto = presentation_time_offset * media_info_.reference_time_scale();
340 media_info_.set_presentation_time_offset(pto);
346 const double frame_duration_sec =
347 (double)frame_duration_ / (
double)media_info_.reference_time_scale();
354 mpd_options_.mpd_params.target_segment_duration - frame_duration_sec;
357 media_info_.set_availability_time_offset(ato);
361 double* start_timestamp_seconds,
362 double* end_timestamp_seconds)
const {
363 if (segment_infos_.empty())
366 if (start_timestamp_seconds) {
367 *start_timestamp_seconds =
368 static_cast<double>(segment_infos_.begin()->start_time) /
369 GetTimeScale(media_info_);
371 if (end_timestamp_seconds) {
372 *end_timestamp_seconds =
373 static_cast<double>(segment_infos_.rbegin()->start_time +
374 segment_infos_.rbegin()->duration *
375 (segment_infos_.rbegin()->repeat + 1)) /
376 GetTimeScale(media_info_);
381 bool Representation::HasRequiredMediaInfoFields()
const {
382 if (HasVODOnlyFields(media_info_) && HasLiveOnlyFields(media_info_)) {
383 LOG(ERROR) <<
"MediaInfo cannot have both VOD and Live fields.";
387 if (!media_info_.has_container_type()) {
388 LOG(ERROR) <<
"MediaInfo missing required field: container_type.";
395 void Representation::AddSegmentInfo(int64_t start_time,
397 int64_t segment_number) {
398 const uint64_t kNoRepeat = 0;
399 const int64_t adjusted_duration = AdjustDuration(duration);
401 if (!segment_infos_.empty()) {
403 const SegmentInfo& previous = segment_infos_.back();
404 const int64_t previous_segment_end_time =
405 previous.start_time + previous.duration * (previous.repeat + 1);
408 if (ApproximiatelyEqual(previous_segment_end_time, start_time)) {
409 const int64_t segment_end_time_for_same_duration =
410 previous_segment_end_time + previous.duration;
411 const int64_t actual_segment_end_time = start_time + duration;
414 if (ApproximiatelyEqual(segment_end_time_for_same_duration,
415 actual_segment_end_time)) {
416 ++segment_infos_.back().repeat;
418 segment_infos_.push_back(
419 {previous_segment_end_time,
420 actual_segment_end_time - previous_segment_end_time, kNoRepeat,
427 const int64_t kRoundingErrorGrace = 5;
428 if (previous_segment_end_time + kRoundingErrorGrace < start_time) {
429 LOG(WARNING) << RepresentationAsString() <<
" Found a gap of size "
430 << (start_time - previous_segment_end_time)
431 <<
" > kRoundingErrorGrace (" << kRoundingErrorGrace
432 <<
"). The new segment starts at " << start_time
433 <<
" but the previous segment ends at "
434 << previous_segment_end_time <<
".";
438 if (start_time < previous_segment_end_time - kRoundingErrorGrace) {
440 << RepresentationAsString()
441 <<
" Segments should not be overlapping. The new segment starts at "
442 << start_time <<
" but the previous segment ends at "
443 << previous_segment_end_time <<
".";
446 segment_infos_.push_back(
447 {start_time, adjusted_duration, kNoRepeat, segment_number});
450 void Representation::UpdateSegmentInfo(int64_t duration) {
451 if (!segment_infos_.empty()) {
453 segment_infos_.back().duration = duration;
457 bool Representation::ApproximiatelyEqual(int64_t time1, int64_t time2)
const {
458 if (!allow_approximate_segment_timeline_)
459 return time1 == time2;
469 const double kErrorThresholdSeconds = 0.05;
472 const int32_t error_threshold =
473 std::min(frame_duration_,
474 static_cast<int32_t
>(kErrorThresholdSeconds *
475 media_info_.reference_time_scale()));
476 return std::abs(time1 - time2) <= error_threshold;
479 int64_t Representation::AdjustDuration(int64_t duration)
const {
480 if (!allow_approximate_segment_timeline_)
482 const int64_t scaled_target_duration =
483 mpd_options_.mpd_params.target_segment_duration *
484 media_info_.reference_time_scale();
485 return ApproximiatelyEqual(scaled_target_duration, duration)
486 ? scaled_target_duration
490 void Representation::SlideWindow() {
491 if (mpd_options_.mpd_params.time_shift_buffer_depth <= 0.0 ||
492 mpd_options_.mpd_type == MpdType::kStatic)
495 const int32_t time_scale = GetTimeScale(media_info_);
496 DCHECK_GT(time_scale, 0);
498 const int64_t time_shift_buffer_depth =
static_cast<int64_t
>(
499 mpd_options_.mpd_params.time_shift_buffer_depth * time_scale);
501 if (current_buffer_depth_ <= time_shift_buffer_depth)
504 std::list<SegmentInfo>::iterator first = segment_infos_.begin();
505 std::list<SegmentInfo>::iterator last = first;
506 for (; last != segment_infos_.end(); ++last) {
509 while (last->repeat >= 0 &&
510 current_buffer_depth_ - last->duration >= time_shift_buffer_depth) {
511 current_buffer_depth_ -= last->duration;
512 RemoveOldSegment(&*last);
514 if (last->repeat >= 0)
517 segment_infos_.erase(first, last);
520 void Representation::RemoveOldSegment(SegmentInfo* segment_info) {
521 int64_t segment_start_time = segment_info->start_time;
522 segment_info->start_time += segment_info->duration;
523 segment_info->repeat--;
524 int64_t start_number = segment_info->start_segment_number;
525 segment_info->start_segment_number++;
527 if (mpd_options_.mpd_params.preserved_segments_outside_live_window == 0)
530 segments_to_be_removed_.push_back(
531 media::GetSegmentName(media_info_.segment_template(), segment_start_time,
532 start_number, media_info_.bandwidth()));
533 while (segments_to_be_removed_.size() >
534 mpd_options_.mpd_params.preserved_segments_outside_live_window) {
535 VLOG(2) <<
"Deleting " << segments_to_be_removed_.front();
536 if (!File::Delete(segments_to_be_removed_.front().c_str())) {
537 LOG(WARNING) <<
"Failed to delete " << segments_to_be_removed_.front()
538 <<
"; Will retry later.";
541 segments_to_be_removed_.pop_front();
545 std::string Representation::GetVideoMimeType()
const {
546 return GetMimeType(
"video", media_info_.container_type());
549 std::string Representation::GetAudioMimeType()
const {
550 return GetMimeType(
"audio", media_info_.container_type());
553 std::string Representation::GetTextMimeType()
const {
554 CHECK(media_info_.has_text_info());
555 if (media_info_.text_info().codec() ==
"ttml") {
556 switch (media_info_.container_type()) {
557 case MediaInfo::CONTAINER_TEXT:
558 return "application/ttml+xml";
559 case MediaInfo::CONTAINER_MP4:
560 return "application/mp4";
562 LOG(ERROR) <<
"Failed to determine MIME type for TTML container: "
563 << media_info_.container_type();
567 if (media_info_.text_info().codec() ==
"wvtt") {
568 if (media_info_.container_type() == MediaInfo::CONTAINER_TEXT) {
570 }
else if (media_info_.container_type() == MediaInfo::CONTAINER_MP4) {
571 return "application/mp4";
573 LOG(ERROR) <<
"Failed to determine MIME type for VTT container: "
574 << media_info_.container_type();
578 LOG(ERROR) <<
"Cannot determine MIME type for format: "
579 << media_info_.text_info().codec()
580 <<
" container: " << media_info_.container_type();
584 std::string Representation::RepresentationAsString()
const {
585 std::string s = absl::StrFormat(
"Representation (id=%d,", id_);
586 if (media_info_.has_video_info()) {
587 const MediaInfo_VideoInfo& video_info = media_info_.video_info();
588 absl::StrAppendFormat(&s,
"codec='%s',width=%d,height=%d",
589 video_info.codec().c_str(), video_info.width(),
590 video_info.height());
591 }
else if (media_info_.has_audio_info()) {
592 const MediaInfo_AudioInfo& audio_info = media_info_.audio_info();
593 absl::StrAppendFormat(
594 &s,
"codec='%s',frequency=%d,language='%s'", audio_info.codec().c_str(),
595 audio_info.sampling_frequency(), audio_info.language().c_str());
596 }
else if (media_info_.has_text_info()) {
597 const MediaInfo_TextInfo& text_info = media_info_.text_info();
598 absl::StrAppendFormat(&s,
"codec='%s',language='%s'",
599 text_info.codec().c_str(),
600 text_info.language().c_str());
602 absl::StrAppendFormat(&s,
")");
void AddBlock(uint64_t size_in_bytes, double duration)
virtual void AddContentProtectionElement(const ContentProtectionElement &element)
virtual void AddNewSegment(int64_t start_time, int64_t duration, uint64_t size, int64_t segment_number)
virtual void UpdateContentProtectionPssh(const std::string &drm_uuid, const std::string &pssh)
virtual void UpdateCompletedSegment(int64_t duration, uint64_t size)
void SuppressOnce(SuppressFlag flag)
virtual const MediaInfo & GetMediaInfo() const
void SetAvailabilityTimeOffset()
virtual void SetSampleDuration(int32_t sample_duration)
bool GetStartAndEndTimestamps(double *start_timestamp_seconds, double *end_timestamp_seconds) const
Representation(const MediaInfo &media_info, const MpdOptions &mpd_options, uint32_t representation_id, std::unique_ptr< RepresentationStateChangeListener > state_change_listener)
std::optional< xml::XmlNode > GetXml()
void SetPresentationTimeOffset(double presentation_time_offset)
Set @presentationTimeOffset in SegmentBase / SegmentTemplate.
void SetSegmentDuration()
RepresentationType in MPD.
bool AddVODOnlyInfo(const MediaInfo &media_info, bool use_segment_list, double target_segment_duration)
bool AddLiveOnlyInfo(const MediaInfo &media_info, const std::list< SegmentInfo > &segment_infos, bool low_latency_dash_mode)
bool AddAudioInfo(const MediaInfo::AudioInfo &audio_info)
bool AddVideoInfo(const MediaInfo::VideoInfo &video_info, bool set_width, bool set_height, bool set_frame_rate)
bool SetStringAttribute(const std::string &attribute_name, const std::string &attribute)
bool SetIntegerAttribute(const std::string &attribute_name, uint64_t number)
All the methods that are virtual are virtual for mocking.