7 #include "packager/packager.h"
11 #include "packager/app/libcrypto_threading.h"
12 #include "packager/app/packager_util.h"
13 #include "packager/app/stream_descriptor.h"
14 #include "packager/base/at_exit.h"
15 #include "packager/base/files/file_path.h"
16 #include "packager/base/logging.h"
17 #include "packager/base/path_service.h"
18 #include "packager/base/strings/stringprintf.h"
19 #include "packager/base/threading/simple_thread.h"
20 #include "packager/base/time/clock.h"
21 #include "packager/file/file.h"
22 #include "packager/hls/base/hls_notifier.h"
23 #include "packager/hls/base/simple_hls_notifier.h"
24 #include "packager/media/base/container_names.h"
25 #include "packager/media/base/fourccs.h"
26 #include "packager/media/base/key_source.h"
27 #include "packager/media/base/language_utils.h"
28 #include "packager/media/base/muxer_options.h"
29 #include "packager/media/base/muxer_util.h"
30 #include "packager/media/chunking/chunking_handler.h"
31 #include "packager/media/crypto/encryption_handler.h"
32 #include "packager/media/demuxer/demuxer.h"
33 #include "packager/media/event/combined_muxer_listener.h"
34 #include "packager/media/event/hls_notify_muxer_listener.h"
35 #include "packager/media/event/mpd_notify_muxer_listener.h"
36 #include "packager/media/event/vod_media_info_dump_muxer_listener.h"
37 #include "packager/media/formats/mp2t/ts_muxer.h"
38 #include "packager/media/formats/mp4/mp4_muxer.h"
39 #include "packager/media/formats/webm/webm_muxer.h"
40 #include "packager/media/replicator/replicator.h"
41 #include "packager/media/trick_play/trick_play_handler.h"
42 #include "packager/mpd/base/dash_iop_mpd_notifier.h"
43 #include "packager/mpd/base/media_info.pb.h"
44 #include "packager/mpd/base/mpd_builder.h"
45 #include "packager/mpd/base/simple_mpd_notifier.h"
46 #include "packager/version/version.h"
52 using media::KeySource;
53 using media::MuxerOptions;
58 const char kMediaInfoSuffix[] =
".media_info";
63 std::string DetermineTextFileFormat(
const std::string& file) {
66 LOG(ERROR) <<
"Failed to open file " << file
67 <<
" to determine file format.";
70 MediaContainerName container_name = DetermineContainer(
71 reinterpret_cast<const uint8_t*>(content.data()), content.size());
72 if (container_name == CONTAINER_WEBVTT) {
74 }
else if (container_name == CONTAINER_TTML) {
81 MediaContainerName GetOutputFormat(
const StreamDescriptor& descriptor) {
82 MediaContainerName output_format = CONTAINER_UNKNOWN;
83 if (!descriptor.output_format.empty()) {
84 output_format = DetermineContainerFromFormatName(descriptor.output_format);
85 if (output_format == CONTAINER_UNKNOWN) {
86 LOG(ERROR) <<
"Unable to determine output format from '"
87 << descriptor.output_format <<
"'.";
90 const std::string& output_name = descriptor.output.empty()
91 ? descriptor.segment_template
93 if (output_name.empty())
94 return CONTAINER_UNKNOWN;
95 output_format = DetermineContainerFromFileName(output_name);
96 if (output_format == CONTAINER_UNKNOWN) {
97 LOG(ERROR) <<
"Unable to determine output format from '" << output_name
101 return output_format;
104 Status ValidateStreamDescriptor(
bool dump_stream_info,
105 const StreamDescriptor& stream) {
106 if (stream.input.empty()) {
107 return Status(error::INVALID_ARGUMENT,
"Stream input not specified.");
112 if (dump_stream_info && stream.output.empty() &&
113 stream.segment_template.empty()) {
117 if (stream.output.empty() && stream.segment_template.empty()) {
118 return Status(error::INVALID_ARGUMENT,
119 "Streams must specify 'output' or 'segment template'.");
123 if (stream.stream_selector.empty()) {
124 return Status(error::INVALID_ARGUMENT,
125 "Stream stream_selector not specified.");
129 if (stream.segment_template.length()) {
130 Status template_check = ValidateSegmentTemplate(stream.segment_template);
131 if (!template_check.ok()) {
132 return template_check;
138 const MediaContainerName output_format = GetOutputFormat(stream);
140 if (output_format == CONTAINER_UNKNOWN) {
141 return Status(error::INVALID_ARGUMENT,
"Unsupported output format.");
142 }
else if (output_format == MediaContainerName::CONTAINER_MPEG2TS) {
143 if (stream.segment_template.empty()) {
144 return Status(error::INVALID_ARGUMENT,
145 "Please specify segment_template. Single file TS output is "
152 if (stream.output.length()) {
153 return Status(error::INVALID_ARGUMENT,
154 "All TS segments must be self-initializing. Stream "
155 "descriptors 'output' or 'init_segment' are not allowed.");
160 if (stream.segment_template.length() && stream.output.empty()) {
161 return Status(error::INVALID_ARGUMENT,
162 "Please specify 'init_segment'. All non-TS multi-segment "
163 "content must provide an init segment.");
170 Status ValidateParams(
const PackagingParams& packaging_params,
171 const std::vector<StreamDescriptor>& stream_descriptors) {
172 if (!packaging_params.chunking_params.segment_sap_aligned &&
173 packaging_params.chunking_params.subsegment_sap_aligned) {
174 return Status(error::INVALID_ARGUMENT,
175 "Setting segment_sap_aligned to false but "
176 "subsegment_sap_aligned to true is not allowed.");
179 if (stream_descriptors.empty()) {
180 return Status(error::INVALID_ARGUMENT,
181 "Stream descriptors cannot be empty.");
186 const bool on_demand_dash_profile =
187 stream_descriptors.begin()->segment_template.empty();
188 for (
const auto& descriptor : stream_descriptors) {
189 if (on_demand_dash_profile != descriptor.segment_template.empty()) {
190 return Status(error::INVALID_ARGUMENT,
191 "Inconsistent stream descriptor specification: "
192 "segment_template should be specified for none or all "
193 "stream descriptors.");
196 Status stream_check = ValidateStreamDescriptor(
197 packaging_params.test_params.dump_stream_info, descriptor);
199 if (!stream_check.ok()) {
204 if (packaging_params.output_media_info && !on_demand_dash_profile) {
206 return Status(error::UNIMPLEMENTED,
207 "--output_media_info is only supported for on-demand profile "
208 "(not using segment_template).");
214 bool StreamDescriptorCompareFn(
const StreamDescriptor& a,
215 const StreamDescriptor& b) {
216 if (a.input == b.input) {
217 if (a.stream_selector == b.stream_selector) {
220 if (a.trick_play_factor == 0 || b.trick_play_factor == 0) {
221 return a.trick_play_factor == 0;
223 return a.trick_play_factor > b.trick_play_factor;
226 return a.stream_selector < b.stream_selector;
230 return a.input < b.input;
235 class FakeClock :
public base::Clock {
237 base::Time Now()
override {
return base::Time(); }
240 class Job :
public base::SimpleThread {
242 Job(
const std::string& name, std::shared_ptr<OriginHandler> work)
243 : SimpleThread(name),
245 wait_(base::WaitableEvent::ResetPolicy::MANUAL,
246 base::WaitableEvent::InitialState::NOT_SIGNALED) {}
250 status_ = work_->Initialize();
258 const Status& status()
const {
return status_; }
260 base::WaitableEvent* wait() {
return &wait_; }
263 Job(
const Job&) =
delete;
264 Job& operator=(
const Job&) =
delete;
266 void Run()
override {
268 status_ = work_->Run();
272 std::shared_ptr<OriginHandler> work_;
275 base::WaitableEvent wait_;
278 bool StreamInfoToTextMediaInfo(
const StreamDescriptor& stream_descriptor,
279 MediaInfo* text_media_info) {
280 const std::string& language = stream_descriptor.language;
281 const std::string format = DetermineTextFileFormat(stream_descriptor.input);
282 if (format.empty()) {
283 LOG(ERROR) <<
"Failed to determine the text file format for "
284 << stream_descriptor.input;
288 if (!
File::Copy(stream_descriptor.input.c_str(),
289 stream_descriptor.output.c_str())) {
290 LOG(ERROR) <<
"Failed to copy the input file (" << stream_descriptor.input
291 <<
") to output file (" << stream_descriptor.output <<
").";
295 text_media_info->set_media_file_name(stream_descriptor.output);
296 text_media_info->set_container_type(MediaInfo::CONTAINER_TEXT);
298 if (stream_descriptor.bandwidth != 0) {
299 text_media_info->set_bandwidth(stream_descriptor.bandwidth);
304 const int kDefaultTextBandwidth = 256;
305 text_media_info->set_bandwidth(kDefaultTextBandwidth);
308 MediaInfo::TextInfo* text_info = text_media_info->mutable_text_info();
309 text_info->set_format(format);
310 if (!language.empty())
311 text_info->set_language(language);
316 std::unique_ptr<MuxerListener> CreateMuxerListener(
317 const StreamDescriptor& stream,
319 bool output_media_info,
320 MpdNotifier* mpd_notifier,
321 hls::HlsNotifier* hls_notifier) {
322 std::unique_ptr<CombinedMuxerListener> combined_listener(
323 new CombinedMuxerListener);
325 if (output_media_info) {
326 std::unique_ptr<MuxerListener> listener(
327 new VodMediaInfoDumpMuxerListener(stream.output + kMediaInfoSuffix));
328 combined_listener->AddListener(std::move(listener));
332 std::unique_ptr<MuxerListener> listener(
333 new MpdNotifyMuxerListener(mpd_notifier));
334 combined_listener->AddListener(std::move(listener));
340 std::string group_id = stream.hls_group_id;
341 std::string name = stream.hls_name;
342 std::string hls_playlist_name = stream.hls_playlist_name;
343 if (group_id.empty())
346 name = base::StringPrintf(
"stream_%d", stream_number);
347 if (hls_playlist_name.empty())
348 hls_playlist_name = base::StringPrintf(
"stream_%d.m3u8", stream_number);
350 std::unique_ptr<MuxerListener> listener(
new HlsNotifyMuxerListener(
351 hls_playlist_name, name, group_id, hls_notifier));
352 combined_listener->AddListener(std::move(listener));
355 return std::move(combined_listener);
358 std::shared_ptr<Muxer> CreateMuxer(
const PackagingParams& packaging_params,
359 const StreamDescriptor& stream,
361 std::unique_ptr<MuxerListener> listener) {
362 const MediaContainerName format = GetOutputFormat(stream);
364 MuxerOptions options;
365 options.mp4_params = packaging_params.mp4_output_params;
366 options.temp_dir = packaging_params.temp_dir;
367 options.bandwidth = stream.bandwidth;
368 options.output_file_name = stream.output;
369 options.segment_template = stream.segment_template;
371 std::shared_ptr<Muxer> muxer;
375 muxer = std::make_shared<webm::WebMMuxer>(options);
377 case CONTAINER_MPEG2TS:
378 muxer = std::make_shared<mp2t::TsMuxer>(options);
381 muxer = std::make_shared<mp4::MP4Muxer>(options);
384 LOG(ERROR) <<
"Cannot support muxing to " << format;
395 muxer->set_clock(clock);
399 muxer->SetMuxerListener(std::move(listener));
405 std::shared_ptr<MediaHandler> CreateEncryptionHandler(
406 const PackagingParams& packaging_params,
407 const StreamDescriptor& stream,
408 KeySource* key_source) {
409 if (stream.skip_encryption) {
418 EncryptionParams encryption_params = packaging_params.encryption_params;
423 if (GetOutputFormat(stream) == CONTAINER_MPEG2TS) {
424 VLOG(1) <<
"Use Apple Sample AES encryption for MPEG2TS.";
425 encryption_params.protection_scheme = kAppleSampleAesProtectionScheme;
428 if (!stream.drm_label.empty()) {
429 const std::string& drm_label = stream.drm_label;
430 encryption_params.stream_label_func =
431 [drm_label](
const EncryptionParams::EncryptedStreamAttributes&) {
434 }
else if (!encryption_params.stream_label_func) {
435 const int kDefaultMaxSdPixels = 768 * 576;
436 const int kDefaultMaxHdPixels = 1920 * 1080;
437 const int kDefaultMaxUhd1Pixels = 4096 * 2160;
438 encryption_params.stream_label_func = std::bind(
440 kDefaultMaxHdPixels, kDefaultMaxUhd1Pixels, std::placeholders::_1);
443 return std::make_shared<EncryptionHandler>(encryption_params, key_source);
446 Status CreateTextJobs(
447 int first_stream_number,
448 const std::vector<std::reference_wrapper<const StreamDescriptor>>& streams,
449 const PackagingParams& packaging_params,
450 MpdNotifier* mpd_notifier,
451 std::vector<std::unique_ptr<Job>>* jobs) {
454 int stream_number = first_stream_number - 1;
456 for (
const StreamDescriptor& stream : streams) {
459 const MediaContainerName output_format = GetOutputFormat(stream);
461 if (output_format == CONTAINER_MOV) {
466 MediaInfo text_media_info;
467 if (!StreamInfoToTextMediaInfo(stream, &text_media_info)) {
468 return Status(error::INVALID_ARGUMENT,
469 "Could not create media info for stream.");
474 if (mpd_notifier->NotifyNewContainer(text_media_info, &unused)) {
475 mpd_notifier->Flush();
477 return Status(error::PARSER_FAILURE,
478 "Failed to process text file " + stream.input);
482 if (packaging_params.output_media_info) {
484 text_media_info, stream.output + kMediaInfoSuffix);
492 Status CreateAudioVideoJobs(
493 int first_stream_number,
494 const std::vector<std::reference_wrapper<const StreamDescriptor>>& streams,
495 const PackagingParams& packaging_params,
496 FakeClock* fake_clock,
497 KeySource* encryption_key_source,
498 MpdNotifier* mpd_notifier,
499 hls::HlsNotifier* hls_notifier,
500 std::vector<std::unique_ptr<Job>>* jobs) {
504 std::shared_ptr<Demuxer> demuxer;
507 std::shared_ptr<MediaHandler> replicator;
509 std::string previous_input;
510 std::string previous_selector;
514 int stream_number = first_stream_number - 1;
516 for (
const StreamDescriptor& stream : streams) {
520 if (previous_input != stream.input) {
521 demuxer = std::make_shared<Demuxer>(stream.input);
523 demuxer->set_dump_stream_info(
524 packaging_params.test_params.dump_stream_info);
525 if (packaging_params.decryption_params.key_provider !=
526 KeyProvider::kNone) {
527 std::unique_ptr<KeySource> decryption_key_source(
528 CreateDecryptionKeySource(packaging_params.decryption_params));
529 if (!decryption_key_source) {
531 error::INVALID_ARGUMENT,
532 "Must define decryption key source when defining key provider");
534 demuxer->SetKeySource(std::move(decryption_key_source));
537 jobs->emplace_back(
new media::Job(
"RemuxJob", demuxer));
540 if (!stream.language.empty()) {
541 demuxer->SetLanguageOverride(stream.stream_selector, stream.language);
544 const bool new_source = previous_input != stream.input ||
545 previous_selector != stream.stream_selector;
546 previous_input = stream.input;
547 previous_selector = stream.stream_selector;
551 if (stream.output.empty() && stream.segment_template.empty()) {
556 replicator = std::make_shared<Replicator>();
558 std::shared_ptr<MediaHandler> chunker =
559 std::make_shared<ChunkingHandler>(packaging_params.chunking_params);
561 std::shared_ptr<MediaHandler> encryptor = CreateEncryptionHandler(
562 packaging_params, stream, encryption_key_source);
570 status.Update(demuxer->SetHandler(stream.stream_selector, chunker));
571 status.Update(chunker->AddHandler(encryptor));
572 status.Update(encryptor->AddHandler(replicator));
574 status.Update(demuxer->SetHandler(stream.stream_selector, chunker));
575 status.Update(chunker->AddHandler(replicator));
582 if (!stream.language.empty()) {
583 demuxer->SetLanguageOverride(stream.stream_selector, stream.language);
588 std::unique_ptr<MuxerListener> muxer_listener = CreateMuxerListener(
589 stream, stream_number, packaging_params.output_media_info, mpd_notifier,
591 std::shared_ptr<Muxer> muxer = CreateMuxer(
592 packaging_params, stream,
593 packaging_params.test_params.inject_fake_clock ? fake_clock :
nullptr,
594 std::move(muxer_listener));
597 return Status(error::INVALID_ARGUMENT,
"Failed to create muxer for " +
599 stream.stream_selector);
602 std::shared_ptr<MediaHandler> trick_play;
603 if (stream.trick_play_factor) {
604 trick_play = std::make_shared<TrickPlayHandler>(stream.trick_play_factor);
609 status.Update(replicator->AddHandler(trick_play));
610 status.Update(trick_play->AddHandler(muxer));
612 status.Update(replicator->AddHandler(muxer));
623 Status CreateAllJobs(
const std::vector<StreamDescriptor>& stream_descriptors,
624 const PackagingParams& packaging_params,
625 FakeClock* fake_clock,
626 KeySource* encryption_key_source,
627 MpdNotifier* mpd_notifier,
628 hls::HlsNotifier* hls_notifier,
629 std::vector<std::unique_ptr<Job>>* jobs) {
633 std::vector<std::reference_wrapper<const StreamDescriptor>> text_streams;
634 std::vector<std::reference_wrapper<const StreamDescriptor>>
637 for (
const StreamDescriptor& stream : stream_descriptors) {
641 if (stream.stream_selector ==
"text") {
642 text_streams.push_back(stream);
644 audio_video_streams.push_back(stream);
650 std::sort(audio_video_streams.begin(), audio_video_streams.end(),
651 media::StreamDescriptorCompareFn);
653 int stream_number = 0;
657 status.Update(CreateTextJobs(stream_number, text_streams, packaging_params,
658 mpd_notifier, jobs));
660 stream_number += text_streams.size();
662 status.Update(CreateAudioVideoJobs(
663 stream_number, audio_video_streams, packaging_params, fake_clock,
664 encryption_key_source, mpd_notifier, hls_notifier, jobs));
671 for (
const std::unique_ptr<Job>& job : *jobs) {
673 status.Update(job->status());
679 Status RunJobs(
const std::vector<std::unique_ptr<Job>>& jobs) {
685 std::vector<Job*> active_jobs;
686 std::vector<base::WaitableEvent*> active_waits;
690 for (
auto& job : jobs) {
693 active_jobs.push_back(job.get());
694 active_waits.push_back(job->wait());
699 while (status.ok() && active_jobs.size()) {
703 base::WaitableEvent::WaitMany(active_waits.data(), active_waits.size());
704 Job* job = active_jobs[done];
707 status.Update(job->status());
710 active_jobs.erase(active_jobs.begin() + done);
711 active_waits.erase(active_waits.begin() + done);
716 for (
auto& job : active_jobs) {
720 for (
auto& job : active_jobs) {
730 struct Packager::PackagerInternal {
731 media::FakeClock fake_clock;
732 std::unique_ptr<KeySource> encryption_key_source;
733 std::unique_ptr<MpdNotifier> mpd_notifier;
734 std::unique_ptr<hls::HlsNotifier> hls_notifier;
735 std::vector<std::unique_ptr<media::Job>> jobs;
736 BufferCallbackParams buffer_callback_params;
739 Packager::Packager() {}
741 Packager::~Packager() {}
745 const std::vector<StreamDescriptor>& stream_descriptors) {
747 static base::AtExitManager exit;
751 return Status(error::INVALID_ARGUMENT,
"Already initialized.");
754 media::ValidateParams(packaging_params, stream_descriptors);
755 if (!param_check.ok()) {
760 SetPackagerVersionForTesting(
764 std::unique_ptr<PackagerInternal>
internal(
new PackagerInternal);
768 internal->encryption_key_source = CreateEncryptionKeySource(
769 static_cast<media::FourCC>(
772 if (!internal->encryption_key_source)
773 return Status(error::INVALID_ARGUMENT,
"Failed to create key source.");
782 if (internal->buffer_callback_params.write_func) {
784 internal->buffer_callback_params, mpd_params.
mpd_output);
790 const bool on_demand_dash_profile =
791 stream_descriptors.begin()->segment_template.empty();
793 media::GetMpdOptions(on_demand_dash_profile, mpd_params);
799 if (!internal->mpd_notifier->Init()) {
800 LOG(ERROR) <<
"MpdNotifier failed to initialize.";
801 return Status(error::INVALID_ARGUMENT,
802 "Failed to initialize MpdNotifier.");
807 base::FilePath master_playlist_path(
809 base::FilePath master_playlist_name = master_playlist_path.BaseName();
814 master_playlist_path.DirName().AsEndingWithSeparator().AsUTF8Unsafe(),
815 master_playlist_name.AsUTF8Unsafe()));
818 std::vector<StreamDescriptor> streams_for_jobs;
824 if (internal->buffer_callback_params.read_func) {
829 if (internal->buffer_callback_params.write_func) {
833 internal->buffer_callback_params, descriptor.segment_template);
841 error::INVALID_ARGUMENT,
842 "Unknown/invalid language specified: " + descriptor.language);
846 streams_for_jobs.push_back(copy);
849 Status status = media::CreateAllJobs(
850 streams_for_jobs, packaging_params, &internal->fake_clock,
851 internal->encryption_key_source.get(),
internal->mpd_notifier.get(),
852 internal->hls_notifier.get(), &
internal->jobs);
858 internal_ = std::move(
internal);
864 return Status(error::INVALID_ARGUMENT,
"Not yet initialized.");
865 Status status = media::RunJobs(internal_->jobs);
869 if (internal_->hls_notifier) {
870 if (!internal_->hls_notifier->Flush())
871 return Status(error::INVALID_ARGUMENT,
"Failed to flush Hls.");
873 if (internal_->mpd_notifier) {
874 if (!internal_->mpd_notifier->Flush())
875 return Status(error::INVALID_ARGUMENT,
"Failed to flush Mpd.");
882 LOG(INFO) <<
"Not yet initialized. Return directly.";
885 for (
const std::unique_ptr<media::Job>& job : internal_->jobs)
890 return GetPackagerVersion();
898 if (stream_attributes.stream_type ==
899 EncryptionParams::EncryptedStreamAttributes::kAudio)
901 if (stream_attributes.stream_type ==
902 EncryptionParams::EncryptedStreamAttributes::kVideo) {
903 const int pixels = stream_attributes.oneof.video.width *
904 stream_attributes.oneof.video.height;
905 if (pixels <= max_sd_pixels)
907 if (pixels <= max_hd_pixels)
909 if (pixels <= max_uhd1_pixels)
BufferCallbackParams buffer_callback_params
Buffer callback params.
std::string master_playlist_output
HLS master playlist output path.
DASH MPD related parameters.
Defines a single input/output stream.
std::string input
Input/source media file path or network stream URL. Required.
HlsParams hls_params
HLS related parameters.
Status Initialize(const PackagingParams &packaging_params, const std::vector< StreamDescriptor > &stream_descriptors)
static std::string DefaultStreamLabelFunction(int max_sd_pixels, int max_hd_pixels, int max_uhd1_pixels, const EncryptionParams::EncryptedStreamAttributes &stream_attributes)
std::string segment_template
Specifies segment template. Can be empty.
static bool Copy(const char *from_file_name, const char *to_file_name)
static bool ReadFileToString(const char *file_name, std::string *contents)
bool generate_dash_if_iop_compliant_mpd
Try to generate DASH-IF IOP compliant MPD.
static std::string GetLibraryVersion()
std::string LanguageToISO_639_2(const std::string &language)
std::string injected_library_version
MpdParams mpd_params
DASH MPD related parameters.
double time_shift_buffer_depth
EncryptionParams encryption_params
Encryption and Decryption Parameters.
std::string mpd_output
MPD output file path.
static std::string MakeCallbackFileName(const BufferCallbackParams &callback_params, const std::string &name)
Encrypted stream information that is used to determine stream label.
void Cancel()
Cancel packaging. Note that it has to be called from another thread.
HlsPlaylistType playlist_type
HLS playlist type. See HLS specification for details.