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  muxer_listener = vod_media_info_dump_muxer_listener.Pass();
311  }
312  if (mpd_notifier) {
313  scoped_ptr<MpdNotifyMuxerListener> mpd_notify_muxer_listener(
314  new MpdNotifyMuxerListener(mpd_notifier));
315  muxer_listener = mpd_notify_muxer_listener.Pass();
316  }
317 
318  if (muxer_listener)
319  muxer->SetMuxerListener(muxer_listener.Pass());
320 
321  if (!AddStreamToMuxer(remux_jobs->back()->demuxer()->streams(),
322  stream_iter->stream_selector,
323  stream_iter->language,
324  muxer.get()))
325  return false;
326  remux_jobs->back()->AddMuxer(muxer.Pass());
327  }
328 
329  return true;
330 }
331 
332 Status RunRemuxJobs(const std::vector<RemuxJob*>& remux_jobs) {
333  // Start the job threads.
334  for (std::vector<RemuxJob*>::const_iterator job_iter = remux_jobs.begin();
335  job_iter != remux_jobs.end();
336  ++job_iter) {
337  (*job_iter)->Start();
338  }
339 
340  // Wait for all jobs to complete or an error occurs.
341  Status status;
342  bool all_joined;
343  do {
344  all_joined = true;
345  for (std::vector<RemuxJob*>::const_iterator job_iter = remux_jobs.begin();
346  job_iter != remux_jobs.end();
347  ++job_iter) {
348  if ((*job_iter)->HasBeenJoined()) {
349  status = (*job_iter)->status();
350  if (!status.ok())
351  break;
352  } else {
353  all_joined = false;
354  (*job_iter)->Join();
355  }
356  }
357  } while (!all_joined && status.ok());
358 
359  return status;
360 }
361 
362 bool RunPackager(const StreamDescriptorList& stream_descriptors) {
363  if (!AssignFlagsFromProfile())
364  return false;
365 
366  if (FLAGS_output_media_info && !FLAGS_mpd_output.empty()) {
367  NOTIMPLEMENTED() << "ERROR: --output_media_info and --mpd_output do not "
368  "work together.";
369  return false;
370  }
371  if (FLAGS_output_media_info && !FLAGS_single_segment) {
372  // TODO(rkuroiwa, kqyang): Support partial media info dump for live.
373  NOTIMPLEMENTED() << "ERROR: --output_media_info is only supported if "
374  "--single_segment is true.";
375  return false;
376  }
377 
378  // Get basic muxer options.
379  MuxerOptions muxer_options;
380  if (!GetMuxerOptions(&muxer_options))
381  return false;
382 
383  MpdOptions mpd_options;
384  if (!GetMpdOptions(&mpd_options))
385  return false;
386 
387  // Create encryption key source if needed.
388  scoped_ptr<KeySource> encryption_key_source;
389  if (FLAGS_enable_widevine_encryption || FLAGS_enable_fixed_key_encryption) {
390  encryption_key_source = CreateEncryptionKeySource();
391  if (!encryption_key_source)
392  return false;
393  }
394 
395  scoped_ptr<MpdNotifier> mpd_notifier;
396  if (!FLAGS_mpd_output.empty()) {
397  DashProfile profile =
398  FLAGS_single_segment ? kOnDemandProfile : kLiveProfile;
399  std::vector<std::string> base_urls;
400  base::SplitString(FLAGS_base_urls, ',', &base_urls);
401  if (FLAGS_generate_dash_if_iop_compliant_mpd) {
402  mpd_notifier.reset(new DashIopMpdNotifier(profile, mpd_options, base_urls,
403  FLAGS_mpd_output));
404  } else {
405  mpd_notifier.reset(new SimpleMpdNotifier(profile, mpd_options, base_urls,
406  FLAGS_mpd_output));
407  }
408  if (!mpd_notifier->Init()) {
409  LOG(ERROR) << "MpdNotifier failed to initialize.";
410  return false;
411  }
412  }
413 
414  std::vector<RemuxJob*> remux_jobs;
415  STLElementDeleter<std::vector<RemuxJob*> > scoped_jobs_deleter(&remux_jobs);
416  FakeClock fake_clock;
417  if (!CreateRemuxJobs(stream_descriptors, muxer_options, &fake_clock,
418  encryption_key_source.get(), mpd_notifier.get(),
419  &remux_jobs)) {
420  return false;
421  }
422 
423  Status status = RunRemuxJobs(remux_jobs);
424  if (!status.ok()) {
425  LOG(ERROR) << "Packaging Error: " << status.ToString();
426  return false;
427  }
428 
429  printf("Packaging completed successfully.\n");
430  return true;
431 }
432 
433 int PackagerMain(int argc, char** argv) {
434  base::AtExitManager exit;
435  // Needed to enable VLOG/DVLOG through --vmodule or --v.
436  base::CommandLine::Init(argc, argv);
437  CHECK(logging::InitLogging(logging::LoggingSettings()));
438 
439  google::SetUsageMessage(base::StringPrintf(kUsage, argv[0]));
440  google::ParseCommandLineFlags(&argc, &argv, true);
441  if (argc < 2) {
442  std::string version_string =
443  base::StringPrintf("edash-packager version %s", kPackagerVersion);
444  google::ShowUsageWithFlags(version_string.c_str());
445  return kSuccess;
446  }
447 
449  return kArgumentValidationFailed;
450 
451  edash_packager::media::LibcryptoThreading libcrypto_threading;
452  // TODO(tinskip): Make InsertStreamDescriptor a member of
453  // StreamDescriptorList.
454  StreamDescriptorList stream_descriptors;
455  for (int i = 1; i < argc; ++i) {
456  if (!InsertStreamDescriptor(argv[i], &stream_descriptors))
457  return kArgumentValidationFailed;
458  }
459  return RunPackager(stream_descriptors) ? kSuccess : kPackagingFailed;
460 }
461 
462 } // namespace media
463 } // namespace edash_packager
464 
465 int main(int argc, char** argv) {
466  return edash_packager::media::PackagerMain(argc, argv);
467 }
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