Shaka Packager SDK
packager.cc
1 // Copyright 2017 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 "packager/packager.h"
8 
9 #include <algorithm>
10 
11 #include "packager/app/job_manager.h"
12 #include "packager/app/libcrypto_threading.h"
13 #include "packager/app/muxer_factory.h"
14 #include "packager/app/packager_util.h"
15 #include "packager/app/stream_descriptor.h"
16 #include "packager/base/at_exit.h"
17 #include "packager/base/files/file_path.h"
18 #include "packager/base/logging.h"
19 #include "packager/base/optional.h"
20 #include "packager/base/path_service.h"
21 #include "packager/base/strings/string_util.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/file/file.h"
26 #include "packager/hls/base/hls_notifier.h"
27 #include "packager/hls/base/simple_hls_notifier.h"
28 #include "packager/media/ad_cue_generator/ad_cue_generator.h"
29 #include "packager/media/base/container_names.h"
30 #include "packager/media/base/fourccs.h"
31 #include "packager/media/base/key_source.h"
32 #include "packager/media/base/language_utils.h"
33 #include "packager/media/base/muxer.h"
34 #include "packager/media/base/muxer_options.h"
35 #include "packager/media/base/muxer_util.h"
36 #include "packager/media/chunking/chunking_handler.h"
37 #include "packager/media/chunking/cue_alignment_handler.h"
38 #include "packager/media/chunking/text_chunker.h"
39 #include "packager/media/crypto/encryption_handler.h"
40 #include "packager/media/demuxer/demuxer.h"
41 #include "packager/media/event/muxer_listener_factory.h"
42 #include "packager/media/event/vod_media_info_dump_muxer_listener.h"
43 #include "packager/media/formats/webvtt/text_padder.h"
44 #include "packager/media/formats/webvtt/text_readers.h"
45 #include "packager/media/formats/webvtt/webvtt_parser.h"
46 #include "packager/media/formats/webvtt/webvtt_text_output_handler.h"
47 #include "packager/media/formats/webvtt/webvtt_to_mp4_handler.h"
48 #include "packager/media/replicator/replicator.h"
49 #include "packager/media/trick_play/trick_play_handler.h"
50 #include "packager/mpd/base/media_info.pb.h"
51 #include "packager/mpd/base/mpd_builder.h"
52 #include "packager/mpd/base/simple_mpd_notifier.h"
53 #include "packager/status_macros.h"
54 #include "packager/version/version.h"
55 
56 namespace shaka {
57 
58 // TODO(kqyang): Clean up namespaces.
59 using media::Demuxer;
60 using media::JobManager;
61 using media::KeySource;
62 using media::MuxerOptions;
63 using media::SyncPointQueue;
64 
65 namespace media {
66 namespace {
67 
68 const char kMediaInfoSuffix[] = ".media_info";
69 
70 Status ChainHandlers(
71  std::initializer_list<std::shared_ptr<MediaHandler>> list) {
72  std::shared_ptr<MediaHandler> previous;
73 
74  for (auto& next : list) {
75  // Skip null entries.
76  if (!next) {
77  continue;
78  }
79 
80  if (previous) {
81  RETURN_IF_ERROR(previous->AddHandler(next));
82  }
83 
84  previous = std::move(next);
85  }
86 
87  return Status::OK;
88 }
89 
90 MuxerOptions CreateMuxerOptions(const StreamDescriptor& stream,
91  const PackagingParams& params) {
92  MuxerOptions options;
93 
94  options.mp4_params = params.mp4_output_params;
95  options.temp_dir = params.temp_dir;
96  options.bandwidth = stream.bandwidth;
97  options.output_file_name = stream.output;
98  options.segment_template = stream.segment_template;
99 
100  return options;
101 }
102 
103 MuxerListenerFactory::StreamData ToMuxerListenerData(
104  const StreamDescriptor& stream) {
105  MuxerListenerFactory::StreamData data;
106  data.media_info_output = stream.output;
107  data.hls_group_id = stream.hls_group_id;
108  data.hls_name = stream.hls_name;
109  data.hls_playlist_name = stream.hls_playlist_name;
110  data.hls_iframe_playlist_name = stream.hls_iframe_playlist_name;
111  return data;
112 };
113 
114 // TODO(rkuroiwa): Write TTML and WebVTT parser (demuxing) for a better check
115 // and for supporting live/segmenting (muxing). With a demuxer and a muxer,
116 // CreateAllJobs() shouldn't treat text as a special case.
117 bool DetermineTextFileCodec(const std::string& file, std::string* out) {
118  CHECK(out);
119 
120  std::string content;
121  if (!File::ReadFileToString(file.c_str(), &content)) {
122  LOG(ERROR) << "Failed to open file " << file
123  << " to determine file format.";
124  return false;
125  }
126 
127  const uint8_t* content_data =
128  reinterpret_cast<const uint8_t*>(content.data());
129  MediaContainerName container_name =
130  DetermineContainer(content_data, content.size());
131 
132  if (container_name == CONTAINER_WEBVTT) {
133  *out = "wvtt";
134  return true;
135  }
136 
137  if (container_name == CONTAINER_TTML) {
138  *out = "ttml";
139  return true;
140  }
141 
142  return false;
143 }
144 
145 MediaContainerName GetOutputFormat(const StreamDescriptor& descriptor) {
146  if (!descriptor.output_format.empty()) {
147  MediaContainerName format =
148  DetermineContainerFromFormatName(descriptor.output_format);
149  if (format == CONTAINER_UNKNOWN) {
150  LOG(ERROR) << "Unable to determine output format from '"
151  << descriptor.output_format << "'.";
152  }
153  return format;
154  }
155 
156  base::Optional<MediaContainerName> format_from_output;
157  base::Optional<MediaContainerName> format_from_segment;
158  if (!descriptor.output.empty()) {
159  format_from_output = DetermineContainerFromFileName(descriptor.output);
160  if (format_from_output.value() == CONTAINER_UNKNOWN) {
161  LOG(ERROR) << "Unable to determine output format from '"
162  << descriptor.output << "'.";
163  }
164  }
165  if (!descriptor.segment_template.empty()) {
166  format_from_segment =
167  DetermineContainerFromFileName(descriptor.segment_template);
168  if (format_from_segment.value() == CONTAINER_UNKNOWN) {
169  LOG(ERROR) << "Unable to determine output format from '"
170  << descriptor.segment_template << "'.";
171  }
172  }
173 
174  if (format_from_output && format_from_segment) {
175  if (format_from_output.value() != format_from_segment.value()) {
176  LOG(ERROR) << "Output format determined from '" << descriptor.output
177  << "' differs from output format determined from '"
178  << descriptor.segment_template << "'.";
179  return CONTAINER_UNKNOWN;
180  }
181  }
182 
183  if (format_from_output)
184  return format_from_output.value();
185  if (format_from_segment)
186  return format_from_segment.value();
187  return CONTAINER_UNKNOWN;
188 }
189 
190 Status ValidateStreamDescriptor(bool dump_stream_info,
191  const StreamDescriptor& stream) {
192  if (stream.input.empty()) {
193  return Status(error::INVALID_ARGUMENT, "Stream input not specified.");
194  }
195 
196  // The only time a stream can have no outputs, is when dump stream info is
197  // set.
198  if (dump_stream_info && stream.output.empty() &&
199  stream.segment_template.empty()) {
200  return Status::OK;
201  }
202 
203  if (stream.output.empty() && stream.segment_template.empty()) {
204  return Status(error::INVALID_ARGUMENT,
205  "Streams must specify 'output' or 'segment template'.");
206  }
207 
208  // Whenever there is output, a stream must be selected.
209  if (stream.stream_selector.empty()) {
210  return Status(error::INVALID_ARGUMENT,
211  "Stream stream_selector not specified.");
212  }
213 
214  // If a segment template is provided, it must be valid.
215  if (stream.segment_template.length()) {
216  RETURN_IF_ERROR(ValidateSegmentTemplate(stream.segment_template));
217  }
218 
219  if (stream.output.find('$') != std::string::npos) {
220  // "$" is only allowed if the output file name is a template, which is
221  // used to support one file per Representation per Period when there are
222  // Ad Cues.
223  RETURN_IF_ERROR(ValidateSegmentTemplate(stream.output));
224  }
225 
226  // There are some specifics that must be checked based on which format
227  // we are writing to.
228  const MediaContainerName output_format = GetOutputFormat(stream);
229 
230  if (output_format == CONTAINER_UNKNOWN) {
231  return Status(error::INVALID_ARGUMENT, "Unsupported output format.");
232  } else if (output_format == MediaContainerName::CONTAINER_MPEG2TS) {
233  if (stream.segment_template.empty()) {
234  return Status(
235  error::INVALID_ARGUMENT,
236  "Please specify 'segment_template'. Single file TS output is "
237  "not supported.");
238  }
239 
240  // Right now the init segment is saved in |output| for multi-segment
241  // content. However, for TS all segments must be self-initializing so
242  // there cannot be an init segment.
243  if (stream.output.length()) {
244  return Status(error::INVALID_ARGUMENT,
245  "All TS segments must be self-initializing. Stream "
246  "descriptors 'output' or 'init_segment' are not allowed.");
247  }
248  } else if (output_format == CONTAINER_WEBVTT ||
249  output_format == CONTAINER_AAC || output_format == CONTAINER_AC3 ||
250  output_format == CONTAINER_EAC3) {
251  // There is no need for an init segment when outputting because there is no
252  // initialization data.
253  if (stream.segment_template.length() && stream.output.length()) {
254  return Status(
255  error::INVALID_ARGUMENT,
256  "Segmented WebVTT or PackedAudio output cannot have an init segment. "
257  "Do not specify stream descriptors 'output' or 'init_segment' when "
258  "using 'segment_template'.");
259  }
260  } else {
261  // For any other format, if there is a segment template, there must be an
262  // init segment provided.
263  if (stream.segment_template.length() && stream.output.empty()) {
264  return Status(error::INVALID_ARGUMENT,
265  "Please specify 'init_segment'. All non-TS multi-segment "
266  "content must provide an init segment.");
267  }
268  }
269 
270  return Status::OK;
271 }
272 
273 Status ValidateParams(const PackagingParams& packaging_params,
274  const std::vector<StreamDescriptor>& stream_descriptors) {
275  if (!packaging_params.chunking_params.segment_sap_aligned &&
276  packaging_params.chunking_params.subsegment_sap_aligned) {
277  return Status(error::INVALID_ARGUMENT,
278  "Setting segment_sap_aligned to false but "
279  "subsegment_sap_aligned to true is not allowed.");
280  }
281 
282  if (stream_descriptors.empty()) {
283  return Status(error::INVALID_ARGUMENT,
284  "Stream descriptors cannot be empty.");
285  }
286 
287  // On demand profile generates single file segment while live profile
288  // generates multiple segments specified using segment template.
289  const bool on_demand_dash_profile =
290  stream_descriptors.begin()->segment_template.empty();
291  for (const auto& descriptor : stream_descriptors) {
292  if (on_demand_dash_profile != descriptor.segment_template.empty()) {
293  return Status(error::INVALID_ARGUMENT,
294  "Inconsistent stream descriptor specification: "
295  "segment_template should be specified for none or all "
296  "stream descriptors.");
297  }
298 
299  RETURN_IF_ERROR(ValidateStreamDescriptor(
300  packaging_params.test_params.dump_stream_info, descriptor));
301 
302  if (base::StartsWith(descriptor.input, "udp://",
303  base::CompareCase::SENSITIVE)) {
304  const HlsParams& hls_params = packaging_params.hls_params;
305  if (!hls_params.master_playlist_output.empty() &&
306  hls_params.playlist_type == HlsPlaylistType::kVod) {
307  LOG(WARNING)
308  << "Seeing UDP input with HLS Playlist Type set to VOD. The "
309  "playlists will only be generated when UDP socket is closed. "
310  "If you want to do live packaging, --hls_playlist_type needs to "
311  "be set to LIVE.";
312  }
313  // Skip the check for DASH as DASH defaults to 'dynamic' MPD when segment
314  // template is provided.
315  }
316  }
317 
318  if (packaging_params.output_media_info && !on_demand_dash_profile) {
319  // TODO(rkuroiwa, kqyang): Support partial media info dump for live.
320  return Status(error::UNIMPLEMENTED,
321  "--output_media_info is only supported for on-demand profile "
322  "(not using segment_template).");
323  }
324 
325  return Status::OK;
326 }
327 
328 bool StreamDescriptorCompareFn(const StreamDescriptor& a,
329  const StreamDescriptor& b) {
330  if (a.input == b.input) {
331  if (a.stream_selector == b.stream_selector) {
332  // The MPD notifier requires that the main track comes first, so make
333  // sure that happens.
334  if (a.trick_play_factor == 0 || b.trick_play_factor == 0) {
335  return a.trick_play_factor == 0;
336  } else {
337  return a.trick_play_factor > b.trick_play_factor;
338  }
339  } else {
340  return a.stream_selector < b.stream_selector;
341  }
342  }
343 
344  return a.input < b.input;
345 }
346 
347 // A fake clock that always return time 0 (epoch). Should only be used for
348 // testing.
349 class FakeClock : public base::Clock {
350  public:
351  base::Time Now() override { return base::Time(); }
352 };
353 
354 bool StreamInfoToTextMediaInfo(const StreamDescriptor& stream_descriptor,
355  MediaInfo* text_media_info) {
356  std::string codec;
357  if (!DetermineTextFileCodec(stream_descriptor.input, &codec)) {
358  LOG(ERROR) << "Failed to determine the text file format for "
359  << stream_descriptor.input;
360  return false;
361  }
362 
363  MediaInfo::TextInfo* text_info = text_media_info->mutable_text_info();
364  text_info->set_codec(codec);
365 
366  const std::string& language = stream_descriptor.language;
367  if (!language.empty()) {
368  text_info->set_language(language);
369  }
370 
371  text_media_info->set_media_file_name(stream_descriptor.output);
372  text_media_info->set_container_type(MediaInfo::CONTAINER_TEXT);
373 
374  if (stream_descriptor.bandwidth != 0) {
375  text_media_info->set_bandwidth(stream_descriptor.bandwidth);
376  } else {
377  // Text files are usually small and since the input is one file; there's no
378  // way for the player to do ranged requests. So set this value to something
379  // reasonable.
380  const int kDefaultTextBandwidth = 256;
381  text_media_info->set_bandwidth(kDefaultTextBandwidth);
382  }
383 
384  return true;
385 }
386 
390 Status CreateDemuxer(const StreamDescriptor& stream,
391  const PackagingParams& packaging_params,
392  std::shared_ptr<Demuxer>* new_demuxer) {
393  std::shared_ptr<Demuxer> demuxer = std::make_shared<Demuxer>(stream.input);
394  demuxer->set_dump_stream_info(packaging_params.test_params.dump_stream_info);
395 
396  if (packaging_params.decryption_params.key_provider != KeyProvider::kNone) {
397  std::unique_ptr<KeySource> decryption_key_source(
398  CreateDecryptionKeySource(packaging_params.decryption_params));
399  if (!decryption_key_source) {
400  return Status(
401  error::INVALID_ARGUMENT,
402  "Must define decryption key source when defining key provider");
403  }
404  demuxer->SetKeySource(std::move(decryption_key_source));
405  }
406 
407  *new_demuxer = std::move(demuxer);
408  return Status::OK;
409 }
410 
411 std::shared_ptr<MediaHandler> CreateEncryptionHandler(
412  const PackagingParams& packaging_params,
413  const StreamDescriptor& stream,
414  KeySource* key_source) {
415  if (stream.skip_encryption) {
416  return nullptr;
417  }
418 
419  if (!key_source) {
420  return nullptr;
421  }
422 
423  // Make a copy so that we can modify it for this specific stream.
424  EncryptionParams encryption_params = packaging_params.encryption_params;
425 
426  // Use Sample AES in MPEG2TS.
427  // TODO(kqyang): Consider adding a new flag to enable Sample AES as we
428  // will support CENC in TS in the future.
429  if (GetOutputFormat(stream) == CONTAINER_MPEG2TS ||
430  GetOutputFormat(stream) == CONTAINER_AAC ||
431  GetOutputFormat(stream) == CONTAINER_AC3 ||
432  GetOutputFormat(stream) == CONTAINER_EAC3) {
433  VLOG(1) << "Use Apple Sample AES encryption for MPEG2TS or Packed Audio.";
434  encryption_params.protection_scheme = kAppleSampleAesProtectionScheme;
435  }
436 
437  if (!stream.drm_label.empty()) {
438  const std::string& drm_label = stream.drm_label;
439  encryption_params.stream_label_func =
440  [drm_label](const EncryptionParams::EncryptedStreamAttributes&) {
441  return drm_label;
442  };
443  } else if (!encryption_params.stream_label_func) {
444  const int kDefaultMaxSdPixels = 768 * 576;
445  const int kDefaultMaxHdPixels = 1920 * 1080;
446  const int kDefaultMaxUhd1Pixels = 4096 * 2160;
447  encryption_params.stream_label_func = std::bind(
448  &Packager::DefaultStreamLabelFunction, kDefaultMaxSdPixels,
449  kDefaultMaxHdPixels, kDefaultMaxUhd1Pixels, std::placeholders::_1);
450  }
451 
452  return std::make_shared<EncryptionHandler>(encryption_params, key_source);
453 }
454 
455 std::unique_ptr<TextChunker> CreateTextChunker(
456  const ChunkingParams& chunking_params) {
457  const float segment_length_in_seconds =
458  chunking_params.segment_duration_in_seconds;
459  const uint64_t segment_length_in_ms =
460  static_cast<uint64_t>(segment_length_in_seconds * 1000);
461 
462  return std::unique_ptr<TextChunker>(new TextChunker(segment_length_in_ms));
463 }
464 
465 Status CreateHlsTextJob(const StreamDescriptor& stream,
466  const PackagingParams& packaging_params,
467  std::unique_ptr<MuxerListener> muxer_listener,
468  SyncPointQueue* sync_points,
469  JobManager* job_manager) {
470  DCHECK(muxer_listener);
471  DCHECK(job_manager);
472 
473  if (stream.segment_template.empty()) {
474  return Status(error::INVALID_ARGUMENT,
475  "Cannot output text (" + stream.input +
476  ") to HLS with no segment template");
477  }
478 
479  // Text files are usually small and since the input is one file;
480  // there's no way for the player to do ranged requests. So set this
481  // value to something reasonable if it is missing.
482  MuxerOptions muxer_options = CreateMuxerOptions(stream, packaging_params);
483  muxer_options.bandwidth = stream.bandwidth ? stream.bandwidth : 256;
484 
485  auto output = std::make_shared<WebVttTextOutputHandler>(
486  muxer_options, std::move(muxer_listener));
487 
488  std::unique_ptr<FileReader> reader;
489  RETURN_IF_ERROR(FileReader::Open(stream.input, &reader));
490 
491  const int64_t kNoDuration = 0;
492  auto parser =
493  std::make_shared<WebVttParser>(std::move(reader), stream.language);
494  auto padder = std::make_shared<TextPadder>(kNoDuration);
495  auto cue_aligner = sync_points
496  ? std::make_shared<CueAlignmentHandler>(sync_points)
497  : nullptr;
498  auto chunker = CreateTextChunker(packaging_params.chunking_params);
499 
500  job_manager->Add("Segmented Text Job", parser);
501 
502  return ChainHandlers({std::move(parser), std::move(padder),
503  std::move(cue_aligner), std::move(chunker),
504  std::move(output)});
505 }
506 
507 Status CreateWebVttToMp4TextJob(const StreamDescriptor& stream,
508  const PackagingParams& packaging_params,
509  std::unique_ptr<MuxerListener> muxer_listener,
510  SyncPointQueue* sync_points,
511  MuxerFactory* muxer_factory,
512  std::shared_ptr<OriginHandler>* root) {
513  std::unique_ptr<FileReader> reader;
514  RETURN_IF_ERROR(FileReader::Open(stream.input, &reader));
515 
516  const int64_t kNoDuration = 0;
517  auto parser =
518  std::make_shared<WebVttParser>(std::move(reader), stream.language);
519  auto padder = std::make_shared<TextPadder>(kNoDuration);
520 
521  auto text_to_mp4 = std::make_shared<WebVttToMp4Handler>();
522  auto muxer = muxer_factory->CreateMuxer(GetOutputFormat(stream), stream);
523  muxer->SetMuxerListener(std::move(muxer_listener));
524 
525  // Optional Cue Alignment Handler
526  std::shared_ptr<MediaHandler> cue_aligner;
527  if (sync_points) {
528  cue_aligner = std::make_shared<CueAlignmentHandler>(sync_points);
529  }
530 
531  std::shared_ptr<MediaHandler> chunker =
532  CreateTextChunker(packaging_params.chunking_params);
533 
534  *root = parser;
535 
536  return ChainHandlers({std::move(parser), std::move(padder),
537  std::move(cue_aligner), std::move(chunker),
538  std::move(text_to_mp4), std::move(muxer)});
539 }
540 
541 Status CreateTextJobs(
542  const std::vector<std::reference_wrapper<const StreamDescriptor>>& streams,
543  const PackagingParams& packaging_params,
544  SyncPointQueue* sync_points,
545  MuxerListenerFactory* muxer_listener_factory,
546  MuxerFactory* muxer_factory,
547  MpdNotifier* mpd_notifier,
548  JobManager* job_manager) {
549  DCHECK(muxer_listener_factory);
550  DCHECK(job_manager);
551  for (const StreamDescriptor& stream : streams) {
552  // There are currently four options:
553  // TEXT WEBVTT --> TEXT WEBVTT [ supported ]
554  // TEXT WEBVTT --> MP4 WEBVTT [ supported ]
555  // MP4 WEBVTT --> MP4 WEBVTT [ unsupported ]
556  // MP4 WEBVTT --> TEXT WEBVTT [ unsupported ]
557  const auto input_container = DetermineContainerFromFileName(stream.input);
558  const auto output_container = GetOutputFormat(stream);
559 
560  if (input_container != CONTAINER_WEBVTT) {
561  return Status(error::INVALID_ARGUMENT,
562  "Text output format is not support for " + stream.input);
563  }
564 
565  if (output_container == CONTAINER_MOV) {
566  std::unique_ptr<MuxerListener> muxer_listener =
567  muxer_listener_factory->CreateListener(ToMuxerListenerData(stream));
568 
569  std::shared_ptr<OriginHandler> root;
570  RETURN_IF_ERROR(CreateWebVttToMp4TextJob(
571  stream, packaging_params, std::move(muxer_listener), sync_points,
572  muxer_factory, &root));
573 
574  job_manager->Add("MP4 text job", std::move(root));
575  } else {
576  std::unique_ptr<MuxerListener> hls_listener =
577  muxer_listener_factory->CreateHlsListener(
578  ToMuxerListenerData(stream));
579 
580  // Check input to ensure that output is possible.
581  if (hls_listener) {
582  if (stream.segment_template.empty() || !stream.output.empty()) {
583  return Status(error::INVALID_ARGUMENT,
584  "segment_template needs to be specified for HLS text "
585  "output. Single file output is not supported yet.");
586  }
587  }
588 
589  if (mpd_notifier && !stream.segment_template.empty()) {
590  return Status(error::INVALID_ARGUMENT,
591  "Cannot create text output for MPD with segment output.");
592  }
593 
594  // If we are outputting to HLS, then create the HLS test pipeline that
595  // will create segmented text output.
596  if (hls_listener) {
597  RETURN_IF_ERROR(CreateHlsTextJob(stream, packaging_params,
598  std::move(hls_listener), sync_points,
599  job_manager));
600  }
601 
602  if (!stream.output.empty()) {
603  if (!File::Copy(stream.input.c_str(), stream.output.c_str())) {
604  std::string error;
605  base::StringAppendF(
606  &error, "Failed to copy the input file (%s) to output file (%s).",
607  stream.input.c_str(), stream.output.c_str());
608  return Status(error::FILE_FAILURE, error);
609  }
610 
611  MediaInfo text_media_info;
612  if (!StreamInfoToTextMediaInfo(stream, &text_media_info)) {
613  return Status(error::INVALID_ARGUMENT,
614  "Could not create media info for stream.");
615  }
616 
617  // If we are outputting to MPD, just add the input to the outputted
618  // manifest.
619  if (mpd_notifier) {
620  uint32_t unused;
621  if (mpd_notifier->NotifyNewContainer(text_media_info, &unused)) {
622  mpd_notifier->Flush();
623  } else {
624  return Status(error::PARSER_FAILURE,
625  "Failed to process text file " + stream.input);
626  }
627  }
628 
629  if (packaging_params.output_media_info) {
631  text_media_info, stream.output + kMediaInfoSuffix);
632  }
633  }
634  }
635  }
636 
637  return Status::OK;
638 }
639 
640 Status CreateAudioVideoJobs(
641  const std::vector<std::reference_wrapper<const StreamDescriptor>>& streams,
642  const PackagingParams& packaging_params,
643  KeySource* encryption_key_source,
644  SyncPointQueue* sync_points,
645  MuxerListenerFactory* muxer_listener_factory,
646  MuxerFactory* muxer_factory,
647  JobManager* job_manager) {
648  DCHECK(muxer_listener_factory);
649  DCHECK(muxer_factory);
650  DCHECK(job_manager);
651  // Store all the demuxers in a map so that we can look up a stream's demuxer.
652  // This is step one in making this part of the pipeline less dependant on
653  // order.
654  std::map<std::string, std::shared_ptr<Demuxer>> sources;
655  std::map<std::string, std::shared_ptr<MediaHandler>> cue_aligners;
656 
657  for (const StreamDescriptor& stream : streams) {
658  bool seen_input_before = sources.find(stream.input) != sources.end();
659  if (seen_input_before) {
660  continue;
661  }
662 
663  RETURN_IF_ERROR(
664  CreateDemuxer(stream, packaging_params, &sources[stream.input]));
665  cue_aligners[stream.input] =
666  sync_points ? std::make_shared<CueAlignmentHandler>(sync_points)
667  : nullptr;
668  }
669 
670  for (auto& source : sources) {
671  job_manager->Add("RemuxJob", source.second);
672  }
673 
674  // Replicators are shared among all streams with the same input and stream
675  // selector.
676  std::shared_ptr<MediaHandler> replicator;
677 
678  std::string previous_input;
679  std::string previous_selector;
680 
681  for (const StreamDescriptor& stream : streams) {
682  // Get the demuxer for this stream.
683  auto& demuxer = sources[stream.input];
684  auto& cue_aligner = cue_aligners[stream.input];
685 
686  const bool new_input_file = stream.input != previous_input;
687  const bool new_stream =
688  new_input_file || previous_selector != stream.stream_selector;
689  previous_input = stream.input;
690  previous_selector = stream.stream_selector;
691 
692  // If the stream has no output, then there is no reason setting-up the rest
693  // of the pipeline.
694  if (stream.output.empty() && stream.segment_template.empty()) {
695  continue;
696  }
697 
698  // Just because it is a different stream descriptor does not mean it is a
699  // new stream. Multiple stream descriptors may have the same stream but
700  // only differ by trick play factor.
701  if (new_stream) {
702  if (!stream.language.empty()) {
703  demuxer->SetLanguageOverride(stream.stream_selector, stream.language);
704  }
705 
706  replicator = std::make_shared<Replicator>();
707  auto chunker =
708  std::make_shared<ChunkingHandler>(packaging_params.chunking_params);
709  auto encryptor = CreateEncryptionHandler(packaging_params, stream,
710  encryption_key_source);
711 
712  // TODO(vaage) : Create a nicer way to connect handlers to demuxers.
713  if (sync_points) {
714  RETURN_IF_ERROR(
715  ChainHandlers({cue_aligner, chunker, encryptor, replicator}));
716  RETURN_IF_ERROR(
717  demuxer->SetHandler(stream.stream_selector, cue_aligner));
718  } else {
719  RETURN_IF_ERROR(ChainHandlers({chunker, encryptor, replicator}));
720  RETURN_IF_ERROR(demuxer->SetHandler(stream.stream_selector, chunker));
721  }
722  }
723 
724  // Create the muxer (output) for this track.
725  std::shared_ptr<Muxer> muxer =
726  muxer_factory->CreateMuxer(GetOutputFormat(stream), stream);
727  if (!muxer) {
728  return Status(error::INVALID_ARGUMENT, "Failed to create muxer for " +
729  stream.input + ":" +
730  stream.stream_selector);
731  }
732 
733  std::unique_ptr<MuxerListener> muxer_listener =
734  muxer_listener_factory->CreateListener(ToMuxerListenerData(stream));
735  muxer->SetMuxerListener(std::move(muxer_listener));
736 
737  // Trick play is optional.
738  std::shared_ptr<MediaHandler> trick_play =
739  stream.trick_play_factor
740  ? std::make_shared<TrickPlayHandler>(stream.trick_play_factor)
741  : nullptr;
742 
743  RETURN_IF_ERROR(ChainHandlers({replicator, trick_play, muxer}));
744  }
745 
746  return Status::OK;
747 }
748 
749 Status CreateAllJobs(const std::vector<StreamDescriptor>& stream_descriptors,
750  const PackagingParams& packaging_params,
751  MpdNotifier* mpd_notifier,
752  KeySource* encryption_key_source,
753  SyncPointQueue* sync_points,
754  MuxerListenerFactory* muxer_listener_factory,
755  MuxerFactory* muxer_factory,
756  JobManager* job_manager) {
757  DCHECK(muxer_factory);
758  DCHECK(muxer_listener_factory);
759  DCHECK(job_manager);
760 
761  // Group all streams based on which pipeline they will use.
762  std::vector<std::reference_wrapper<const StreamDescriptor>> text_streams;
763  std::vector<std::reference_wrapper<const StreamDescriptor>>
764  audio_video_streams;
765 
766  for (const StreamDescriptor& stream : stream_descriptors) {
767  // TODO: Find a better way to determine what stream type a stream
768  // descriptor is as |stream_selector| may use an index. This would
769  // also allow us to use a simpler audio pipeline.
770  if (stream.stream_selector == "text") {
771  text_streams.push_back(stream);
772  } else {
773  audio_video_streams.push_back(stream);
774  }
775  }
776 
777  // Audio/Video streams need to be in sorted order so that demuxers and trick
778  // play handlers get setup correctly.
779  std::sort(audio_video_streams.begin(), audio_video_streams.end(),
780  media::StreamDescriptorCompareFn);
781 
782  RETURN_IF_ERROR(CreateTextJobs(text_streams, packaging_params, sync_points,
783  muxer_listener_factory, muxer_factory,
784  mpd_notifier, job_manager));
785  RETURN_IF_ERROR(CreateAudioVideoJobs(
786  audio_video_streams, packaging_params, encryption_key_source, sync_points,
787  muxer_listener_factory, muxer_factory, job_manager));
788 
789  // Initialize processing graph.
790  return job_manager->InitializeJobs();
791 }
792 
793 } // namespace
794 } // namespace media
795 
796 struct Packager::PackagerInternal {
797  media::FakeClock fake_clock;
798  std::unique_ptr<KeySource> encryption_key_source;
799  std::unique_ptr<MpdNotifier> mpd_notifier;
800  std::unique_ptr<hls::HlsNotifier> hls_notifier;
801  BufferCallbackParams buffer_callback_params;
802  std::unique_ptr<media::JobManager> job_manager;
803 };
804 
805 Packager::Packager() {}
806 
807 Packager::~Packager() {}
808 
810  const PackagingParams& packaging_params,
811  const std::vector<StreamDescriptor>& stream_descriptors) {
812  // Needed by base::WorkedPool used in ThreadedIoFile.
813  static base::AtExitManager exit;
814  static media::LibcryptoThreading libcrypto_threading;
815 
816  if (internal_)
817  return Status(error::INVALID_ARGUMENT, "Already initialized.");
818 
819  RETURN_IF_ERROR(media::ValidateParams(packaging_params, stream_descriptors));
820 
821  if (!packaging_params.test_params.injected_library_version.empty()) {
822  SetPackagerVersionForTesting(
823  packaging_params.test_params.injected_library_version);
824  }
825 
826  std::unique_ptr<PackagerInternal> internal(new PackagerInternal);
827 
828  // Create encryption key source if needed.
829  if (packaging_params.encryption_params.key_provider != KeyProvider::kNone) {
830  internal->encryption_key_source = CreateEncryptionKeySource(
831  static_cast<media::FourCC>(
832  packaging_params.encryption_params.protection_scheme),
833  packaging_params.encryption_params);
834  if (!internal->encryption_key_source)
835  return Status(error::INVALID_ARGUMENT, "Failed to create key source.");
836  }
837 
838  // Store callback params to make it available during packaging.
839  internal->buffer_callback_params = packaging_params.buffer_callback_params;
840 
841  // Update MPD output and HLS output if callback param is specified.
842  MpdParams mpd_params = packaging_params.mpd_params;
843  HlsParams hls_params = packaging_params.hls_params;
844  if (internal->buffer_callback_params.write_func) {
846  internal->buffer_callback_params, mpd_params.mpd_output);
848  internal->buffer_callback_params, hls_params.master_playlist_output);
849  }
850  // Both DASH and HLS require language to follow RFC5646
851  // (https://tools.ietf.org/html/rfc5646), which requires the language to be
852  // in the shortest form.
853  mpd_params.default_language =
855  hls_params.default_language =
857 
858  if (!mpd_params.mpd_output.empty()) {
859  const bool on_demand_dash_profile =
860  stream_descriptors.begin()->segment_template.empty();
861  const double target_segment_duration =
863  const MpdOptions mpd_options = media::GetMpdOptions(
864  on_demand_dash_profile, mpd_params, target_segment_duration);
865  internal->mpd_notifier.reset(new SimpleMpdNotifier(mpd_options));
866  if (!internal->mpd_notifier->Init()) {
867  LOG(ERROR) << "MpdNotifier failed to initialize.";
868  return Status(error::INVALID_ARGUMENT,
869  "Failed to initialize MpdNotifier.");
870  }
871  }
872 
873  if (!hls_params.master_playlist_output.empty()) {
874  internal->hls_notifier.reset(new hls::SimpleHlsNotifier(hls_params));
875  }
876 
877  std::unique_ptr<SyncPointQueue> sync_points;
878  if (!packaging_params.ad_cue_generator_params.cue_points.empty()) {
879  sync_points.reset(
880  new SyncPointQueue(packaging_params.ad_cue_generator_params));
881  }
882  internal->job_manager.reset(new JobManager(std::move(sync_points)));
883 
884  std::vector<StreamDescriptor> streams_for_jobs;
885 
886  for (const StreamDescriptor& descriptor : stream_descriptors) {
887  // We may need to overwrite some values, so make a copy first.
888  StreamDescriptor copy = descriptor;
889 
890  if (internal->buffer_callback_params.read_func) {
891  copy.input = File::MakeCallbackFileName(internal->buffer_callback_params,
892  descriptor.input);
893  }
894 
895  if (internal->buffer_callback_params.write_func) {
896  copy.output = File::MakeCallbackFileName(internal->buffer_callback_params,
897  descriptor.output);
899  internal->buffer_callback_params, descriptor.segment_template);
900  }
901 
902  // Update language to ISO_639_2 code if set.
903  if (!copy.language.empty()) {
904  copy.language = LanguageToISO_639_2(descriptor.language);
905  if (copy.language == "und") {
906  return Status(
907  error::INVALID_ARGUMENT,
908  "Unknown/invalid language specified: " + descriptor.language);
909  }
910  }
911 
912  streams_for_jobs.push_back(copy);
913  }
914 
915  media::MuxerFactory muxer_factory(packaging_params);
916  if (packaging_params.test_params.inject_fake_clock) {
917  muxer_factory.OverrideClock(&internal->fake_clock);
918  }
919 
920  media::MuxerListenerFactory muxer_listener_factory(
921  packaging_params.output_media_info, internal->mpd_notifier.get(),
922  internal->hls_notifier.get());
923 
924  RETURN_IF_ERROR(media::CreateAllJobs(
925  streams_for_jobs, packaging_params, internal->mpd_notifier.get(),
926  internal->encryption_key_source.get(),
927  internal->job_manager->sync_points(), &muxer_listener_factory,
928  &muxer_factory, internal->job_manager.get()));
929 
930  internal_ = std::move(internal);
931  return Status::OK;
932 }
933 
935  if (!internal_)
936  return Status(error::INVALID_ARGUMENT, "Not yet initialized.");
937 
938  RETURN_IF_ERROR(internal_->job_manager->RunJobs());
939 
940  if (internal_->hls_notifier) {
941  if (!internal_->hls_notifier->Flush())
942  return Status(error::INVALID_ARGUMENT, "Failed to flush Hls.");
943  }
944  if (internal_->mpd_notifier) {
945  if (!internal_->mpd_notifier->Flush())
946  return Status(error::INVALID_ARGUMENT, "Failed to flush Mpd.");
947  }
948  return Status::OK;
949 }
950 
952  if (!internal_) {
953  LOG(INFO) << "Not yet initialized. Return directly.";
954  return;
955  }
956  internal_->job_manager->CancelJobs();
957 }
958 
960  return GetPackagerVersion();
961 }
962 
964  int max_sd_pixels,
965  int max_hd_pixels,
966  int max_uhd1_pixels,
967  const EncryptionParams::EncryptedStreamAttributes& stream_attributes) {
968  if (stream_attributes.stream_type ==
969  EncryptionParams::EncryptedStreamAttributes::kAudio)
970  return "AUDIO";
971  if (stream_attributes.stream_type ==
972  EncryptionParams::EncryptedStreamAttributes::kVideo) {
973  const int pixels = stream_attributes.oneof.video.width *
974  stream_attributes.oneof.video.height;
975  if (pixels <= max_sd_pixels)
976  return "SD";
977  if (pixels <= max_hd_pixels)
978  return "HD";
979  if (pixels <= max_uhd1_pixels)
980  return "UHD1";
981  return "UHD2";
982  }
983  return "";
984 }
985 
986 } // namespace shaka
BufferCallbackParams buffer_callback_params
Buffer callback params.
Definition: packager.h:62
std::string master_playlist_output
HLS master playlist output path.
Definition: hls_params.h:27
DASH MPD related parameters.
Definition: mpd_params.h:16
Defines a single input/output stream.
Definition: packager.h:69
std::string input
Input/source media file path or network stream URL. Required.
Definition: packager.h:71
HlsParams hls_params
HLS related parameters.
Definition: packager.h:55
Status Initialize(const PackagingParams &packaging_params, const std::vector< StreamDescriptor > &stream_descriptors)
Definition: packager.cc:809
std::string default_language
Definition: mpd_params.h:56
static std::string DefaultStreamLabelFunction(int max_sd_pixels, int max_hd_pixels, int max_uhd1_pixels, const EncryptionParams::EncryptedStreamAttributes &stream_attributes)
Definition: packager.cc:963
ChunkingParams chunking_params
Chunking (segmentation) related parameters.
Definition: packager.h:44
std::vector< Cuepoint > cue_points
List of cuepoints.
HLS related parameters.
Definition: hls_params.h:23
std::string LanguageToShortestForm(const std::string &language)
std::string segment_template
Specifies segment template. Can be empty.
Definition: packager.h:81
static bool Copy(const char *from_file_name, const char *to_file_name)
Definition: file.cc:281
static bool ReadFileToString(const char *file_name, std::string *contents)
Definition: file.cc:216
bool inject_fake_clock
Definition: packager.h:31
Convenience class which initializes and terminates libcrypto threading.
All the methods that are virtual are virtual for mocking.
static std::string GetLibraryVersion()
Definition: packager.cc:959
std::string LanguageToISO_639_2(const std::string &language)
std::string injected_library_version
Definition: packager.h:34
MpdParams mpd_params
DASH MPD related parameters.
Definition: packager.h:53
AdCueGeneratorParams ad_cue_generator_params
Out of band cuepoint parameters.
Definition: packager.h:47
static bool WriteMediaInfoToFile(const MediaInfo &media_info, const std::string &output_file_path)
EncryptionParams encryption_params
Encryption and Decryption Parameters.
Definition: packager.h:58
std::string mpd_output
MPD output file path.
Definition: mpd_params.h:18
A synchronized queue for cue points.
Status Run()
Definition: packager.cc:934
static std::string MakeCallbackFileName(const BufferCallbackParams &callback_params, const std::string &name)
Definition: file.cc:354
std::string output
Definition: packager.h:79
Encrypted stream information that is used to determine stream label.
void OverrideClock(base::Clock *clock)
std::string default_language
Definition: hls_params.h:48
double segment_duration_in_seconds
Segment duration in seconds.
Defines Mpd Options.
Definition: mpd_options.h:25
void Cancel()
Cancel packaging. Note that it has to be called from another thread.
Definition: packager.cc:951
Packaging parameters.
Definition: packager.h:38
static Status Open(const std::string &filename, std::unique_ptr< FileReader > *out)
Definition: text_readers.cc:15
std::string language
Definition: packager.h:104