7#include <packager/packager.h>
22#include <absl/log/check.h>
23#include <absl/log/log.h>
24#include <absl/strings/ascii.h>
25#include <absl/strings/match.h>
26#include <absl/strings/str_format.h>
28#include <packager/app/job_manager.h>
29#include <packager/app/muxer_factory.h>
30#include <packager/app/packager_util.h>
31#include <packager/app/single_thread_job_manager.h>
32#include <packager/buffer_callback_params.h>
33#include <packager/cea_caption.h>
34#include <packager/chunking_params.h>
35#include <packager/crypto_params.h>
36#include <packager/file.h>
37#include <packager/hls/base/hls_notifier.h>
38#include <packager/hls/base/simple_hls_notifier.h>
39#include <packager/hls_params.h>
40#include <packager/macros/status.h>
41#include <packager/media/base/cc_stream_filter.h>
42#include <packager/media/base/container_names.h>
43#include <packager/media/base/fourccs.h>
44#include <packager/media/base/language_utils.h>
45#include <packager/media/base/muxer.h>
46#include <packager/media/base/muxer_options.h>
47#include <packager/media/base/muxer_util.h>
48#include <packager/media/chunking/chunking_handler.h>
49#include <packager/media/chunking/cue_alignment_handler.h>
50#include <packager/media/chunking/segment_coordinator.h>
51#include <packager/media/chunking/text_chunker.h>
52#include <packager/media/crypto/encryption_handler.h>
53#include <packager/media/demuxer/demuxer.h>
54#include <packager/media/event/muxer_listener_factory.h>
55#include <packager/media/event/vod_media_info_dump_muxer_listener.h>
56#include <packager/media/formats/ttml/ttml_to_mp4_handler.h>
57#include <packager/media/formats/webvtt/text_padder.h>
58#include <packager/media/formats/webvtt/webvtt_to_mp4_handler.h>
59#include <packager/media/replicator/replicator.h>
60#include <packager/media/trick_play/trick_play_handler.h>
61#include <packager/mpd/base/media_info.pb.h>
62#include <packager/mpd/base/simple_mpd_notifier.h>
63#include <packager/status.h>
64#include <packager/utils/clock.h>
65#include <packager/version/version.h>
71using media::JobManager;
72using media::KeySource;
73using media::MuxerOptions;
74using media::SingleThreadJobManager;
75using media::SyncPointQueue;
80const char kMediaInfoSuffix[] =
".media_info";
82MuxerListenerFactory::StreamData ToMuxerListenerData(
83 const StreamDescriptor& stream) {
84 MuxerListenerFactory::StreamData data;
85 data.media_info_output = stream.output;
87 data.hls_group_id = stream.hls_group_id;
88 data.hls_name = stream.hls_name;
89 data.hls_playlist_name = stream.hls_playlist_name;
90 data.hls_iframe_playlist_name = stream.hls_iframe_playlist_name;
91 data.hls_characteristics = stream.hls_characteristics;
92 data.forced_subtitle = stream.forced_subtitle;
93 data.hls_only = stream.hls_only;
95 data.dash_accessiblities = stream.dash_accessiblities;
96 data.dash_roles = stream.dash_roles;
97 data.dash_only = stream.dash_only;
98 data.index = stream.index;
99 data.dash_label = stream.dash_label;
100 data.input_format = stream.input_format;
107bool DetermineTextFileCodec(
const std::string& file, std::string* out) {
111 if (!File::ReadFileToString(file.c_str(), &content)) {
112 LOG(ERROR) <<
"Failed to open file " << file
113 <<
" to determine file format.";
117 const uint8_t* content_data =
118 reinterpret_cast<const uint8_t*
>(content.data());
119 MediaContainerName container_name =
120 DetermineContainer(content_data, content.size());
122 if (container_name == CONTAINER_WEBVTT) {
127 if (container_name == CONTAINER_TTML) {
135MediaContainerName GetOutputFormat(
const StreamDescriptor& descriptor) {
136 if (!descriptor.output_format.empty()) {
137 MediaContainerName format =
138 DetermineContainerFromFormatName(descriptor.output_format);
139 if (format == CONTAINER_UNKNOWN) {
140 LOG(ERROR) <<
"Unable to determine output format from '"
141 << descriptor.output_format <<
"'.";
146 std::optional<MediaContainerName> format_from_output;
147 std::optional<MediaContainerName> format_from_segment;
148 if (!descriptor.output.empty()) {
149 format_from_output = DetermineContainerFromFileName(descriptor.output);
150 if (format_from_output.value() == CONTAINER_UNKNOWN) {
151 LOG(ERROR) <<
"Unable to determine output format from '"
152 << descriptor.output <<
"'.";
155 if (!descriptor.segment_template.empty()) {
156 format_from_segment =
157 DetermineContainerFromFileName(descriptor.segment_template);
158 if (format_from_segment.value() == CONTAINER_UNKNOWN) {
159 LOG(ERROR) <<
"Unable to determine output format from '"
160 << descriptor.segment_template <<
"'.";
164 if (format_from_output && format_from_segment) {
165 if (format_from_output.value() != format_from_segment.value()) {
166 LOG(ERROR) <<
"Output format determined from '" << descriptor.output
167 <<
"' differs from output format determined from '"
168 << descriptor.segment_template <<
"'.";
169 return CONTAINER_UNKNOWN;
173 if (format_from_output)
174 return format_from_output.value();
175 if (format_from_segment)
176 return format_from_segment.value();
177 return CONTAINER_UNKNOWN;
180MediaContainerName GetTextOutputCodec(
const StreamDescriptor& descriptor) {
181 const auto output_container = GetOutputFormat(descriptor);
182 if (output_container != CONTAINER_MOV)
183 return output_container;
185 const auto input_container = DetermineContainerFromFileName(descriptor.input);
186 if (absl::AsciiStrToLower(descriptor.output_format) ==
"vtt+mp4" ||
187 absl::AsciiStrToLower(descriptor.output_format) ==
"webvtt+mp4") {
188 return CONTAINER_WEBVTT;
189 }
else if (absl::AsciiStrToLower(descriptor.output_format) !=
"ttml+mp4" &&
190 input_container == CONTAINER_WEBVTT) {
192 return CONTAINER_WEBVTT;
195 return CONTAINER_TTML;
199bool IsTextStream(
const StreamDescriptor& stream) {
200 if (stream.stream_selector ==
"text")
202 if (absl::AsciiStrToLower(stream.output_format) ==
"vtt+mp4" ||
203 absl::AsciiStrToLower(stream.output_format) ==
"webvtt+mp4" ||
204 absl::AsciiStrToLower(stream.output_format) ==
"ttml+mp4") {
208 auto output_format = GetOutputFormat(stream);
209 return output_format == CONTAINER_WEBVTT || output_format == CONTAINER_TTML;
212Status ValidateStreamDescriptor(
bool dump_stream_info,
213 const StreamDescriptor& stream) {
214 if (stream.input.empty()) {
215 return Status(error::INVALID_ARGUMENT,
"Stream input not specified.");
220 if (dump_stream_info && stream.output.empty() &&
221 stream.segment_template.empty()) {
225 if (stream.output.empty() && stream.segment_template.empty()) {
226 return Status(error::INVALID_ARGUMENT,
227 "Streams must specify 'output' or 'segment template'.");
231 if (stream.stream_selector.empty()) {
232 return Status(error::INVALID_ARGUMENT,
233 "Stream stream_selector not specified.");
237 if (stream.segment_template.length()) {
238 RETURN_IF_ERROR(ValidateSegmentTemplate(stream.segment_template));
243 const MediaContainerName output_format = GetOutputFormat(stream);
245 if (output_format == CONTAINER_UNKNOWN) {
246 return Status(error::INVALID_ARGUMENT,
"Unsupported output format.");
249 if (output_format == CONTAINER_WEBVTT || output_format == CONTAINER_TTML ||
250 output_format == CONTAINER_AAC || output_format == CONTAINER_MP3 ||
251 output_format == CONTAINER_AC3 || output_format == CONTAINER_EAC3 ||
252 output_format == CONTAINER_MPEG2TS) {
255 if (stream.segment_template.length() && stream.output.length()) {
257 error::INVALID_ARGUMENT,
258 "Segmented subtitles, PackedAudio or TS output cannot have an init "
259 "segment. Do not specify stream descriptors 'output' or "
260 "'init_segment' when using 'segment_template'.");
265 if (stream.segment_template.length() && stream.output.empty()) {
266 return Status(error::INVALID_ARGUMENT,
267 "Please specify 'init_segment'. All non-TS multi-segment "
268 "content must provide an init segment.");
272 if (stream.output.find(
'$') != std::string::npos) {
273 if (output_format == CONTAINER_WEBVTT) {
275 error::UNIMPLEMENTED,
276 "WebVTT output with one file per Representation per Period "
277 "is not supported yet. Please use fMP4 instead. If that needs to be "
278 "supported, please file a feature request on GitHub.");
283 RETURN_IF_ERROR(ValidateSegmentTemplate(stream.output));
289Status ValidateParams(
const PackagingParams& packaging_params,
290 const std::vector<StreamDescriptor>& stream_descriptors) {
291 if (!packaging_params.chunking_params.segment_sap_aligned &&
292 packaging_params.chunking_params.subsegment_sap_aligned) {
293 return Status(error::INVALID_ARGUMENT,
294 "Setting segment_sap_aligned to false but "
295 "subsegment_sap_aligned to true is not allowed.");
298 if (packaging_params.chunking_params.start_segment_number < 0) {
299 return Status(error::INVALID_ARGUMENT,
300 "Negative --start_segment_number is not allowed.");
303 if (stream_descriptors.empty()) {
304 return Status(error::INVALID_ARGUMENT,
305 "Stream descriptors cannot be empty.");
310 const bool on_demand_dash_profile =
311 stream_descriptors.begin()->segment_template.empty();
312 std::set<std::string> outputs;
313 std::set<std::string> segment_templates;
314 for (
const auto& descriptor : stream_descriptors) {
315 if (on_demand_dash_profile != descriptor.segment_template.empty()) {
316 return Status(error::INVALID_ARGUMENT,
317 "Inconsistent stream descriptor specification: "
318 "segment_template should be specified for none or all "
319 "stream descriptors.");
322 RETURN_IF_ERROR(ValidateStreamDescriptor(
323 packaging_params.test_params.dump_stream_info, descriptor));
325 if (absl::StartsWith(descriptor.input,
"udp://")) {
326 const HlsParams& hls_params = packaging_params.hls_params;
327 if (!hls_params.master_playlist_output.empty() &&
328 hls_params.playlist_type == HlsPlaylistType::kVod) {
330 <<
"Seeing UDP input with HLS Playlist Type set to VOD. The "
331 "playlists will only be generated when UDP socket is closed. "
332 "If you want to do live packaging, --hls_playlist_type needs to "
339 if (!descriptor.output.empty()) {
340 if (outputs.find(descriptor.output) != outputs.end()) {
342 error::INVALID_ARGUMENT,
343 "Seeing duplicated outputs '" + descriptor.output +
344 "' in stream descriptors. Every output must be unique.");
346 outputs.insert(descriptor.output);
348 if (!descriptor.segment_template.empty()) {
349 if (segment_templates.find(descriptor.segment_template) !=
350 segment_templates.end()) {
351 return Status(error::INVALID_ARGUMENT,
352 "Seeing duplicated segment templates '" +
353 descriptor.segment_template +
354 "' in stream descriptors. Every segment template "
357 segment_templates.insert(descriptor.segment_template);
361 if (packaging_params.output_media_info && !on_demand_dash_profile) {
363 return Status(error::UNIMPLEMENTED,
364 "--output_media_info is only supported for on-demand profile "
365 "(not using segment_template).");
368 if (on_demand_dash_profile &&
369 !packaging_params.mpd_params.mpd_output.empty() &&
370 !packaging_params.mp4_output_params.generate_sidx_in_media_segments &&
371 !packaging_params.mpd_params.use_segment_list) {
373 error::UNIMPLEMENTED,
374 "--generate_sidx_in_media_segments is required for DASH "
375 "on-demand profile (not using segment_template or segment list).");
378 if (packaging_params.chunking_params.low_latency_dash_mode &&
379 packaging_params.chunking_params.subsegment_duration_in_seconds) {
386 return Status(error::INVALID_ARGUMENT,
387 "--fragment_duration cannot be set "
388 "if --low_latency_dash_mode is enabled.");
391 if (packaging_params.mpd_params.low_latency_dash_mode &&
392 packaging_params.mpd_params.utc_timings.empty()) {
394 return Status(error::INVALID_ARGUMENT,
395 "--utc_timings must be be set "
396 "if --low_latency_dash_mode is enabled.");
402bool StreamDescriptorCompareFn(
const StreamDescriptor& a,
403 const StreamDescriptor& b) {
409 if (a.input == b.input) {
410 if (a.stream_selector == b.stream_selector) {
413 return a.trick_play_factor < b.trick_play_factor;
415 return a.stream_selector < b.stream_selector;
418 return a.input < b.input;
423class FakeClock :
public Clock {
425 time_point now() noexcept
override {
426 return std::chrono::system_clock::time_point(std::chrono::seconds(0));
430bool StreamInfoToTextMediaInfo(
const StreamDescriptor& stream_descriptor,
431 MediaInfo* text_media_info) {
433 if (!DetermineTextFileCodec(stream_descriptor.input, &codec)) {
434 LOG(ERROR) <<
"Failed to determine the text file format for "
435 << stream_descriptor.input;
439 MediaInfo::TextInfo* text_info = text_media_info->mutable_text_info();
440 text_info->set_codec(codec);
442 const std::string& language = stream_descriptor.language;
443 if (!language.empty()) {
444 text_info->set_language(language);
447 if (stream_descriptor.index.has_value()) {
448 text_media_info->set_index(stream_descriptor.index.value());
451 text_media_info->set_media_file_name(stream_descriptor.output);
452 text_media_info->set_container_type(MediaInfo::CONTAINER_TEXT);
454 if (stream_descriptor.bandwidth != 0) {
455 text_media_info->set_bandwidth(stream_descriptor.bandwidth);
460 const int kDefaultTextBandwidth = 256;
461 text_media_info->set_bandwidth(kDefaultTextBandwidth);
464 if (!stream_descriptor.dash_roles.empty()) {
465 for (
const auto& dash_role : stream_descriptor.dash_roles) {
466 text_media_info->add_dash_roles(dash_role);
476Status CreateDemuxer(
const StreamDescriptor& stream,
477 const PackagingParams& packaging_params,
478 std::shared_ptr<Demuxer>* new_demuxer) {
479 std::shared_ptr<Demuxer> demuxer = std::make_shared<Demuxer>(stream.input);
480 demuxer->set_dump_stream_info(packaging_params.test_params.dump_stream_info);
481 demuxer->set_input_format(stream.input_format);
483 if (packaging_params.decryption_params.key_provider != KeyProvider::kNone) {
484 std::unique_ptr<KeySource> decryption_key_source(
485 CreateDecryptionKeySource(packaging_params.decryption_params));
486 if (!decryption_key_source) {
488 error::INVALID_ARGUMENT,
489 "Must define decryption key source when defining key provider");
491 demuxer->SetKeySource(std::move(decryption_key_source));
494 *new_demuxer = std::move(demuxer);
498std::shared_ptr<MediaHandler> CreateEncryptionHandler(
499 const PackagingParams& packaging_params,
500 const StreamDescriptor& stream,
501 KeySource* key_source,
503 if (stream.skip_encryption) {
512 EncryptionParams encryption_params = packaging_params.encryption_params;
516 if (encryption_params.protection_scheme ==
517 EncryptionParams::kProtectionSchemeAes128) {
518 const MediaContainerName output_format = GetOutputFormat(stream);
519 if (output_format != CONTAINER_MPEG2TS && output_format != CONTAINER_AAC &&
520 output_format != CONTAINER_AC3 && output_format != CONTAINER_EAC3 &&
521 output_format != CONTAINER_MOV) {
522 *status = Status(error::INVALID_ARGUMENT,
523 "protection_scheme=aes128 is not supported for this "
524 "output container.");
533 if (GetOutputFormat(stream) == CONTAINER_MPEG2TS ||
534 GetOutputFormat(stream) == CONTAINER_AAC ||
535 GetOutputFormat(stream) == CONTAINER_AC3 ||
536 GetOutputFormat(stream) == CONTAINER_EAC3) {
537 if (encryption_params.protection_scheme !=
538 EncryptionParams::kProtectionSchemeAes128) {
539 VLOG(1) <<
"Use Apple Sample AES encryption for MPEG2TS or Packed Audio.";
540 encryption_params.protection_scheme = kAppleSampleAesProtectionScheme;
544 if (!stream.drm_label.empty()) {
545 const std::string& drm_label = stream.drm_label;
546 encryption_params.stream_label_func =
547 [drm_label](
const EncryptionParams::EncryptedStreamAttributes&) {
550 }
else if (!encryption_params.stream_label_func) {
551 const int kDefaultMaxSdPixels = 768 * 576;
552 const int kDefaultMaxHdPixels = 1920 * 1080;
553 const int kDefaultMaxUhd1Pixels = 4096 * 2160;
554 encryption_params.stream_label_func = std::bind(
555 &Packager::DefaultStreamLabelFunction, kDefaultMaxSdPixels,
556 kDefaultMaxHdPixels, kDefaultMaxUhd1Pixels, std::placeholders::_1);
559 return std::make_shared<EncryptionHandler>(encryption_params, key_source);
562std::unique_ptr<MediaHandler> CreateTextChunker(
563 const ChunkingParams& chunking_params,
564 bool use_segment_coordinator =
false) {
565 const float segment_length_in_seconds =
566 chunking_params.segment_duration_in_seconds;
567 return std::unique_ptr<MediaHandler>(
new TextChunker(
568 segment_length_in_seconds, chunking_params.start_segment_number,
569 chunking_params.ts_ttx_heartbeat_shift, use_segment_coordinator));
572Status CreateTtmlJobs(
573 const std::vector<std::reference_wrapper<const StreamDescriptor>>& streams,
574 const PackagingParams& packaging_params,
575 SyncPointQueue* sync_points,
576 MuxerFactory* muxer_factory,
577 MpdNotifier* mpd_notifier,
578 JobManager* job_manager) {
580 for (
const StreamDescriptor& stream : streams) {
582 if (!packaging_params.hls_params.master_playlist_output.empty() &&
584 return Status(error::INVALID_ARGUMENT,
585 "HLS does not support TTML in xml format.");
588 if (!stream.segment_template.empty()) {
589 return Status(error::INVALID_ARGUMENT,
590 "Segmented TTML is not supported.");
593 if (GetOutputFormat(stream) != CONTAINER_TTML) {
594 return Status(error::INVALID_ARGUMENT,
595 "Converting TTML to other formats is not supported");
598 if (!stream.output.empty()) {
599 if (!File::Copy(stream.input.c_str(), stream.output.c_str())) {
601 absl::StrAppendFormat(
602 &error,
"Failed to copy the input file (%s) to output file (%s).",
603 stream.input.c_str(), stream.output.c_str());
604 return Status(error::FILE_FAILURE, error);
607 MediaInfo text_media_info;
608 if (!StreamInfoToTextMediaInfo(stream, &text_media_info)) {
609 return Status(error::INVALID_ARGUMENT,
610 "Could not create media info for stream.");
617 if (mpd_notifier->NotifyNewContainer(text_media_info, &unused)) {
618 mpd_notifier->Flush();
620 return Status(error::PARSER_FAILURE,
621 "Failed to process text file " + stream.input);
625 if (packaging_params.output_media_info) {
627 text_media_info, stream.output + kMediaInfoSuffix);
635Status CreateAudioVideoJobs(
636 const std::vector<std::reference_wrapper<const StreamDescriptor>>& streams,
637 const PackagingParams& packaging_params,
638 KeySource* encryption_key_source,
639 SyncPointQueue* sync_points,
640 MuxerListenerFactory* muxer_listener_factory,
641 MuxerFactory* muxer_factory,
642 JobManager* job_manager) {
643 DCHECK(muxer_listener_factory);
644 DCHECK(muxer_factory);
649 std::map<std::string, std::shared_ptr<Demuxer>> sources;
650 std::map<std::string, std::shared_ptr<MediaHandler>> cue_aligners;
651 std::map<std::string, std::shared_ptr<SegmentCoordinator>>
652 segment_coordinators;
654 for (
const StreamDescriptor& stream : streams) {
655 bool seen_input_before = sources.find(stream.input) != sources.end();
656 if (seen_input_before) {
661 CreateDemuxer(stream, packaging_params, &sources[stream.input]));
662 cue_aligners[stream.input] =
663 sync_points ? std::make_shared<CueAlignmentHandler>(sync_points)
665 segment_coordinators[stream.input] = std::make_shared<SegmentCoordinator>();
668 for (
auto& source : sources) {
669 job_manager->Add(
"RemuxJob", source.second);
674 std::shared_ptr<MediaHandler> replicator;
676 std::string previous_input;
677 std::string previous_selector;
680 std::map<std::string, size_t> stream_counters;
682 for (
const StreamDescriptor& stream : streams) {
684 auto& demuxer = sources[stream.input];
685 auto& cue_aligner = cue_aligners[stream.input];
686 auto& segment_coordinator = segment_coordinators[stream.input];
688 const bool new_input_file = stream.input != previous_input;
689 const bool new_stream =
690 new_input_file || previous_selector != stream.stream_selector;
691 const bool is_text = IsTextStream(stream);
692 const bool is_teletext = is_text && stream.cc_index >= 0;
694 previous_input = stream.input;
695 previous_selector = stream.stream_selector;
699 if (stream.output.empty() && stream.segment_template.empty()) {
707 if (!stream.language.empty()) {
708 demuxer->SetLanguageOverride(stream.stream_selector, stream.language);
711 std::vector<std::shared_ptr<MediaHandler>> handlers;
717 if (is_text && stream.cc_index < 0) {
718 handlers.emplace_back(std::make_shared<TextPadder>(
719 packaging_params.default_text_zero_bias_ms));
722 handlers.emplace_back(cue_aligner);
726 size_t stream_index = stream_counters[stream.input]++;
728 segment_coordinator->MarkAsTeletextStream(stream_index);
734 handlers.emplace_back(std::make_shared<ChunkingHandler>(
735 packaging_params.chunking_params));
736 handlers.emplace_back(segment_coordinator);
737 Status enc_handler_status;
738 handlers.emplace_back(CreateEncryptionHandler(packaging_params, stream,
739 encryption_key_source,
740 &enc_handler_status));
741 RETURN_IF_ERROR(enc_handler_status);
745 handlers.emplace_back(segment_coordinator);
748 replicator = std::make_shared<Replicator>();
749 handlers.emplace_back(replicator);
751 RETURN_IF_ERROR(MediaHandler::Chain(handlers));
752 RETURN_IF_ERROR(demuxer->SetHandler(stream.stream_selector, handlers[0]));
756 const auto output_format = GetOutputFormat(stream);
757 std::shared_ptr<Muxer> muxer =
758 muxer_factory->CreateMuxer(output_format, stream);
760 return Status(error::INVALID_ARGUMENT,
"Failed to create muxer for " +
762 stream.stream_selector);
765 std::unique_ptr<MuxerListener> muxer_listener =
766 muxer_listener_factory->CreateListener(ToMuxerListenerData(stream));
767 muxer->SetMuxerListener(std::move(muxer_listener));
769 std::vector<std::shared_ptr<MediaHandler>> handlers;
770 handlers.emplace_back(replicator);
773 if (stream.trick_play_factor) {
774 handlers.emplace_back(
775 std::make_shared<TrickPlayHandler>(stream.trick_play_factor));
778 if (stream.cc_index >= 0) {
779 handlers.emplace_back(
780 std::make_shared<CcStreamFilter>(stream.language, stream.cc_index));
784 (!stream.segment_template.empty() || output_format == CONTAINER_MOV)) {
786 bool use_coordinator = is_teletext;
787 handlers.emplace_back(
788 CreateTextChunker(packaging_params.chunking_params, use_coordinator));
791 if (is_text && output_format == CONTAINER_MOV) {
792 const auto output_codec = GetTextOutputCodec(stream);
793 if (output_codec == CONTAINER_WEBVTT) {
794 handlers.emplace_back(std::make_shared<WebVttToMp4Handler>());
795 }
else if (output_codec == CONTAINER_TTML) {
796 handlers.emplace_back(std::make_shared<ttml::TtmlToMp4Handler>());
800 handlers.emplace_back(muxer);
801 RETURN_IF_ERROR(MediaHandler::Chain(handlers));
807Status CreateAllJobs(
const std::vector<StreamDescriptor>& stream_descriptors,
808 const PackagingParams& packaging_params,
809 MpdNotifier* mpd_notifier,
810 KeySource* encryption_key_source,
811 SyncPointQueue* sync_points,
812 MuxerListenerFactory* muxer_listener_factory,
813 MuxerFactory* muxer_factory,
814 JobManager* job_manager) {
815 DCHECK(muxer_factory);
816 DCHECK(muxer_listener_factory);
820 std::vector<std::reference_wrapper<const StreamDescriptor>> ttml_streams;
821 std::vector<std::reference_wrapper<const StreamDescriptor>>
824 bool has_transport_audio_video_streams =
false;
825 bool has_non_transport_audio_video_streams =
false;
827 for (
const StreamDescriptor& stream : stream_descriptors) {
828 const auto input_container = DetermineContainerFromFileName(stream.input);
829 const auto output_format = GetOutputFormat(stream);
830 if (input_container == CONTAINER_TTML) {
831 ttml_streams.push_back(stream);
833 audio_video_streams.push_back(stream);
834 switch (output_format) {
835 case CONTAINER_MPEG2TS:
840 has_transport_audio_video_streams =
true;
843 case CONTAINER_WEBVTT:
846 has_non_transport_audio_video_streams =
true;
854 std::sort(audio_video_streams.begin(), audio_video_streams.end(),
855 media::StreamDescriptorCompareFn);
857 if (packaging_params.transport_stream_timestamp_offset_ms > 0) {
858 if (has_transport_audio_video_streams &&
859 has_non_transport_audio_video_streams) {
860 LOG(WARNING) <<
"There may be problems mixing transport streams and "
861 "non-transport streams. For example, the subtitles may "
862 "be out of sync with non-transport streams.";
863 }
else if (has_non_transport_audio_video_streams) {
866 muxer_factory->SetTsStreamOffset(0);
870 RETURN_IF_ERROR(CreateTtmlJobs(ttml_streams, packaging_params, sync_points,
871 muxer_factory, mpd_notifier, job_manager));
872 RETURN_IF_ERROR(CreateAudioVideoJobs(
873 audio_video_streams, packaging_params, encryption_key_source, sync_points,
874 muxer_listener_factory, muxer_factory, job_manager));
877 return job_manager->InitializeJobs();
883struct Packager::PackagerInternal {
884 std::shared_ptr<media::FakeClock> fake_clock;
885 std::unique_ptr<KeySource> encryption_key_source;
886 std::unique_ptr<MpdNotifier> mpd_notifier;
887 std::unique_ptr<hls::HlsNotifier> hls_notifier;
888 BufferCallbackParams buffer_callback_params;
889 std::unique_ptr<media::JobManager> job_manager;
892Packager::Packager() {}
894Packager::~Packager() {}
896Status Packager::Initialize(
897 const PackagingParams& packaging_params,
898 const std::vector<StreamDescriptor>& stream_descriptors) {
900 return Status(error::INVALID_ARGUMENT,
"Already initialized.");
902 RETURN_IF_ERROR(media::ValidateParams(packaging_params, stream_descriptors));
904 if (!packaging_params.test_params.injected_library_version.empty()) {
905 SetPackagerVersionForTesting(
906 packaging_params.test_params.injected_library_version);
909 std::unique_ptr<PackagerInternal> internal(
new PackagerInternal);
912 if (packaging_params.encryption_params.key_provider != KeyProvider::kNone) {
913 internal->encryption_key_source = CreateEncryptionKeySource(
914 static_cast<media::FourCC
>(
915 packaging_params.encryption_params.protection_scheme),
916 packaging_params.encryption_params);
917 if (!internal->encryption_key_source)
918 return Status(error::INVALID_ARGUMENT,
"Failed to create key source.");
922 MpdParams mpd_params = packaging_params.mpd_params;
923 HlsParams hls_params = packaging_params.hls_params;
927 const double target_segment_duration =
928 packaging_params.chunking_params.segment_duration_in_seconds;
929 mpd_params.target_segment_duration = target_segment_duration;
930 hls_params.target_segment_duration = target_segment_duration;
933 internal->buffer_callback_params = packaging_params.buffer_callback_params;
934 if (internal->buffer_callback_params.write_func) {
935 mpd_params.mpd_output = File::MakeCallbackFileName(
936 internal->buffer_callback_params, mpd_params.mpd_output);
937 hls_params.master_playlist_output = File::MakeCallbackFileName(
938 internal->buffer_callback_params, hls_params.master_playlist_output);
944 mpd_params.default_language =
946 mpd_params.default_text_language =
948 hls_params.default_language =
950 hls_params.default_text_language =
952 hls_params.is_independent_segments =
953 packaging_params.chunking_params.segment_sap_aligned;
955 for (
const auto& caption : packaging_params.closed_captions) {
956 CeaCaption dash_caption = caption;
958 mpd_params.closed_captions.push_back(dash_caption);
960 CeaCaption hls_caption = caption;
962 hls_params.closed_captions.push_back(hls_caption);
965 if (!mpd_params.mpd_output.empty()) {
966 const bool on_demand_dash_profile =
967 stream_descriptors.begin()->segment_template.empty();
968 const MpdOptions mpd_options =
969 media::GetMpdOptions(on_demand_dash_profile, mpd_params);
970 internal->mpd_notifier.reset(
new SimpleMpdNotifier(mpd_options));
971 if (!internal->mpd_notifier->Init()) {
972 LOG(ERROR) <<
"MpdNotifier failed to initialize.";
973 return Status(error::INVALID_ARGUMENT,
974 "Failed to initialize MpdNotifier.");
978 if (!hls_params.master_playlist_output.empty()) {
979 internal->hls_notifier.reset(
new hls::SimpleHlsNotifier(hls_params));
982 std::unique_ptr<SyncPointQueue> sync_points;
983 if (!packaging_params.ad_cue_generator_params.cue_points.empty()) {
985 new SyncPointQueue(packaging_params.ad_cue_generator_params));
987 if (packaging_params.single_threaded) {
988 internal->job_manager.reset(
989 new SingleThreadJobManager(std::move(sync_points)));
991 internal->job_manager.reset(
new JobManager(std::move(sync_points)));
994 std::vector<StreamDescriptor> streams_for_jobs;
996 for (
const StreamDescriptor& descriptor : stream_descriptors) {
998 StreamDescriptor copy = descriptor;
1000 if (internal->buffer_callback_params.read_func) {
1001 copy.input = File::MakeCallbackFileName(internal->buffer_callback_params,
1005 if (internal->buffer_callback_params.write_func) {
1006 copy.output = File::MakeCallbackFileName(internal->buffer_callback_params,
1008 copy.segment_template = File::MakeCallbackFileName(
1009 internal->buffer_callback_params, descriptor.segment_template);
1013 if (!copy.language.empty()) {
1015 if (copy.language ==
"und") {
1017 error::INVALID_ARGUMENT,
1018 "Unknown/invalid language specified: " + descriptor.language);
1022 streams_for_jobs.push_back(copy);
1025 media::MuxerFactory muxer_factory(packaging_params);
1026 if (packaging_params.test_params.inject_fake_clock) {
1027 internal->fake_clock.reset(
new media::FakeClock());
1028 muxer_factory.OverrideClock(internal->fake_clock);
1031 media::MuxerListenerFactory muxer_listener_factory(
1032 packaging_params.output_media_info,
1033 packaging_params.mpd_params.use_segment_list,
1034 internal->mpd_notifier.get(), internal->hls_notifier.get());
1036 RETURN_IF_ERROR(media::CreateAllJobs(
1037 streams_for_jobs, packaging_params, internal->mpd_notifier.get(),
1038 internal->encryption_key_source.get(),
1039 internal->job_manager->sync_points(), &muxer_listener_factory,
1040 &muxer_factory, internal->job_manager.get()));
1042 internal_ = std::move(internal);
1046Status Packager::Run() {
1048 return Status(error::INVALID_ARGUMENT,
"Not yet initialized.");
1050 RETURN_IF_ERROR(internal_->job_manager->RunJobs());
1052 if (internal_->hls_notifier) {
1053 if (!internal_->hls_notifier->Flush())
1054 return Status(error::INVALID_ARGUMENT,
"Failed to flush Hls.");
1056 if (internal_->mpd_notifier) {
1057 if (!internal_->mpd_notifier->Flush())
1058 return Status(error::INVALID_ARGUMENT,
"Failed to flush Mpd.");
1063void Packager::Cancel() {
1065 LOG(INFO) <<
"Not yet initialized. Return directly.";
1068 internal_->job_manager->CancelJobs();
1071std::string Packager::GetLibraryVersion() {
1072 return GetPackagerVersion();
1075std::string Packager::DefaultStreamLabelFunction(
1078 int max_uhd1_pixels,
1079 const EncryptionParams::EncryptedStreamAttributes& stream_attributes) {
1080 if (stream_attributes.stream_type ==
1081 EncryptionParams::EncryptedStreamAttributes::kAudio)
1083 if (stream_attributes.stream_type ==
1084 EncryptionParams::EncryptedStreamAttributes::kVideo) {
1085 const int pixels = stream_attributes.oneof.video.width *
1086 stream_attributes.oneof.video.height;
1087 if (pixels <= max_sd_pixels)
1089 if (pixels <= max_hd_pixels)
1091 if (pixels <= max_uhd1_pixels)
All the methods that are virtual are virtual for mocking.
std::string LanguageToISO_639_2(const std::string &language)
std::string LanguageToShortestForm(const std::string &language)