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