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/demuxer.h"
33 #include "packager/media/base/fourccs.h"
34 #include "packager/media/base/key_source.h"
35 #include "packager/media/base/muxer_options.h"
36 #include "packager/media/base/muxer_util.h"
37 #include "packager/media/event/hls_notify_muxer_listener.h"
38 #include "packager/media/event/mpd_notify_muxer_listener.h"
39 #include "packager/media/event/vod_media_info_dump_muxer_listener.h"
40 #include "packager/media/file/file.h"
41 #include "packager/media/formats/mp2t/ts_muxer.h"
42 #include "packager/media/formats/mp4/mp4_muxer.h"
43 #include "packager/media/formats/webm/webm_muxer.h"
44 #include "packager/mpd/base/dash_iop_mpd_notifier.h"
45 #include "packager/mpd/base/media_info.pb.h"
46 #include "packager/mpd/base/mpd_builder.h"
47 #include "packager/mpd/base/simple_mpd_notifier.h"
48 #include "packager/version/version.h"
54 #endif // defined(OS_WIN)
56 DEFINE_bool(use_fake_clock_for_muxer,
58 "Set to true to use a fake clock for muxer. With this flag set, "
59 "creation time and modification time in outputs are set to 0. "
60 "Should only be used for testing.");
61 DEFINE_bool(override_version,
63 "Override packager version in the generated outputs with "
64 "--test_version if it is set to true. Should be used for "
66 DEFINE_string(test_version,
68 "Packager version for testing. Ignored if --override_version is "
69 "false. Should be used for testing only.");
76 "%s [flags] <stream_descriptor> ...\n\n"
77 " stream_descriptor consists of comma separated field_name/value pairs:\n"
78 " field_name=value,[field_name=value,]...\n"
79 " Supported field names are as follows:\n"
80 " - input (in): Required input/source media file path or network stream\n"
82 " - stream_selector (stream): Required field with value 'audio',\n"
83 " 'video', or stream number (zero based).\n"
84 " - output (out): Required output file (single file) or initialization\n"
85 " file path (multiple file).\n"
86 " - segment_template (segment): Optional value which specifies the\n"
87 " naming pattern for the segment files, and that the stream should be\n"
88 " split into multiple files. Its presence should be consistent across\n"
90 " - bandwidth (bw): Optional value which contains a user-specified\n"
91 " content bit rate for the stream, in bits/sec. If specified, this\n"
92 " value is propagated to the $Bandwidth$ template parameter for\n"
93 " segment names. If not specified, its value may be estimated.\n"
94 " - language (lang): Optional value which contains a user-specified\n"
95 " language tag. If specified, this value overrides any language\n"
96 " metadata in the input track.\n"
97 " - output_format (format): Optional value which specifies the format\n"
98 " of the output files (MP4 or WebM). If not specified, it will be\n"
99 " derived from the file extension of the output file.\n"
100 " - hls_name: Required for audio when outputting HLS.\n"
101 " name of the output stream. This is not (necessarily) the same as\n"
102 " output. This is used as the NAME attribute for EXT-X-MEDIA\n"
103 " - hls_group_id: Required for audio when outputting HLS.\n"
104 " The group ID for the output stream. For HLS this is used as the\n"
105 " GROUP-ID attribute for EXT-X-MEDIA.\n"
106 " - playlist_name: Required for HLS output.\n"
107 " Name of the playlist for the stream. Usually ends with '.m3u8'.\n";
109 const char kMediaInfoSuffix[] =
".media_info";
113 kArgumentValidationFailed,
121 std::string DetermineTextFileFormat(
const std::string& file) {
124 LOG(ERROR) <<
"Failed to open file " << file
125 <<
" to determine file format.";
128 MediaContainerName container_name = DetermineContainer(
129 reinterpret_cast<const uint8_t*>(content.data()), content.size());
130 if (container_name == CONTAINER_WEBVTT) {
132 }
else if (container_name == CONTAINER_TTML) {
139 FourCC GetProtectionScheme(
const std::string& protection_scheme) {
140 if (protection_scheme ==
"cenc") {
142 }
else if (protection_scheme ==
"cens") {
144 }
else if (protection_scheme ==
"cbc1") {
146 }
else if (protection_scheme ==
"cbcs") {
149 LOG(ERROR) <<
"Unknown protection scheme: " << protection_scheme;
158 class FakeClock :
public base::Clock {
160 base::Time Now()
override {
return base::Time(); }
164 class RemuxJob :
public base::SimpleThread {
166 RemuxJob(std::unique_ptr<Demuxer> demuxer)
167 : SimpleThread(
"RemuxJob"), demuxer_(std::move(demuxer)) {}
169 ~RemuxJob()
override {}
171 void AddMuxer(std::unique_ptr<Muxer> mux) {
172 muxers_.push_back(std::move(mux));
175 Demuxer* demuxer() {
return demuxer_.get(); }
176 Status status() {
return status_; }
179 void Run()
override {
181 status_ = demuxer_->Run();
184 std::unique_ptr<Demuxer> demuxer_;
185 std::vector<std::unique_ptr<Muxer>> muxers_;
188 DISALLOW_COPY_AND_ASSIGN(RemuxJob);
191 bool StreamInfoToTextMediaInfo(
const StreamDescriptor& stream_descriptor,
192 const MuxerOptions& stream_muxer_options,
193 MediaInfo* text_media_info) {
194 const std::string& language = stream_descriptor.language;
195 std::string format = DetermineTextFileFormat(stream_descriptor.input);
196 if (format.empty()) {
197 LOG(ERROR) <<
"Failed to determine the text file format for "
198 << stream_descriptor.input;
202 if (!
File::Copy(stream_descriptor.input.c_str(),
203 stream_muxer_options.output_file_name.c_str())) {
204 LOG(ERROR) <<
"Failed to copy the input file (" << stream_descriptor.input
205 <<
") to output file (" << stream_muxer_options.output_file_name
210 text_media_info->set_media_file_name(stream_muxer_options.output_file_name);
211 text_media_info->set_container_type(MediaInfo::CONTAINER_TEXT);
213 if (stream_muxer_options.bandwidth != 0) {
214 text_media_info->set_bandwidth(stream_muxer_options.bandwidth);
219 text_media_info->set_bandwidth(256);
222 MediaInfo::TextInfo* text_info = text_media_info->mutable_text_info();
223 text_info->set_format(format);
224 if (!language.empty())
225 text_info->set_language(language);
230 std::unique_ptr<Muxer> CreateOutputMuxer(
const MuxerOptions& options,
231 MediaContainerName container) {
232 if (container == CONTAINER_WEBM) {
233 return std::unique_ptr<Muxer>(
new webm::WebMMuxer(options));
234 }
else if (container == CONTAINER_MPEG2TS) {
235 return std::unique_ptr<Muxer>(
new mp2t::TsMuxer(options));
237 DCHECK_EQ(container, CONTAINER_MOV);
238 return std::unique_ptr<Muxer>(
new mp4::MP4Muxer(options));
242 bool CreateRemuxJobs(
const StreamDescriptorList& stream_descriptors,
243 const MuxerOptions& muxer_options,
244 FakeClock* fake_clock,
245 KeySource* key_source,
246 MpdNotifier* mpd_notifier,
247 hls::HlsNotifier* hls_notifier,
248 std::vector<std::unique_ptr<RemuxJob>>* remux_jobs) {
250 DCHECK(!(mpd_notifier && hls_notifier));
253 std::string previous_input;
254 int stream_number = 0;
255 for (StreamDescriptorList::const_iterator
256 stream_iter = stream_descriptors.begin();
257 stream_iter != stream_descriptors.end();
258 ++stream_iter, ++stream_number) {
260 MuxerOptions stream_muxer_options(muxer_options);
261 stream_muxer_options.output_file_name = stream_iter->output;
262 if (!stream_iter->segment_template.empty()) {
263 if (!ValidateSegmentTemplate(stream_iter->segment_template)) {
264 LOG(ERROR) <<
"ERROR: segment template with '"
265 << stream_iter->segment_template <<
"' is invalid.";
268 stream_muxer_options.segment_template = stream_iter->segment_template;
270 stream_muxer_options.bandwidth = stream_iter->bandwidth;
273 if (stream_iter->stream_selector ==
"text") {
274 MediaInfo text_media_info;
275 if (!StreamInfoToTextMediaInfo(*stream_iter, stream_muxer_options,
282 if (!mpd_notifier->NotifyNewContainer(text_media_info, &unused)) {
283 LOG(ERROR) <<
"Failed to process text file " << stream_iter->input;
285 mpd_notifier->Flush();
287 }
else if (FLAGS_output_media_info) {
290 stream_muxer_options.output_file_name + kMediaInfoSuffix);
293 <<
"--mpd_output or --output_media_info flags are "
294 "required for text output. Skipping manifest related output for "
295 << stream_iter->input;
300 if (stream_iter->input != previous_input) {
302 std::unique_ptr<Demuxer> demuxer(
new Demuxer(stream_iter->input));
303 if (FLAGS_enable_widevine_decryption ||
304 FLAGS_enable_fixed_key_decryption) {
305 std::unique_ptr<KeySource> key_source(CreateDecryptionKeySource());
308 demuxer->SetKeySource(std::move(key_source));
310 Status status = demuxer->Initialize();
312 LOG(ERROR) <<
"Demuxer failed to initialize: " << status.ToString();
315 if (FLAGS_dump_stream_info) {
316 printf(
"\nFile \"%s\":\n", stream_iter->input.c_str());
317 DumpStreamInfo(demuxer->streams());
318 if (stream_iter->output.empty())
321 remux_jobs->emplace_back(
new RemuxJob(std::move(demuxer)));
322 previous_input = stream_iter->input;
324 DCHECK(!remux_jobs->empty());
326 std::unique_ptr<Muxer> muxer(
327 CreateOutputMuxer(stream_muxer_options, stream_iter->output_format));
328 if (FLAGS_use_fake_clock_for_muxer) muxer->set_clock(fake_clock);
331 muxer->SetKeySource(key_source,
334 FLAGS_max_uhd1_pixels,
336 FLAGS_crypto_period_duration,
337 GetProtectionScheme(FLAGS_protection_scheme));
340 std::unique_ptr<MuxerListener> muxer_listener;
341 DCHECK(!(FLAGS_output_media_info && mpd_notifier));
342 if (FLAGS_output_media_info) {
343 const std::string output_media_info_file_name =
344 stream_muxer_options.output_file_name + kMediaInfoSuffix;
345 std::unique_ptr<VodMediaInfoDumpMuxerListener>
346 vod_media_info_dump_muxer_listener(
347 new VodMediaInfoDumpMuxerListener(output_media_info_file_name));
348 muxer_listener = std::move(vod_media_info_dump_muxer_listener);
351 std::unique_ptr<MpdNotifyMuxerListener> mpd_notify_muxer_listener(
352 new MpdNotifyMuxerListener(mpd_notifier));
353 muxer_listener = std::move(mpd_notify_muxer_listener);
359 std::string group_id = stream_iter->hls_group_id;
360 std::string name = stream_iter->hls_name;
361 std::string hls_playlist_name = stream_iter->hls_playlist_name;
362 if (group_id.empty())
365 name = base::StringPrintf(
"stream_%d", stream_number);
366 if (hls_playlist_name.empty())
367 hls_playlist_name = base::StringPrintf(
"stream_%d.m3u8", stream_number);
369 muxer_listener.reset(
new HlsNotifyMuxerListener(hls_playlist_name, name,
370 group_id, hls_notifier));
374 muxer->SetMuxerListener(std::move(muxer_listener));
376 if (!AddStreamToMuxer(remux_jobs->back()->demuxer()->streams(),
377 stream_iter->stream_selector,
378 stream_iter->language,
382 remux_jobs->back()->AddMuxer(std::move(muxer));
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 const FourCC protection_scheme = GetProtectionScheme(FLAGS_protection_scheme);
415 if (protection_scheme == FOURCC_NULL)
418 if (FLAGS_output_media_info && !FLAGS_mpd_output.empty()) {
419 NOTIMPLEMENTED() <<
"ERROR: --output_media_info and --mpd_output do not "
426 if (!FLAGS_mpd_output.empty() && !FLAGS_hls_master_playlist_output.empty()) {
427 LOG(ERROR) <<
"Cannot output both MPD and HLS.";
432 MuxerOptions muxer_options;
433 if (!GetMuxerOptions(&muxer_options))
436 DCHECK(!stream_descriptors.empty());
439 const bool on_demand_dash_profile =
440 stream_descriptors.begin()->segment_template.empty();
441 for (
const auto& stream_descriptor : stream_descriptors) {
442 if (on_demand_dash_profile != stream_descriptor.segment_template.empty()) {
443 LOG(ERROR) <<
"Inconsistent stream descriptor specification: "
444 "segment_template should be specified for none or all "
445 "stream descriptors.";
449 if (FLAGS_output_media_info && !on_demand_dash_profile) {
451 NOTIMPLEMENTED() <<
"ERROR: --output_media_info is only supported for "
452 "on-demand profile (not using segment_template).";
456 MpdOptions mpd_options;
457 if (!GetMpdOptions(on_demand_dash_profile, &mpd_options))
461 std::unique_ptr<KeySource> encryption_key_source;
462 if (FLAGS_enable_widevine_encryption || FLAGS_enable_fixed_key_encryption ||
463 FLAGS_enable_playready_encryption) {
464 encryption_key_source = CreateEncryptionKeySource();
465 if (!encryption_key_source)
469 std::unique_ptr<MpdNotifier> mpd_notifier;
470 if (!FLAGS_mpd_output.empty()) {
471 std::vector<std::string> base_urls = base::SplitString(
472 FLAGS_base_urls,
",", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
473 if (FLAGS_generate_dash_if_iop_compliant_mpd) {
475 new DashIopMpdNotifier(mpd_options, base_urls, FLAGS_mpd_output));
478 new SimpleMpdNotifier(mpd_options, base_urls, FLAGS_mpd_output));
480 if (!mpd_notifier->Init()) {
481 LOG(ERROR) <<
"MpdNotifier failed to initialize.";
486 std::unique_ptr<hls::HlsNotifier> hls_notifier;
487 if (!FLAGS_hls_master_playlist_output.empty()) {
488 base::FilePath master_playlist_path(
489 base::FilePath::FromUTF8Unsafe(FLAGS_hls_master_playlist_output));
490 base::FilePath master_playlist_name = master_playlist_path.BaseName();
492 hls_notifier.reset(
new hls::SimpleHlsNotifier(
493 hls::HlsNotifier::HlsProfile::kOnDemandProfile, FLAGS_hls_base_url,
494 master_playlist_path.DirName().AsEndingWithSeparator().AsUTF8Unsafe(),
495 master_playlist_name.AsUTF8Unsafe()));
498 std::vector<std::unique_ptr<RemuxJob>> remux_jobs;
499 FakeClock fake_clock;
500 if (!CreateRemuxJobs(stream_descriptors, muxer_options, &fake_clock,
501 encryption_key_source.get(), mpd_notifier.get(),
502 hls_notifier.get(), &remux_jobs)) {
506 Status status = RunRemuxJobs(remux_jobs);
508 LOG(ERROR) <<
"Packaging Error: " << status.ToString();
513 if (!hls_notifier->Flush())
517 if (!mpd_notifier->Flush())
521 printf(
"Packaging completed successfully.\n");
525 int PackagerMain(
int argc,
char** argv) {
526 base::AtExitManager exit;
528 base::CommandLine::Init(argc, argv);
531 logging::LoggingSettings log_settings;
532 log_settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
533 CHECK(logging::InitLogging(log_settings));
535 google::SetVersionString(GetPackagerVersion());
536 google::SetUsageMessage(base::StringPrintf(kUsage, argv[0]));
537 google::ParseCommandLineFlags(&argc, &argv,
true);
539 google::ShowUsageWithFlags(
"Usage");
545 return kArgumentValidationFailed;
548 if (FLAGS_override_version)
549 SetPackagerVersionForTesting(FLAGS_test_version);
551 LibcryptoThreading libcrypto_threading;
554 StreamDescriptorList stream_descriptors;
555 for (
int i = 1; i < argc; ++i) {
556 if (!InsertStreamDescriptor(argv[i], &stream_descriptors))
557 return kArgumentValidationFailed;
559 return RunPackager(stream_descriptors) ? kSuccess : kPackagingFailed;
567 int wmain(
int argc,
wchar_t* argv[],
wchar_t* envp[]) {
568 std::unique_ptr<char* [], std::function<void(char**)>> utf8_argv(
569 new char*[argc], [argc](
char** utf8_args) {
577 std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
578 for (
int idx = 0; idx < argc; ++idx) {
579 std::string utf8_arg(converter.to_bytes(argv[idx]));
581 utf8_argv[idx] =
new char[utf8_arg.size()];
582 memcpy(utf8_argv[idx], &utf8_arg[0], utf8_arg.size());
584 return shaka::media::PackagerMain(argc, utf8_argv.get());
587 int main(
int argc,
char** argv) {
588 return shaka::media::PackagerMain(argc, argv);
590 #endif // defined(OS_WIN)
bool ValidateWidevineCryptoFlags()
bool ValidateFixedCryptoFlags()
bool ValidatePRCryptoFlags()