DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs 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/libcrypto_threading.h"
12 #include "packager/app/mpd_flags.h"
13 #include "packager/app/muxer_flags.h"
14 #include "packager/app/packager_util.h"
15 #include "packager/app/stream_descriptor.h"
16 #include "packager/app/vlog_flags.h"
17 #include "packager/app/widevine_encryption_flags.h"
18 #include "packager/base/at_exit.h"
19 #include "packager/base/command_line.h"
20 #include "packager/base/logging.h"
21 #include "packager/base/stl_util.h"
22 #include "packager/base/strings/string_split.h"
23 #include "packager/base/strings/stringprintf.h"
24 #include "packager/base/threading/simple_thread.h"
25 #include "packager/base/time/clock.h"
26 #include "packager/media/base/container_names.h"
27 #include "packager/media/base/demuxer.h"
28 #include "packager/media/base/fourccs.h"
29 #include "packager/media/base/key_source.h"
30 #include "packager/media/base/muxer_options.h"
31 #include "packager/media/base/muxer_util.h"
32 #include "packager/media/event/mpd_notify_muxer_listener.h"
33 #include "packager/media/event/vod_media_info_dump_muxer_listener.h"
34 #include "packager/media/file/file.h"
35 #include "packager/media/formats/mp2t/ts_muxer.h"
36 #include "packager/media/formats/mp4/mp4_muxer.h"
37 #include "packager/media/formats/webm/webm_muxer.h"
38 #include "packager/mpd/base/dash_iop_mpd_notifier.h"
39 #include "packager/mpd/base/media_info.pb.h"
40 #include "packager/mpd/base/mpd_builder.h"
41 #include "packager/mpd/base/simple_mpd_notifier.h"
42 #include "packager/version/version.h"
43 
44 DEFINE_bool(use_fake_clock_for_muxer,
45  false,
46  "Set to true to use a fake clock for muxer. With this flag set, "
47  "creation time and modification time in outputs are set to 0. "
48  "Should only be used for testing.");
49 
50 namespace {
51 const char kUsage[] =
52  "Packager driver program. Usage:\n\n"
53  "%s [flags] <stream_descriptor> ...\n"
54  "stream_descriptor consists of comma separated field_name/value pairs:\n"
55  "field_name=value,[field_name=value,]...\n"
56  "Supported field names are as follows:\n"
57  " - input (in): Required input/source media file path or network stream\n"
58  " URL.\n"
59  " - stream_selector (stream): Required field with value 'audio',\n"
60  " 'video', or stream number (zero based).\n"
61  " - output (out): Required output file (single file) or initialization\n"
62  " file path (multiple file).\n"
63  " - segment_template (segment): Optional value which specifies the\n"
64  " naming pattern for the segment files, and that the stream should be\n"
65  " split into multiple files. Its presence should be consistent across\n"
66  " streams.\n"
67  " - bandwidth (bw): Optional value which contains a user-specified\n"
68  " content bit rate for the stream, in bits/sec. If specified, this\n"
69  " value is propagated to the $Bandwidth$ template parameter for\n"
70  " segment names. If not specified, its value may be estimated.\n"
71  " - language (lang): Optional value which contains a user-specified\n"
72  " language tag. If specified, this value overrides any language\n"
73  " metadata in the input track.\n"
74  " - output_format (format): Optional value which specifies the format\n"
75  " of the output files (MP4 or WebM). If not specified, it will be\n"
76  " derived from the file extension of the output file.\n";
77 
78 const char kMediaInfoSuffix[] = ".media_info";
79 
80 enum ExitStatus {
81  kSuccess = 0,
82  kArgumentValidationFailed,
83  kPackagingFailed,
84  kInternalError,
85 };
86 
87 // TODO(rkuroiwa): Write TTML and WebVTT parser (demuxing) for a better check
88 // and for supporting live/segmenting (muxing). With a demuxer and a muxer,
89 // CreateRemuxJobs() shouldn't treat text as a special case.
90 std::string DetermineTextFileFormat(const std::string& file) {
91  std::string content;
92  if (!edash_packager::media::File::ReadFileToString(file.c_str(), &content)) {
93  LOG(ERROR) << "Failed to open file " << file
94  << " to determine file format.";
95  return "";
96  }
97  edash_packager::media::MediaContainerName container_name =
98  edash_packager::media::DetermineContainer(
99  reinterpret_cast<const uint8_t*>(content.data()), content.size());
100  if (container_name == edash_packager::media::CONTAINER_WEBVTT) {
101  return "vtt";
102  } else if (container_name == edash_packager::media::CONTAINER_TTML) {
103  return "ttml";
104  }
105 
106  return "";
107 }
108 
109 edash_packager::media::FourCC GetProtectionScheme(
110  const std::string& protection_scheme) {
111  if (protection_scheme == "cenc") {
112  return edash_packager::media::FOURCC_cenc;
113  } else if (protection_scheme == "cens") {
114  return edash_packager::media::FOURCC_cens;
115  } else if (protection_scheme == "cbc1") {
116  return edash_packager::media::FOURCC_cbc1;
117  } else if (protection_scheme == "cbcs") {
118  return edash_packager::media::FOURCC_cbcs;
119  } else {
120  LOG(ERROR) << "Unknown protection scheme: " << protection_scheme;
121  return edash_packager::media::FOURCC_NULL;
122  }
123 }
124 
125 } // namespace
126 
127 namespace edash_packager {
128 namespace media {
129 
130 // A fake clock that always return time 0 (epoch). Should only be used for
131 // testing.
132 class FakeClock : public base::Clock {
133  public:
134  base::Time Now() override { return base::Time(); }
135 };
136 
137 // Demux, Mux(es) and worker thread used to remux a source file/stream.
138 class RemuxJob : public base::SimpleThread {
139  public:
140  RemuxJob(scoped_ptr<Demuxer> demuxer)
141  : SimpleThread("RemuxJob"),
142  demuxer_(demuxer.Pass()) {}
143 
144  ~RemuxJob() override {
145  STLDeleteElements(&muxers_);
146  }
147 
148  void AddMuxer(scoped_ptr<Muxer> mux) {
149  muxers_.push_back(mux.release());
150  }
151 
152  Demuxer* demuxer() { return demuxer_.get(); }
153  Status status() { return status_; }
154 
155  private:
156  void Run() override {
157  DCHECK(demuxer_);
158  status_ = demuxer_->Run();
159  }
160 
161  scoped_ptr<Demuxer> demuxer_;
162  std::vector<Muxer*> muxers_;
163  Status status_;
164 
165  DISALLOW_COPY_AND_ASSIGN(RemuxJob);
166 };
167 
168 bool StreamInfoToTextMediaInfo(const StreamDescriptor& stream_descriptor,
169  const MuxerOptions& stream_muxer_options,
170  MediaInfo* text_media_info) {
171  const std::string& language = stream_descriptor.language;
172  std::string format = DetermineTextFileFormat(stream_descriptor.input);
173  if (format.empty()) {
174  LOG(ERROR) << "Failed to determine the text file format for "
175  << stream_descriptor.input;
176  return false;
177  }
178 
179  if (!File::Copy(stream_descriptor.input.c_str(),
180  stream_muxer_options.output_file_name.c_str())) {
181  LOG(ERROR) << "Failed to copy the input file (" << stream_descriptor.input
182  << ") to output file (" << stream_muxer_options.output_file_name
183  << ").";
184  return false;
185  }
186 
187  text_media_info->set_media_file_name(stream_muxer_options.output_file_name);
188  text_media_info->set_container_type(MediaInfo::CONTAINER_TEXT);
189 
190  if (stream_muxer_options.bandwidth != 0) {
191  text_media_info->set_bandwidth(stream_muxer_options.bandwidth);
192  } else {
193  // Text files are usually small and since the input is one file; there's no
194  // way for the player to do ranged requests. So set this value to something
195  // reasonable.
196  text_media_info->set_bandwidth(256);
197  }
198 
199  MediaInfo::TextInfo* text_info = text_media_info->mutable_text_info();
200  text_info->set_format(format);
201  if (!language.empty())
202  text_info->set_language(language);
203 
204  return true;
205 }
206 
207 scoped_ptr<Muxer> CreateOutputMuxer(const MuxerOptions& options,
208  MediaContainerName container) {
209  if (container == CONTAINER_WEBM) {
210  return scoped_ptr<Muxer>(new webm::WebMMuxer(options));
211  } else if (container == CONTAINER_MPEG2TS) {
212  return scoped_ptr<Muxer>(new mp2t::TsMuxer(options));
213  } else {
214  DCHECK_EQ(container, CONTAINER_MOV);
215  return scoped_ptr<Muxer>(new mp4::MP4Muxer(options));
216  }
217 }
218 
219 bool CreateRemuxJobs(const StreamDescriptorList& stream_descriptors,
220  const MuxerOptions& muxer_options,
221  FakeClock* fake_clock,
222  KeySource* key_source,
223  MpdNotifier* mpd_notifier,
224  std::vector<RemuxJob*>* remux_jobs) {
225  DCHECK(remux_jobs);
226 
227  std::string previous_input;
228  for (StreamDescriptorList::const_iterator stream_iter =
229  stream_descriptors.begin();
230  stream_iter != stream_descriptors.end();
231  ++stream_iter) {
232  // Process stream descriptor.
233  MuxerOptions stream_muxer_options(muxer_options);
234  stream_muxer_options.output_file_name = stream_iter->output;
235  if (!stream_iter->segment_template.empty()) {
236  if (!ValidateSegmentTemplate(stream_iter->segment_template)) {
237  LOG(ERROR) << "ERROR: segment template with '"
238  << stream_iter->segment_template << "' is invalid.";
239  return false;
240  }
241  stream_muxer_options.segment_template = stream_iter->segment_template;
242  }
243  stream_muxer_options.bandwidth = stream_iter->bandwidth;
244 
245  // Handle text input.
246  if (stream_iter->stream_selector == "text") {
247  MediaInfo text_media_info;
248  if (!StreamInfoToTextMediaInfo(*stream_iter, stream_muxer_options,
249  &text_media_info)) {
250  return false;
251  }
252 
253  if (mpd_notifier) {
254  uint32 unused;
255  if (!mpd_notifier->NotifyNewContainer(text_media_info, &unused)) {
256  LOG(ERROR) << "Failed to process text file " << stream_iter->input;
257  } else {
258  mpd_notifier->Flush();
259  }
260  } else if (FLAGS_output_media_info) {
262  text_media_info,
263  stream_muxer_options.output_file_name + kMediaInfoSuffix);
264  } else {
265  NOTIMPLEMENTED()
266  << "--mpd_output or --output_media_info flags are "
267  "required for text output. Skipping manifest related output for "
268  << stream_iter->input;
269  }
270  continue;
271  }
272 
273  if (stream_iter->input != previous_input) {
274  // New remux job needed. Create demux and job thread.
275  scoped_ptr<Demuxer> demuxer(new Demuxer(stream_iter->input));
276  if (FLAGS_enable_widevine_decryption ||
277  FLAGS_enable_fixed_key_decryption) {
278  scoped_ptr<KeySource> key_source(CreateDecryptionKeySource());
279  if (!key_source)
280  return false;
281  demuxer->SetKeySource(key_source.Pass());
282  }
283  Status status = demuxer->Initialize();
284  if (!status.ok()) {
285  LOG(ERROR) << "Demuxer failed to initialize: " << status.ToString();
286  return false;
287  }
288  if (FLAGS_dump_stream_info) {
289  printf("\nFile \"%s\":\n", stream_iter->input.c_str());
290  DumpStreamInfo(demuxer->streams());
291  if (stream_iter->output.empty())
292  continue; // just need stream info.
293  }
294  remux_jobs->push_back(new RemuxJob(demuxer.Pass()));
295  previous_input = stream_iter->input;
296  }
297  DCHECK(!remux_jobs->empty());
298 
299  MediaContainerName output_format = stream_iter->output_format;
300  if (output_format == CONTAINER_UNKNOWN) {
301  output_format =
302  DetermineContainerFromFileName(stream_muxer_options.output_file_name);
303 
304  if (output_format == CONTAINER_UNKNOWN) {
305  LOG(ERROR) << "Unable to determine output format for file "
306  << stream_muxer_options.output_file_name;
307  return false;
308  }
309  }
310 
311  scoped_ptr<Muxer> muxer(
312  CreateOutputMuxer(stream_muxer_options, output_format));
313  if (FLAGS_use_fake_clock_for_muxer) muxer->set_clock(fake_clock);
314 
315  if (key_source) {
316  muxer->SetKeySource(key_source,
317  FLAGS_max_sd_pixels,
318  FLAGS_clear_lead,
319  FLAGS_crypto_period_duration,
320  GetProtectionScheme(FLAGS_protection_scheme));
321  }
322 
323  scoped_ptr<MuxerListener> muxer_listener;
324  DCHECK(!(FLAGS_output_media_info && mpd_notifier));
325  if (FLAGS_output_media_info) {
326  const std::string output_media_info_file_name =
327  stream_muxer_options.output_file_name + kMediaInfoSuffix;
328  scoped_ptr<VodMediaInfoDumpMuxerListener>
329  vod_media_info_dump_muxer_listener(
330  new VodMediaInfoDumpMuxerListener(output_media_info_file_name));
331  muxer_listener = vod_media_info_dump_muxer_listener.Pass();
332  }
333  if (mpd_notifier) {
334  scoped_ptr<MpdNotifyMuxerListener> mpd_notify_muxer_listener(
335  new MpdNotifyMuxerListener(mpd_notifier));
336  muxer_listener = mpd_notify_muxer_listener.Pass();
337  }
338 
339  if (muxer_listener)
340  muxer->SetMuxerListener(muxer_listener.Pass());
341 
342  if (!AddStreamToMuxer(remux_jobs->back()->demuxer()->streams(),
343  stream_iter->stream_selector,
344  stream_iter->language,
345  muxer.get()))
346  return false;
347  remux_jobs->back()->AddMuxer(muxer.Pass());
348  }
349 
350  return true;
351 }
352 
353 Status RunRemuxJobs(const std::vector<RemuxJob*>& remux_jobs) {
354  // Start the job threads.
355  for (std::vector<RemuxJob*>::const_iterator job_iter = remux_jobs.begin();
356  job_iter != remux_jobs.end();
357  ++job_iter) {
358  (*job_iter)->Start();
359  }
360 
361  // Wait for all jobs to complete or an error occurs.
362  Status status;
363  bool all_joined;
364  do {
365  all_joined = true;
366  for (std::vector<RemuxJob*>::const_iterator job_iter = remux_jobs.begin();
367  job_iter != remux_jobs.end();
368  ++job_iter) {
369  if ((*job_iter)->HasBeenJoined()) {
370  status = (*job_iter)->status();
371  if (!status.ok())
372  break;
373  } else {
374  all_joined = false;
375  (*job_iter)->Join();
376  }
377  }
378  } while (!all_joined && status.ok());
379 
380  return status;
381 }
382 
383 bool RunPackager(const StreamDescriptorList& stream_descriptors) {
384  const FourCC protection_scheme = GetProtectionScheme(FLAGS_protection_scheme);
385  if (protection_scheme == FOURCC_NULL)
386  return false;
387  if (protection_scheme == FOURCC_cbc1 || protection_scheme == FOURCC_cbcs) {
388  if (!FLAGS_iv.empty() && FLAGS_iv.size() != 16) {
389  LOG(ERROR) << "Iv size should be 16 bytes for CBC encryption mode.";
390  return false;
391  }
392  }
393 
394  if (!AssignFlagsFromProfile())
395  return false;
396 
397  if (FLAGS_output_media_info && !FLAGS_mpd_output.empty()) {
398  NOTIMPLEMENTED() << "ERROR: --output_media_info and --mpd_output do not "
399  "work together.";
400  return false;
401  }
402  if (FLAGS_output_media_info && !FLAGS_single_segment) {
403  // TODO(rkuroiwa, kqyang): Support partial media info dump for live.
404  NOTIMPLEMENTED() << "ERROR: --output_media_info is only supported if "
405  "--single_segment is true.";
406  return false;
407  }
408 
409  // Get basic muxer options.
410  MuxerOptions muxer_options;
411  if (!GetMuxerOptions(&muxer_options))
412  return false;
413 
414  MpdOptions mpd_options;
415  if (!GetMpdOptions(&mpd_options))
416  return false;
417 
418  // Create encryption key source if needed.
419  scoped_ptr<KeySource> encryption_key_source;
420  if (FLAGS_enable_widevine_encryption || FLAGS_enable_fixed_key_encryption) {
421  encryption_key_source = CreateEncryptionKeySource();
422  if (!encryption_key_source)
423  return false;
424  }
425 
426  scoped_ptr<MpdNotifier> mpd_notifier;
427  if (!FLAGS_mpd_output.empty()) {
428  DashProfile profile =
429  FLAGS_single_segment ? kOnDemandProfile : kLiveProfile;
430  std::vector<std::string> base_urls;
431  base::SplitString(FLAGS_base_urls, ',', &base_urls);
432  if (FLAGS_generate_dash_if_iop_compliant_mpd) {
433  mpd_notifier.reset(new DashIopMpdNotifier(profile, mpd_options, base_urls,
434  FLAGS_mpd_output));
435  } else {
436  mpd_notifier.reset(new SimpleMpdNotifier(profile, mpd_options, base_urls,
437  FLAGS_mpd_output));
438  }
439  if (!mpd_notifier->Init()) {
440  LOG(ERROR) << "MpdNotifier failed to initialize.";
441  return false;
442  }
443  }
444 
445  std::vector<RemuxJob*> remux_jobs;
446  STLElementDeleter<std::vector<RemuxJob*> > scoped_jobs_deleter(&remux_jobs);
447  FakeClock fake_clock;
448  if (!CreateRemuxJobs(stream_descriptors, muxer_options, &fake_clock,
449  encryption_key_source.get(), mpd_notifier.get(),
450  &remux_jobs)) {
451  return false;
452  }
453 
454  Status status = RunRemuxJobs(remux_jobs);
455  if (!status.ok()) {
456  LOG(ERROR) << "Packaging Error: " << status.ToString();
457  return false;
458  }
459 
460  printf("Packaging completed successfully.\n");
461  return true;
462 }
463 
464 int PackagerMain(int argc, char** argv) {
465  base::AtExitManager exit;
466  // Needed to enable VLOG/DVLOG through --vmodule or --v.
467  base::CommandLine::Init(argc, argv);
468  CHECK(logging::InitLogging(logging::LoggingSettings()));
469 
470  google::SetUsageMessage(base::StringPrintf(kUsage, argv[0]));
471  google::ParseCommandLineFlags(&argc, &argv, true);
472  if (argc < 2) {
473  std::string version_string =
474  base::StringPrintf("edash-packager version %s", kPackagerVersion);
475  google::ShowUsageWithFlags(version_string.c_str());
476  return kSuccess;
477  }
478 
480  return kArgumentValidationFailed;
481 
482  edash_packager::media::LibcryptoThreading libcrypto_threading;
483  // TODO(tinskip): Make InsertStreamDescriptor a member of
484  // StreamDescriptorList.
485  StreamDescriptorList stream_descriptors;
486  for (int i = 1; i < argc; ++i) {
487  if (!InsertStreamDescriptor(argv[i], &stream_descriptors))
488  return kArgumentValidationFailed;
489  }
490  return RunPackager(stream_descriptors) ? kSuccess : kPackagingFailed;
491 }
492 
493 } // namespace media
494 } // namespace edash_packager
495 
496 int main(int argc, char** argv) {
497  return edash_packager::media::PackagerMain(argc, argv);
498 }
static bool ReadFileToString(const char *file_name, std::string *contents)
Definition: file.cc:184
Convenience class which initializes and terminates libcrypto threading.
static bool WriteMediaInfoToFile(const MediaInfo &media_info, const std::string &output_file_path)
static bool Copy(const char *from_file_name, const char *to_file_name)
Definition: file.cc:202