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