7 #include <gflags/gflags.h> 10 #include "packager/app/ad_cue_generator_flags.h" 11 #include "packager/app/crypto_flags.h" 12 #include "packager/app/hls_flags.h" 13 #include "packager/app/manifest_flags.h" 14 #include "packager/app/mpd_flags.h" 15 #include "packager/app/muxer_flags.h" 16 #include "packager/app/packager_util.h" 17 #include "packager/app/playready_key_encryption_flags.h" 18 #include "packager/app/protection_system_flags.h" 19 #include "packager/app/raw_key_encryption_flags.h" 20 #include "packager/app/stream_descriptor.h" 21 #include "packager/app/vlog_flags.h" 22 #include "packager/app/widevine_encryption_flags.h" 23 #include "packager/base/command_line.h" 24 #include "packager/base/logging.h" 25 #include "packager/base/optional.h" 26 #include "packager/base/strings/string_number_conversions.h" 27 #include "packager/base/strings/string_split.h" 28 #include "packager/base/strings/string_util.h" 29 #include "packager/base/strings/stringprintf.h" 30 #include "packager/file/file.h" 31 #include "packager/packager.h" 32 #include "packager/tools/license_notice.h" 38 #endif // defined(OS_WIN) 40 DEFINE_bool(dump_stream_info,
false,
"Dump demuxed stream info.");
41 DEFINE_bool(licenses,
false,
"Dump licenses.");
42 DEFINE_bool(quiet,
false,
"When enabled, LOG(INFO) output is suppressed.");
43 DEFINE_bool(use_fake_clock_for_muxer,
45 "Set to true to use a fake clock for muxer. With this flag set, " 46 "creation time and modification time in outputs are set to 0. " 47 "Should only be used for testing.");
48 DEFINE_string(test_packager_version,
50 "Packager version for testing. Should be used for testing only.");
56 "%s [flags] <stream_descriptor> ...\n\n" 57 " stream_descriptor consists of comma separated field_name/value pairs:\n" 58 " field_name=value,[field_name=value,]...\n" 59 " Supported field names are as follows (names in parenthesis are alias):\n" 60 " - input (in): Required input/source media file path or network stream\n" 62 " - stream_selector (stream): Required field with value 'audio',\n" 63 " 'video', 'text', or stream number (zero based).\n" 64 " - output (out,init_segment): Required output file (single file) or\n" 65 " initialization file path (multiple file).\n" 66 " - segment_template (segment): Optional value which specifies the\n" 67 " naming pattern for the segment files, and that the stream should be\n" 68 " split into multiple files. Its presence should be consistent across\n" 70 " - bandwidth (bw): Optional value which contains a user-specified\n" 71 " maximum bit rate for the stream, in bits/sec. If specified, this\n" 72 " value is propagated to (HLS) EXT-X-STREAM-INF:BANDWIDTH or (DASH)\n" 73 " Representation@bandwidth and the $Bandwidth$ template parameter for\n" 74 " segment names. If not specified, the bandwidth value is estimated\n" 75 " from content bitrate. Note that it only affects the generated\n" 76 " manifests/playlists; it has no effect on the media content itself.\n" 77 " - language (lang): Optional value which contains a user-specified\n" 78 " language tag. If specified, this value overrides any language\n" 79 " metadata in the input stream.\n" 80 " - output_format (format): Optional value which specifies the format\n" 81 " of the output files (MP4 or WebM). If not specified, it will be\n" 82 " derived from the file extension of the output file.\n" 83 " - skip_encryption=0|1: Optional. Defaults to 0 if not specified. If\n" 84 " it is set to 1, no encryption of the stream will be made.\n" 85 " - drm_label: Optional value for custom DRM label, which defines the\n" 86 " encryption key applied to the stream. Typical values include AUDIO,\n" 87 " SD, HD, UHD1, UHD2. For raw key, it should be a label defined in\n" 88 " --keys. If not provided, the DRM label is derived from stream type\n" 89 " (video, audio), resolution, etc.\n" 90 " Note that it is case sensitive.\n" 91 " - trick_play_factor (tpf): Optional value which specifies the trick\n" 92 " play, a.k.a. trick mode, stream sampling rate among key frames.\n" 93 " If specified, the output is a trick play stream.\n" 94 " - hls_name: Used for HLS audio to set the NAME attribute for\n" 95 " EXT-X-MEDIA. Defaults to the base of the playlist name.\n" 96 " - hls_group_id: Used for HLS audio to set the GROUP-ID attribute for\n" 97 " EXT-X-MEDIA. Defaults to 'audio' if not specified.\n" 98 " - playlist_name: The HLS playlist file to create. Usually ends with\n" 99 " '.m3u8', and is relative to --hls_master_playlist_output. If\n" 100 " unspecified, defaults to something of the form 'stream_0.m3u8',\n" 101 " 'stream_1.m3u8', 'stream_2.m3u8', etc.\n" 102 " - iframe_playlist_name: The optional HLS I-Frames only playlist file\n" 103 " to create. Usually ends with '.m3u8', and is relative to\n" 104 " hls_master_playlist_output. Should only be set for video streams. If\n" 105 " unspecified, no I-Frames only playlist is created.\n" 106 " - hls_characteristics (charcs): Optional colon/semicolon separated\n" 107 " list of values for the CHARACTERISTICS attribute for EXT-X-MEDIA.\n" 108 " See CHARACTERISTICS attribute in http://bit.ly/2OOUkdB for details.\n" 109 " - dash_accessibilities (accessibilities): Optional semicolon separated\n" 110 " list of values for DASH Accessibility elements. The value should be\n" 111 " in the format: scheme_id_uri=value.\n" 112 " - dash_roles (roles): Optional semicolon separated list of values for\n" 113 " DASH Role elements. The value should be one of: caption, subtitle,\n" 114 " main, alternate, supplementary, commentary and dub. See DASH\n" 115 " (ISO/IEC 23009-1) specification for details.\n";
118 const char kDrmLabelLabel[] =
"label";
119 const char kKeyIdLabel[] =
"key_id";
120 const char kKeyLabel[] =
"key";
124 kArgumentValidationFailed,
129 bool GetWidevineSigner(WidevineSigner* signer) {
130 signer->signer_name = FLAGS_signer;
131 if (!FLAGS_aes_signing_key_bytes.empty()) {
132 signer->signing_key_type = WidevineSigner::SigningKeyType::kAes;
133 signer->aes.key = FLAGS_aes_signing_key_bytes;
134 signer->aes.iv = FLAGS_aes_signing_iv_bytes;
135 }
else if (!FLAGS_rsa_signing_key_path.empty()) {
136 signer->signing_key_type = WidevineSigner::SigningKeyType::kRsa;
139 LOG(ERROR) <<
"Failed to read from '" << FLAGS_rsa_signing_key_path
147 bool GetHlsPlaylistType(
const std::string& playlist_type,
149 if (base::ToUpperASCII(playlist_type) ==
"VOD") {
150 *playlist_type_enum = HlsPlaylistType::kVod;
151 }
else if (base::ToUpperASCII(playlist_type) ==
"LIVE") {
152 *playlist_type_enum = HlsPlaylistType::kLive;
153 }
else if (base::ToUpperASCII(playlist_type) ==
"EVENT") {
154 *playlist_type_enum = HlsPlaylistType::kEvent;
156 LOG(ERROR) <<
"Unrecognized playlist type " << playlist_type;
162 bool GetProtectionScheme(uint32_t* protection_scheme) {
163 if (FLAGS_protection_scheme ==
"cenc") {
167 if (FLAGS_protection_scheme ==
"cbc1") {
168 *protection_scheme = EncryptionParams::kProtectionSchemeCbc1;
171 if (FLAGS_protection_scheme ==
"cbcs") {
172 *protection_scheme = EncryptionParams::kProtectionSchemeCbcs;
175 if (FLAGS_protection_scheme ==
"cens") {
176 *protection_scheme = EncryptionParams::kProtectionSchemeCens;
179 LOG(ERROR) <<
"Unrecognized protection_scheme " << FLAGS_protection_scheme;
183 bool ParseKeys(
const std::string& keys, RawKeyParams* raw_key) {
184 for (
const std::string& key_data : base::SplitString(
185 keys,
",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) {
186 base::StringPairs string_pairs;
187 base::SplitStringIntoKeyValuePairs(key_data,
'=',
':', &string_pairs);
189 std::map<std::string, std::string> value_map;
190 for (
const auto& string_pair : string_pairs)
191 value_map[string_pair.first] = string_pair.second;
192 const std::string drm_label = value_map[kDrmLabelLabel];
193 if (raw_key->key_map.find(drm_label) != raw_key->key_map.end()) {
194 LOG(ERROR) <<
"Seeing duplicated DRM label '" << drm_label <<
"'.";
197 auto& key_info = raw_key->key_map[drm_label];
198 if (value_map[kKeyIdLabel].empty() ||
199 !base::HexStringToBytes(value_map[kKeyIdLabel], &key_info.key_id)) {
200 LOG(ERROR) <<
"Empty key id or invalid hex string for key id: " 201 << value_map[kKeyIdLabel];
204 if (value_map[kKeyLabel].empty() ||
205 !base::HexStringToBytes(value_map[kKeyLabel], &key_info.key)) {
206 LOG(ERROR) <<
"Empty key or invalid hex string for key: " 207 << value_map[kKeyLabel];
214 bool GetRawKeyParams(RawKeyParams* raw_key) {
215 raw_key->iv = FLAGS_iv_bytes;
216 raw_key->pssh = FLAGS_pssh_bytes;
217 if (!FLAGS_keys.empty()) {
218 if (!ParseKeys(FLAGS_keys, raw_key)) {
219 LOG(ERROR) <<
"Failed to parse --keys " << FLAGS_keys;
224 RawKeyParams::KeyInfo& key_info = raw_key->key_map[
""];
225 key_info.key_id = FLAGS_key_id_bytes;
226 key_info.key = FLAGS_key_bytes;
231 bool ParseAdCues(
const std::string& ad_cues, std::vector<Cuepoint>* cuepoints) {
233 size_t duration_count = 0;
235 for (
const std::string& ad_cue : base::SplitString(
236 ad_cues,
";", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) {
238 auto split_ad_cue = base::SplitString(ad_cue,
",", base::TRIM_WHITESPACE,
239 base::SPLIT_WANT_NONEMPTY);
240 if (split_ad_cue.size() > 2) {
241 LOG(ERROR) <<
"Failed to parse --ad_cues " << ad_cues
242 <<
" Each ad cue must contain no more than 2 components.";
244 if (!base::StringToDouble(split_ad_cue.front(),
245 &cuepoint.start_time_in_seconds)) {
246 LOG(ERROR) <<
"Failed to parse --ad_cues " << ad_cues
247 <<
" Start time component must be of type double.";
250 if (split_ad_cue.size() > 1) {
252 if (!base::StringToDouble(split_ad_cue[1],
253 &cuepoint.duration_in_seconds)) {
254 LOG(ERROR) <<
"Failed to parse --ad_cues " << ad_cues
255 <<
" Duration component must be of type double.";
259 cuepoints->push_back(cuepoint);
262 if (duration_count > 0 && duration_count != cuepoints->size()) {
263 LOG(ERROR) <<
"Failed to parse --ad_cues " << ad_cues
264 <<
" Duration component is optional. However if it is supplied," 265 <<
" it must be supplied consistently across all cuepoints.";
271 bool ParseProtectionSystems(
272 const std::string& protection_systems_str,
273 std::vector<EncryptionParams::ProtectionSystem>* protection_systems) {
274 protection_systems->clear();
276 std::map<std::string, EncryptionParams::ProtectionSystem> mapping = {
277 {
"common", EncryptionParams::ProtectionSystem::kCommonSystem},
278 {
"commonsystem", EncryptionParams::ProtectionSystem::kCommonSystem},
279 {
"fairplay", EncryptionParams::ProtectionSystem::kFairPlay},
280 {
"marlin", EncryptionParams::ProtectionSystem::kMarlin},
281 {
"playready", EncryptionParams::ProtectionSystem::kPlayReady},
282 {
"widevine", EncryptionParams::ProtectionSystem::kWidevine},
285 for (
const std::string& protection_system :
286 base::SplitString(base::ToLowerASCII(protection_systems_str),
",",
287 base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) {
288 auto iter = mapping.find(protection_system);
289 if (iter == mapping.end()) {
290 LOG(ERROR) <<
"Seeing unrecognized protection system: " 291 << protection_system;
294 protection_systems->push_back(iter->second);
299 base::Optional<PackagingParams> GetPackagingParams() {
300 PackagingParams packaging_params;
302 packaging_params.temp_dir = FLAGS_temp_dir;
304 AdCueGeneratorParams& ad_cue_generator_params =
305 packaging_params.ad_cue_generator_params;
306 if (!ParseAdCues(FLAGS_ad_cues, &ad_cue_generator_params.cue_points)) {
307 return base::nullopt;
310 ChunkingParams& chunking_params = packaging_params.chunking_params;
311 chunking_params.segment_duration_in_seconds = FLAGS_segment_duration;
312 chunking_params.subsegment_duration_in_seconds = FLAGS_fragment_duration;
313 chunking_params.segment_sap_aligned = FLAGS_segment_sap_aligned;
314 chunking_params.subsegment_sap_aligned = FLAGS_fragment_sap_aligned;
316 int num_key_providers = 0;
317 EncryptionParams& encryption_params = packaging_params.encryption_params;
318 if (FLAGS_enable_widevine_encryption) {
319 encryption_params.key_provider = KeyProvider::kWidevine;
322 if (FLAGS_enable_playready_encryption) {
323 encryption_params.key_provider = KeyProvider::kPlayReady;
326 if (FLAGS_enable_raw_key_encryption) {
327 encryption_params.key_provider = KeyProvider::kRawKey;
330 if (num_key_providers > 1) {
331 LOG(ERROR) <<
"Only one of --enable_widevine_encryption, " 332 "--enable_playready_encryption, " 333 "--enable_raw_key_encryption can be enabled.";
334 return base::nullopt;
337 if (!ParseProtectionSystems(FLAGS_protection_systems,
338 &encryption_params.protection_systems)) {
339 return base::nullopt;
342 if (encryption_params.key_provider != KeyProvider::kNone) {
343 encryption_params.clear_lead_in_seconds = FLAGS_clear_lead;
344 if (!GetProtectionScheme(&encryption_params.protection_scheme))
345 return base::nullopt;
346 encryption_params.crypto_period_duration_in_seconds =
347 FLAGS_crypto_period_duration;
348 encryption_params.vp9_subsample_encryption = FLAGS_vp9_subsample_encryption;
349 encryption_params.stream_label_func = std::bind(
351 FLAGS_max_hd_pixels, FLAGS_max_uhd1_pixels, std::placeholders::_1);
353 switch (encryption_params.key_provider) {
354 case KeyProvider::kWidevine: {
355 WidevineEncryptionParams& widevine = encryption_params.widevine;
356 widevine.key_server_url = FLAGS_key_server_url;
358 widevine.content_id = FLAGS_content_id_bytes;
359 widevine.policy = FLAGS_policy;
360 widevine.group_id = FLAGS_group_id_bytes;
361 widevine.enable_entitlement_license = FLAGS_enable_entitlement_license;
362 if (!GetWidevineSigner(&widevine.signer))
363 return base::nullopt;
366 case KeyProvider::kPlayReady: {
367 PlayReadyEncryptionParams& playready = encryption_params.playready;
368 playready.key_server_url = FLAGS_playready_server_url;
369 playready.program_identifier = FLAGS_program_identifier;
370 playready.ca_file = FLAGS_ca_file;
371 playready.client_cert_file = FLAGS_client_cert_file;
372 playready.client_cert_private_key_file =
373 FLAGS_client_cert_private_key_file;
374 playready.client_cert_private_key_password =
375 FLAGS_client_cert_private_key_password;
378 case KeyProvider::kRawKey: {
379 if (!GetRawKeyParams(&encryption_params.raw_key))
380 return base::nullopt;
383 case KeyProvider::kNone:
387 num_key_providers = 0;
388 DecryptionParams& decryption_params = packaging_params.decryption_params;
389 if (FLAGS_enable_widevine_decryption) {
390 decryption_params.key_provider = KeyProvider::kWidevine;
393 if (FLAGS_enable_raw_key_decryption) {
394 decryption_params.key_provider = KeyProvider::kRawKey;
397 if (num_key_providers > 1) {
398 LOG(ERROR) <<
"Only one of --enable_widevine_decryption, " 399 "--enable_raw_key_decryption can be enabled.";
400 return base::nullopt;
402 switch (decryption_params.key_provider) {
403 case KeyProvider::kWidevine: {
404 WidevineDecryptionParams& widevine = decryption_params.widevine;
405 widevine.key_server_url = FLAGS_key_server_url;
406 if (!GetWidevineSigner(&widevine.signer))
407 return base::nullopt;
410 case KeyProvider::kRawKey: {
411 if (!GetRawKeyParams(&decryption_params.raw_key))
412 return base::nullopt;
415 case KeyProvider::kPlayReady:
416 case KeyProvider::kNone:
420 Mp4OutputParams& mp4_params = packaging_params.mp4_output_params;
421 mp4_params.generate_sidx_in_media_segments =
422 FLAGS_generate_sidx_in_media_segments;
423 mp4_params.include_pssh_in_stream = FLAGS_mp4_include_pssh_in_stream;
425 packaging_params.transport_stream_timestamp_offset_ms =
426 FLAGS_transport_stream_timestamp_offset_ms;
428 packaging_params.output_media_info = FLAGS_output_media_info;
430 MpdParams& mpd_params = packaging_params.mpd_params;
431 mpd_params.mpd_output = FLAGS_mpd_output;
432 mpd_params.base_urls = base::SplitString(
433 FLAGS_base_urls,
",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
434 mpd_params.min_buffer_time = FLAGS_min_buffer_time;
435 mpd_params.minimum_update_period = FLAGS_minimum_update_period;
436 mpd_params.suggested_presentation_delay = FLAGS_suggested_presentation_delay;
437 mpd_params.time_shift_buffer_depth = FLAGS_time_shift_buffer_depth;
438 mpd_params.preserved_segments_outside_live_window =
439 FLAGS_preserved_segments_outside_live_window;
441 if (!FLAGS_utc_timings.empty()) {
442 base::StringPairs pairs;
443 if (!base::SplitStringIntoKeyValuePairs(FLAGS_utc_timings,
'=',
',',
445 LOG(ERROR) <<
"Invalid --utc_timings scheme_id_uri/value pairs.";
446 return base::nullopt;
448 for (
const auto& string_pair : pairs) {
449 mpd_params.utc_timings.push_back({string_pair.first, string_pair.second});
453 mpd_params.default_language = FLAGS_default_language;
454 mpd_params.default_text_language = FLAGS_default_text_language;
455 mpd_params.generate_static_live_mpd = FLAGS_generate_static_live_mpd;
456 mpd_params.generate_dash_if_iop_compliant_mpd =
457 FLAGS_generate_dash_if_iop_compliant_mpd;
458 mpd_params.allow_approximate_segment_timeline =
459 FLAGS_allow_approximate_segment_timeline;
461 HlsParams& hls_params = packaging_params.hls_params;
462 if (!GetHlsPlaylistType(FLAGS_hls_playlist_type, &hls_params.playlist_type)) {
463 return base::nullopt;
465 hls_params.master_playlist_output = FLAGS_hls_master_playlist_output;
466 hls_params.base_url = FLAGS_hls_base_url;
467 hls_params.key_uri = FLAGS_hls_key_uri;
468 hls_params.time_shift_buffer_depth = FLAGS_time_shift_buffer_depth;
469 hls_params.preserved_segments_outside_live_window =
470 FLAGS_preserved_segments_outside_live_window;
471 hls_params.default_language = FLAGS_default_language;
472 hls_params.default_text_language = FLAGS_default_text_language;
474 TestParams& test_params = packaging_params.test_params;
475 test_params.dump_stream_info = FLAGS_dump_stream_info;
476 test_params.inject_fake_clock = FLAGS_use_fake_clock_for_muxer;
477 if (!FLAGS_test_packager_version.empty())
478 test_params.injected_library_version = FLAGS_test_packager_version;
480 return packaging_params;
483 int PackagerMain(
int argc,
char** argv) {
485 base::CommandLine::Init(argc, argv);
488 logging::LoggingSettings log_settings;
489 log_settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
490 CHECK(logging::InitLogging(log_settings));
493 google::SetUsageMessage(base::StringPrintf(kUsage, argv[0]));
494 google::ParseCommandLineFlags(&argc, &argv,
true);
495 if (FLAGS_licenses) {
496 for (
const char* line : kLicenseNotice)
497 std::cout << line << std::endl;
501 google::ShowUsageWithFlags(
"Usage");
505 logging::SetMinLogLevel(logging::LOG_WARNING);
509 return kArgumentValidationFailed;
512 base::Optional<PackagingParams> packaging_params = GetPackagingParams();
513 if (!packaging_params)
514 return kArgumentValidationFailed;
516 std::vector<StreamDescriptor> stream_descriptors;
517 for (
int i = 1; i < argc; ++i) {
518 base::Optional<StreamDescriptor> stream_descriptor =
520 if (!stream_descriptor)
521 return kArgumentValidationFailed;
522 stream_descriptors.push_back(stream_descriptor.value());
526 packager.Initialize(packaging_params.value(), stream_descriptors);
528 LOG(ERROR) <<
"Failed to initialize packager: " << status.ToString();
529 return kArgumentValidationFailed;
531 status = packager.Run();
533 LOG(ERROR) <<
"Packaging Error: " << status.ToString();
534 return kPackagingFailed;
537 printf(
"Packaging completed successfully.\n");
546 int wmain(
int argc,
wchar_t* argv[],
wchar_t* envp[]) {
547 std::unique_ptr<char* [], std::function<void(char**)>> utf8_argv(
548 new char*[argc], [argc](
char** utf8_args) {
556 std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
557 for (
int idx = 0; idx < argc; ++idx) {
558 std::string utf8_arg(converter.to_bytes(argv[idx]));
560 utf8_argv[idx] =
new char[utf8_arg.size()];
561 memcpy(utf8_argv[idx], &utf8_arg[0], utf8_arg.size());
563 return shaka::PackagerMain(argc, utf8_argv.get());
566 int main(
int argc,
char** argv) {
567 return shaka::PackagerMain(argc, argv);
569 #endif // defined(OS_WIN) static std::string DefaultStreamLabelFunction(int max_sd_pixels, int max_hd_pixels, int max_uhd1_pixels, const EncryptionParams::EncryptedStreamAttributes &stream_attributes)
base::Optional< StreamDescriptor > ParseStreamDescriptor(const std::string &descriptor_string)
static bool ReadFileToString(const char *file_name, std::string *contents)
bool ValidateRawKeyCryptoFlags()
bool ValidateWidevineCryptoFlags()
All the methods that are virtual are virtual for mocking.
static std::string GetLibraryVersion()
static constexpr uint32_t kProtectionSchemeCenc
The protection scheme: "cenc", "cens", "cbc1", "cbcs".
bool ValidatePRCryptoFlags()