DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator
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/crypto_flags.h"
11 #include "packager/app/fixed_key_encryption_flags.h"
12 #include "packager/app/hls_flags.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/logging.h"
23 #include "packager/base/optional.h"
24 #include "packager/base/strings/string_number_conversions.h"
25 #include "packager/base/strings/string_split.h"
26 #include "packager/base/strings/stringprintf.h"
27 #include "packager/media/file/file.h"
28 #include "packager/packager.h"
29 #include "packager/version/version.h"
30 
31 #if defined(OS_WIN)
32 #include <codecvt>
33 #include <functional>
34 #include <locale>
35 #endif // defined(OS_WIN)
36 
37 DEFINE_bool(override_version,
38  false,
39  "Override packager version in the generated outputs with "
40  "--test_version if it is set to true. Should be used for "
41  "testing only.");
42 DEFINE_string(test_version,
43  "",
44  "Packager version for testing. Ignored if --override_version is "
45  "false. Should be used for testing only.");
46 
47 namespace shaka {
48 namespace {
49 
50 const char kUsage[] =
51  "%s [flags] <stream_descriptor> ...\n\n"
52  " stream_descriptor consists of comma separated field_name/value pairs:\n"
53  " field_name=value,[field_name=value,]...\n"
54  " Supported field names are as follows (names in parenthesis are alias):\n"
55  " - input (in): Required input/source media file path or network stream\n"
56  " URL.\n"
57  " - stream_selector (stream): Required field with value 'audio',\n"
58  " 'video', 'text', or stream number (zero based).\n"
59  " - output (out,init_segment): Required output file (single file) or\n"
60  " initialization file path (multiple file).\n"
61  " - segment_template (segment): Optional value which specifies the\n"
62  " naming pattern for the segment files, and that the stream should be\n"
63  " split into multiple files. Its presence should be consistent across\n"
64  " streams.\n"
65  " - bandwidth (bw): Optional value which contains a user-specified\n"
66  " content bit rate for the stream, in bits/sec. If specified, this\n"
67  " value is propagated to the $Bandwidth$ template parameter for\n"
68  " segment names. If not specified, its value may be estimated.\n"
69  " - language (lang): Optional value which contains a user-specified\n"
70  " language tag. If specified, this value overrides any language\n"
71  " metadata in the input stream.\n"
72  " - output_format (format): Optional value which specifies the format\n"
73  " of the output files (MP4 or WebM). If not specified, it will be\n"
74  " derived from the file extension of the output file.\n"
75  " - skip_encryption=0|1: Optional. Defaults to 0 if not specified. If\n"
76  " it is set to 1, no encryption of the stream will be made.\n"
77  " - trick_play_factor (tpf): Optional value which specifies the trick\n"
78  " play, a.k.a. trick mode, stream sampling rate among key frames.\n"
79  " If specified, the output is a trick play stream.\n"
80  " - hls_name: Required for audio when outputting HLS.\n"
81  " name of the output stream. This is not (necessarily) the same as\n"
82  " output. This is used as the NAME attribute for EXT-X-MEDIA\n"
83  " - hls_group_id: Required for audio when outputting HLS.\n"
84  " The group ID for the output stream. This is used as the GROUP-ID\n"
85  " attribute for EXT-X-MEDIA.\n"
86  " - playlist_name: Required for HLS output.\n"
87  " Name of the playlist for the stream. Usually ends with '.m3u8'.\n";
88 
89 enum ExitStatus {
90  kSuccess = 0,
91  kArgumentValidationFailed,
92  kPackagingFailed,
93  kInternalError,
94 };
95 
96 base::Optional<PackagingParams> GetPackagingParams() {
97  PackagingParams packaging_params;
98 
99  ChunkingParams& chunking_params = packaging_params.chunking_params;
100  chunking_params.segment_duration_in_seconds = FLAGS_segment_duration;
101  chunking_params.subsegment_duration_in_seconds = FLAGS_fragment_duration;
102  chunking_params.segment_sap_aligned = FLAGS_segment_sap_aligned;
103  chunking_params.subsegment_sap_aligned = FLAGS_fragment_sap_aligned;
104 
105  int num_key_providers = 0;
106  EncryptionParams& encryption_params = packaging_params.encryption_params;
107  if (FLAGS_enable_widevine_encryption) {
108  encryption_params.key_provider = KeyProvider::kWidevine;
109  ++num_key_providers;
110  }
111  if (FLAGS_enable_playready_encryption) {
112  encryption_params.key_provider = KeyProvider::kPlayready;
113  ++num_key_providers;
114  }
115  if (FLAGS_enable_fixed_key_encryption) {
116  encryption_params.key_provider = KeyProvider::kRawKey;
117  ++num_key_providers;
118  }
119  if (num_key_providers > 1) {
120  LOG(ERROR) << "Only one of --enable_widevine_encryption, "
121  "--enable_playready_encryption, "
122  "--enable_fixed_key_encryption can be enabled.";
123  return base::nullopt;
124  }
125 
126  if (encryption_params.key_provider != KeyProvider::kNone) {
127  encryption_params.clear_lead_in_seconds = FLAGS_clear_lead;
128  encryption_params.protection_scheme = FLAGS_protection_scheme;
129  encryption_params.crypto_period_duration_in_seconds =
130  FLAGS_crypto_period_duration;
131  encryption_params.vp9_subsample_encryption = FLAGS_vp9_subsample_encryption;
132  encryption_params.stream_label_func = std::bind(
133  &EncryptionParams::DefaultStreamLabelFunction, FLAGS_max_sd_pixels,
134  FLAGS_max_hd_pixels, FLAGS_max_uhd1_pixels, std::placeholders::_1);
135  }
136  switch (encryption_params.key_provider) {
137  case KeyProvider::kWidevine: {
138  WidevineEncryptionParams& widevine = encryption_params.widevine;
139  widevine.key_server_url = FLAGS_key_server_url;
140  widevine.include_common_pssh = FLAGS_include_common_pssh;
141 
142  if (!base::HexStringToBytes(FLAGS_content_id, &widevine.content_id)) {
143  LOG(ERROR) << "Invalid content_id hex string specified.";
144  return base::nullopt;
145  }
146  widevine.policy = FLAGS_policy;
147  widevine.signer.signer_name = FLAGS_signer;
148  if (!FLAGS_aes_signing_key.empty() && !FLAGS_rsa_signing_key_path.empty()) {
149  LOG(ERROR) << "Only one of --aes_signing_key and "
150  "--rsa_signing_key_path is needed.";
151  return base::nullopt;
152  }
153  WidevineSigner& signer = widevine.signer;
154  if (!FLAGS_aes_signing_key.empty()) {
155  // TODO(kqyang): Take care of hex conversion and file read here.
156  signer.signing_key_type = WidevineSigner::SigningKeyType::kAes;
157  signer.aes.key = FLAGS_aes_signing_key;
158  signer.aes.iv = FLAGS_aes_signing_iv;
159  }
160  if (!FLAGS_rsa_signing_key_path.empty()) {
161  signer.signing_key_type = WidevineSigner::SigningKeyType::kRsa;
162  if (!media::File::ReadFileToString(FLAGS_rsa_signing_key_path.c_str(),
163  &signer.rsa.key)) {
164  LOG(ERROR) << "Failed to read from '" << FLAGS_rsa_signing_key_path
165  << "'.";
166  return base::nullopt;
167  }
168  }
169  break;
170  }
171  case KeyProvider::kPlayready: {
172  PlayreadyEncryptionParams& playready = encryption_params.playready;
173  playready.key_server_url = FLAGS_playready_server_url;
174  playready.program_identifier = FLAGS_program_identifier;
175  playready.ca_file = FLAGS_ca_file;
176  playready.client_cert_file = FLAGS_client_cert_file;
177  playready.client_cert_private_key_file =
178  FLAGS_client_cert_private_key_file;
179  playready.client_cert_private_key_password =
180  FLAGS_client_cert_private_key_password;
181  playready.key_id = FLAGS_playready_key_id;
182  playready.key = FLAGS_playready_key;
183  break;
184  }
185  case KeyProvider::kRawKey: {
186  RawKeyEncryptionParams& raw_key = encryption_params.raw_key;
187  raw_key.iv = FLAGS_iv;
188  raw_key.pssh = FLAGS_pssh;
189  // An empty TrackType specifies the default KeyPair.
190  RawKeyEncryptionParams::KeyPair& key_pair = raw_key.key_map[""];
191  // TODO(kqyang): Take care of hex conversion here.
192  key_pair.key_id = FLAGS_key_id;
193  key_pair.key = FLAGS_key;
194  break;
195  }
196  case KeyProvider::kNone:
197  break;
198  }
199 
200  num_key_providers = 0;
201  DecryptionParams& decryption_params = packaging_params.decryption_params;
202  if (FLAGS_enable_widevine_decryption) {
203  decryption_params.key_provider = KeyProvider::kWidevine;
204  ++num_key_providers;
205  }
206  if (FLAGS_enable_fixed_key_decryption) {
207  decryption_params.key_provider = KeyProvider::kRawKey;
208  ++num_key_providers;
209  }
210  if (num_key_providers > 1) {
211  LOG(ERROR) << "Only one of --enable_widevine_decryption, "
212  "--enable_fixed_key_decryption can be enabled.";
213  return base::nullopt;
214  }
215  switch (decryption_params.key_provider) {
216  case KeyProvider::kWidevine: {
217  WidevineDecryptionParams& widevine = decryption_params.widevine;
218  widevine.key_server_url = FLAGS_key_server_url;
219 
220  widevine.signer.signer_name = FLAGS_signer;
221  if (!FLAGS_aes_signing_key.empty() && !FLAGS_rsa_signing_key_path.empty()) {
222  LOG(ERROR) << "Only one of --aes_signing_key and "
223  "--rsa_signing_key_path is needed.";
224  return base::nullopt;
225  }
226  WidevineSigner& signer = widevine.signer;
227  if (!FLAGS_aes_signing_key.empty()) {
228  // TODO(kqyang): Take care of hex conversion and file read here.
229  signer.signing_key_type = WidevineSigner::SigningKeyType::kAes;
230  signer.aes.key = FLAGS_aes_signing_key;
231  signer.aes.iv = FLAGS_aes_signing_iv;
232  }
233  if (!FLAGS_rsa_signing_key_path.empty()) {
234  signer.signing_key_type = WidevineSigner::SigningKeyType::kRsa;
235  if (!media::File::ReadFileToString(FLAGS_rsa_signing_key_path.c_str(),
236  &signer.rsa.key)) {
237  LOG(ERROR) << "Failed to read from '" << FLAGS_rsa_signing_key_path
238  << "'.";
239  return base::nullopt;
240  }
241  }
242  break;
243  }
244  case KeyProvider::kRawKey: {
245  RawKeyDecryptionParams& raw_key = decryption_params.raw_key;
246  // An empty TrackType specifies the default KeyPair.
247  RawKeyDecryptionParams::KeyPair& key_pair = raw_key.key_map[""];
248  // TODO(kqyang): Take care of hex conversion here.
249  key_pair.key_id = FLAGS_key_id;
250  key_pair.key = FLAGS_key;
251  break;
252  }
253  case KeyProvider::kNone:
254  case KeyProvider::kPlayready:
255  break;
256  }
257 
258  Mp4OutputParams& mp4_params = packaging_params.mp4_output_params;
259  mp4_params.num_subsegments_per_sidx = FLAGS_num_subsegments_per_sidx;
260  if (FLAGS_mp4_use_decoding_timestamp_in_timeline) {
261  LOG(WARNING) << "Flag --mp4_use_decoding_timestamp_in_timeline is set. "
262  "Note that it is a temporary hack to workaround Chromium "
263  "bug https://crbug.com/398130. The flag may be removed "
264  "when the Chromium bug is fixed.";
265  }
266  mp4_params.use_decoding_timestamp_in_timeline =
267  FLAGS_mp4_use_decoding_timestamp_in_timeline;
268  mp4_params.include_pssh_in_stream = FLAGS_mp4_include_pssh_in_stream;
269 
270  packaging_params.output_media_info = FLAGS_output_media_info;
271 
272  MpdParams& mpd_params = packaging_params.mpd_params;
273  mpd_params.generate_static_live_mpd = FLAGS_generate_static_mpd;
274  mpd_params.mpd_output = FLAGS_mpd_output;
275  mpd_params.base_urls = base::SplitString(
276  FLAGS_base_urls, ",", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
277  mpd_params.generate_dash_if_iop_compliant_mpd =
278  FLAGS_generate_dash_if_iop_compliant_mpd;
279  mpd_params.minimum_update_period = FLAGS_minimum_update_period;
280  mpd_params.min_buffer_time = FLAGS_min_buffer_time;
281  mpd_params.time_shift_buffer_depth = FLAGS_time_shift_buffer_depth;
282  mpd_params.suggested_presentation_delay = FLAGS_suggested_presentation_delay;
283  mpd_params.default_language = FLAGS_default_language;
284 
285  HlsParams& hls_params = packaging_params.hls_params;
286  hls_params.master_playlist_output = FLAGS_hls_master_playlist_output;
287  hls_params.base_url = FLAGS_hls_base_url;
288 
289  return packaging_params;
290 }
291 
292 int PackagerMain(int argc, char** argv) {
293  base::AtExitManager exit;
294  // Needed to enable VLOG/DVLOG through --vmodule or --v.
295  base::CommandLine::Init(argc, argv);
296 
297  // Set up logging.
298  logging::LoggingSettings log_settings;
299  log_settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
300  CHECK(logging::InitLogging(log_settings));
301 
302  google::SetVersionString(GetPackagerVersion());
303  google::SetUsageMessage(base::StringPrintf(kUsage, argv[0]));
304  google::ParseCommandLineFlags(&argc, &argv, true);
305  if (argc < 2) {
306  google::ShowUsageWithFlags("Usage");
307  return kSuccess;
308  }
309 
312  return kArgumentValidationFailed;
313  }
314 
315  if (FLAGS_override_version)
316  SetPackagerVersionForTesting(FLAGS_test_version);
317 
318  base::Optional<PackagingParams> packaging_params = GetPackagingParams();
319  if (!packaging_params)
320  return kArgumentValidationFailed;
321 
322  std::vector<StreamDescriptor> stream_descriptors;
323  for (int i = 1; i < argc; ++i) {
324  base::Optional<StreamDescriptor> stream_descriptor =
325  ParseStreamDescriptor(argv[i]);
326  if (!stream_descriptor)
327  return kArgumentValidationFailed;
328  stream_descriptors.push_back(stream_descriptor.value());
329  }
330  ShakaPackager packager;
331  media::Status status =
332  packager.Initialize(packaging_params.value(), stream_descriptors);
333  if (!status.ok()) {
334  LOG(ERROR) << "Failed to initialize packager: " << status.ToString();
335  return kArgumentValidationFailed;
336  }
337  status = packager.Run();
338  if (!status.ok()) {
339  LOG(ERROR) << "Packaging Error: " << status.ToString();
340  return kPackagingFailed;
341  }
342  printf("Packaging completed successfully.\n");
343  return kSuccess;
344 }
345 
346 } // namespace
347 } // namespace shaka
348 
349 #if defined(OS_WIN)
350 // Windows wmain, which converts wide character arguments to UTF-8.
351 int wmain(int argc, wchar_t* argv[], wchar_t* envp[]) {
352  std::unique_ptr<char* [], std::function<void(char**)>> utf8_argv(
353  new char*[argc], [argc](char** utf8_args) {
354  // TODO(tinskip): This leaks, but if this code is enabled, it crashes.
355  // Figure out why. I suspect gflags does something funny with the
356  // argument array.
357  // for (int idx = 0; idx < argc; ++idx)
358  // delete[] utf8_args[idx];
359  delete[] utf8_args;
360  });
361  std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
362  for (int idx = 0; idx < argc; ++idx) {
363  std::string utf8_arg(converter.to_bytes(argv[idx]));
364  utf8_arg += '\0';
365  utf8_argv[idx] = new char[utf8_arg.size()];
366  memcpy(utf8_argv[idx], &utf8_arg[0], utf8_arg.size());
367  }
368  return shaka::PackagerMain(argc, utf8_argv.get());
369 }
370 #else
371 int main(int argc, char** argv) {
372  return shaka::PackagerMain(argc, argv);
373 }
374 #endif // defined(OS_WIN)
base::Optional< StreamDescriptor > ParseStreamDescriptor(const std::string &descriptor_string)
bool ValidateWidevineCryptoFlags()
static bool ReadFileToString(const char *file_name, std::string *contents)
Definition: file.cc:185
bool ValidateFixedCryptoFlags()