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