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