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