7#include <packager/hls/base/media_playlist.h>
22#include <absl/log/check.h>
23#include <absl/log/log.h>
24#include <absl/strings/str_format.h>
25#include <absl/time/civil_time.h>
26#include <absl/time/time.h>
28#include <packager/file.h>
29#include <packager/hls/base/tag.h>
30#include <packager/hls_params.h>
31#include <packager/macros/logging.h>
32#include <packager/media/base/fourccs.h>
33#include <packager/media/base/language_utils.h>
34#include <packager/media/base/muxer_util.h>
35#include <packager/version/version.h>
41int32_t GetTimeScale(
const MediaInfo& media_info) {
42 if (media_info.has_reference_time_scale())
43 return media_info.reference_time_scale();
45 if (media_info.has_video_info())
46 return media_info.video_info().time_scale();
48 if (media_info.has_audio_info())
49 return media_info.audio_info().time_scale();
53std::string AdjustVideoCodec(
const std::string& codec) {
61 std::string adjusted_codec = codec;
62 std::string fourcc = codec.substr(0, 4);
64 adjusted_codec =
"avc1" + codec.substr(4);
65 else if (fourcc ==
"hev1")
66 adjusted_codec =
"hvc1" + codec.substr(4);
67 else if (fourcc ==
"dvhe")
68 adjusted_codec =
"dvh1" + codec.substr(4);
69 if (adjusted_codec != codec) {
70 VLOG(1) <<
"Adusting video codec string from " << codec <<
" to "
73 return adjusted_codec;
82std::string GetLanguage(
const MediaInfo& media_info) {
84 if (media_info.has_audio_info()) {
85 lang = media_info.audio_info().language();
86 }
else if (media_info.has_text_info()) {
87 lang = media_info.text_info().language();
92void AppendExtXMap(
const MediaInfo& media_info, std::string* out) {
93 if (media_info.has_init_segment_url()) {
94 Tag tag(
"#EXT-X-MAP", out);
95 tag.AddQuotedString(
"URI", media_info.init_segment_url().data());
97 }
else if (media_info.has_media_file_url() && media_info.has_init_range()) {
100 Tag tag(
"#EXT-X-MAP", out);
101 tag.AddQuotedString(
"URI", media_info.media_file_url().data());
103 if (media_info.has_init_range()) {
104 const uint64_t begin = media_info.init_range().begin();
105 const uint64_t end = media_info.init_range().end();
106 const uint64_t length = end - begin + 1;
108 tag.AddQuotedNumberPair(
"BYTERANGE", length,
'@', begin);
117std::string CreatePlaylistHeader(
118 const MediaInfo& media_info,
119 int32_t target_duration,
120 HlsPlaylistType type,
121 MediaPlaylist::MediaPlaylistStreamType stream_type,
122 uint32_t media_sequence_number,
123 int discontinuity_sequence_number,
124 std::optional<double> start_time_offset) {
125 const std::string version = GetPackagerVersion();
126 std::string version_line;
127 if (!version.empty()) {
129 absl::StrFormat(
"## Generated with %s version %s\n",
130 GetPackagerProjectUrl().c_str(), version.c_str());
134 std::string header = absl::StrFormat(
138 "#EXT-X-TARGETDURATION:%d\n",
139 version_line.c_str(), target_duration);
142 case HlsPlaylistType::kVod:
143 header +=
"#EXT-X-PLAYLIST-TYPE:VOD\n";
145 case HlsPlaylistType::kEvent:
146 header +=
"#EXT-X-PLAYLIST-TYPE:EVENT\n";
148 case HlsPlaylistType::kLive:
149 if (media_sequence_number > 0) {
150 absl::StrAppendFormat(&header,
"#EXT-X-MEDIA-SEQUENCE:%d\n",
151 media_sequence_number);
153 if (discontinuity_sequence_number > 0) {
154 absl::StrAppendFormat(&header,
"#EXT-X-DISCONTINUITY-SEQUENCE:%d\n",
155 discontinuity_sequence_number);
159 NOTIMPLEMENTED() <<
"Unexpected MediaPlaylistType "
160 <<
static_cast<int>(type);
163 MediaPlaylist::MediaPlaylistStreamType::kVideoIFramesOnly) {
164 absl::StrAppendFormat(&header,
"#EXT-X-I-FRAMES-ONLY\n");
166 if (start_time_offset.has_value()) {
167 absl::StrAppendFormat(&header,
"#EXT-X-START:TIME-OFFSET=%f\n",
168 start_time_offset.value());
173 AppendExtXMap(media_info, &header);
180HlsEntry::HlsEntry(HlsEntry::EntryType type) : type_(type) {}
181HlsEntry::~HlsEntry() {}
183class SegmentInfoEntry :
public HlsEntry {
191 SegmentInfoEntry(
const std::string& file_name,
193 double duration_seconds,
195 uint64_t start_byte_offset,
196 uint64_t segment_file_size,
197 uint64_t previous_segment_end_offset);
199 std::string ToString()
override;
200 int64_t start_time()
const {
return start_time_; }
201 double duration_seconds()
const {
return duration_seconds_; }
202 void set_duration_seconds(
double duration_seconds) {
203 duration_seconds_ = duration_seconds;
207 SegmentInfoEntry(
const SegmentInfoEntry&) =
delete;
208 SegmentInfoEntry& operator=(
const SegmentInfoEntry&) =
delete;
210 const std::string file_name_;
211 const int64_t start_time_;
212 double duration_seconds_;
213 const bool use_byte_range_;
214 const uint64_t start_byte_offset_;
215 const uint64_t segment_file_size_;
216 const uint64_t previous_segment_end_offset_;
219SegmentInfoEntry::SegmentInfoEntry(
const std::string& file_name,
221 double duration_seconds,
223 uint64_t start_byte_offset,
224 uint64_t segment_file_size,
225 uint64_t previous_segment_end_offset)
226 : HlsEntry(HlsEntry::EntryType::kExtInf),
227 file_name_(file_name),
228 start_time_(start_time),
229 duration_seconds_(duration_seconds),
230 use_byte_range_(use_byte_range),
231 start_byte_offset_(start_byte_offset),
232 segment_file_size_(segment_file_size),
233 previous_segment_end_offset_(previous_segment_end_offset) {}
235std::string SegmentInfoEntry::ToString() {
236 std::string result = absl::StrFormat(
"#EXTINF:%.3f,", duration_seconds_);
238 if (use_byte_range_) {
239 absl::StrAppendFormat(&result,
"\n#EXT-X-BYTERANGE:%" PRIu64,
241 if (previous_segment_end_offset_ + 1 != start_byte_offset_) {
242 absl::StrAppendFormat(&result,
"@%" PRIu64, start_byte_offset_);
246 absl::StrAppendFormat(&result,
"\n%s", file_name_.c_str());
251class DiscontinuityEntry :
public HlsEntry {
253 DiscontinuityEntry();
255 std::string ToString()
override;
258 DiscontinuityEntry(
const DiscontinuityEntry&) =
delete;
259 DiscontinuityEntry& operator=(
const DiscontinuityEntry&) =
delete;
262DiscontinuityEntry::DiscontinuityEntry()
263 : HlsEntry(HlsEntry::EntryType::kExtDiscontinuity) {}
265std::string DiscontinuityEntry::ToString() {
266 return "#EXT-X-DISCONTINUITY";
269ProgramDateTimeEntry::ProgramDateTimeEntry(
const absl::Time& program_time)
270 : HlsEntry(HlsEntry::EntryType::kProgramDateTime),
271 program_time_(program_time) {}
273std::string ProgramDateTimeEntry::ToString() {
274 absl::CivilSecond cs =
275 absl::ToCivilSecond(program_time_, absl::UTCTimeZone());
277 int64_t total_ms = absl::ToUnixMillis(program_time_);
278 int ms =
static_cast<int>(total_ms % 1000);
282 return absl::StrFormat(
283 "#EXT-X-PROGRAM-DATE-TIME:%04d-%02d-%02dT%02d:%02d:%02d.%03dZ", cs.year(),
284 cs.month(), cs.day(), cs.hour(), cs.minute(), cs.second(), ms);
287class PlacementOpportunityEntry :
public HlsEntry {
289 PlacementOpportunityEntry();
291 std::string ToString()
override;
294 PlacementOpportunityEntry(
const PlacementOpportunityEntry&) =
delete;
295 PlacementOpportunityEntry& operator=(
const PlacementOpportunityEntry&) =
299PlacementOpportunityEntry::PlacementOpportunityEntry()
300 : HlsEntry(HlsEntry::EntryType::kExtPlacementOpportunity) {}
302std::string PlacementOpportunityEntry::ToString() {
303 return "#EXT-X-PLACEMENT-OPPORTUNITY";
306EncryptionInfoEntry::EncryptionInfoEntry(MediaPlaylist::EncryptionMethod method,
307 const std::string& url,
308 const std::string& key_id,
309 const std::string& iv,
310 const std::string& key_format,
311 const std::string& key_format_versions)
312 : HlsEntry(HlsEntry::EntryType::kExtKey),
317 key_format_(key_format),
318 key_format_versions_(key_format_versions) {}
320std::string EncryptionInfoEntry::ToString() {
324std::string EncryptionInfoEntry::ToString(std::string tag_name) {
325 std::string tag_string;
326 if (tag_name.empty())
327 tag_name =
"#EXT-X-KEY";
328 Tag tag(tag_name, &tag_string);
330 if (method_ == MediaPlaylist::EncryptionMethod::kSampleAes) {
331 tag.AddString(
"METHOD",
"SAMPLE-AES");
332 }
else if (method_ == MediaPlaylist::EncryptionMethod::kAes128) {
333 tag.AddString(
"METHOD",
"AES-128");
334 }
else if (method_ == MediaPlaylist::EncryptionMethod::kSampleAesCenc) {
335 tag.AddString(
"METHOD",
"SAMPLE-AES-CTR");
337 DCHECK(method_ == MediaPlaylist::EncryptionMethod::kNone);
338 tag.AddString(
"METHOD",
"NONE");
341 tag.AddQuotedString(
"URI", url_);
343 if (!key_id_.empty()) {
344 tag.AddString(
"KEYID", key_id_);
347 tag.AddString(
"IV", iv_);
349 if (!key_format_versions_.empty()) {
350 tag.AddQuotedString(
"KEYFORMATVERSIONS", key_format_versions_);
352 if (!key_format_.empty()) {
353 tag.AddQuotedString(
"KEYFORMAT", key_format_);
359MediaPlaylist::MediaPlaylist(
const HlsParams& hls_params,
360 const std::string& file_name,
361 const std::string& name,
362 const std::string& group_id)
363 : hls_params_(hls_params),
364 file_name_(file_name),
367 media_sequence_number_(hls_params_.media_sequence_number),
368 reference_time_(absl::InfinitePast()) {
370 if (media_sequence_number_ > 0)
371 entries_.emplace_back(
new DiscontinuityEntry());
374MediaPlaylist::~MediaPlaylist() {}
377 MediaPlaylistStreamType stream_type) {
378 stream_type_ = stream_type;
390 const std::vector<std::string>& characteristics) {
391 characteristics_ = characteristics;
395 media_info_.set_index(index);
399 forced_subtitle_ = forced_subtitle;
403 MediaPlaylist::EncryptionMethod method,
404 const std::string& url,
405 const std::string& key_id,
406 const std::string& iv,
407 const std::string& key_format,
408 const std::string& key_format_versions) {
410 method, url, key_id, iv, key_format, key_format_versions));
414 const int32_t time_scale = GetTimeScale(media_info);
415 if (time_scale == 0) {
416 LOG(ERROR) <<
"MediaInfo does not contain a valid timescale.";
420 if (media_info.has_video_info()) {
421 stream_type_ = MediaPlaylistStreamType::kVideo;
422 codec_ = AdjustVideoCodec(media_info.video_info().codec());
423 if (media_info.video_info().has_supplemental_codec() &&
424 media_info.video_info().has_compatible_brand()) {
425 supplemental_codec_ =
426 AdjustVideoCodec(media_info.video_info().supplemental_codec());
427 compatible_brand_ =
static_cast<media::FourCC
>(
428 media_info.video_info().compatible_brand());
430 }
else if (media_info.has_audio_info()) {
431 stream_type_ = MediaPlaylistStreamType::kAudio;
432 codec_ = media_info.audio_info().codec();
434 stream_type_ = MediaPlaylistStreamType::kSubtitle;
435 codec_ = media_info.text_info().codec();
438 time_scale_ = time_scale;
439 media_info_ = media_info;
440 language_ = GetLanguage(media_info);
441 use_byte_range_ = !media_info_.has_segment_template_url() &&
442 media_info_.container_type() != MediaInfo::CONTAINER_TEXT;
444 std::vector<std::string>(media_info_.hls_characteristics().begin(),
445 media_info_.hls_characteristics().end());
447 forced_subtitle_ = media_info_.forced_subtitle();
453 if (media_info_.has_video_info())
454 media_info_.mutable_video_info()->set_frame_duration(sample_duration);
460 uint64_t start_byte_offset,
462 if (stream_type_ == MediaPlaylistStreamType::kVideoIFramesOnly) {
463 if (key_frames_.empty())
466 AdjustLastSegmentInfoEntryDuration(key_frames_.front().timestamp);
468 for (
auto iter = key_frames_.begin(); iter != key_frames_.end(); ++iter) {
471 const int64_t next_timestamp = std::next(iter) == key_frames_.end()
472 ? (start_time + duration)
473 : std::next(iter)->timestamp;
474 AddSegmentInfoEntry(file_name, iter->timestamp,
475 next_timestamp - iter->timestamp,
476 iter->start_byte_offset, iter->size);
481 return AddSegmentInfoEntry(file_name, start_time, duration, start_byte_offset,
486 reference_time_ = reference_time;
490 uint64_t start_byte_offset,
492 if (stream_type_ != MediaPlaylistStreamType::kVideoIFramesOnly) {
493 if (stream_type_ != MediaPlaylistStreamType::kVideo) {
495 <<
"I-Frames Only playlist applies to video renditions only.";
498 stream_type_ = MediaPlaylistStreamType::kVideoIFramesOnly;
499 use_byte_range_ =
true;
501 key_frames_.push_back({timestamp, start_byte_offset, size, std::string(
"")});
505 const std::string& url,
506 const std::string& key_id,
507 const std::string& iv,
508 const std::string& key_format,
509 const std::string& key_format_versions) {
510 if (!inserted_discontinuity_tag_) {
513 if (!entries_.empty())
514 entries_.emplace_back(
new DiscontinuityEntry());
515 inserted_discontinuity_tag_ =
true;
518 method, url, key_id, iv, key_format, key_format_versions));
522 entries_.emplace_back(
new PlacementOpportunityEntry());
526 bool event_to_vod_on_end_of_stream,
528 if (!target_duration_set_) {
532 HlsPlaylistType playlist_type = hls_params_.playlist_type;
533 if (event_to_vod_on_end_of_stream && end_stream &&
534 playlist_type == HlsPlaylistType::kEvent) {
535 playlist_type = HlsPlaylistType::kVod;
538 std::string content = CreatePlaylistHeader(
539 media_info_, target_duration_, playlist_type, stream_type_,
540 media_sequence_number_, discontinuity_sequence_number_,
541 hls_params_.start_time_offset);
543 for (
const auto& entry : entries_)
544 absl::StrAppendFormat(&content,
"%s\n", entry->ToString().c_str());
546 if (playlist_type == HlsPlaylistType::kVod) {
547 content +=
"#EXT-X-ENDLIST\n";
550 if (!File::WriteFileAtomically(file_path.string().c_str(), content)) {
551 LOG(ERROR) <<
"Failed to write playlist to: " << file_path.string();
558 if (media_info_.has_bandwidth())
559 return media_info_.bandwidth();
560 return bandwidth_estimator_.
Max();
564 return bandwidth_estimator_.
Estimate();
568 return longest_segment_duration_seconds_;
572 if (target_duration_set_) {
573 if (target_duration_ == target_duration)
575 VLOG(1) <<
"Updating target duration from " << target_duration_ <<
" to "
578 target_duration_ = target_duration;
579 target_duration_set_ =
true;
583 return media_info_.audio_info().num_channels();
587 return media_info_.audio_info().codec_specific_data().ec3_joc_complexity();
591 return media_info_.audio_info().codec_specific_data().ac4_ims_flag();
595 return media_info_.audio_info().codec_specific_data().ac4_cbi_flag();
599 uint32_t* height)
const {
602 if (media_info_.has_video_info()) {
603 const double pixel_aspect_ratio =
604 media_info_.video_info().pixel_height() > 0
605 ?
static_cast<double>(media_info_.video_info().pixel_width()) /
606 media_info_.video_info().pixel_height()
608 *width =
static_cast<uint32_t
>(media_info_.video_info().width() *
610 *height = media_info_.video_info().height();
618 if (codec_.find(
"dvh") == 0)
623 switch (media_info_.video_info().transfer_characteristics()) {
631 if (!supplemental_codec_.empty() &&
632 compatible_brand_ == media::FOURCC_db4g)
650 if (media_info_.video_info().frame_duration() == 0)
652 return static_cast<double>(time_scale_) /
653 media_info_.video_info().frame_duration();
656void MediaPlaylist::AddSegmentInfoEntry(
const std::string& segment_file_name,
659 uint64_t start_byte_offset,
661 if (time_scale_ == 0) {
662 LOG(WARNING) <<
"Timescale is not set and the duration for " << duration
663 <<
" cannot be calculated. The output will be wrong.";
665 entries_.emplace_back(
new SegmentInfoEntry(
666 segment_file_name, 0.0, 0.0, use_byte_range_, start_byte_offset, size,
667 previous_segment_end_offset_));
678 const double segment_duration_seconds =
679 static_cast<double>(duration) / time_scale_;
680 longest_segment_duration_seconds_ =
681 std::max(longest_segment_duration_seconds_, segment_duration_seconds);
682 bandwidth_estimator_.
AddBlock(size, segment_duration_seconds);
683 current_buffer_depth_ += segment_duration_seconds;
685 if (!entries_.empty() &&
686 entries_.back()->type() == HlsEntry::EntryType::kExtInf) {
687 const SegmentInfoEntry* segment_info =
688 static_cast<SegmentInfoEntry*
>(entries_.back().get());
689 if (segment_info->start_time() > start_time) {
691 <<
"Insert a discontinuity tag after the segment with start time "
692 << segment_info->start_time() <<
" as the next segment starts at "
693 << start_time <<
".";
694 entries_.emplace_back(
new DiscontinuityEntry());
698 if (hls_params_.add_program_date_time &&
699 reference_time_ != absl::InfinitePast()) {
702 bool is_first_segment =
true;
703 bool is_discontinuity =
false;
704 if (!entries_.empty()) {
705 for (
auto it = entries_.rbegin(); it != entries_.rend(); ++it) {
706 if ((*it)->type() == HlsEntry::EntryType::kExtInf) {
707 is_first_segment =
false;
712 const auto& last = *entries_.back();
713 if (last.type() == HlsEntry::EntryType::kExtDiscontinuity) {
714 is_discontinuity =
true;
715 }
else if (entries_.size() >= 2) {
716 const auto& second_last = **std::prev(entries_.cend(), 2);
717 if (last.type() == HlsEntry::EntryType::kExtKey &&
718 second_last.type() == HlsEntry::EntryType::kExtDiscontinuity) {
719 is_discontinuity =
true;
724 if (is_first_segment || is_discontinuity) {
725 const absl::Time program_time =
727 absl::Seconds(
static_cast<double>(start_time) / time_scale_);
728 entries_.emplace_back(
new ProgramDateTimeEntry(program_time));
732 entries_.emplace_back(
new SegmentInfoEntry(
733 segment_file_name, start_time, segment_duration_seconds, use_byte_range_,
734 start_byte_offset, size, previous_segment_end_offset_));
735 previous_segment_end_offset_ = start_byte_offset + size - 1;
738void MediaPlaylist::AdjustLastSegmentInfoEntryDuration(int64_t next_timestamp) {
739 if (time_scale_ == 0)
742 const double next_timestamp_seconds =
743 static_cast<double>(next_timestamp) / time_scale_;
745 for (
auto iter = entries_.rbegin(); iter != entries_.rend(); ++iter) {
746 if (iter->get()->type() == HlsEntry::EntryType::kExtInf) {
747 SegmentInfoEntry* segment_info =
748 reinterpret_cast<SegmentInfoEntry*
>(iter->get());
750 const double segment_duration_seconds =
751 next_timestamp_seconds -
752 static_cast<double>(segment_info->start_time()) / time_scale_;
754 if (segment_duration_seconds > 0)
755 segment_info->set_duration_seconds(segment_duration_seconds);
756 longest_segment_duration_seconds_ =
757 std::max(longest_segment_duration_seconds_, segment_duration_seconds);
771void MediaPlaylist::SlideWindow() {
772 if (hls_params_.time_shift_buffer_depth <= 0.0 ||
773 hls_params_.playlist_type != HlsPlaylistType::kLive) {
776 DCHECK_GT(time_scale_, 0);
778 if (current_buffer_depth_ <= hls_params_.time_shift_buffer_depth)
788 std::list<std::unique_ptr<HlsEntry>> ext_x_keys;
791 HlsEntry::EntryType prev_entry_type = HlsEntry::EntryType::kExtInf;
793 std::list<std::unique_ptr<HlsEntry>>::iterator last = entries_.begin();
794 for (; last != entries_.end(); ++last) {
795 HlsEntry::EntryType entry_type = last->get()->type();
796 if (entry_type == HlsEntry::EntryType::kExtKey) {
797 if (prev_entry_type != HlsEntry::EntryType::kExtKey)
799 ext_x_keys.push_back(std::move(*last));
800 }
else if (entry_type == HlsEntry::EntryType::kExtDiscontinuity) {
801 ++discontinuity_sequence_number_;
803 DCHECK_EQ(
static_cast<int>(entry_type),
804 static_cast<int>(HlsEntry::EntryType::kExtInf));
806 const SegmentInfoEntry& segment_info =
807 *
reinterpret_cast<SegmentInfoEntry*
>(last->get());
810 const bool segment_within_time_shift_buffer =
811 current_buffer_depth_ - segment_info.duration_seconds() <
812 hls_params_.time_shift_buffer_depth;
813 if (segment_within_time_shift_buffer)
815 current_buffer_depth_ -= segment_info.duration_seconds();
816 RemoveOldSegment(segment_info.start_time());
817 media_sequence_number_++;
819 prev_entry_type = entry_type;
821 entries_.erase(entries_.begin(), last);
823 entries_.insert(entries_.begin(), std::make_move_iterator(ext_x_keys.begin()),
824 std::make_move_iterator(ext_x_keys.end()));
827void MediaPlaylist::RemoveOldSegment(int64_t start_time) {
828 if (hls_params_.preserved_segments_outside_live_window == 0)
830 if (stream_type_ == MediaPlaylistStreamType::kVideoIFramesOnly)
833 segments_to_be_removed_.push_back(media::GetSegmentName(
834 media_info_.segment_template(), start_time, media_sequence_number_ + 1,
835 media_info_.bandwidth()));
836 while (segments_to_be_removed_.size() >
837 hls_params_.preserved_segments_outside_live_window) {
838 const std::string& file_name = segments_to_be_removed_.front();
839 VLOG(2) <<
"Deleting " << file_name;
845 if (!File::Delete(file_name.c_str()) &&
846 File::GetFileSize(file_name.c_str()) >= 0) {
847 LOG(WARNING) <<
"Failed to delete " << file_name <<
"; Will retry later.";
850 segments_to_be_removed_.pop_front();
void AddBlock(uint64_t size_in_bytes, double duration)
uint64_t Estimate() const
All the methods that are virtual are virtual for mocking.
std::string LanguageToShortestForm(const std::string &language)