7 #include <gflags/gflags.h>
10 #include "packager/app/fixed_key_encryption_flags.h"
11 #include "packager/app/hls_flags.h"
12 #include "packager/app/libcrypto_threading.h"
13 #include "packager/app/mpd_flags.h"
14 #include "packager/app/muxer_flags.h"
15 #include "packager/app/packager_util.h"
16 #include "packager/app/playready_key_encryption_flags.h"
17 #include "packager/app/stream_descriptor.h"
18 #include "packager/app/vlog_flags.h"
19 #include "packager/app/widevine_encryption_flags.h"
20 #include "packager/base/at_exit.h"
21 #include "packager/base/command_line.h"
22 #include "packager/base/files/file_path.h"
23 #include "packager/base/logging.h"
24 #include "packager/base/path_service.h"
25 #include "packager/base/strings/string_split.h"
26 #include "packager/base/strings/stringprintf.h"
27 #include "packager/base/threading/simple_thread.h"
28 #include "packager/base/time/clock.h"
29 #include "packager/hls/base/hls_notifier.h"
30 #include "packager/hls/base/simple_hls_notifier.h"
31 #include "packager/media/base/container_names.h"
32 #include "packager/media/base/fourccs.h"
33 #include "packager/media/base/key_source.h"
34 #include "packager/media/base/muxer_options.h"
35 #include "packager/media/base/muxer_util.h"
36 #include "packager/media/chunking/chunking_handler.h"
37 #include "packager/media/crypto/encryption_handler.h"
38 #include "packager/media/demuxer/demuxer.h"
39 #include "packager/media/event/hls_notify_muxer_listener.h"
40 #include "packager/media/event/mpd_notify_muxer_listener.h"
41 #include "packager/media/event/vod_media_info_dump_muxer_listener.h"
42 #include "packager/media/file/file.h"
43 #include "packager/media/formats/mp2t/ts_muxer.h"
44 #include "packager/media/formats/mp4/mp4_muxer.h"
45 #include "packager/media/formats/webm/webm_muxer.h"
46 #include "packager/mpd/base/dash_iop_mpd_notifier.h"
47 #include "packager/mpd/base/media_info.pb.h"
48 #include "packager/mpd/base/mpd_builder.h"
49 #include "packager/mpd/base/simple_mpd_notifier.h"
50 #include "packager/version/version.h"
56 #endif // defined(OS_WIN)
58 DEFINE_bool(use_fake_clock_for_muxer,
60 "Set to true to use a fake clock for muxer. With this flag set, "
61 "creation time and modification time in outputs are set to 0. "
62 "Should only be used for testing.");
63 DEFINE_bool(override_version,
65 "Override packager version in the generated outputs with "
66 "--test_version if it is set to true. Should be used for "
68 DEFINE_string(test_version,
70 "Packager version for testing. Ignored if --override_version is "
71 "false. Should be used for testing only.");
78 "%s [flags] <stream_descriptor> ...\n\n"
79 " stream_descriptor consists of comma separated field_name/value pairs:\n"
80 " field_name=value,[field_name=value,]...\n"
81 " Supported field names are as follows:\n"
82 " - input (in): Required input/source media file path or network stream\n"
84 " - stream_selector (stream): Required field with value 'audio',\n"
85 " 'video', 'text', or stream number (zero based).\n"
86 " - output (out): Required output file (single file) or initialization\n"
87 " file path (multiple file).\n"
88 " - segment_template (segment): Optional value which specifies the\n"
89 " naming pattern for the segment files, and that the stream should be\n"
90 " split into multiple files. Its presence should be consistent across\n"
92 " - bandwidth (bw): Optional value which contains a user-specified\n"
93 " content bit rate for the stream, in bits/sec. If specified, this\n"
94 " value is propagated to the $Bandwidth$ template parameter for\n"
95 " segment names. If not specified, its value may be estimated.\n"
96 " - language (lang): Optional value which contains a user-specified\n"
97 " language tag. If specified, this value overrides any language\n"
98 " metadata in the input track.\n"
99 " - output_format (format): Optional value which specifies the format\n"
100 " of the output files (MP4 or WebM). If not specified, it will be\n"
101 " derived from the file extension of the output file.\n"
102 " - hls_name: Required for audio when outputting HLS.\n"
103 " name of the output stream. This is not (necessarily) the same as\n"
104 " output. This is used as the NAME attribute for EXT-X-MEDIA\n"
105 " - hls_group_id: Required for audio when outputting HLS.\n"
106 " The group ID for the output stream. For HLS this is used as the\n"
107 " GROUP-ID attribute for EXT-X-MEDIA.\n"
108 " - playlist_name: Required for HLS output.\n"
109 " Name of the playlist for the stream. Usually ends with '.m3u8'.\n";
111 const char kMediaInfoSuffix[] =
".media_info";
115 kArgumentValidationFailed,
123 std::string DetermineTextFileFormat(
const std::string& file) {
126 LOG(ERROR) <<
"Failed to open file " << file
127 <<
" to determine file format.";
130 MediaContainerName container_name = DetermineContainer(
131 reinterpret_cast<const uint8_t*>(content.data()), content.size());
132 if (container_name == CONTAINER_WEBVTT) {
134 }
else if (container_name == CONTAINER_TTML) {
145 class FakeClock :
public base::Clock {
147 base::Time Now()
override {
return base::Time(); }
151 class RemuxJob :
public base::SimpleThread {
153 RemuxJob(std::unique_ptr<Demuxer> demuxer)
154 : SimpleThread(
"RemuxJob"), demuxer_(std::move(demuxer)) {}
156 ~RemuxJob()
override {}
158 Demuxer* demuxer() {
return demuxer_.get(); }
159 Status status() {
return status_; }
162 void Run()
override {
164 status_ = demuxer_->Run();
167 std::unique_ptr<Demuxer> demuxer_;
170 DISALLOW_COPY_AND_ASSIGN(RemuxJob);
173 bool StreamInfoToTextMediaInfo(
const StreamDescriptor& stream_descriptor,
174 const MuxerOptions& stream_muxer_options,
175 MediaInfo* text_media_info) {
176 const std::string& language = stream_descriptor.language;
177 std::string format = DetermineTextFileFormat(stream_descriptor.input);
178 if (format.empty()) {
179 LOG(ERROR) <<
"Failed to determine the text file format for "
180 << stream_descriptor.input;
184 if (!
File::Copy(stream_descriptor.input.c_str(),
185 stream_muxer_options.output_file_name.c_str())) {
186 LOG(ERROR) <<
"Failed to copy the input file (" << stream_descriptor.input
187 <<
") to output file (" << stream_muxer_options.output_file_name
192 text_media_info->set_media_file_name(stream_muxer_options.output_file_name);
193 text_media_info->set_container_type(MediaInfo::CONTAINER_TEXT);
195 if (stream_muxer_options.bandwidth != 0) {
196 text_media_info->set_bandwidth(stream_muxer_options.bandwidth);
201 text_media_info->set_bandwidth(256);
204 MediaInfo::TextInfo* text_info = text_media_info->mutable_text_info();
205 text_info->set_format(format);
206 if (!language.empty())
207 text_info->set_language(language);
212 std::shared_ptr<Muxer> CreateOutputMuxer(
const MuxerOptions& options,
213 MediaContainerName container) {
214 if (container == CONTAINER_WEBM) {
215 return std::shared_ptr<Muxer>(
new webm::WebMMuxer(options));
216 }
else if (container == CONTAINER_MPEG2TS) {
217 return std::shared_ptr<Muxer>(
new mp2t::TsMuxer(options));
219 DCHECK_EQ(container, CONTAINER_MOV);
220 return std::shared_ptr<Muxer>(
new mp4::MP4Muxer(options));
224 bool CreateRemuxJobs(
const StreamDescriptorList& stream_descriptors,
225 const ChunkingOptions& chunking_options,
226 const EncryptionOptions& encryption_options,
227 const MuxerOptions& muxer_options,
228 FakeClock* fake_clock,
229 KeySource* encryption_key_source,
230 MpdNotifier* mpd_notifier,
231 hls::HlsNotifier* hls_notifier,
232 std::vector<std::unique_ptr<RemuxJob>>* remux_jobs) {
234 DCHECK(!(mpd_notifier && hls_notifier));
237 std::string previous_input;
238 int stream_number = 0;
239 for (StreamDescriptorList::const_iterator
240 stream_iter = stream_descriptors.begin();
241 stream_iter != stream_descriptors.end();
242 ++stream_iter, ++stream_number) {
244 MuxerOptions stream_muxer_options(muxer_options);
245 stream_muxer_options.output_file_name = stream_iter->output;
246 if (!stream_iter->segment_template.empty()) {
247 if (!ValidateSegmentTemplate(stream_iter->segment_template)) {
248 LOG(ERROR) <<
"ERROR: segment template with '"
249 << stream_iter->segment_template <<
"' is invalid.";
252 stream_muxer_options.segment_template = stream_iter->segment_template;
254 stream_muxer_options.bandwidth = stream_iter->bandwidth;
256 if (stream_iter->stream_selector ==
"text" &&
257 stream_iter->output_format != CONTAINER_MOV) {
258 MediaInfo text_media_info;
259 if (!StreamInfoToTextMediaInfo(*stream_iter, stream_muxer_options,
266 if (!mpd_notifier->NotifyNewContainer(text_media_info, &unused)) {
267 LOG(ERROR) <<
"Failed to process text file " << stream_iter->input;
269 mpd_notifier->Flush();
271 }
else if (FLAGS_output_media_info) {
274 stream_muxer_options.output_file_name + kMediaInfoSuffix);
277 <<
"--mpd_output or --output_media_info flags are "
278 "required for text output. Skipping manifest related output for "
279 << stream_iter->input;
284 if (stream_iter->input != previous_input) {
286 std::unique_ptr<Demuxer> demuxer(
new Demuxer(stream_iter->input));
287 demuxer->set_dump_stream_info(FLAGS_dump_stream_info);
288 if (FLAGS_enable_widevine_decryption ||
289 FLAGS_enable_fixed_key_decryption) {
290 std::unique_ptr<KeySource> decryption_key_source(
291 CreateDecryptionKeySource());
292 if (!decryption_key_source)
294 demuxer->SetKeySource(std::move(decryption_key_source));
296 remux_jobs->emplace_back(
new RemuxJob(std::move(demuxer)));
297 previous_input = stream_iter->input;
299 if (stream_iter->output.empty() && stream_iter->segment_template.empty())
302 DCHECK(!remux_jobs->empty());
304 std::shared_ptr<Muxer> muxer(
305 CreateOutputMuxer(stream_muxer_options, stream_iter->output_format));
306 if (FLAGS_use_fake_clock_for_muxer) muxer->set_clock(fake_clock);
308 std::unique_ptr<MuxerListener> muxer_listener;
309 DCHECK(!(FLAGS_output_media_info && mpd_notifier));
310 if (FLAGS_output_media_info) {
311 const std::string output_media_info_file_name =
312 stream_muxer_options.output_file_name + kMediaInfoSuffix;
313 std::unique_ptr<VodMediaInfoDumpMuxerListener>
314 vod_media_info_dump_muxer_listener(
315 new VodMediaInfoDumpMuxerListener(output_media_info_file_name));
316 muxer_listener = std::move(vod_media_info_dump_muxer_listener);
319 std::unique_ptr<MpdNotifyMuxerListener> mpd_notify_muxer_listener(
320 new MpdNotifyMuxerListener(mpd_notifier));
321 muxer_listener = std::move(mpd_notify_muxer_listener);
327 std::string group_id = stream_iter->hls_group_id;
328 std::string name = stream_iter->hls_name;
329 std::string hls_playlist_name = stream_iter->hls_playlist_name;
330 if (group_id.empty())
333 name = base::StringPrintf(
"stream_%d", stream_number);
334 if (hls_playlist_name.empty())
335 hls_playlist_name = base::StringPrintf(
"stream_%d.m3u8", stream_number);
337 muxer_listener.reset(
new HlsNotifyMuxerListener(hls_playlist_name, name,
338 group_id, hls_notifier));
342 muxer->SetMuxerListener(std::move(muxer_listener));
345 auto chunking_handler = std::make_shared<ChunkingHandler>(chunking_options);
346 if (encryption_key_source) {
347 auto new_encryption_options = encryption_options;
351 if (stream_iter->output_format == CONTAINER_MPEG2TS) {
352 LOG(INFO) <<
"Use Apple Sample AES encryption for MPEG2TS.";
353 new_encryption_options.protection_scheme =
354 kAppleSampleAesProtectionScheme;
356 auto encryption_handler = std::make_shared<EncryptionHandler>(
357 new_encryption_options, encryption_key_source);
358 status.Update(encryption_handler->SetHandler(0, std::move(muxer)));
360 chunking_handler->SetHandler(0, std::move(encryption_handler)));
362 status.Update(chunking_handler->SetHandler(0, std::move(muxer)));
365 auto* demuxer = remux_jobs->back()->demuxer();
366 const std::string& stream_selector = stream_iter->stream_selector;
367 status.Update(demuxer->SetHandler(stream_selector, chunking_handler));
370 LOG(ERROR) <<
"Failed to setup graph: " << status;
373 if (!stream_iter->language.empty())
374 demuxer->SetLanguageOverride(stream_selector, stream_iter->language);
378 for (
const std::unique_ptr<RemuxJob>& job : *remux_jobs) {
379 Status status = job->demuxer()->Initialize();
381 LOG(ERROR) <<
"Failed to initialize processing graph " << status;
388 Status RunRemuxJobs(
const std::vector<std::unique_ptr<RemuxJob>>& remux_jobs) {
390 for (
const std::unique_ptr<RemuxJob>& job : remux_jobs)
398 for (
const std::unique_ptr<RemuxJob>& job : remux_jobs) {
399 if (job->HasBeenJoined()) {
400 status = job->status();
408 }
while (!all_joined && status.ok());
413 bool RunPackager(
const StreamDescriptorList& stream_descriptors) {
414 if (FLAGS_output_media_info && !FLAGS_mpd_output.empty()) {
415 NOTIMPLEMENTED() <<
"ERROR: --output_media_info and --mpd_output do not "
422 if (!FLAGS_mpd_output.empty() && !FLAGS_hls_master_playlist_output.empty()) {
423 LOG(ERROR) <<
"Cannot output both MPD and HLS.";
427 ChunkingOptions chunking_options = GetChunkingOptions();
428 EncryptionOptions encryption_options = GetEncryptionOptions();
430 MuxerOptions muxer_options = GetMuxerOptions();
432 DCHECK(!stream_descriptors.empty());
435 const bool on_demand_dash_profile =
436 stream_descriptors.begin()->segment_template.empty();
437 for (
const auto& stream_descriptor : stream_descriptors) {
438 if (on_demand_dash_profile != stream_descriptor.segment_template.empty()) {
439 LOG(ERROR) <<
"Inconsistent stream descriptor specification: "
440 "segment_template should be specified for none or all "
441 "stream descriptors.";
445 if (FLAGS_output_media_info && !on_demand_dash_profile) {
447 NOTIMPLEMENTED() <<
"ERROR: --output_media_info is only supported for "
448 "on-demand profile (not using segment_template).";
452 MpdOptions mpd_options = GetMpdOptions(on_demand_dash_profile);
455 std::unique_ptr<KeySource> encryption_key_source;
456 if (FLAGS_enable_widevine_encryption || FLAGS_enable_fixed_key_encryption ||
457 FLAGS_enable_playready_encryption) {
458 if (encryption_options.protection_scheme == FOURCC_NULL)
460 encryption_key_source = CreateEncryptionKeySource();
461 if (!encryption_key_source)
465 std::unique_ptr<MpdNotifier> mpd_notifier;
466 if (!FLAGS_mpd_output.empty()) {
467 std::vector<std::string> base_urls = base::SplitString(
468 FLAGS_base_urls,
",", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
469 if (FLAGS_generate_dash_if_iop_compliant_mpd) {
471 new DashIopMpdNotifier(mpd_options, base_urls, FLAGS_mpd_output));
474 new SimpleMpdNotifier(mpd_options, base_urls, FLAGS_mpd_output));
476 if (!mpd_notifier->Init()) {
477 LOG(ERROR) <<
"MpdNotifier failed to initialize.";
482 std::unique_ptr<hls::HlsNotifier> hls_notifier;
483 if (!FLAGS_hls_master_playlist_output.empty()) {
484 base::FilePath master_playlist_path(
485 base::FilePath::FromUTF8Unsafe(FLAGS_hls_master_playlist_output));
486 base::FilePath master_playlist_name = master_playlist_path.BaseName();
488 hls_notifier.reset(
new hls::SimpleHlsNotifier(
489 hls::HlsNotifier::HlsProfile::kOnDemandProfile, FLAGS_hls_base_url,
490 master_playlist_path.DirName().AsEndingWithSeparator().AsUTF8Unsafe(),
491 master_playlist_name.AsUTF8Unsafe()));
494 std::vector<std::unique_ptr<RemuxJob>> remux_jobs;
495 FakeClock fake_clock;
496 if (!CreateRemuxJobs(stream_descriptors, chunking_options, encryption_options,
497 muxer_options, &fake_clock, encryption_key_source.get(),
498 mpd_notifier.get(), hls_notifier.get(), &remux_jobs)) {
502 Status status = RunRemuxJobs(remux_jobs);
504 LOG(ERROR) <<
"Packaging Error: " << status.ToString();
509 if (!hls_notifier->Flush())
513 if (!mpd_notifier->Flush())
517 printf(
"Packaging completed successfully.\n");
521 int PackagerMain(
int argc,
char** argv) {
522 base::AtExitManager exit;
524 base::CommandLine::Init(argc, argv);
527 logging::LoggingSettings log_settings;
528 log_settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
529 CHECK(logging::InitLogging(log_settings));
531 google::SetVersionString(GetPackagerVersion());
532 google::SetUsageMessage(base::StringPrintf(kUsage, argv[0]));
533 google::ParseCommandLineFlags(&argc, &argv,
true);
535 google::ShowUsageWithFlags(
"Usage");
541 return kArgumentValidationFailed;
544 if (FLAGS_override_version)
545 SetPackagerVersionForTesting(FLAGS_test_version);
547 LibcryptoThreading libcrypto_threading;
550 StreamDescriptorList stream_descriptors;
551 for (
int i = 1; i < argc; ++i) {
552 if (!InsertStreamDescriptor(argv[i], &stream_descriptors))
553 return kArgumentValidationFailed;
555 return RunPackager(stream_descriptors) ? kSuccess : kPackagingFailed;
563 int wmain(
int argc,
wchar_t* argv[],
wchar_t* envp[]) {
564 std::unique_ptr<char* [], std::function<void(char**)>> utf8_argv(
565 new char*[argc], [argc](
char** utf8_args) {
573 std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
574 for (
int idx = 0; idx < argc; ++idx) {
575 std::string utf8_arg(converter.to_bytes(argv[idx]));
577 utf8_argv[idx] =
new char[utf8_arg.size()];
578 memcpy(utf8_argv[idx], &utf8_arg[0], utf8_arg.size());
580 return shaka::media::PackagerMain(argc, utf8_argv.get());
583 int main(
int argc,
char** argv) {
584 return shaka::media::PackagerMain(argc, argv);
586 #endif // defined(OS_WIN)
bool ValidateWidevineCryptoFlags()
bool ValidateFixedCryptoFlags()
bool ValidatePRCryptoFlags()