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  "Packager driver program. Usage:\n\n"
76  "%s [flags] <stream_descriptor> ...\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  void AddMuxer(std::unique_ptr<Muxer> mux) {
172  muxers_.push_back(std::move(mux));
173  }
174 
175  Demuxer* demuxer() { return demuxer_.get(); }
176  Status status() { return status_; }
177 
178  private:
179  void Run() override {
180  DCHECK(demuxer_);
181  status_ = demuxer_->Run();
182  }
183 
184  std::unique_ptr<Demuxer> demuxer_;
185  std::vector<std::unique_ptr<Muxer>> muxers_;
186  Status status_;
187 
188  DISALLOW_COPY_AND_ASSIGN(RemuxJob);
189 };
190 
191 bool StreamInfoToTextMediaInfo(const StreamDescriptor& stream_descriptor,
192  const MuxerOptions& stream_muxer_options,
193  MediaInfo* text_media_info) {
194  const std::string& language = stream_descriptor.language;
195  std::string format = DetermineTextFileFormat(stream_descriptor.input);
196  if (format.empty()) {
197  LOG(ERROR) << "Failed to determine the text file format for "
198  << stream_descriptor.input;
199  return false;
200  }
201 
202  if (!File::Copy(stream_descriptor.input.c_str(),
203  stream_muxer_options.output_file_name.c_str())) {
204  LOG(ERROR) << "Failed to copy the input file (" << stream_descriptor.input
205  << ") to output file (" << stream_muxer_options.output_file_name
206  << ").";
207  return false;
208  }
209 
210  text_media_info->set_media_file_name(stream_muxer_options.output_file_name);
211  text_media_info->set_container_type(MediaInfo::CONTAINER_TEXT);
212 
213  if (stream_muxer_options.bandwidth != 0) {
214  text_media_info->set_bandwidth(stream_muxer_options.bandwidth);
215  } else {
216  // Text files are usually small and since the input is one file; there's no
217  // way for the player to do ranged requests. So set this value to something
218  // reasonable.
219  text_media_info->set_bandwidth(256);
220  }
221 
222  MediaInfo::TextInfo* text_info = text_media_info->mutable_text_info();
223  text_info->set_format(format);
224  if (!language.empty())
225  text_info->set_language(language);
226 
227  return true;
228 }
229 
230 std::unique_ptr<Muxer> CreateOutputMuxer(const MuxerOptions& options,
231  MediaContainerName container) {
232  if (container == CONTAINER_WEBM) {
233  return std::unique_ptr<Muxer>(new webm::WebMMuxer(options));
234  } else if (container == CONTAINER_MPEG2TS) {
235  return std::unique_ptr<Muxer>(new mp2t::TsMuxer(options));
236  } else {
237  DCHECK_EQ(container, CONTAINER_MOV);
238  return std::unique_ptr<Muxer>(new mp4::MP4Muxer(options));
239  }
240 }
241 
242 bool CreateRemuxJobs(const StreamDescriptorList& stream_descriptors,
243  const MuxerOptions& muxer_options,
244  FakeClock* fake_clock,
245  KeySource* key_source,
246  MpdNotifier* mpd_notifier,
247  hls::HlsNotifier* hls_notifier,
248  std::vector<std::unique_ptr<RemuxJob>>* remux_jobs) {
249  // No notifiers OR (mpd_notifier XOR hls_notifier); which is NAND.
250  DCHECK(!(mpd_notifier && hls_notifier));
251  DCHECK(remux_jobs);
252 
253  std::string previous_input;
254  int stream_number = 0;
255  for (StreamDescriptorList::const_iterator
256  stream_iter = stream_descriptors.begin();
257  stream_iter != stream_descriptors.end();
258  ++stream_iter, ++stream_number) {
259  // Process stream descriptor.
260  MuxerOptions stream_muxer_options(muxer_options);
261  stream_muxer_options.output_file_name = stream_iter->output;
262  if (!stream_iter->segment_template.empty()) {
263  if (!ValidateSegmentTemplate(stream_iter->segment_template)) {
264  LOG(ERROR) << "ERROR: segment template with '"
265  << stream_iter->segment_template << "' is invalid.";
266  return false;
267  }
268  stream_muxer_options.segment_template = stream_iter->segment_template;
269  if (stream_muxer_options.single_segment) {
270  LOG(WARNING) << "Segment template and single segment are incompatible, "
271  "setting single segment to false.";
272  stream_muxer_options.single_segment = false;
273  }
274  }
275  stream_muxer_options.bandwidth = stream_iter->bandwidth;
276 
277  // Handle text input.
278  if (stream_iter->stream_selector == "text") {
279  MediaInfo text_media_info;
280  if (!StreamInfoToTextMediaInfo(*stream_iter, stream_muxer_options,
281  &text_media_info)) {
282  return false;
283  }
284 
285  if (mpd_notifier) {
286  uint32_t unused;
287  if (!mpd_notifier->NotifyNewContainer(text_media_info, &unused)) {
288  LOG(ERROR) << "Failed to process text file " << stream_iter->input;
289  } else {
290  mpd_notifier->Flush();
291  }
292  } else if (FLAGS_output_media_info) {
294  text_media_info,
295  stream_muxer_options.output_file_name + kMediaInfoSuffix);
296  } else {
297  NOTIMPLEMENTED()
298  << "--mpd_output or --output_media_info flags are "
299  "required for text output. Skipping manifest related output for "
300  << stream_iter->input;
301  }
302  continue;
303  }
304 
305  if (stream_iter->input != previous_input) {
306  // New remux job needed. Create demux and job thread.
307  std::unique_ptr<Demuxer> demuxer(new Demuxer(stream_iter->input));
308  if (FLAGS_enable_widevine_decryption ||
309  FLAGS_enable_fixed_key_decryption) {
310  std::unique_ptr<KeySource> key_source(CreateDecryptionKeySource());
311  if (!key_source)
312  return false;
313  demuxer->SetKeySource(std::move(key_source));
314  }
315  Status status = demuxer->Initialize();
316  if (!status.ok()) {
317  LOG(ERROR) << "Demuxer failed to initialize: " << status.ToString();
318  return false;
319  }
320  if (FLAGS_dump_stream_info) {
321  printf("\nFile \"%s\":\n", stream_iter->input.c_str());
322  DumpStreamInfo(demuxer->streams());
323  if (stream_iter->output.empty())
324  continue; // just need stream info.
325  }
326  remux_jobs->emplace_back(new RemuxJob(std::move(demuxer)));
327  previous_input = stream_iter->input;
328  }
329  DCHECK(!remux_jobs->empty());
330 
331  std::unique_ptr<Muxer> muxer(
332  CreateOutputMuxer(stream_muxer_options, stream_iter->output_format));
333  if (FLAGS_use_fake_clock_for_muxer) muxer->set_clock(fake_clock);
334 
335  if (key_source) {
336  muxer->SetKeySource(key_source,
337  FLAGS_max_sd_pixels,
338  FLAGS_clear_lead,
339  FLAGS_crypto_period_duration,
340  GetProtectionScheme(FLAGS_protection_scheme));
341  }
342 
343  std::unique_ptr<MuxerListener> muxer_listener;
344  DCHECK(!(FLAGS_output_media_info && mpd_notifier));
345  if (FLAGS_output_media_info) {
346  const std::string output_media_info_file_name =
347  stream_muxer_options.output_file_name + kMediaInfoSuffix;
348  std::unique_ptr<VodMediaInfoDumpMuxerListener>
349  vod_media_info_dump_muxer_listener(
350  new VodMediaInfoDumpMuxerListener(output_media_info_file_name));
351  muxer_listener = std::move(vod_media_info_dump_muxer_listener);
352  }
353  if (mpd_notifier) {
354  std::unique_ptr<MpdNotifyMuxerListener> mpd_notify_muxer_listener(
355  new MpdNotifyMuxerListener(mpd_notifier));
356  muxer_listener = std::move(mpd_notify_muxer_listener);
357  }
358 
359  if (hls_notifier) {
360  // TODO(rkuroiwa): Do some smart stuff to group the audios, e.g. detect
361  // languages.
362  std::string group_id = stream_iter->hls_group_id;
363  std::string name = stream_iter->hls_name;
364  std::string hls_playlist_name = stream_iter->hls_playlist_name;
365  if (group_id.empty())
366  group_id = "audio";
367  if (name.empty())
368  name = base::StringPrintf("stream_%d", stream_number);
369  if (hls_playlist_name.empty())
370  hls_playlist_name = base::StringPrintf("stream_%d.m3u8", stream_number);
371 
372  muxer_listener.reset(new HlsNotifyMuxerListener(hls_playlist_name, name,
373  group_id, hls_notifier));
374  }
375 
376  if (muxer_listener)
377  muxer->SetMuxerListener(std::move(muxer_listener));
378 
379  if (!AddStreamToMuxer(remux_jobs->back()->demuxer()->streams(),
380  stream_iter->stream_selector,
381  stream_iter->language,
382  muxer.get())) {
383  return false;
384  }
385  remux_jobs->back()->AddMuxer(std::move(muxer));
386  }
387 
388  return true;
389 }
390 
391 Status RunRemuxJobs(const std::vector<std::unique_ptr<RemuxJob>>& remux_jobs) {
392  // Start the job threads.
393  for (const std::unique_ptr<RemuxJob>& job : remux_jobs)
394  job->Start();
395 
396  // Wait for all jobs to complete or an error occurs.
397  Status status;
398  bool all_joined;
399  do {
400  all_joined = true;
401  for (const std::unique_ptr<RemuxJob>& job : remux_jobs) {
402  if (job->HasBeenJoined()) {
403  status = job->status();
404  if (!status.ok())
405  break;
406  } else {
407  all_joined = false;
408  job->Join();
409  }
410  }
411  } while (!all_joined && status.ok());
412 
413  return status;
414 }
415 
416 bool RunPackager(const StreamDescriptorList& stream_descriptors) {
417  const FourCC protection_scheme = GetProtectionScheme(FLAGS_protection_scheme);
418  if (protection_scheme == FOURCC_NULL)
419  return false;
420 
421  if (!AssignFlagsFromProfile())
422  return false;
423 
424  if (FLAGS_output_media_info && !FLAGS_mpd_output.empty()) {
425  NOTIMPLEMENTED() << "ERROR: --output_media_info and --mpd_output do not "
426  "work together.";
427  return false;
428  }
429  if (FLAGS_output_media_info && !FLAGS_single_segment) {
430  // TODO(rkuroiwa, kqyang): Support partial media info dump for live.
431  NOTIMPLEMENTED() << "ERROR: --output_media_info is only supported if "
432  "--single_segment is true.";
433  return false;
434  }
435 
436  // Since there isn't a muxer listener that can output both MPD and HLS,
437  // disallow specifying both MPD and HLS flags.
438  if (!FLAGS_mpd_output.empty() && !FLAGS_hls_master_playlist_output.empty()) {
439  LOG(ERROR) << "Cannot output both MPD and HLS.";
440  return false;
441  }
442 
443  // Get basic muxer options.
444  MuxerOptions muxer_options;
445  if (!GetMuxerOptions(&muxer_options))
446  return false;
447 
448  MpdOptions mpd_options;
449  if (!GetMpdOptions(&mpd_options))
450  return false;
451 
452  // Create encryption key source if needed.
453  std::unique_ptr<KeySource> encryption_key_source;
454  if (FLAGS_enable_widevine_encryption || FLAGS_enable_fixed_key_encryption) {
455  encryption_key_source = CreateEncryptionKeySource();
456  if (!encryption_key_source)
457  return false;
458  }
459 
460  std::unique_ptr<MpdNotifier> mpd_notifier;
461  if (!FLAGS_mpd_output.empty()) {
462  DashProfile profile =
463  FLAGS_single_segment ? kOnDemandProfile : kLiveProfile;
464  std::vector<std::string> base_urls = base::SplitString(
465  FLAGS_base_urls, ",", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
466  if (FLAGS_generate_dash_if_iop_compliant_mpd) {
467  mpd_notifier.reset(new DashIopMpdNotifier(profile, mpd_options, base_urls,
468  FLAGS_mpd_output));
469  } else {
470  mpd_notifier.reset(new SimpleMpdNotifier(profile, mpd_options, base_urls,
471  FLAGS_mpd_output));
472  }
473  if (!mpd_notifier->Init()) {
474  LOG(ERROR) << "MpdNotifier failed to initialize.";
475  return false;
476  }
477  }
478 
479  std::unique_ptr<hls::HlsNotifier> hls_notifier;
480  if (!FLAGS_hls_master_playlist_output.empty()) {
481  base::FilePath master_playlist_path(
482  base::FilePath::FromUTF8Unsafe(FLAGS_hls_master_playlist_output));
483  base::FilePath master_playlist_name = master_playlist_path.BaseName();
484 
485  hls_notifier.reset(new hls::SimpleHlsNotifier(
486  hls::HlsNotifier::HlsProfile::kOnDemandProfile, FLAGS_hls_base_url,
487  master_playlist_path.DirName().AsEndingWithSeparator().AsUTF8Unsafe(),
488  master_playlist_name.AsUTF8Unsafe()));
489  }
490 
491  std::vector<std::unique_ptr<RemuxJob>> remux_jobs;
492  FakeClock fake_clock;
493  if (!CreateRemuxJobs(stream_descriptors, muxer_options, &fake_clock,
494  encryption_key_source.get(), mpd_notifier.get(),
495  hls_notifier.get(), &remux_jobs)) {
496  return false;
497  }
498 
499  Status status = RunRemuxJobs(remux_jobs);
500  if (!status.ok()) {
501  LOG(ERROR) << "Packaging Error: " << status.ToString();
502  return false;
503  }
504 
505  if (hls_notifier) {
506  if (!hls_notifier->Flush())
507  return false;
508  }
509  if (mpd_notifier) {
510  if (!mpd_notifier->Flush())
511  return false;
512  }
513 
514  printf("Packaging completed successfully.\n");
515  return true;
516 }
517 
518 int PackagerMain(int argc, char** argv) {
519  base::AtExitManager exit;
520  // Needed to enable VLOG/DVLOG through --vmodule or --v.
521  base::CommandLine::Init(argc, argv);
522 
523  // Set up logging.
524  logging::LoggingSettings log_settings;
525  log_settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
526  CHECK(logging::InitLogging(log_settings));
527 
528  google::SetUsageMessage(base::StringPrintf(kUsage, argv[0]));
529  google::ParseCommandLineFlags(&argc, &argv, true);
530  if (argc < 2) {
531  const std::string version_string = base::StringPrintf(
532  "shaka-packager version %s", GetPackagerVersion().c_str());
533  google::ShowUsageWithFlags(version_string.c_str());
534  return kSuccess;
535  }
536 
538  return kArgumentValidationFailed;
539 
540  if (FLAGS_override_version)
541  SetPackagerVersionForTesting(FLAGS_test_version);
542 
543  LibcryptoThreading libcrypto_threading;
544  // TODO(tinskip): Make InsertStreamDescriptor a member of
545  // StreamDescriptorList.
546  StreamDescriptorList stream_descriptors;
547  for (int i = 1; i < argc; ++i) {
548  if (!InsertStreamDescriptor(argv[i], &stream_descriptors))
549  return kArgumentValidationFailed;
550  }
551  return RunPackager(stream_descriptors) ? kSuccess : kPackagingFailed;
552 }
553 
554 } // namespace media
555 } // namespace shaka
556 
557 #if defined(OS_WIN)
558 // Windows wmain, which converts wide character arguments to UTF-8.
559 int wmain(int argc, wchar_t* argv[], wchar_t* envp[]) {
560  std::unique_ptr<char* [], std::function<void(char**)>> utf8_argv(
561  new char*[argc], [argc](char** utf8_args) {
562  // TODO(tinskip): This leaks, but if this code is enabled, it crashes.
563  // Figure out why. I suspect gflags does something funny with the
564  // argument array.
565  // for (int idx = 0; idx < argc; ++idx)
566  // delete[] utf8_args[idx];
567  delete[] utf8_args;
568  });
569  std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
570  for (int idx = 0; idx < argc; ++idx) {
571  std::string utf8_arg(converter.to_bytes(argv[idx]));
572  utf8_arg += '\0';
573  utf8_argv[idx] = new char[utf8_arg.size()];
574  memcpy(utf8_argv[idx], &utf8_arg[0], utf8_arg.size());
575  }
576  return shaka::media::PackagerMain(argc, utf8_argv.get());
577 }
578 #else
579 int main(int argc, char** argv) {
580  return shaka::media::PackagerMain(argc, argv);
581 }
582 #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()