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/demuxer.h"
26 #include "packager/media/base/key_source.h"
27 #include "packager/media/base/muxer_options.h"
28 #include "packager/media/base/muxer_util.h"
29 #include "packager/media/event/mpd_notify_muxer_listener.h"
30 #include "packager/media/event/vod_media_info_dump_muxer_listener.h"
31 #include "packager/media/formats/mp4/mp4_muxer.h"
32 #include "packager/mpd/base/dash_iop_mpd_notifier.h"
33 #include "packager/mpd/base/mpd_builder.h"
34 #include "packager/mpd/base/simple_mpd_notifier.h"
35 
36 DEFINE_bool(use_fake_clock_for_muxer,
37  false,
38  "Set to true to use a fake clock for muxer. With this flag set, "
39  "creation time and modification time in outputs are set to 0. "
40  "Should only be used for testing.");
41 
42 namespace {
43 const char kUsage[] =
44  "Packager driver program. Sample Usage:\n"
45  "%s [flags] <stream_descriptor> ...\n"
46  "stream_descriptor consists of comma separated field_name/value pairs:\n"
47  "field_name=value,[field_name=value,]...\n"
48  "Supported field names are as follows:\n"
49  " - input (in): Required input/source media file path or network stream "
50  "URL.\n"
51  " - stream_selector (stream): Required field with value 'audio', 'video', "
52  "or stream number (zero based).\n"
53  " - output (out): Required output file (single file) or initialization "
54  "file path (multiple file).\n"
55  " - segment_template (segment): Optional value which specifies the "
56  "naming pattern for the segment files, and that the stream should be "
57  "split into multiple files. Its presence should be consistent across "
58  "streams.\n"
59  " - bandwidth (bw): Optional value which contains a user-specified "
60  "content bit rate for the stream, in bits/sec. If specified, this value is "
61  "propagated to the $Bandwidth$ template parameter for segment names. "
62  "If not specified, its value may be estimated.\n"
63  " - language (lang): Optional value which contains a user-specified "
64  "language tag. If specified, this value overrides any language metadata "
65  "in the input track.\n";
66 
67 enum ExitStatus {
68  kSuccess = 0,
69  kNoArgument,
70  kArgumentValidationFailed,
71  kPackagingFailed,
72  kInternalError,
73 };
74 } // namespace
75 
76 namespace edash_packager {
77 namespace media {
78 
79 // A fake clock that always return time 0 (epoch). Should only be used for
80 // testing.
81 class FakeClock : public base::Clock {
82  public:
83  base::Time Now() override { return base::Time(); }
84 };
85 
86 // Demux, Mux(es) and worker thread used to remux a source file/stream.
87 class RemuxJob : public base::SimpleThread {
88  public:
89  RemuxJob(scoped_ptr<Demuxer> demuxer)
90  : SimpleThread("RemuxJob"),
91  demuxer_(demuxer.Pass()) {}
92 
93  ~RemuxJob() override {
94  STLDeleteElements(&muxers_);
95  }
96 
97  void AddMuxer(scoped_ptr<Muxer> mux) {
98  muxers_.push_back(mux.release());
99  }
100 
101  Demuxer* demuxer() { return demuxer_.get(); }
102  Status status() { return status_; }
103 
104  private:
105  void Run() override {
106  DCHECK(demuxer_);
107  status_ = demuxer_->Run();
108  }
109 
110  scoped_ptr<Demuxer> demuxer_;
111  std::vector<Muxer*> muxers_;
112  Status status_;
113 
114  DISALLOW_COPY_AND_ASSIGN(RemuxJob);
115 };
116 
117 bool CreateRemuxJobs(const StreamDescriptorList& stream_descriptors,
118  const MuxerOptions& muxer_options,
119  FakeClock* fake_clock,
120  KeySource* key_source,
121  MpdNotifier* mpd_notifier,
122  std::vector<RemuxJob*>* remux_jobs) {
123  DCHECK(remux_jobs);
124 
125  std::string previous_input;
126  for (StreamDescriptorList::const_iterator stream_iter =
127  stream_descriptors.begin();
128  stream_iter != stream_descriptors.end();
129  ++stream_iter) {
130  // Process stream descriptor.
131  MuxerOptions stream_muxer_options(muxer_options);
132  stream_muxer_options.output_file_name = stream_iter->output;
133  if (!stream_iter->segment_template.empty()) {
134  if (!ValidateSegmentTemplate(stream_iter->segment_template)) {
135  LOG(ERROR) << "ERROR: segment template with '"
136  << stream_iter->segment_template << "' is invalid.";
137  return false;
138  }
139  stream_muxer_options.segment_template = stream_iter->segment_template;
140  }
141  stream_muxer_options.bandwidth = stream_iter->bandwidth;
142 
143  if (stream_iter->input != previous_input) {
144  // New remux job needed. Create demux and job thread.
145  scoped_ptr<Demuxer> demuxer(new Demuxer(stream_iter->input));
146  if (FLAGS_enable_widevine_decryption ||
147  FLAGS_enable_fixed_key_decryption) {
148  scoped_ptr<KeySource> key_source(CreateDecryptionKeySource());
149  if (!key_source)
150  return false;
151  demuxer->SetKeySource(key_source.Pass());
152  }
153  Status status = demuxer->Initialize();
154  if (!status.ok()) {
155  LOG(ERROR) << "Demuxer failed to initialize: " << status.ToString();
156  return false;
157  }
158  if (FLAGS_dump_stream_info) {
159  printf("\nFile \"%s\":\n", stream_iter->input.c_str());
160  DumpStreamInfo(demuxer->streams());
161  if (stream_iter->output.empty())
162  continue; // just need stream info.
163  }
164  remux_jobs->push_back(new RemuxJob(demuxer.Pass()));
165  previous_input = stream_iter->input;
166  }
167  DCHECK(!remux_jobs->empty());
168 
169  scoped_ptr<Muxer> muxer(new mp4::MP4Muxer(stream_muxer_options));
170  if (FLAGS_use_fake_clock_for_muxer) muxer->set_clock(fake_clock);
171 
172  if (key_source) {
173  muxer->SetKeySource(key_source,
174  FLAGS_max_sd_pixels,
175  FLAGS_clear_lead,
176  FLAGS_crypto_period_duration);
177  }
178 
179  scoped_ptr<MuxerListener> muxer_listener;
180  DCHECK(!(FLAGS_output_media_info && mpd_notifier));
181  if (FLAGS_output_media_info) {
182  const std::string output_media_info_file_name =
183  stream_muxer_options.output_file_name + ".media_info";
184  scoped_ptr<VodMediaInfoDumpMuxerListener>
185  vod_media_info_dump_muxer_listener(
186  new VodMediaInfoDumpMuxerListener(output_media_info_file_name));
187  vod_media_info_dump_muxer_listener->SetContentProtectionSchemeIdUri(
188  FLAGS_scheme_id_uri);
189  muxer_listener = vod_media_info_dump_muxer_listener.Pass();
190  }
191  if (mpd_notifier) {
192  scoped_ptr<MpdNotifyMuxerListener> mpd_notify_muxer_listener(
193  new MpdNotifyMuxerListener(mpd_notifier));
194  mpd_notify_muxer_listener->SetContentProtectionSchemeIdUri(
195  FLAGS_scheme_id_uri);
196  muxer_listener = mpd_notify_muxer_listener.Pass();
197  }
198 
199  if (muxer_listener)
200  muxer->SetMuxerListener(muxer_listener.Pass());
201 
202  if (!AddStreamToMuxer(remux_jobs->back()->demuxer()->streams(),
203  stream_iter->stream_selector,
204  stream_iter->language,
205  muxer.get()))
206  return false;
207  remux_jobs->back()->AddMuxer(muxer.Pass());
208  }
209 
210  return true;
211 }
212 
213 Status RunRemuxJobs(const std::vector<RemuxJob*>& remux_jobs) {
214  // Start the job threads.
215  for (std::vector<RemuxJob*>::const_iterator job_iter = remux_jobs.begin();
216  job_iter != remux_jobs.end();
217  ++job_iter) {
218  (*job_iter)->Start();
219  }
220 
221  // Wait for all jobs to complete or an error occurs.
222  Status status;
223  bool all_joined;
224  do {
225  all_joined = true;
226  for (std::vector<RemuxJob*>::const_iterator job_iter = remux_jobs.begin();
227  job_iter != remux_jobs.end();
228  ++job_iter) {
229  if ((*job_iter)->HasBeenJoined()) {
230  status = (*job_iter)->status();
231  if (!status.ok())
232  break;
233  } else {
234  all_joined = false;
235  (*job_iter)->Join();
236  }
237  }
238  } while (!all_joined && status.ok());
239 
240  return status;
241 }
242 
243 bool RunPackager(const StreamDescriptorList& stream_descriptors) {
244  if (!AssignFlagsFromProfile())
245  return false;
246 
247  if (FLAGS_output_media_info && !FLAGS_mpd_output.empty()) {
248  NOTIMPLEMENTED() << "ERROR: --output_media_info and --mpd_output do not "
249  "work together.";
250  return false;
251  }
252  if (FLAGS_output_media_info && !FLAGS_single_segment) {
253  // TODO(rkuroiwa, kqyang): Support partial media info dump for live.
254  NOTIMPLEMENTED() << "ERROR: --output_media_info is only supported if "
255  "--single_segment is true.";
256  return false;
257  }
258 
259  // Get basic muxer options.
260  MuxerOptions muxer_options;
261  if (!GetMuxerOptions(&muxer_options))
262  return false;
263 
264  MpdOptions mpd_options;
265  if (!GetMpdOptions(&mpd_options))
266  return false;
267 
268  // Create encryption key source if needed.
269  scoped_ptr<KeySource> encryption_key_source;
270  if (FLAGS_enable_widevine_encryption || FLAGS_enable_fixed_key_encryption) {
271  encryption_key_source = CreateEncryptionKeySource();
272  if (!encryption_key_source)
273  return false;
274  }
275 
276  scoped_ptr<MpdNotifier> mpd_notifier;
277  if (!FLAGS_mpd_output.empty()) {
278  DashProfile profile =
279  FLAGS_single_segment ? kOnDemandProfile : kLiveProfile;
280  std::vector<std::string> base_urls;
281  base::SplitString(FLAGS_base_urls, ',', &base_urls);
282  if (FLAGS_generate_dash_if_iop_compliant_mpd) {
283  mpd_notifier.reset(new DashIopMpdNotifier(profile, mpd_options, base_urls,
284  FLAGS_mpd_output));
285  } else {
286  mpd_notifier.reset(new SimpleMpdNotifier(profile, mpd_options, base_urls,
287  FLAGS_mpd_output));
288  }
289  if (!mpd_notifier->Init()) {
290  LOG(ERROR) << "MpdNotifier failed to initialize.";
291  return false;
292  }
293  }
294 
295  std::vector<RemuxJob*> remux_jobs;
296  STLElementDeleter<std::vector<RemuxJob*> > scoped_jobs_deleter(&remux_jobs);
297  FakeClock fake_clock;
298  if (!CreateRemuxJobs(stream_descriptors, muxer_options, &fake_clock,
299  encryption_key_source.get(), mpd_notifier.get(),
300  &remux_jobs)) {
301  return false;
302  }
303 
304  Status status = RunRemuxJobs(remux_jobs);
305  if (!status.ok()) {
306  LOG(ERROR) << "Packaging Error: " << status.ToString();
307  return false;
308  }
309 
310  printf("Packaging completed successfully.\n");
311  return true;
312 }
313 
314 int PackagerMain(int argc, char** argv) {
315  // Needed to enable VLOG/DVLOG through --vmodule or --v.
316  base::CommandLine::Init(argc, argv);
317  CHECK(logging::InitLogging(logging::LoggingSettings()));
318 
319  google::SetUsageMessage(base::StringPrintf(kUsage, argv[0]));
320  google::ParseCommandLineFlags(&argc, &argv, true);
321  if (argc < 2) {
322  google::ShowUsageWithFlags(argv[0]);
323  return kNoArgument;
324  }
325 
327  return kArgumentValidationFailed;
328 
329  edash_packager::media::LibcryptoThreading libcrypto_threading;
330  // TODO(tinskip): Make InsertStreamDescriptor a member of
331  // StreamDescriptorList.
332  StreamDescriptorList stream_descriptors;
333  for (int i = 1; i < argc; ++i) {
334  if (!InsertStreamDescriptor(argv[i], &stream_descriptors))
335  return kArgumentValidationFailed;
336  }
337  return RunPackager(stream_descriptors) ? kSuccess : kPackagingFailed;
338 }
339 
340 } // namespace media
341 } // namespace edash_packager
342 
343 int main(int argc, char** argv) {
344  return edash_packager::media::PackagerMain(argc, argv);
345 }
Convenience class which initializes and terminates libcrypto threading.