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/encryption_modes.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::EncryptionMode GetEncryptionMode(
109  const std::string& protection_scheme) {
110  if (protection_scheme == "cenc") {
111  return edash_packager::media::kEncryptionModeAesCtr;
112  } else if (protection_scheme == "cbc1") {
113  return edash_packager::media::kEncryptionModeAesCbc;
114  } else {
115  LOG(ERROR) << "Protection scheme is unknown.";
116  return edash_packager::media::kEncryptionModeUnknown;
117  }
118 }
119 
120 } // namespace
121 
122 namespace edash_packager {
123 namespace media {
124 
125 // A fake clock that always return time 0 (epoch). Should only be used for
126 // testing.
127 class FakeClock : public base::Clock {
128  public:
129  base::Time Now() override { return base::Time(); }
130 };
131 
132 // Demux, Mux(es) and worker thread used to remux a source file/stream.
133 class RemuxJob : public base::SimpleThread {
134  public:
135  RemuxJob(scoped_ptr<Demuxer> demuxer)
136  : SimpleThread("RemuxJob"),
137  demuxer_(demuxer.Pass()) {}
138 
139  ~RemuxJob() override {
140  STLDeleteElements(&muxers_);
141  }
142 
143  void AddMuxer(scoped_ptr<Muxer> mux) {
144  muxers_.push_back(mux.release());
145  }
146 
147  Demuxer* demuxer() { return demuxer_.get(); }
148  Status status() { return status_; }
149 
150  private:
151  void Run() override {
152  DCHECK(demuxer_);
153  status_ = demuxer_->Run();
154  }
155 
156  scoped_ptr<Demuxer> demuxer_;
157  std::vector<Muxer*> muxers_;
158  Status status_;
159 
160  DISALLOW_COPY_AND_ASSIGN(RemuxJob);
161 };
162 
163 bool StreamInfoToTextMediaInfo(const StreamDescriptor& stream_descriptor,
164  const MuxerOptions& stream_muxer_options,
165  MediaInfo* text_media_info) {
166  const std::string& language = stream_descriptor.language;
167  std::string format = DetermineTextFileFormat(stream_descriptor.input);
168  if (format.empty()) {
169  LOG(ERROR) << "Failed to determine the text file format for "
170  << stream_descriptor.input;
171  return false;
172  }
173 
174  if (!File::Copy(stream_descriptor.input.c_str(),
175  stream_muxer_options.output_file_name.c_str())) {
176  LOG(ERROR) << "Failed to copy the input file (" << stream_descriptor.input
177  << ") to output file (" << stream_muxer_options.output_file_name
178  << ").";
179  return false;
180  }
181 
182  text_media_info->set_media_file_name(stream_muxer_options.output_file_name);
183  text_media_info->set_container_type(MediaInfo::CONTAINER_TEXT);
184 
185  if (stream_muxer_options.bandwidth != 0) {
186  text_media_info->set_bandwidth(stream_muxer_options.bandwidth);
187  } else {
188  // Text files are usually small and since the input is one file; there's no
189  // way for the player to do ranged requests. So set this value to something
190  // reasonable.
191  text_media_info->set_bandwidth(256);
192  }
193 
194  MediaInfo::TextInfo* text_info = text_media_info->mutable_text_info();
195  text_info->set_format(format);
196  if (!language.empty())
197  text_info->set_language(language);
198 
199  return true;
200 }
201 
202 scoped_ptr<Muxer> CreateOutputMuxer(const MuxerOptions& options,
203  MediaContainerName container) {
204  if (container == CONTAINER_WEBM) {
205  return scoped_ptr<Muxer>(new webm::WebMMuxer(options));
206  } else {
207  DCHECK_EQ(container, CONTAINER_MOV);
208  return scoped_ptr<Muxer>(new mp4::MP4Muxer(options));
209  }
210 }
211 
212 bool CreateRemuxJobs(const StreamDescriptorList& stream_descriptors,
213  const MuxerOptions& muxer_options,
214  FakeClock* fake_clock,
215  KeySource* key_source,
216  MpdNotifier* mpd_notifier,
217  std::vector<RemuxJob*>* remux_jobs) {
218  DCHECK(remux_jobs);
219 
220  std::string previous_input;
221  for (StreamDescriptorList::const_iterator stream_iter =
222  stream_descriptors.begin();
223  stream_iter != stream_descriptors.end();
224  ++stream_iter) {
225  // Process stream descriptor.
226  MuxerOptions stream_muxer_options(muxer_options);
227  stream_muxer_options.output_file_name = stream_iter->output;
228  if (!stream_iter->segment_template.empty()) {
229  if (!ValidateSegmentTemplate(stream_iter->segment_template)) {
230  LOG(ERROR) << "ERROR: segment template with '"
231  << stream_iter->segment_template << "' is invalid.";
232  return false;
233  }
234  stream_muxer_options.segment_template = stream_iter->segment_template;
235  }
236  stream_muxer_options.bandwidth = stream_iter->bandwidth;
237 
238  // Handle text input.
239  if (stream_iter->stream_selector == "text") {
240  MediaInfo text_media_info;
241  if (!StreamInfoToTextMediaInfo(*stream_iter, stream_muxer_options,
242  &text_media_info)) {
243  return false;
244  }
245 
246  if (mpd_notifier) {
247  uint32 unused;
248  if (!mpd_notifier->NotifyNewContainer(text_media_info, &unused)) {
249  LOG(ERROR) << "Failed to process text file " << stream_iter->input;
250  } else {
251  mpd_notifier->Flush();
252  }
253  } else if (FLAGS_output_media_info) {
255  text_media_info,
256  stream_muxer_options.output_file_name + kMediaInfoSuffix);
257  } else {
258  NOTIMPLEMENTED()
259  << "--mpd_output or --output_media_info flags are "
260  "required for text output. Skipping manifest related output for "
261  << stream_iter->input;
262  }
263  continue;
264  }
265 
266  if (stream_iter->input != previous_input) {
267  // New remux job needed. Create demux and job thread.
268  scoped_ptr<Demuxer> demuxer(new Demuxer(stream_iter->input));
269  if (FLAGS_enable_widevine_decryption ||
270  FLAGS_enable_fixed_key_decryption) {
271  scoped_ptr<KeySource> key_source(CreateDecryptionKeySource());
272  if (!key_source)
273  return false;
274  demuxer->SetKeySource(key_source.Pass());
275  }
276  Status status = demuxer->Initialize();
277  if (!status.ok()) {
278  LOG(ERROR) << "Demuxer failed to initialize: " << status.ToString();
279  return false;
280  }
281  if (FLAGS_dump_stream_info) {
282  printf("\nFile \"%s\":\n", stream_iter->input.c_str());
283  DumpStreamInfo(demuxer->streams());
284  if (stream_iter->output.empty())
285  continue; // just need stream info.
286  }
287  remux_jobs->push_back(new RemuxJob(demuxer.Pass()));
288  previous_input = stream_iter->input;
289  }
290  DCHECK(!remux_jobs->empty());
291 
292  MediaContainerName output_format = stream_iter->output_format;
293  if (output_format == CONTAINER_UNKNOWN) {
294  output_format =
295  DetermineContainerFromFileName(stream_muxer_options.output_file_name);
296 
297  if (output_format == CONTAINER_UNKNOWN) {
298  LOG(ERROR) << "Unable to determine output format for file "
299  << stream_muxer_options.output_file_name;
300  return false;
301  }
302  }
303 
304  scoped_ptr<Muxer> muxer(
305  CreateOutputMuxer(stream_muxer_options, output_format));
306  if (FLAGS_use_fake_clock_for_muxer) muxer->set_clock(fake_clock);
307 
308  if (key_source) {
309  muxer->SetKeySource(key_source,
310  FLAGS_max_sd_pixels,
311  FLAGS_clear_lead,
312  FLAGS_crypto_period_duration,
313  GetEncryptionMode(FLAGS_protection_scheme));
314  }
315 
316  scoped_ptr<MuxerListener> muxer_listener;
317  DCHECK(!(FLAGS_output_media_info && mpd_notifier));
318  if (FLAGS_output_media_info) {
319  const std::string output_media_info_file_name =
320  stream_muxer_options.output_file_name + kMediaInfoSuffix;
321  scoped_ptr<VodMediaInfoDumpMuxerListener>
322  vod_media_info_dump_muxer_listener(
323  new VodMediaInfoDumpMuxerListener(output_media_info_file_name));
324  muxer_listener = vod_media_info_dump_muxer_listener.Pass();
325  }
326  if (mpd_notifier) {
327  scoped_ptr<MpdNotifyMuxerListener> mpd_notify_muxer_listener(
328  new MpdNotifyMuxerListener(mpd_notifier));
329  muxer_listener = mpd_notify_muxer_listener.Pass();
330  }
331 
332  if (muxer_listener)
333  muxer->SetMuxerListener(muxer_listener.Pass());
334 
335  if (!AddStreamToMuxer(remux_jobs->back()->demuxer()->streams(),
336  stream_iter->stream_selector,
337  stream_iter->language,
338  muxer.get()))
339  return false;
340  remux_jobs->back()->AddMuxer(muxer.Pass());
341  }
342 
343  return true;
344 }
345 
346 Status RunRemuxJobs(const std::vector<RemuxJob*>& remux_jobs) {
347  // Start the job threads.
348  for (std::vector<RemuxJob*>::const_iterator job_iter = remux_jobs.begin();
349  job_iter != remux_jobs.end();
350  ++job_iter) {
351  (*job_iter)->Start();
352  }
353 
354  // Wait for all jobs to complete or an error occurs.
355  Status status;
356  bool all_joined;
357  do {
358  all_joined = true;
359  for (std::vector<RemuxJob*>::const_iterator job_iter = remux_jobs.begin();
360  job_iter != remux_jobs.end();
361  ++job_iter) {
362  if ((*job_iter)->HasBeenJoined()) {
363  status = (*job_iter)->status();
364  if (!status.ok())
365  break;
366  } else {
367  all_joined = false;
368  (*job_iter)->Join();
369  }
370  }
371  } while (!all_joined && status.ok());
372 
373  return status;
374 }
375 
376 bool RunPackager(const StreamDescriptorList& stream_descriptors) {
377  EncryptionMode encryption_mode = GetEncryptionMode(FLAGS_protection_scheme);
378  if (encryption_mode == kEncryptionModeUnknown)
379  return false;
380 
381  if (!AssignFlagsFromProfile())
382  return false;
383 
384  if (FLAGS_output_media_info && !FLAGS_mpd_output.empty()) {
385  NOTIMPLEMENTED() << "ERROR: --output_media_info and --mpd_output do not "
386  "work together.";
387  return false;
388  }
389  if (FLAGS_output_media_info && !FLAGS_single_segment) {
390  // TODO(rkuroiwa, kqyang): Support partial media info dump for live.
391  NOTIMPLEMENTED() << "ERROR: --output_media_info is only supported if "
392  "--single_segment is true.";
393  return false;
394  }
395 
396  // Get basic muxer options.
397  MuxerOptions muxer_options;
398  if (!GetMuxerOptions(&muxer_options))
399  return false;
400 
401  MpdOptions mpd_options;
402  if (!GetMpdOptions(&mpd_options))
403  return false;
404 
405  // Create encryption key source if needed.
406  scoped_ptr<KeySource> encryption_key_source;
407  if (FLAGS_enable_widevine_encryption || FLAGS_enable_fixed_key_encryption) {
408  encryption_key_source = CreateEncryptionKeySource();
409  if (!encryption_key_source)
410  return false;
411  }
412 
413  scoped_ptr<MpdNotifier> mpd_notifier;
414  if (!FLAGS_mpd_output.empty()) {
415  DashProfile profile =
416  FLAGS_single_segment ? kOnDemandProfile : kLiveProfile;
417  std::vector<std::string> base_urls;
418  base::SplitString(FLAGS_base_urls, ',', &base_urls);
419  if (FLAGS_generate_dash_if_iop_compliant_mpd) {
420  mpd_notifier.reset(new DashIopMpdNotifier(profile, mpd_options, base_urls,
421  FLAGS_mpd_output));
422  } else {
423  mpd_notifier.reset(new SimpleMpdNotifier(profile, mpd_options, base_urls,
424  FLAGS_mpd_output));
425  }
426  if (!mpd_notifier->Init()) {
427  LOG(ERROR) << "MpdNotifier failed to initialize.";
428  return false;
429  }
430  }
431 
432  std::vector<RemuxJob*> remux_jobs;
433  STLElementDeleter<std::vector<RemuxJob*> > scoped_jobs_deleter(&remux_jobs);
434  FakeClock fake_clock;
435  if (!CreateRemuxJobs(stream_descriptors, muxer_options, &fake_clock,
436  encryption_key_source.get(), mpd_notifier.get(),
437  &remux_jobs)) {
438  return false;
439  }
440 
441  Status status = RunRemuxJobs(remux_jobs);
442  if (!status.ok()) {
443  LOG(ERROR) << "Packaging Error: " << status.ToString();
444  return false;
445  }
446 
447  printf("Packaging completed successfully.\n");
448  return true;
449 }
450 
451 int PackagerMain(int argc, char** argv) {
452  base::AtExitManager exit;
453  // Needed to enable VLOG/DVLOG through --vmodule or --v.
454  base::CommandLine::Init(argc, argv);
455  CHECK(logging::InitLogging(logging::LoggingSettings()));
456 
457  google::SetUsageMessage(base::StringPrintf(kUsage, argv[0]));
458  google::ParseCommandLineFlags(&argc, &argv, true);
459  if (argc < 2) {
460  std::string version_string =
461  base::StringPrintf("edash-packager version %s", kPackagerVersion);
462  google::ShowUsageWithFlags(version_string.c_str());
463  return kSuccess;
464  }
465 
467  return kArgumentValidationFailed;
468 
469  edash_packager::media::LibcryptoThreading libcrypto_threading;
470  // TODO(tinskip): Make InsertStreamDescriptor a member of
471  // StreamDescriptorList.
472  StreamDescriptorList stream_descriptors;
473  for (int i = 1; i < argc; ++i) {
474  if (!InsertStreamDescriptor(argv[i], &stream_descriptors))
475  return kArgumentValidationFailed;
476  }
477  return RunPackager(stream_descriptors) ? kSuccess : kPackagingFailed;
478 }
479 
480 } // namespace media
481 } // namespace edash_packager
482 
483 int main(int argc, char** argv) {
484  return edash_packager::media::PackagerMain(argc, argv);
485 }
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