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