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