Shaka Packager SDK
packager_main.cc
1 // Copyright 2014 Google Inc. All rights reserved.
2 //
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file or at
5 // https://developers.google.com/open-source/licenses/bsd
6 
7 #include <gflags/gflags.h>
8 #include <iostream>
9 
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/raw_key_encryption_flags.h"
19 #include "packager/app/stream_descriptor.h"
20 #include "packager/app/vlog_flags.h"
21 #include "packager/app/widevine_encryption_flags.h"
22 #include "packager/base/command_line.h"
23 #include "packager/base/logging.h"
24 #include "packager/base/optional.h"
25 #include "packager/base/strings/string_number_conversions.h"
26 #include "packager/base/strings/string_split.h"
27 #include "packager/base/strings/string_util.h"
28 #include "packager/base/strings/stringprintf.h"
29 #include "packager/file/file.h"
30 #include "packager/packager.h"
31 
32 #if defined(OS_WIN)
33 #include <codecvt>
34 #include <functional>
35 #include <locale>
36 #endif // defined(OS_WIN)
37 
38 DEFINE_bool(dump_stream_info, false, "Dump demuxed stream info.");
39 DEFINE_bool(use_fake_clock_for_muxer,
40  false,
41  "Set to true to use a fake clock for muxer. With this flag set, "
42  "creation time and modification time in outputs are set to 0. "
43  "Should only be used for testing.");
44 DEFINE_bool(override_version,
45  false,
46  "Override packager version in the generated outputs with "
47  "--test_version if it is set to true. Should be used for "
48  "testing only.");
49 DEFINE_string(test_version,
50  "",
51  "Packager version for testing. Ignored if --override_version is "
52  "false. Should be used for testing only.");
53 
54 namespace shaka {
55 namespace {
56 
57 const char kUsage[] =
58  "%s [flags] <stream_descriptor> ...\n\n"
59  " stream_descriptor consists of comma separated field_name/value pairs:\n"
60  " field_name=value,[field_name=value,]...\n"
61  " Supported field names are as follows (names in parenthesis are alias):\n"
62  " - input (in): Required input/source media file path or network stream\n"
63  " URL.\n"
64  " - stream_selector (stream): Required field with value 'audio',\n"
65  " 'video', 'text', or stream number (zero based).\n"
66  " - output (out,init_segment): Required output file (single file) or\n"
67  " initialization file path (multiple file).\n"
68  " - segment_template (segment): Optional value which specifies the\n"
69  " naming pattern for the segment files, and that the stream should be\n"
70  " split into multiple files. Its presence should be consistent across\n"
71  " streams.\n"
72  " - bandwidth (bw): Optional value which contains a user-specified\n"
73  " content bit rate for the stream, in bits/sec. If specified, this\n"
74  " value is propagated to (HLS) EXT-X-STREAM-INF:BANDWIDTH or (DASH)\n"
75  " Representation@bandwidth and the $Bandwidth$ template parameter for\n"
76  " segment names. If not specified, the bandwidth value is estimated\n"
77  " from content bitrate. Note that it only affects the generated\n"
78  " manifests/playlists; it has no effect on the media content itself.\n"
79  " - language (lang): Optional value which contains a user-specified\n"
80  " language tag. If specified, this value overrides any language\n"
81  " metadata in the input stream.\n"
82  " - output_format (format): Optional value which specifies the format\n"
83  " of the output files (MP4 or WebM). If not specified, it will be\n"
84  " derived from the file extension of the output file.\n"
85  " - skip_encryption=0|1: Optional. Defaults to 0 if not specified. If\n"
86  " it is set to 1, no encryption of the stream will be made.\n"
87  " - drm_label: Optional value for custom DRM label, which defines the\n"
88  " encryption key applied to the stream. Typical values include AUDIO,\n"
89  " SD, HD, UHD1, UHD2. For raw key, it should be a label defined in\n"
90  " --keys. If not provided, the DRM label is derived from stream type\n"
91  " (video, audio), resolution, etc.\n"
92  " Note that it is case sensitive.\n"
93  " - trick_play_factor (tpf): Optional value which specifies the trick\n"
94  " play, a.k.a. trick mode, stream sampling rate among key frames.\n"
95  " If specified, the output is a trick play stream.\n"
96  " - hls_name: Used for HLS audio to set the NAME attribute for\n"
97  " EXT-X-MEDIA. Defaults to the base of the playlist name.\n"
98  " - hls_group_id: Used for HLS audio to set the GROUP-ID attribute for\n"
99  " EXT-X-MEDIA. Defaults to 'audio' if not specified.\n"
100  " - playlist_name: The HLS playlist file to create. Usually ends with\n"
101  " '.m3u8', and is relative to --hls_master_playlist_output. If\n"
102  " unspecified, defaults to something of the form 'stream_0.m3u8',\n"
103  " 'stream_1.m3u8', 'stream_2.m3u8', etc.\n"
104  " - iframe_playlist_name: The optional HLS I-Frames only playlist file\n"
105  " to create. Usually ends with '.m3u8', and is relative to\n"
106  " hls_master_playlist_output. Should only be set for video streams. If\n"
107  " unspecified, no I-Frames only playlist is created.\n";
108 
109 // Labels for parameters in RawKey key info.
110 const char kDrmLabelLabel[] = "label";
111 const char kKeyIdLabel[] = "key_id";
112 const char kKeyLabel[] = "key";
113 
114 enum ExitStatus {
115  kSuccess = 0,
116  kArgumentValidationFailed,
117  kPackagingFailed,
118  kInternalError,
119 };
120 
121 bool GetWidevineSigner(WidevineSigner* signer) {
122  signer->signer_name = FLAGS_signer;
123  if (!FLAGS_aes_signing_key_bytes.empty()) {
124  signer->signing_key_type = WidevineSigner::SigningKeyType::kAes;
125  signer->aes.key = FLAGS_aes_signing_key_bytes;
126  signer->aes.iv = FLAGS_aes_signing_iv_bytes;
127  } else if (!FLAGS_rsa_signing_key_path.empty()) {
128  signer->signing_key_type = WidevineSigner::SigningKeyType::kRsa;
129  if (!File::ReadFileToString(FLAGS_rsa_signing_key_path.c_str(),
130  &signer->rsa.key)) {
131  LOG(ERROR) << "Failed to read from '" << FLAGS_rsa_signing_key_path
132  << "'.";
133  return false;
134  }
135  }
136  return true;
137 }
138 
139 bool GetHlsPlaylistType(const std::string& playlist_type,
140  HlsPlaylistType* playlist_type_enum) {
141  if (base::ToUpperASCII(playlist_type) == "VOD") {
142  *playlist_type_enum = HlsPlaylistType::kVod;
143  } else if (base::ToUpperASCII(playlist_type) == "LIVE") {
144  *playlist_type_enum = HlsPlaylistType::kLive;
145  } else if (base::ToUpperASCII(playlist_type) == "EVENT") {
146  *playlist_type_enum = HlsPlaylistType::kEvent;
147  } else {
148  LOG(ERROR) << "Unrecognized playlist type " << playlist_type;
149  return false;
150  }
151  return true;
152 }
153 
154 bool GetProtectionScheme(uint32_t* protection_scheme) {
155  if (FLAGS_protection_scheme == "cenc") {
156  *protection_scheme = EncryptionParams::kProtectionSchemeCenc;
157  return true;
158  }
159  if (FLAGS_protection_scheme == "cbc1") {
160  *protection_scheme = EncryptionParams::kProtectionSchemeCbc1;
161  return true;
162  }
163  if (FLAGS_protection_scheme == "cbcs") {
164  *protection_scheme = EncryptionParams::kProtectionSchemeCbcs;
165  return true;
166  }
167  if (FLAGS_protection_scheme == "cens") {
168  *protection_scheme = EncryptionParams::kProtectionSchemeCens;
169  return true;
170  }
171  LOG(ERROR) << "Unrecognized protection_scheme " << FLAGS_protection_scheme;
172  return false;
173 }
174 
175 bool ParseKeys(const std::string& keys, RawKeyParams* raw_key) {
176  for (const std::string& key_data : base::SplitString(
177  keys, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) {
178  base::StringPairs string_pairs;
179  base::SplitStringIntoKeyValuePairs(key_data, '=', ':', &string_pairs);
180 
181  std::map<std::string, std::string> value_map;
182  for (const auto& string_pair : string_pairs)
183  value_map[string_pair.first] = string_pair.second;
184  const std::string drm_label = value_map[kDrmLabelLabel];
185  if (raw_key->key_map.find(drm_label) != raw_key->key_map.end()) {
186  LOG(ERROR) << "Seeing duplicated DRM label '" << drm_label << "'.";
187  return false;
188  }
189  auto& key_info = raw_key->key_map[drm_label];
190  if (value_map[kKeyIdLabel].empty() ||
191  !base::HexStringToBytes(value_map[kKeyIdLabel], &key_info.key_id)) {
192  LOG(ERROR) << "Empty key id or invalid hex string for key id: "
193  << value_map[kKeyIdLabel];
194  return false;
195  }
196  if (value_map[kKeyLabel].empty() ||
197  !base::HexStringToBytes(value_map[kKeyLabel], &key_info.key)) {
198  LOG(ERROR) << "Empty key or invalid hex string for key: "
199  << value_map[kKeyLabel];
200  return false;
201  }
202  }
203  return true;
204 }
205 
206 bool GetRawKeyParams(RawKeyParams* raw_key) {
207  raw_key->iv = FLAGS_iv_bytes;
208  raw_key->pssh = FLAGS_pssh_bytes;
209  if (!FLAGS_keys.empty()) {
210  if (!ParseKeys(FLAGS_keys, raw_key)) {
211  LOG(ERROR) << "Failed to parse --keys " << FLAGS_keys;
212  return false;
213  }
214  } else {
215  // An empty StreamLabel specifies the default key info.
216  RawKeyParams::KeyInfo& key_info = raw_key->key_map[""];
217  key_info.key_id = FLAGS_key_id_bytes;
218  key_info.key = FLAGS_key_bytes;
219  }
220  return true;
221 }
222 
223 bool ParseAdCues(const std::string& ad_cues, std::vector<Cuepoint>* cuepoints) {
224  // Track if optional field is supplied consistently across all cue points.
225  size_t duration_count = 0;
226 
227  for (const std::string& ad_cue : base::SplitString(
228  ad_cues, ";", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) {
229  Cuepoint cuepoint;
230  auto split_ad_cue = base::SplitString(ad_cue, ",", base::TRIM_WHITESPACE,
231  base::SPLIT_WANT_NONEMPTY);
232  if (split_ad_cue.size() > 2) {
233  LOG(ERROR) << "Failed to parse --ad_cues " << ad_cues
234  << " Each ad cue must contain no more than 2 components.";
235  }
236  if (!base::StringToDouble(split_ad_cue.front(),
237  &cuepoint.start_time_in_seconds)) {
238  LOG(ERROR) << "Failed to parse --ad_cues " << ad_cues
239  << " Start time component must be of type double.";
240  return false;
241  }
242  if (split_ad_cue.size() > 1) {
243  duration_count++;
244  if (!base::StringToDouble(split_ad_cue[1],
245  &cuepoint.duration_in_seconds)) {
246  LOG(ERROR) << "Failed to parse --ad_cues " << ad_cues
247  << " Duration component must be of type double.";
248  return false;
249  }
250  }
251  cuepoints->push_back(cuepoint);
252  }
253 
254  if (duration_count > 0 && duration_count != cuepoints->size()) {
255  LOG(ERROR) << "Failed to parse --ad_cues " << ad_cues
256  << " Duration component is optional. However if it is supplied,"
257  << " it must be supplied consistently across all cuepoints.";
258  return false;
259  }
260  return true;
261 }
262 
263 base::Optional<PackagingParams> GetPackagingParams() {
264  PackagingParams packaging_params;
265 
266  packaging_params.temp_dir = FLAGS_temp_dir;
267 
268  AdCueGeneratorParams& ad_cue_generator_params =
269  packaging_params.ad_cue_generator_params;
270  if (!ParseAdCues(FLAGS_ad_cues, &ad_cue_generator_params.cue_points)) {
271  return base::nullopt;
272  }
273 
274  ChunkingParams& chunking_params = packaging_params.chunking_params;
275  chunking_params.segment_duration_in_seconds = FLAGS_segment_duration;
276  chunking_params.subsegment_duration_in_seconds = FLAGS_fragment_duration;
277  chunking_params.segment_sap_aligned = FLAGS_segment_sap_aligned;
278  chunking_params.subsegment_sap_aligned = FLAGS_fragment_sap_aligned;
279 
280  int num_key_providers = 0;
281  EncryptionParams& encryption_params = packaging_params.encryption_params;
282  if (FLAGS_enable_widevine_encryption) {
283  encryption_params.key_provider = KeyProvider::kWidevine;
284  ++num_key_providers;
285  }
286  if (FLAGS_enable_playready_encryption) {
287  encryption_params.key_provider = KeyProvider::kPlayready;
288  ++num_key_providers;
289  }
290  if (FLAGS_enable_raw_key_encryption) {
291  encryption_params.key_provider = KeyProvider::kRawKey;
292  ++num_key_providers;
293  }
294  if (num_key_providers > 1) {
295  LOG(ERROR) << "Only one of --enable_widevine_encryption, "
296  "--enable_playready_encryption, "
297  "--enable_raw_key_encryption can be enabled.";
298  return base::nullopt;
299  }
300 
301  if (encryption_params.key_provider != KeyProvider::kNone) {
302  encryption_params.clear_lead_in_seconds = FLAGS_clear_lead;
303  if (!GetProtectionScheme(&encryption_params.protection_scheme))
304  return base::nullopt;
305  encryption_params.crypto_period_duration_in_seconds =
306  FLAGS_crypto_period_duration;
307  encryption_params.vp9_subsample_encryption = FLAGS_vp9_subsample_encryption;
308  encryption_params.stream_label_func = std::bind(
309  &Packager::DefaultStreamLabelFunction, FLAGS_max_sd_pixels,
310  FLAGS_max_hd_pixels, FLAGS_max_uhd1_pixels, std::placeholders::_1);
311  }
312  switch (encryption_params.key_provider) {
313  case KeyProvider::kWidevine: {
314  WidevineEncryptionParams& widevine = encryption_params.widevine;
315  widevine.key_server_url = FLAGS_key_server_url;
316  widevine.include_common_pssh = FLAGS_include_common_pssh;
317 
318  widevine.content_id = FLAGS_content_id_bytes;
319  widevine.policy = FLAGS_policy;
320  widevine.group_id = FLAGS_group_id_bytes;
321  if (!GetWidevineSigner(&widevine.signer))
322  return base::nullopt;
323  break;
324  }
325  case KeyProvider::kPlayready: {
326  PlayreadyEncryptionParams& playready = encryption_params.playready;
327  playready.key_server_url = FLAGS_playready_server_url;
328  playready.program_identifier = FLAGS_program_identifier;
329  playready.ca_file = FLAGS_ca_file;
330  playready.client_cert_file = FLAGS_client_cert_file;
331  playready.client_cert_private_key_file =
332  FLAGS_client_cert_private_key_file;
333  playready.client_cert_private_key_password =
334  FLAGS_client_cert_private_key_password;
335  playready.key_id = FLAGS_playready_key_id_bytes;
336  playready.key = FLAGS_playready_key_bytes;
337  break;
338  }
339  case KeyProvider::kRawKey: {
340  if (!GetRawKeyParams(&encryption_params.raw_key))
341  return base::nullopt;
342  break;
343  }
344  case KeyProvider::kNone:
345  break;
346  }
347 
348  num_key_providers = 0;
349  DecryptionParams& decryption_params = packaging_params.decryption_params;
350  if (FLAGS_enable_widevine_decryption) {
351  decryption_params.key_provider = KeyProvider::kWidevine;
352  ++num_key_providers;
353  }
354  if (FLAGS_enable_raw_key_decryption) {
355  decryption_params.key_provider = KeyProvider::kRawKey;
356  ++num_key_providers;
357  }
358  if (num_key_providers > 1) {
359  LOG(ERROR) << "Only one of --enable_widevine_decryption, "
360  "--enable_raw_key_decryption can be enabled.";
361  return base::nullopt;
362  }
363  switch (decryption_params.key_provider) {
364  case KeyProvider::kWidevine: {
365  WidevineDecryptionParams& widevine = decryption_params.widevine;
366  widevine.key_server_url = FLAGS_key_server_url;
367  if (!GetWidevineSigner(&widevine.signer))
368  return base::nullopt;
369  break;
370  }
371  case KeyProvider::kRawKey: {
372  if (!GetRawKeyParams(&decryption_params.raw_key))
373  return base::nullopt;
374  break;
375  }
376  case KeyProvider::kPlayready:
377  case KeyProvider::kNone:
378  break;
379  }
380 
381  Mp4OutputParams& mp4_params = packaging_params.mp4_output_params;
382  mp4_params.num_subsegments_per_sidx = FLAGS_num_subsegments_per_sidx;
383  if (FLAGS_mp4_use_decoding_timestamp_in_timeline) {
384  LOG(WARNING) << "Flag --mp4_use_decoding_timestamp_in_timeline is set. "
385  "Note that it is a temporary hack to workaround Chromium "
386  "bug https://crbug.com/398130. The flag may be removed "
387  "when the Chromium bug is fixed.";
388  }
389  mp4_params.use_decoding_timestamp_in_timeline =
390  FLAGS_mp4_use_decoding_timestamp_in_timeline;
391  mp4_params.include_pssh_in_stream = FLAGS_mp4_include_pssh_in_stream;
392 
393  packaging_params.output_media_info = FLAGS_output_media_info;
394 
395  MpdParams& mpd_params = packaging_params.mpd_params;
396  mpd_params.generate_static_live_mpd = FLAGS_generate_static_mpd;
397  mpd_params.mpd_output = FLAGS_mpd_output;
398  mpd_params.base_urls = base::SplitString(
399  FLAGS_base_urls, ",", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
400  mpd_params.generate_dash_if_iop_compliant_mpd =
401  FLAGS_generate_dash_if_iop_compliant_mpd;
402  mpd_params.minimum_update_period = FLAGS_minimum_update_period;
403  mpd_params.min_buffer_time = FLAGS_min_buffer_time;
404  mpd_params.time_shift_buffer_depth = FLAGS_time_shift_buffer_depth;
405  mpd_params.suggested_presentation_delay = FLAGS_suggested_presentation_delay;
406  mpd_params.default_language = FLAGS_default_language;
407 
408  HlsParams& hls_params = packaging_params.hls_params;
409  if (!GetHlsPlaylistType(FLAGS_hls_playlist_type, &hls_params.playlist_type)) {
410  return base::nullopt;
411  }
412  hls_params.master_playlist_output = FLAGS_hls_master_playlist_output;
413  hls_params.base_url = FLAGS_hls_base_url;
414  hls_params.key_uri = FLAGS_hls_key_uri;
415  hls_params.time_shift_buffer_depth = FLAGS_time_shift_buffer_depth;
416  hls_params.default_language = FLAGS_default_language;
417 
418  TestParams& test_params = packaging_params.test_params;
419  test_params.dump_stream_info = FLAGS_dump_stream_info;
420  test_params.inject_fake_clock = FLAGS_use_fake_clock_for_muxer;
421  if (FLAGS_override_version)
422  test_params.injected_library_version = FLAGS_test_version;
423 
424  return packaging_params;
425 }
426 
427 int PackagerMain(int argc, char** argv) {
428  // Needed to enable VLOG/DVLOG through --vmodule or --v.
429  base::CommandLine::Init(argc, argv);
430 
431  // Set up logging.
432  logging::LoggingSettings log_settings;
433  log_settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
434  CHECK(logging::InitLogging(log_settings));
435 
436  google::SetVersionString(shaka::Packager::GetLibraryVersion());
437  google::SetUsageMessage(base::StringPrintf(kUsage, argv[0]));
438  google::ParseCommandLineFlags(&argc, &argv, true);
439  if (argc < 2) {
440  google::ShowUsageWithFlags("Usage");
441  return kSuccess;
442  }
443 
446  return kArgumentValidationFailed;
447  }
448 
449  base::Optional<PackagingParams> packaging_params = GetPackagingParams();
450  if (!packaging_params)
451  return kArgumentValidationFailed;
452 
453  std::vector<StreamDescriptor> stream_descriptors;
454  for (int i = 1; i < argc; ++i) {
455  base::Optional<StreamDescriptor> stream_descriptor =
456  ParseStreamDescriptor(argv[i]);
457  if (!stream_descriptor)
458  return kArgumentValidationFailed;
459  stream_descriptors.push_back(stream_descriptor.value());
460  }
461  Packager packager;
462  Status status =
463  packager.Initialize(packaging_params.value(), stream_descriptors);
464  if (!status.ok()) {
465  LOG(ERROR) << "Failed to initialize packager: " << status.ToString();
466  return kArgumentValidationFailed;
467  }
468  status = packager.Run();
469  if (!status.ok()) {
470  LOG(ERROR) << "Packaging Error: " << status.ToString();
471  return kPackagingFailed;
472  }
473  printf("Packaging completed successfully.\n");
474  return kSuccess;
475 }
476 
477 } // namespace
478 } // namespace shaka
479 
480 #if defined(OS_WIN)
481 // Windows wmain, which converts wide character arguments to UTF-8.
482 int wmain(int argc, wchar_t* argv[], wchar_t* envp[]) {
483  std::unique_ptr<char* [], std::function<void(char**)>> utf8_argv(
484  new char*[argc], [argc](char** utf8_args) {
485  // TODO(tinskip): This leaks, but if this code is enabled, it crashes.
486  // Figure out why. I suspect gflags does something funny with the
487  // argument array.
488  // for (int idx = 0; idx < argc; ++idx)
489  // delete[] utf8_args[idx];
490  delete[] utf8_args;
491  });
492  std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
493  for (int idx = 0; idx < argc; ++idx) {
494  std::string utf8_arg(converter.to_bytes(argv[idx]));
495  utf8_arg += '\0';
496  utf8_argv[idx] = new char[utf8_arg.size()];
497  memcpy(utf8_argv[idx], &utf8_arg[0], utf8_arg.size());
498  }
499  return shaka::PackagerMain(argc, utf8_argv.get());
500 }
501 #else
502 int main(int argc, char** argv) {
503  return shaka::PackagerMain(argc, argv);
504 }
505 #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)
Definition: packager.cc:941
HlsPlaylistType
Definition: hls_params.h:16
base::Optional< StreamDescriptor > ParseStreamDescriptor(const std::string &descriptor_string)
static bool ReadFileToString(const char *file_name, std::string *contents)
Definition: file.cc:216
bool ValidateRawKeyCryptoFlags()
bool ValidateWidevineCryptoFlags()
All the methods that are virtual are virtual for mocking.
static std::string GetLibraryVersion()
Definition: packager.cc:937
static constexpr uint32_t kProtectionSchemeCenc
The protection scheme: "cenc", "cens", "cbc1", "cbcs".