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/media/trick_play/trick_play_handler.h"
47 #include "packager/mpd/base/dash_iop_mpd_notifier.h"
48 #include "packager/mpd/base/media_info.pb.h"
49 #include "packager/mpd/base/mpd_builder.h"
50 #include "packager/mpd/base/simple_mpd_notifier.h"
51 #include "packager/version/version.h"
57 #endif // defined(OS_WIN)
59 DEFINE_bool(use_fake_clock_for_muxer,
61 "Set to true to use a fake clock for muxer. With this flag set, "
62 "creation time and modification time in outputs are set to 0. "
63 "Should only be used for testing.");
64 DEFINE_bool(override_version,
66 "Override packager version in the generated outputs with "
67 "--test_version if it is set to true. Should be used for "
69 DEFINE_string(test_version,
71 "Packager version for testing. Ignored if --override_version is "
72 "false. Should be used for testing only.");
79 "%s [flags] <stream_descriptor> ...\n\n"
80 " stream_descriptor consists of comma separated field_name/value pairs:\n"
81 " field_name=value,[field_name=value,]...\n"
82 " Supported field names are as follows (names in parenthesis are alias):\n"
83 " - input (in): Required input/source media file path or network stream\n"
85 " - stream_selector (stream): Required field with value 'audio',\n"
86 " 'video', 'text', or stream number (zero based).\n"
87 " - output (out,init_segment): Required output file (single file) or\n"
88 " initialization file path (multiple file).\n"
89 " - segment_template (segment): Optional value which specifies the\n"
90 " naming pattern for the segment files, and that the stream should be\n"
91 " split into multiple files. Its presence should be consistent across\n"
93 " - bandwidth (bw): Optional value which contains a user-specified\n"
94 " content bit rate for the stream, in bits/sec. If specified, this\n"
95 " value is propagated to the $Bandwidth$ template parameter for\n"
96 " segment names. If not specified, its value may be estimated.\n"
97 " - language (lang): Optional value which contains a user-specified\n"
98 " language tag. If specified, this value overrides any language\n"
99 " metadata in the input track.\n"
100 " - output_format (format): Optional value which specifies the format\n"
101 " of the output files (MP4 or WebM). If not specified, it will be\n"
102 " derived from the file extension of the output file.\n"
103 " - trick_play_factor (tpf): Optional value which specifies the trick\n"
104 " play, a.k.a. trick mode, stream sampling rate among key frames.\n"
105 " If specified, the output is a trick play stream.\n"
106 " - hls_name: Required for audio when outputting HLS.\n"
107 " name of the output stream. This is not (necessarily) the same as\n"
108 " output. This is used as the NAME attribute for EXT-X-MEDIA\n"
109 " - hls_group_id: Required for audio when outputting HLS.\n"
110 " The group ID for the output stream. For HLS this is used as the\n"
111 " GROUP-ID attribute for EXT-X-MEDIA.\n"
112 " - playlist_name: Required for HLS output.\n"
113 " Name of the playlist for the stream. Usually ends with '.m3u8'.\n"
114 " - skip_encryption=0|1: Optional. Defaults to 0 if not specified. If\n"
115 " it is set to 1, no encryption of the stream will be made.\n";
117 const char kMediaInfoSuffix[] =
".media_info";
121 kArgumentValidationFailed,
129 std::string DetermineTextFileFormat(
const std::string& file) {
132 LOG(ERROR) <<
"Failed to open file " << file
133 <<
" to determine file format.";
136 MediaContainerName container_name = DetermineContainer(
137 reinterpret_cast<const uint8_t*>(content.data()), content.size());
138 if (container_name == CONTAINER_WEBVTT) {
140 }
else if (container_name == CONTAINER_TTML) {
151 class FakeClock :
public base::Clock {
153 base::Time Now()
override {
return base::Time(); }
157 class RemuxJob :
public base::SimpleThread {
159 RemuxJob(std::unique_ptr<Demuxer> demuxer)
160 : SimpleThread(
"RemuxJob"), demuxer_(std::move(demuxer)) {}
162 ~RemuxJob()
override {}
164 Demuxer* demuxer() {
return demuxer_.get(); }
165 Status status() {
return status_; }
168 void Run()
override {
170 status_ = demuxer_->Run();
173 std::unique_ptr<Demuxer> demuxer_;
176 DISALLOW_COPY_AND_ASSIGN(RemuxJob);
179 bool StreamInfoToTextMediaInfo(
const StreamDescriptor& stream_descriptor,
180 const MuxerOptions& stream_muxer_options,
181 MediaInfo* text_media_info) {
182 const std::string& language = stream_descriptor.language;
183 std::string format = DetermineTextFileFormat(stream_descriptor.input);
184 if (format.empty()) {
185 LOG(ERROR) <<
"Failed to determine the text file format for "
186 << stream_descriptor.input;
190 if (!
File::Copy(stream_descriptor.input.c_str(),
191 stream_muxer_options.output_file_name.c_str())) {
192 LOG(ERROR) <<
"Failed to copy the input file (" << stream_descriptor.input
193 <<
") to output file (" << stream_muxer_options.output_file_name
198 text_media_info->set_media_file_name(stream_muxer_options.output_file_name);
199 text_media_info->set_container_type(MediaInfo::CONTAINER_TEXT);
201 if (stream_muxer_options.bandwidth != 0) {
202 text_media_info->set_bandwidth(stream_muxer_options.bandwidth);
207 text_media_info->set_bandwidth(256);
210 MediaInfo::TextInfo* text_info = text_media_info->mutable_text_info();
211 text_info->set_format(format);
212 if (!language.empty())
213 text_info->set_language(language);
218 std::shared_ptr<Muxer> CreateOutputMuxer(
const MuxerOptions& options,
219 MediaContainerName container) {
220 if (container == CONTAINER_WEBM) {
221 return std::shared_ptr<Muxer>(
new webm::WebMMuxer(options));
222 }
else if (container == CONTAINER_MPEG2TS) {
223 return std::shared_ptr<Muxer>(
new mp2t::TsMuxer(options));
225 DCHECK_EQ(container, CONTAINER_MOV);
226 return std::shared_ptr<Muxer>(
new mp4::MP4Muxer(options));
230 bool CreateRemuxJobs(
const StreamDescriptorList& stream_descriptors,
231 const ChunkingOptions& chunking_options,
232 const EncryptionOptions& encryption_options,
233 const MuxerOptions& muxer_options,
234 FakeClock* fake_clock,
235 KeySource* encryption_key_source,
236 MpdNotifier* mpd_notifier,
237 hls::HlsNotifier* hls_notifier,
238 std::vector<std::unique_ptr<RemuxJob>>* remux_jobs) {
240 DCHECK(!(mpd_notifier && hls_notifier));
243 std::shared_ptr<TrickPlayHandler> trick_play_handler;
245 std::string previous_input;
246 std::string previous_stream_selector;
247 int stream_number = 0;
248 for (StreamDescriptorList::const_iterator
249 stream_iter = stream_descriptors.begin();
250 stream_iter != stream_descriptors.end();
251 ++stream_iter, ++stream_number) {
253 MuxerOptions stream_muxer_options(muxer_options);
254 stream_muxer_options.output_file_name = stream_iter->output;
255 if (!stream_iter->segment_template.empty()) {
256 if (!ValidateSegmentTemplate(stream_iter->segment_template)) {
257 LOG(ERROR) <<
"ERROR: segment template with '"
258 << stream_iter->segment_template <<
"' is invalid.";
261 stream_muxer_options.segment_template = stream_iter->segment_template;
263 stream_muxer_options.bandwidth = stream_iter->bandwidth;
265 if (stream_iter->stream_selector ==
"text" &&
266 stream_iter->output_format != CONTAINER_MOV) {
267 MediaInfo text_media_info;
268 if (!StreamInfoToTextMediaInfo(*stream_iter, stream_muxer_options,
275 if (!mpd_notifier->NotifyNewContainer(text_media_info, &unused)) {
276 LOG(ERROR) <<
"Failed to process text file " << stream_iter->input;
278 mpd_notifier->Flush();
280 }
else if (FLAGS_output_media_info) {
283 stream_muxer_options.output_file_name + kMediaInfoSuffix);
286 <<
"--mpd_output or --output_media_info flags are "
287 "required for text output. Skipping manifest related output for "
288 << stream_iter->input;
293 if (stream_iter->input != previous_input) {
295 std::unique_ptr<Demuxer> demuxer(
new Demuxer(stream_iter->input));
296 demuxer->set_dump_stream_info(FLAGS_dump_stream_info);
297 if (FLAGS_enable_widevine_decryption ||
298 FLAGS_enable_fixed_key_decryption) {
299 std::unique_ptr<KeySource> decryption_key_source(
300 CreateDecryptionKeySource());
301 if (!decryption_key_source)
303 demuxer->SetKeySource(std::move(decryption_key_source));
305 remux_jobs->emplace_back(
new RemuxJob(std::move(demuxer)));
306 trick_play_handler.reset();
307 previous_input = stream_iter->input;
309 if (stream_iter->output.empty() && stream_iter->segment_template.empty())
312 DCHECK(!remux_jobs->empty());
318 if (stream_iter->stream_selector != previous_stream_selector) {
319 previous_stream_selector = stream_iter->stream_selector;
320 trick_play_handler.reset();
323 std::shared_ptr<Muxer> muxer(
324 CreateOutputMuxer(stream_muxer_options, stream_iter->output_format));
325 if (FLAGS_use_fake_clock_for_muxer) muxer->set_clock(fake_clock);
327 std::unique_ptr<MuxerListener> muxer_listener;
328 DCHECK(!(FLAGS_output_media_info && mpd_notifier));
329 if (FLAGS_output_media_info) {
330 const std::string output_media_info_file_name =
331 stream_muxer_options.output_file_name + kMediaInfoSuffix;
332 std::unique_ptr<VodMediaInfoDumpMuxerListener>
333 vod_media_info_dump_muxer_listener(
334 new VodMediaInfoDumpMuxerListener(output_media_info_file_name));
335 muxer_listener = std::move(vod_media_info_dump_muxer_listener);
338 std::unique_ptr<MpdNotifyMuxerListener> mpd_notify_muxer_listener(
339 new MpdNotifyMuxerListener(mpd_notifier));
340 muxer_listener = std::move(mpd_notify_muxer_listener);
346 std::string group_id = stream_iter->hls_group_id;
347 std::string name = stream_iter->hls_name;
348 std::string hls_playlist_name = stream_iter->hls_playlist_name;
349 if (group_id.empty())
352 name = base::StringPrintf(
"stream_%d", stream_number);
353 if (hls_playlist_name.empty())
354 hls_playlist_name = base::StringPrintf(
"stream_%d.m3u8", stream_number);
356 muxer_listener.reset(
new HlsNotifyMuxerListener(hls_playlist_name, name,
357 group_id, hls_notifier));
361 muxer->SetMuxerListener(std::move(muxer_listener));
366 if (stream_iter->trick_play_factor > 0) {
367 if (!trick_play_handler) {
368 trick_play_handler.reset(
new TrickPlayHandler());
370 trick_play_handler->SetHandlerForTrickPlay(stream_iter->trick_play_factor,
372 if (trick_play_handler->IsConnected())
374 }
else if (trick_play_handler) {
375 trick_play_handler->SetHandlerForMainStream(std::move(muxer));
376 DCHECK(trick_play_handler->IsConnected());
380 std::vector<std::shared_ptr<MediaHandler>> handlers;
382 auto chunking_handler = std::make_shared<ChunkingHandler>(chunking_options);
383 handlers.push_back(chunking_handler);
386 if (encryption_key_source && !stream_iter->skip_encryption) {
387 auto new_encryption_options = encryption_options;
391 if (stream_iter->output_format == CONTAINER_MPEG2TS) {
392 LOG(INFO) <<
"Use Apple Sample AES encryption for MPEG2TS.";
393 new_encryption_options.protection_scheme =
394 kAppleSampleAesProtectionScheme;
396 handlers.emplace_back(
397 new EncryptionHandler(new_encryption_options, encryption_key_source));
402 if (trick_play_handler) {
403 handlers.push_back(trick_play_handler);
405 handlers.push_back(std::move(muxer));
408 auto* demuxer = remux_jobs->back()->demuxer();
409 const std::string& stream_selector = stream_iter->stream_selector;
410 status.Update(demuxer->SetHandler(stream_selector, chunking_handler));
411 status.Update(ConnectHandlers(handlers));
414 LOG(ERROR) <<
"Failed to setup graph: " << status;
417 if (!stream_iter->language.empty())
418 demuxer->SetLanguageOverride(stream_selector, stream_iter->language);
422 for (
const std::unique_ptr<RemuxJob>& job : *remux_jobs) {
423 Status status = job->demuxer()->Initialize();
425 LOG(ERROR) <<
"Failed to initialize processing graph " << status;
432 Status RunRemuxJobs(
const std::vector<std::unique_ptr<RemuxJob>>& remux_jobs) {
434 for (
const std::unique_ptr<RemuxJob>& job : remux_jobs)
442 for (
const std::unique_ptr<RemuxJob>& job : remux_jobs) {
443 if (job->HasBeenJoined()) {
444 status = job->status();
452 }
while (!all_joined && status.ok());
457 bool RunPackager(
const StreamDescriptorList& stream_descriptors) {
458 if (FLAGS_output_media_info && !FLAGS_mpd_output.empty()) {
459 NOTIMPLEMENTED() <<
"ERROR: --output_media_info and --mpd_output do not "
466 if (!FLAGS_mpd_output.empty() && !FLAGS_hls_master_playlist_output.empty()) {
467 LOG(ERROR) <<
"Cannot output both MPD and HLS.";
471 ChunkingOptions chunking_options = GetChunkingOptions();
472 EncryptionOptions encryption_options = GetEncryptionOptions();
474 MuxerOptions muxer_options = GetMuxerOptions();
476 DCHECK(!stream_descriptors.empty());
479 const bool on_demand_dash_profile =
480 stream_descriptors.begin()->segment_template.empty();
481 for (
const auto& stream_descriptor : stream_descriptors) {
482 if (on_demand_dash_profile != stream_descriptor.segment_template.empty()) {
483 LOG(ERROR) <<
"Inconsistent stream descriptor specification: "
484 "segment_template should be specified for none or all "
485 "stream descriptors.";
489 if (FLAGS_output_media_info && !on_demand_dash_profile) {
491 NOTIMPLEMENTED() <<
"ERROR: --output_media_info is only supported for "
492 "on-demand profile (not using segment_template).";
496 MpdOptions mpd_options = GetMpdOptions(on_demand_dash_profile);
499 std::unique_ptr<KeySource> encryption_key_source;
500 if (FLAGS_enable_widevine_encryption || FLAGS_enable_fixed_key_encryption ||
501 FLAGS_enable_playready_encryption) {
502 if (encryption_options.protection_scheme == FOURCC_NULL)
504 encryption_key_source =
505 CreateEncryptionKeySource(encryption_options.protection_scheme);
506 if (!encryption_key_source)
510 std::unique_ptr<MpdNotifier> mpd_notifier;
511 if (!FLAGS_mpd_output.empty()) {
512 std::vector<std::string> base_urls = base::SplitString(
513 FLAGS_base_urls,
",", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
514 if (FLAGS_generate_dash_if_iop_compliant_mpd) {
516 new DashIopMpdNotifier(mpd_options, base_urls, FLAGS_mpd_output));
519 new SimpleMpdNotifier(mpd_options, base_urls, FLAGS_mpd_output));
521 if (!mpd_notifier->Init()) {
522 LOG(ERROR) <<
"MpdNotifier failed to initialize.";
527 std::unique_ptr<hls::HlsNotifier> hls_notifier;
528 if (!FLAGS_hls_master_playlist_output.empty()) {
529 base::FilePath master_playlist_path(
530 base::FilePath::FromUTF8Unsafe(FLAGS_hls_master_playlist_output));
531 base::FilePath master_playlist_name = master_playlist_path.BaseName();
533 hls_notifier.reset(
new hls::SimpleHlsNotifier(
534 hls::HlsNotifier::HlsProfile::kOnDemandProfile, FLAGS_hls_base_url,
535 master_playlist_path.DirName().AsEndingWithSeparator().AsUTF8Unsafe(),
536 master_playlist_name.AsUTF8Unsafe()));
539 std::vector<std::unique_ptr<RemuxJob>> remux_jobs;
540 FakeClock fake_clock;
541 if (!CreateRemuxJobs(stream_descriptors, chunking_options, encryption_options,
542 muxer_options, &fake_clock, encryption_key_source.get(),
543 mpd_notifier.get(), hls_notifier.get(), &remux_jobs)) {
547 Status status = RunRemuxJobs(remux_jobs);
549 LOG(ERROR) <<
"Packaging Error: " << status.ToString();
554 if (!hls_notifier->Flush())
558 if (!mpd_notifier->Flush())
562 printf(
"Packaging completed successfully.\n");
566 int PackagerMain(
int argc,
char** argv) {
567 base::AtExitManager exit;
569 base::CommandLine::Init(argc, argv);
572 logging::LoggingSettings log_settings;
573 log_settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
574 CHECK(logging::InitLogging(log_settings));
576 google::SetVersionString(GetPackagerVersion());
577 google::SetUsageMessage(base::StringPrintf(kUsage, argv[0]));
578 google::ParseCommandLineFlags(&argc, &argv,
true);
580 google::ShowUsageWithFlags(
"Usage");
586 return kArgumentValidationFailed;
589 if (FLAGS_override_version)
590 SetPackagerVersionForTesting(FLAGS_test_version);
592 LibcryptoThreading libcrypto_threading;
595 StreamDescriptorList stream_descriptors;
596 for (
int i = 1; i < argc; ++i) {
597 if (!InsertStreamDescriptor(argv[i], &stream_descriptors))
598 return kArgumentValidationFailed;
600 return RunPackager(stream_descriptors) ? kSuccess : kPackagingFailed;
608 int wmain(
int argc,
wchar_t* argv[],
wchar_t* envp[]) {
609 std::unique_ptr<char* [], std::function<void(char**)>> utf8_argv(
610 new char*[argc], [argc](
char** utf8_args) {
618 std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
619 for (
int idx = 0; idx < argc; ++idx) {
620 std::string utf8_arg(converter.to_bytes(argv[idx]));
622 utf8_argv[idx] =
new char[utf8_arg.size()];
623 memcpy(utf8_argv[idx], &utf8_arg[0], utf8_arg.size());
625 return shaka::media::PackagerMain(argc, utf8_argv.get());
628 int main(
int argc,
char** argv) {
629 return shaka::media::PackagerMain(argc, argv);
631 #endif // defined(OS_WIN)
bool ValidateWidevineCryptoFlags()
bool ValidateFixedCryptoFlags()
bool ValidatePRCryptoFlags()