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