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/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/stream_descriptor.h"
17 #include "packager/app/vlog_flags.h"
18 #include "packager/app/widevine_encryption_flags.h"
19 #include "packager/base/at_exit.h"
20 #include "packager/base/command_line.h"
21 #include "packager/base/files/file_path.h"
22 #include "packager/base/logging.h"
23 #include "packager/base/path_service.h"
24 #include "packager/base/strings/string_split.h"
25 #include "packager/base/strings/stringprintf.h"
26 #include "packager/base/threading/simple_thread.h"
27 #include "packager/base/time/clock.h"
28 #include "packager/hls/base/hls_notifier.h"
29 #include "packager/hls/base/simple_hls_notifier.h"
30 #include "packager/media/base/container_names.h"
31 #include "packager/media/base/demuxer.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/event/hls_notify_muxer_listener.h"
37 #include "packager/media/event/mpd_notify_muxer_listener.h"
38 #include "packager/media/event/vod_media_info_dump_muxer_listener.h"
39 #include "packager/media/file/file.h"
40 #include "packager/media/formats/mp2t/ts_muxer.h"
41 #include "packager/media/formats/mp4/mp4_muxer.h"
42 #include "packager/media/formats/webm/webm_muxer.h"
43 #include "packager/mpd/base/dash_iop_mpd_notifier.h"
44 #include "packager/mpd/base/media_info.pb.h"
45 #include "packager/mpd/base/mpd_builder.h"
46 #include "packager/mpd/base/simple_mpd_notifier.h"
47 #include "packager/version/version.h"
48 
49 #if defined(OS_WIN)
50 #include <codecvt>
51 #include <functional>
52 #include <locale>
53 #endif // defined(OS_WIN)
54 
55 DEFINE_bool(use_fake_clock_for_muxer,
56  false,
57  "Set to true to use a fake clock for muxer. With this flag set, "
58  "creation time and modification time in outputs are set to 0. "
59  "Should only be used for testing.");
60 DEFINE_bool(override_version,
61  false,
62  "Override packager version in the generated outputs with "
63  "--test_version if it is set to true. Should be used for "
64  "testing only.");
65 DEFINE_string(test_version,
66  "",
67  "Packager version for testing. Ignored if --override_version is "
68  "false. Should be used for testing only.");
69 
70 namespace shaka {
71 namespace media {
72 namespace {
73 
74 const char kUsage[] =
75  "%s [flags] <stream_descriptor> ...\n\n"
76  " stream_descriptor consists of comma separated field_name/value pairs:\n"
77  " field_name=value,[field_name=value,]...\n"
78  " Supported field names are as follows:\n"
79  " - input (in): Required input/source media file path or network stream\n"
80  " URL.\n"
81  " - stream_selector (stream): Required field with value 'audio',\n"
82  " 'video', or stream number (zero based).\n"
83  " - output (out): Required output file (single file) or initialization\n"
84  " file path (multiple file).\n"
85  " - segment_template (segment): Optional value which specifies the\n"
86  " naming pattern for the segment files, and that the stream should be\n"
87  " split into multiple files. Its presence should be consistent across\n"
88  " streams.\n"
89  " - bandwidth (bw): Optional value which contains a user-specified\n"
90  " content bit rate for the stream, in bits/sec. If specified, this\n"
91  " value is propagated to the $Bandwidth$ template parameter for\n"
92  " segment names. If not specified, its value may be estimated.\n"
93  " - language (lang): Optional value which contains a user-specified\n"
94  " language tag. If specified, this value overrides any language\n"
95  " metadata in the input track.\n"
96  " - output_format (format): Optional value which specifies the format\n"
97  " of the output files (MP4 or WebM). If not specified, it will be\n"
98  " derived from the file extension of the output file.\n"
99  " - hls_name: Required for audio when outputting HLS.\n"
100  " name of the output stream. This is not (necessarily) the same as\n"
101  " output. This is used as the NAME attribute for EXT-X-MEDIA\n"
102  " - hls_group_id: Required for audio when outputting HLS.\n"
103  " The group ID for the output stream. For HLS this is used as the\n"
104  " GROUP-ID attribute for EXT-X-MEDIA.\n"
105  " - playlist_name: Required for HLS output.\n"
106  " Name of the playlist for the stream. Usually ends with '.m3u8'.\n";
107 
108 const char kMediaInfoSuffix[] = ".media_info";
109 
110 enum ExitStatus {
111  kSuccess = 0,
112  kArgumentValidationFailed,
113  kPackagingFailed,
114  kInternalError,
115 };
116 
117 // TODO(rkuroiwa): Write TTML and WebVTT parser (demuxing) for a better check
118 // and for supporting live/segmenting (muxing). With a demuxer and a muxer,
119 // CreateRemuxJobs() shouldn't treat text as a special case.
120 std::string DetermineTextFileFormat(const std::string& file) {
121  std::string content;
122  if (!File::ReadFileToString(file.c_str(), &content)) {
123  LOG(ERROR) << "Failed to open file " << file
124  << " to determine file format.";
125  return "";
126  }
127  MediaContainerName container_name = DetermineContainer(
128  reinterpret_cast<const uint8_t*>(content.data()), content.size());
129  if (container_name == CONTAINER_WEBVTT) {
130  return "vtt";
131  } else if (container_name == CONTAINER_TTML) {
132  return "ttml";
133  }
134 
135  return "";
136 }
137 
138 FourCC GetProtectionScheme(const std::string& protection_scheme) {
139  if (protection_scheme == "cenc") {
140  return FOURCC_cenc;
141  } else if (protection_scheme == "cens") {
142  return FOURCC_cens;
143  } else if (protection_scheme == "cbc1") {
144  return FOURCC_cbc1;
145  } else if (protection_scheme == "cbcs") {
146  return FOURCC_cbcs;
147  } else {
148  LOG(ERROR) << "Unknown protection scheme: " << protection_scheme;
149  return FOURCC_NULL;
150  }
151 }
152 
153 } // namespace
154 
155 // A fake clock that always return time 0 (epoch). Should only be used for
156 // testing.
157 class FakeClock : public base::Clock {
158  public:
159  base::Time Now() override { return base::Time(); }
160 };
161 
162 // Demux, Mux(es) and worker thread used to remux a source file/stream.
163 class RemuxJob : public base::SimpleThread {
164  public:
165  RemuxJob(std::unique_ptr<Demuxer> demuxer)
166  : SimpleThread("RemuxJob"), demuxer_(std::move(demuxer)) {}
167 
168  ~RemuxJob() override {}
169 
170  void AddMuxer(std::unique_ptr<Muxer> mux) {
171  muxers_.push_back(std::move(mux));
172  }
173 
174  Demuxer* demuxer() { return demuxer_.get(); }
175  Status status() { return status_; }
176 
177  private:
178  void Run() override {
179  DCHECK(demuxer_);
180  status_ = demuxer_->Run();
181  }
182 
183  std::unique_ptr<Demuxer> demuxer_;
184  std::vector<std::unique_ptr<Muxer>> muxers_;
185  Status status_;
186 
187  DISALLOW_COPY_AND_ASSIGN(RemuxJob);
188 };
189 
190 bool StreamInfoToTextMediaInfo(const StreamDescriptor& stream_descriptor,
191  const MuxerOptions& stream_muxer_options,
192  MediaInfo* text_media_info) {
193  const std::string& language = stream_descriptor.language;
194  std::string format = DetermineTextFileFormat(stream_descriptor.input);
195  if (format.empty()) {
196  LOG(ERROR) << "Failed to determine the text file format for "
197  << stream_descriptor.input;
198  return false;
199  }
200 
201  if (!File::Copy(stream_descriptor.input.c_str(),
202  stream_muxer_options.output_file_name.c_str())) {
203  LOG(ERROR) << "Failed to copy the input file (" << stream_descriptor.input
204  << ") to output file (" << stream_muxer_options.output_file_name
205  << ").";
206  return false;
207  }
208 
209  text_media_info->set_media_file_name(stream_muxer_options.output_file_name);
210  text_media_info->set_container_type(MediaInfo::CONTAINER_TEXT);
211 
212  if (stream_muxer_options.bandwidth != 0) {
213  text_media_info->set_bandwidth(stream_muxer_options.bandwidth);
214  } else {
215  // Text files are usually small and since the input is one file; there's no
216  // way for the player to do ranged requests. So set this value to something
217  // reasonable.
218  text_media_info->set_bandwidth(256);
219  }
220 
221  MediaInfo::TextInfo* text_info = text_media_info->mutable_text_info();
222  text_info->set_format(format);
223  if (!language.empty())
224  text_info->set_language(language);
225 
226  return true;
227 }
228 
229 std::unique_ptr<Muxer> CreateOutputMuxer(const MuxerOptions& options,
230  MediaContainerName container) {
231  if (container == CONTAINER_WEBM) {
232  return std::unique_ptr<Muxer>(new webm::WebMMuxer(options));
233  } else if (container == CONTAINER_MPEG2TS) {
234  return std::unique_ptr<Muxer>(new mp2t::TsMuxer(options));
235  } else {
236  DCHECK_EQ(container, CONTAINER_MOV);
237  return std::unique_ptr<Muxer>(new mp4::MP4Muxer(options));
238  }
239 }
240 
241 bool CreateRemuxJobs(const StreamDescriptorList& stream_descriptors,
242  const MuxerOptions& muxer_options,
243  FakeClock* fake_clock,
244  KeySource* key_source,
245  MpdNotifier* mpd_notifier,
246  hls::HlsNotifier* hls_notifier,
247  std::vector<std::unique_ptr<RemuxJob>>* remux_jobs) {
248  // No notifiers OR (mpd_notifier XOR hls_notifier); which is NAND.
249  DCHECK(!(mpd_notifier && hls_notifier));
250  DCHECK(remux_jobs);
251 
252  std::string previous_input;
253  int stream_number = 0;
254  for (StreamDescriptorList::const_iterator
255  stream_iter = stream_descriptors.begin();
256  stream_iter != stream_descriptors.end();
257  ++stream_iter, ++stream_number) {
258  // Process stream descriptor.
259  MuxerOptions stream_muxer_options(muxer_options);
260  stream_muxer_options.output_file_name = stream_iter->output;
261  if (!stream_iter->segment_template.empty()) {
262  if (!ValidateSegmentTemplate(stream_iter->segment_template)) {
263  LOG(ERROR) << "ERROR: segment template with '"
264  << stream_iter->segment_template << "' is invalid.";
265  return false;
266  }
267  stream_muxer_options.segment_template = stream_iter->segment_template;
268  }
269  stream_muxer_options.bandwidth = stream_iter->bandwidth;
270 
271  // Handle text input.
272  if (stream_iter->stream_selector == "text") {
273  MediaInfo text_media_info;
274  if (!StreamInfoToTextMediaInfo(*stream_iter, stream_muxer_options,
275  &text_media_info)) {
276  return false;
277  }
278 
279  if (mpd_notifier) {
280  uint32_t unused;
281  if (!mpd_notifier->NotifyNewContainer(text_media_info, &unused)) {
282  LOG(ERROR) << "Failed to process text file " << stream_iter->input;
283  } else {
284  mpd_notifier->Flush();
285  }
286  } else if (FLAGS_output_media_info) {
288  text_media_info,
289  stream_muxer_options.output_file_name + kMediaInfoSuffix);
290  } else {
291  NOTIMPLEMENTED()
292  << "--mpd_output or --output_media_info flags are "
293  "required for text output. Skipping manifest related output for "
294  << stream_iter->input;
295  }
296  continue;
297  }
298 
299  if (stream_iter->input != previous_input) {
300  // New remux job needed. Create demux and job thread.
301  std::unique_ptr<Demuxer> demuxer(new Demuxer(stream_iter->input));
302  if (FLAGS_enable_widevine_decryption ||
303  FLAGS_enable_fixed_key_decryption) {
304  std::unique_ptr<KeySource> key_source(CreateDecryptionKeySource());
305  if (!key_source)
306  return false;
307  demuxer->SetKeySource(std::move(key_source));
308  }
309  Status status = demuxer->Initialize();
310  if (!status.ok()) {
311  LOG(ERROR) << "Demuxer failed to initialize: " << status.ToString();
312  return false;
313  }
314  if (FLAGS_dump_stream_info) {
315  printf("\nFile \"%s\":\n", stream_iter->input.c_str());
316  DumpStreamInfo(demuxer->streams());
317  if (stream_iter->output.empty())
318  continue; // just need stream info.
319  }
320  remux_jobs->emplace_back(new RemuxJob(std::move(demuxer)));
321  previous_input = stream_iter->input;
322  }
323  DCHECK(!remux_jobs->empty());
324 
325  std::unique_ptr<Muxer> muxer(
326  CreateOutputMuxer(stream_muxer_options, stream_iter->output_format));
327  if (FLAGS_use_fake_clock_for_muxer) muxer->set_clock(fake_clock);
328 
329  if (key_source) {
330  muxer->SetKeySource(key_source,
331  FLAGS_max_sd_pixels,
332  FLAGS_max_hd_pixels,
333  FLAGS_max_uhd1_pixels,
334  FLAGS_clear_lead,
335  FLAGS_crypto_period_duration,
336  GetProtectionScheme(FLAGS_protection_scheme));
337  }
338 
339  std::unique_ptr<MuxerListener> muxer_listener;
340  DCHECK(!(FLAGS_output_media_info && mpd_notifier));
341  if (FLAGS_output_media_info) {
342  const std::string output_media_info_file_name =
343  stream_muxer_options.output_file_name + kMediaInfoSuffix;
344  std::unique_ptr<VodMediaInfoDumpMuxerListener>
345  vod_media_info_dump_muxer_listener(
346  new VodMediaInfoDumpMuxerListener(output_media_info_file_name));
347  muxer_listener = std::move(vod_media_info_dump_muxer_listener);
348  }
349  if (mpd_notifier) {
350  std::unique_ptr<MpdNotifyMuxerListener> mpd_notify_muxer_listener(
351  new MpdNotifyMuxerListener(mpd_notifier));
352  muxer_listener = std::move(mpd_notify_muxer_listener);
353  }
354 
355  if (hls_notifier) {
356  // TODO(rkuroiwa): Do some smart stuff to group the audios, e.g. detect
357  // languages.
358  std::string group_id = stream_iter->hls_group_id;
359  std::string name = stream_iter->hls_name;
360  std::string hls_playlist_name = stream_iter->hls_playlist_name;
361  if (group_id.empty())
362  group_id = "audio";
363  if (name.empty())
364  name = base::StringPrintf("stream_%d", stream_number);
365  if (hls_playlist_name.empty())
366  hls_playlist_name = base::StringPrintf("stream_%d.m3u8", stream_number);
367 
368  muxer_listener.reset(new HlsNotifyMuxerListener(hls_playlist_name, name,
369  group_id, hls_notifier));
370  }
371 
372  if (muxer_listener)
373  muxer->SetMuxerListener(std::move(muxer_listener));
374 
375  if (!AddStreamToMuxer(remux_jobs->back()->demuxer()->streams(),
376  stream_iter->stream_selector,
377  stream_iter->language,
378  muxer.get())) {
379  return false;
380  }
381  remux_jobs->back()->AddMuxer(std::move(muxer));
382  }
383 
384  return true;
385 }
386 
387 Status RunRemuxJobs(const std::vector<std::unique_ptr<RemuxJob>>& remux_jobs) {
388  // Start the job threads.
389  for (const std::unique_ptr<RemuxJob>& job : remux_jobs)
390  job->Start();
391 
392  // Wait for all jobs to complete or an error occurs.
393  Status status;
394  bool all_joined;
395  do {
396  all_joined = true;
397  for (const std::unique_ptr<RemuxJob>& job : remux_jobs) {
398  if (job->HasBeenJoined()) {
399  status = job->status();
400  if (!status.ok())
401  break;
402  } else {
403  all_joined = false;
404  job->Join();
405  }
406  }
407  } while (!all_joined && status.ok());
408 
409  return status;
410 }
411 
412 bool RunPackager(const StreamDescriptorList& stream_descriptors) {
413  const FourCC protection_scheme = GetProtectionScheme(FLAGS_protection_scheme);
414  if (protection_scheme == FOURCC_NULL)
415  return false;
416 
417  if (FLAGS_output_media_info && !FLAGS_mpd_output.empty()) {
418  NOTIMPLEMENTED() << "ERROR: --output_media_info and --mpd_output do not "
419  "work together.";
420  return false;
421  }
422 
423  // Since there isn't a muxer listener that can output both MPD and HLS,
424  // disallow specifying both MPD and HLS flags.
425  if (!FLAGS_mpd_output.empty() && !FLAGS_hls_master_playlist_output.empty()) {
426  LOG(ERROR) << "Cannot output both MPD and HLS.";
427  return false;
428  }
429 
430  // Get basic muxer options.
431  MuxerOptions muxer_options;
432  if (!GetMuxerOptions(&muxer_options))
433  return false;
434 
435  DCHECK(!stream_descriptors.empty());
436  // On demand profile generates single file segment while live profile
437  // generates multiple segments specified using segment template.
438  const bool on_demand_dash_profile =
439  stream_descriptors.begin()->segment_template.empty();
440  for (const auto& stream_descriptor : stream_descriptors) {
441  if (on_demand_dash_profile != stream_descriptor.segment_template.empty()) {
442  LOG(ERROR) << "Inconsistent stream descriptor specification: "
443  "segment_template should be specified for none or all "
444  "stream descriptors.";
445  return false;
446  }
447  }
448  if (FLAGS_output_media_info && !on_demand_dash_profile) {
449  // TODO(rkuroiwa, kqyang): Support partial media info dump for live.
450  NOTIMPLEMENTED() << "ERROR: --output_media_info is only supported for "
451  "on-demand profile (not using segment_template).";
452  return false;
453  }
454 
455  MpdOptions mpd_options;
456  if (!GetMpdOptions(on_demand_dash_profile, &mpd_options))
457  return false;
458 
459  // Create encryption key source if needed.
460  std::unique_ptr<KeySource> encryption_key_source;
461  if (FLAGS_enable_widevine_encryption || FLAGS_enable_fixed_key_encryption) {
462  encryption_key_source = CreateEncryptionKeySource();
463  if (!encryption_key_source)
464  return false;
465  }
466 
467  std::unique_ptr<MpdNotifier> mpd_notifier;
468  if (!FLAGS_mpd_output.empty()) {
469  std::vector<std::string> base_urls = base::SplitString(
470  FLAGS_base_urls, ",", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
471  if (FLAGS_generate_dash_if_iop_compliant_mpd) {
472  mpd_notifier.reset(
473  new DashIopMpdNotifier(mpd_options, base_urls, FLAGS_mpd_output));
474  } else {
475  mpd_notifier.reset(
476  new SimpleMpdNotifier(mpd_options, base_urls, FLAGS_mpd_output));
477  }
478  if (!mpd_notifier->Init()) {
479  LOG(ERROR) << "MpdNotifier failed to initialize.";
480  return false;
481  }
482  }
483 
484  std::unique_ptr<hls::HlsNotifier> hls_notifier;
485  if (!FLAGS_hls_master_playlist_output.empty()) {
486  base::FilePath master_playlist_path(
487  base::FilePath::FromUTF8Unsafe(FLAGS_hls_master_playlist_output));
488  base::FilePath master_playlist_name = master_playlist_path.BaseName();
489 
490  hls_notifier.reset(new hls::SimpleHlsNotifier(
491  hls::HlsNotifier::HlsProfile::kOnDemandProfile, FLAGS_hls_base_url,
492  master_playlist_path.DirName().AsEndingWithSeparator().AsUTF8Unsafe(),
493  master_playlist_name.AsUTF8Unsafe()));
494  }
495 
496  std::vector<std::unique_ptr<RemuxJob>> remux_jobs;
497  FakeClock fake_clock;
498  if (!CreateRemuxJobs(stream_descriptors, muxer_options, &fake_clock,
499  encryption_key_source.get(), mpd_notifier.get(),
500  hls_notifier.get(), &remux_jobs)) {
501  return false;
502  }
503 
504  Status status = RunRemuxJobs(remux_jobs);
505  if (!status.ok()) {
506  LOG(ERROR) << "Packaging Error: " << status.ToString();
507  return false;
508  }
509 
510  if (hls_notifier) {
511  if (!hls_notifier->Flush())
512  return false;
513  }
514  if (mpd_notifier) {
515  if (!mpd_notifier->Flush())
516  return false;
517  }
518 
519  printf("Packaging completed successfully.\n");
520  return true;
521 }
522 
523 int PackagerMain(int argc, char** argv) {
524  base::AtExitManager exit;
525  // Needed to enable VLOG/DVLOG through --vmodule or --v.
526  base::CommandLine::Init(argc, argv);
527 
528  // Set up logging.
529  logging::LoggingSettings log_settings;
530  log_settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
531  CHECK(logging::InitLogging(log_settings));
532 
533  google::SetVersionString(GetPackagerVersion());
534  google::SetUsageMessage(base::StringPrintf(kUsage, argv[0]));
535  google::ParseCommandLineFlags(&argc, &argv, true);
536  if (argc < 2) {
537  google::ShowUsageWithFlags("Usage");
538  return kSuccess;
539  }
540 
542  return kArgumentValidationFailed;
543 
544  if (FLAGS_override_version)
545  SetPackagerVersionForTesting(FLAGS_test_version);
546 
547  LibcryptoThreading libcrypto_threading;
548  // TODO(tinskip): Make InsertStreamDescriptor a member of
549  // StreamDescriptorList.
550  StreamDescriptorList stream_descriptors;
551  for (int i = 1; i < argc; ++i) {
552  if (!InsertStreamDescriptor(argv[i], &stream_descriptors))
553  return kArgumentValidationFailed;
554  }
555  return RunPackager(stream_descriptors) ? kSuccess : kPackagingFailed;
556 }
557 
558 } // namespace media
559 } // namespace shaka
560 
561 #if defined(OS_WIN)
562 // Windows wmain, which converts wide character arguments to UTF-8.
563 int wmain(int argc, wchar_t* argv[], wchar_t* envp[]) {
564  std::unique_ptr<char* [], std::function<void(char**)>> utf8_argv(
565  new char*[argc], [argc](char** utf8_args) {
566  // TODO(tinskip): This leaks, but if this code is enabled, it crashes.
567  // Figure out why. I suspect gflags does something funny with the
568  // argument array.
569  // for (int idx = 0; idx < argc; ++idx)
570  // delete[] utf8_args[idx];
571  delete[] utf8_args;
572  });
573  std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
574  for (int idx = 0; idx < argc; ++idx) {
575  std::string utf8_arg(converter.to_bytes(argv[idx]));
576  utf8_arg += '\0';
577  utf8_argv[idx] = new char[utf8_arg.size()];
578  memcpy(utf8_argv[idx], &utf8_arg[0], utf8_arg.size());
579  }
580  return shaka::media::PackagerMain(argc, utf8_argv.get());
581 }
582 #else
583 int main(int argc, char** argv) {
584  return shaka::media::PackagerMain(argc, argv);
585 }
586 #endif // defined(OS_WIN)
static bool Copy(const char *from_file_name, const char *to_file_name)
Definition: file.cc:203
bool ValidateWidevineCryptoFlags()
static bool WriteMediaInfoToFile(const MediaInfo &media_info, const std::string &output_file_path)
static bool ReadFileToString(const char *file_name, std::string *contents)
Definition: file.cc:185
bool ValidateFixedCryptoFlags()