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