DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator
wvm_media_parser.cc
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "packager/media/formats/wvm/wvm_media_parser.h"
6 
7 #include <map>
8 #include <sstream>
9 #include <vector>
10 
11 #include "packager/base/strings/string_number_conversions.h"
12 #include "packager/media/base/aes_decryptor.h"
13 #include "packager/media/base/audio_stream_info.h"
14 #include "packager/media/base/key_source.h"
15 #include "packager/media/base/media_sample.h"
16 #include "packager/media/base/video_stream_info.h"
17 #include "packager/media/codecs/aac_audio_specific_config.h"
18 #include "packager/media/codecs/avc_decoder_configuration_record.h"
19 #include "packager/media/codecs/es_descriptor.h"
20 #include "packager/media/formats/mp2t/adts_header.h"
21 #include "packager/status.h"
22 
23 #define HAS_HEADER_EXTENSION(x) ((x != 0xBC) && (x != 0xBE) && (x != 0xBF) \
24  && (x != 0xF0) && (x != 0xF2) && (x != 0xF8) \
25  && (x != 0xFF))
26 
27 namespace {
28 const uint32_t kMpeg2ClockRate = 90000;
29 const uint32_t kPesOptPts = 0x80;
30 const uint32_t kPesOptDts = 0x40;
31 const uint32_t kPesOptAlign = 0x04;
32 const uint32_t kPsmStreamId = 0xBC;
33 const uint32_t kPaddingStreamId = 0xBE;
34 const uint32_t kIndexMagic = 0x49444d69;
35 const uint32_t kIndexStreamId = 0xBF; // private_stream_2
36 const uint32_t kIndexVersion4HeaderSize = 12;
37 const uint32_t kEcmStreamId = 0xF0;
38 const uint32_t kV2MetadataStreamId = 0xF1; // EMM_stream
39 const uint32_t kScramblingBitsMask = 0x30;
40 const uint32_t kStartCode1 = 0x00;
41 const uint32_t kStartCode2 = 0x00;
42 const uint32_t kStartCode3 = 0x01;
43 const uint32_t kStartCode4Pack = 0xBA;
44 const uint32_t kStartCode4System = 0xBB;
45 const uint32_t kStartCode4ProgramEnd = 0xB9;
46 const uint32_t kPesStreamIdVideoMask = 0xF0;
47 const uint32_t kPesStreamIdVideo = 0xE0;
48 const uint32_t kPesStreamIdAudioMask = 0xE0;
49 const uint32_t kPesStreamIdAudio = 0xC0;
50 const uint32_t kVersion4 = 4;
51 const size_t kAdtsHeaderMinSize = 7;
52 const uint8_t kAacSampleSizeBits = 16;
53 // Applies to all video streams.
54 const uint8_t kNaluLengthSize = 4; // unit is bytes.
55 // Placeholder sampling frequency for all audio streams, which
56 // will be overwritten after filter parsing.
57 const uint32_t kDefaultSamplingFrequency = 100;
58 const uint16_t kEcmSizeBytes = 80;
59 const uint32_t kInitializationVectorSizeBytes = 16;
60 // ECM fields for processing.
61 const uint32_t kEcmContentKeySizeBytes = 16;
62 const uint32_t kEcmDCPFlagsSizeBytes = 3;
63 const uint32_t kEcmCCIFlagsSizeBytes = 1;
64 const uint32_t kEcmFlagsSizeBytes =
65  kEcmCCIFlagsSizeBytes + kEcmDCPFlagsSizeBytes;
66 const uint32_t kEcmPaddingSizeBytes = 12;
67 const uint32_t kAssetKeySizeBytes = 16;
68 // Default audio and video PES stream IDs.
69 const uint8_t kDefaultAudioStreamId = kPesStreamIdAudio;
70 const uint8_t kDefaultVideoStreamId = kPesStreamIdVideo;
71 
72 enum Type {
73  Type_void = 0,
74  Type_uint8 = 1,
75  Type_int8 = 2,
76  Type_uint16 = 3,
77  Type_int16 = 4,
78  Type_uint32 = 5,
79  Type_int32 = 6,
80  Type_uint64 = 7,
81  Type_int64 = 8,
82  Type_string = 9,
83  Type_BinaryData = 10
84 };
85 } // namespace
86 
87 namespace shaka {
88 namespace media {
89 namespace wvm {
90 
91 WvmMediaParser::WvmMediaParser()
92  : is_initialized_(false),
93  parse_state_(StartCode1),
94  skip_bytes_(0),
95  metadata_is_complete_(false),
96  current_program_id_(0),
97  pes_stream_id_(0),
98  prev_pes_stream_id_(0),
99  pes_packet_bytes_(0),
100  pes_flags_1_(0),
101  pes_flags_2_(0),
102  prev_pes_flags_1_(0),
103  pes_header_data_bytes_(0),
104  timestamp_(0),
105  pts_(0),
106  dts_(0),
107  index_program_id_(0),
108  media_sample_(NULL),
109  crypto_unit_start_pos_(0),
110  stream_id_count_(0),
111  decryption_key_source_(NULL) {}
112 
113 WvmMediaParser::~WvmMediaParser() {}
114 
115 void WvmMediaParser::Init(const InitCB& init_cb,
116  const NewSampleCB& new_sample_cb,
117  KeySource* decryption_key_source) {
118  DCHECK(!is_initialized_);
119  DCHECK(!init_cb.is_null());
120  DCHECK(!new_sample_cb.is_null());
121  decryption_key_source_ = decryption_key_source;
122  init_cb_ = init_cb;
123  new_sample_cb_ = new_sample_cb;
124 }
125 
126 bool WvmMediaParser::Parse(const uint8_t* buf, int size) {
127  size_t num_bytes = 0;
128  size_t prev_size = 0;
129  const uint8_t* read_ptr = buf;
130  const uint8_t* end = read_ptr + size;
131 
132  while (read_ptr < end) {
133  switch (parse_state_) {
134  case StartCode1:
135  if (*read_ptr == kStartCode1) {
136  parse_state_ = StartCode2;
137  }
138  break;
139  case StartCode2:
140  if (*read_ptr == kStartCode2) {
141  parse_state_ = StartCode3;
142  } else {
143  parse_state_ = StartCode1;
144  }
145  break;
146  case StartCode3:
147  if (*read_ptr == kStartCode3) {
148  parse_state_ = StartCode4;
149  } else {
150  parse_state_ = StartCode1;
151  }
152  break;
153  case StartCode4:
154  switch (*read_ptr) {
155  case kStartCode4Pack:
156  parse_state_ = PackHeader1;
157  break;
158  case kStartCode4System:
159  parse_state_ = SystemHeader1;
160  break;
161  case kStartCode4ProgramEnd:
162  parse_state_ = ProgramEnd;
163  continue;
164  default:
165  parse_state_ = PesStreamId;
166  continue;
167  }
168  break;
169  case PackHeader1:
170  parse_state_ = PackHeader2;
171  break;
172  case PackHeader2:
173  parse_state_ = PackHeader3;
174  break;
175  case PackHeader3:
176  parse_state_ = PackHeader4;
177  break;
178  case PackHeader4:
179  parse_state_ = PackHeader5;
180  break;
181  case PackHeader5:
182  parse_state_ = PackHeader6;
183  break;
184  case PackHeader6:
185  parse_state_ = PackHeader7;
186  break;
187  case PackHeader7:
188  parse_state_ = PackHeader8;
189  break;
190  case PackHeader8:
191  parse_state_ = PackHeader9;
192  break;
193  case PackHeader9:
194  parse_state_ = PackHeader10;
195  break;
196  case PackHeader10:
197  skip_bytes_ = *read_ptr & 0x07;
198  parse_state_ = PackHeaderStuffingSkip;
199  break;
200  case SystemHeader1:
201  skip_bytes_ = *read_ptr;
202  skip_bytes_ <<= 8;
203  parse_state_ = SystemHeader2;
204  break;
205  case SystemHeader2:
206  skip_bytes_ |= *read_ptr;
207  parse_state_ = SystemHeaderSkip;
208  break;
209  case PackHeaderStuffingSkip:
210  if (end >= skip_bytes_ + read_ptr) {
211  read_ptr += skip_bytes_;
212  skip_bytes_ = 0;
213  parse_state_ = StartCode1;
214  } else {
215  skip_bytes_ -= (end - read_ptr);
216  read_ptr = end;
217  }
218  continue;
219  case SystemHeaderSkip:
220  if (end >= skip_bytes_ + read_ptr) {
221  read_ptr += skip_bytes_;
222  skip_bytes_ = 0;
223  parse_state_ = StartCode1;
224  } else {
225  uint32_t remaining_size = end - read_ptr;
226  skip_bytes_ -= remaining_size;
227  read_ptr = end;
228  }
229  continue;
230  case PesStreamId:
231  pes_stream_id_ = *read_ptr;
232  if (!metadata_is_complete_ &&
233  (pes_stream_id_ != kPsmStreamId) &&
234  (pes_stream_id_ != kIndexStreamId) &&
235  (pes_stream_id_ != kEcmStreamId) &&
236  (pes_stream_id_ != kV2MetadataStreamId) &&
237  (pes_stream_id_ != kPaddingStreamId)) {
238  metadata_is_complete_ = true;
239  }
240  parse_state_ = PesPacketLength1;
241  break;
242  case PesPacketLength1:
243  pes_packet_bytes_ = *read_ptr;
244  pes_packet_bytes_ <<= 8;
245  parse_state_ = PesPacketLength2;
246  break;
247  case PesPacketLength2:
248  pes_packet_bytes_ |= *read_ptr;
249  if (HAS_HEADER_EXTENSION(pes_stream_id_)) {
250  parse_state_ = PesExtension1;
251  } else {
252  prev_pes_flags_1_ = pes_flags_1_;
253  pes_flags_1_ = pes_flags_2_ = 0;
254  pes_header_data_bytes_ = 0;
255  parse_state_ = PesPayload;
256  }
257  break;
258  case PesExtension1:
259  prev_pes_flags_1_ = pes_flags_1_;
260  pes_flags_1_ = *read_ptr;
261  --pes_packet_bytes_;
262  parse_state_ = PesExtension2;
263  break;
264  case PesExtension2:
265  pes_flags_2_ = *read_ptr;
266  --pes_packet_bytes_;
267  parse_state_ = PesExtension3;
268  break;
269  case PesExtension3:
270  pes_header_data_bytes_ = *read_ptr;
271  --pes_packet_bytes_;
272  if (pes_flags_2_ & kPesOptPts) {
273  parse_state_ = Pts1;
274  } else {
275  parse_state_ = PesHeaderData;
276  }
277  break;
278  case Pts1:
279  timestamp_ = (*read_ptr & 0x0E);
280  --pes_header_data_bytes_;
281  --pes_packet_bytes_;
282  parse_state_ = Pts2;
283  break;
284  case Pts2:
285  timestamp_ <<= 7;
286  timestamp_ |= *read_ptr;
287  --pes_header_data_bytes_;
288  --pes_packet_bytes_;
289  parse_state_ = Pts3;
290  break;
291  case Pts3:
292  timestamp_ <<= 7;
293  timestamp_ |= *read_ptr >> 1;
294  --pes_header_data_bytes_;
295  --pes_packet_bytes_;
296  parse_state_ = Pts4;
297  break;
298  case Pts4:
299  timestamp_ <<= 8;
300  timestamp_ |= *read_ptr;
301  --pes_header_data_bytes_;
302  --pes_packet_bytes_;
303  parse_state_ = Pts5;
304  break;
305  case Pts5:
306  timestamp_ <<= 7;
307  timestamp_ |= *read_ptr >> 1;
308  pts_ = timestamp_;
309  --pes_header_data_bytes_;
310  --pes_packet_bytes_;
311  if (pes_flags_2_ & kPesOptDts) {
312  parse_state_ = Dts1;
313  } else {
314  dts_ = pts_;
315  parse_state_ = PesHeaderData;
316  }
317  break;
318  case Dts1:
319  timestamp_ = (*read_ptr & 0x0E);
320  --pes_header_data_bytes_;
321  --pes_packet_bytes_;
322  parse_state_ = Dts2;
323  break;
324  case Dts2:
325  timestamp_ <<= 7;
326  timestamp_ |= *read_ptr;
327  --pes_header_data_bytes_;
328  --pes_packet_bytes_;
329  parse_state_ = Dts3;
330  break;
331  case Dts3:
332  timestamp_ <<= 7;
333  timestamp_ |= *read_ptr >> 1;
334  --pes_header_data_bytes_;
335  --pes_packet_bytes_;
336  parse_state_ = Dts4;
337  break;
338  case Dts4:
339  timestamp_ <<= 8;
340  timestamp_ |= *read_ptr;
341  --pes_header_data_bytes_;
342  --pes_packet_bytes_;
343  parse_state_ = Dts5;
344  break;
345  case Dts5:
346  timestamp_ <<= 7;
347  timestamp_ |= *read_ptr >> 1;
348  dts_ = timestamp_;
349  --pes_header_data_bytes_;
350  --pes_packet_bytes_;
351  parse_state_ = PesHeaderData;
352  break;
353  case PesHeaderData:
354  num_bytes = end - read_ptr;
355  if (num_bytes >= pes_header_data_bytes_) {
356  num_bytes = pes_header_data_bytes_;
357  parse_state_ = PesPayload;
358  }
359  pes_header_data_bytes_ -= num_bytes;
360  pes_packet_bytes_ -= num_bytes;
361  read_ptr += num_bytes;
362  continue;
363  case PesPayload:
364  switch (pes_stream_id_) {
365  case kPsmStreamId:
366  psm_data_.clear();
367  parse_state_ = PsmPayload;
368  continue;
369  case kPaddingStreamId:
370  parse_state_ = Padding;
371  continue;
372  case kEcmStreamId:
373  ecm_.clear();
374  parse_state_ = EcmPayload;
375  continue;
376  case kIndexStreamId:
377  parse_state_ = IndexPayload;
378  continue;
379  default:
380  if (!DemuxNextPes(false)) {
381  return false;
382  }
383  parse_state_ = EsPayload;
384  }
385  continue;
386  case PsmPayload:
387  num_bytes = end - read_ptr;
388  if (num_bytes >= pes_packet_bytes_) {
389  num_bytes = pes_packet_bytes_;
390  parse_state_ = StartCode1;
391  }
392  if (num_bytes > 0) {
393  pes_packet_bytes_ -= num_bytes;
394  prev_size = psm_data_.size();
395  psm_data_.resize(prev_size + num_bytes);
396  memcpy(&psm_data_[prev_size], read_ptr, num_bytes);
397  }
398  read_ptr += num_bytes;
399  continue;
400  case EcmPayload:
401  num_bytes = end - read_ptr;
402  if (num_bytes >= pes_packet_bytes_) {
403  num_bytes = pes_packet_bytes_;
404  parse_state_ = StartCode1;
405  }
406  if (num_bytes > 0) {
407  pes_packet_bytes_ -= num_bytes;
408  prev_size = ecm_.size();
409  ecm_.resize(prev_size + num_bytes);
410  memcpy(&ecm_[prev_size], read_ptr, num_bytes);
411  }
412  if ((pes_packet_bytes_ == 0) && !ecm_.empty()) {
413  if (!ProcessEcm()) {
414  return(false);
415  }
416  }
417  read_ptr += num_bytes;
418  continue;
419  case IndexPayload:
420  num_bytes = end - read_ptr;
421  if (num_bytes >= pes_packet_bytes_) {
422  num_bytes = pes_packet_bytes_;
423  parse_state_ = StartCode1;
424  }
425  if (num_bytes > 0) {
426  pes_packet_bytes_ -= num_bytes;
427  prev_size = index_data_.size();
428  index_data_.resize(prev_size + num_bytes);
429  memcpy(&index_data_[prev_size], read_ptr, num_bytes);
430  }
431  if (pes_packet_bytes_ == 0 && !index_data_.empty()) {
432  if (!metadata_is_complete_) {
433  if (!ParseIndexEntry()) {
434  return false;
435  }
436  }
437  }
438  read_ptr += num_bytes;
439  continue;
440  case EsPayload:
441  num_bytes = end - read_ptr;
442  if (num_bytes >= pes_packet_bytes_) {
443  num_bytes = pes_packet_bytes_;
444  parse_state_ = StartCode1;
445  }
446  pes_packet_bytes_ -= num_bytes;
447  if (pes_stream_id_ != kV2MetadataStreamId) {
448  sample_data_.resize(sample_data_.size() + num_bytes);
449  memcpy(&sample_data_[sample_data_.size() - num_bytes], read_ptr,
450  num_bytes);
451  }
452  prev_pes_stream_id_ = pes_stream_id_;
453  read_ptr += num_bytes;
454  continue;
455  case Padding:
456  num_bytes = end - read_ptr;
457  if (num_bytes >= pes_packet_bytes_) {
458  num_bytes = pes_packet_bytes_;
459  parse_state_ = StartCode1;
460  }
461  pes_packet_bytes_ -= num_bytes;
462  read_ptr += num_bytes;
463  continue;
464  case ProgramEnd:
465  parse_state_ = StartCode1;
466  metadata_is_complete_ = true;
467  if (!DemuxNextPes(true)) {
468  return false;
469  }
470  if (!Flush()) {
471  return false;
472  }
473  // Reset.
474  dts_ = pts_ = 0;
475  parse_state_ = StartCode1;
476  prev_media_sample_data_.Reset();
477  current_program_id_++;
478  ecm_.clear();
479  index_data_.clear();
480  psm_data_.clear();
481  break;
482  default:
483  break;
484  }
485  ++read_ptr;
486  }
487  return true;
488 }
489 
490 bool WvmMediaParser::EmitLastSample(
491  uint32_t stream_id,
492  const std::shared_ptr<MediaSample>& new_sample) {
493  std::string key = base::UintToString(current_program_id_)
494  .append(":")
495  .append(base::UintToString(stream_id));
496  std::map<std::string, uint32_t>::iterator it =
497  program_demux_stream_map_.find(key);
498  if (it == program_demux_stream_map_.end())
499  return false;
500  return EmitSample(stream_id, (*it).second, new_sample, true);
501 }
502 
503 bool WvmMediaParser::EmitPendingSamples() {
504  // Emit queued samples which were built when not initialized.
505  while (!media_sample_queue_.empty()) {
506  DemuxStreamIdMediaSample& demux_stream_media_sample =
507  media_sample_queue_.front();
508  if (!EmitSample(demux_stream_media_sample.parsed_audio_or_video_stream_id,
509  demux_stream_media_sample.demux_stream_id,
510  demux_stream_media_sample.media_sample,
511  false)) {
512  return false;
513  }
514  media_sample_queue_.pop_front();
515  }
516  return true;
517 }
518 
519 bool WvmMediaParser::Flush() {
520  // Flush the last audio and video sample for current program.
521  // Reset the streamID when successfully emitted.
522  if (prev_media_sample_data_.audio_sample != NULL) {
523  if (!EmitLastSample(prev_pes_stream_id_,
524  prev_media_sample_data_.audio_sample)) {
525  LOG(ERROR) << "Did not emit last sample for audio stream with ID = "
526  << prev_pes_stream_id_;
527  return false;
528  }
529  }
530  if (prev_media_sample_data_.video_sample != NULL) {
531  if (!EmitLastSample(prev_pes_stream_id_,
532  prev_media_sample_data_.video_sample)) {
533  LOG(ERROR) << "Did not emit last sample for video stream with ID = "
534  << prev_pes_stream_id_;
535  return false;
536  }
537  }
538  return true;
539 }
540 
541 bool WvmMediaParser::ParseIndexEntry() {
542  // Do not parse index entry at the beginning of any track *after* the first
543  // track.
544  if (current_program_id_ > 0) {
545  return true;
546  }
547  uint32_t index_size = 0;
548  if (index_data_.size() < kIndexVersion4HeaderSize) {
549  return false;
550  }
551 
552  const uint8_t* read_ptr = index_data_.data();
553  if (ntohlFromBuffer(read_ptr) != kIndexMagic) {
554  index_data_.clear();
555  return false;
556  }
557  read_ptr += 4;
558 
559  uint32_t version = ntohlFromBuffer(read_ptr);
560  read_ptr += 4;
561  if (version == kVersion4) {
562  index_size = kIndexVersion4HeaderSize + ntohlFromBuffer(read_ptr);
563  if (index_data_.size() < index_size) {
564  // We do not yet have the full index. Keep accumulating index data.
565  return true;
566  }
567  read_ptr += sizeof(uint32_t);
568 
569  // Index metadata
570  uint32_t index_metadata_max_size = index_size - kIndexVersion4HeaderSize;
571  if (index_metadata_max_size < sizeof(uint8_t)) {
572  index_data_.clear();
573  return false;
574  }
575 
576  uint64_t track_duration = 0;
577  uint32_t trick_play_factor = 0;
578  uint32_t sampling_frequency = kDefaultSamplingFrequency;
579  uint32_t time_scale = kMpeg2ClockRate;
580  uint16_t video_width = 0;
581  uint16_t video_height = 0;
582  uint32_t pixel_width = 0;
583  uint32_t pixel_height = 0;
584  uint8_t nalu_length_size = kNaluLengthSize;
585  uint8_t num_channels = 0;
586  int audio_pes_stream_id = 0;
587  int video_pes_stream_id = 0;
588  bool has_video = false;
589  bool has_audio = false;
590  std::vector<uint8_t> audio_codec_config;
591  std::vector<uint8_t> video_codec_config;
592  uint8_t num_index_entries = *read_ptr;
593  ++read_ptr;
594  --index_metadata_max_size;
595 
596  for (uint8_t idx = 0; idx < num_index_entries; ++idx) {
597  if (index_metadata_max_size < (2 * sizeof(uint8_t)) + sizeof(uint32_t)) {
598  return false;
599  }
600  uint8_t tag = *read_ptr;
601  ++read_ptr;
602  uint8_t type = *read_ptr;
603  ++read_ptr;
604  uint32_t length = ntohlFromBuffer(read_ptr);
605  read_ptr += sizeof(uint32_t);
606  index_metadata_max_size -= (2 * sizeof(uint8_t)) + sizeof(uint32_t);
607  if (index_metadata_max_size < length) {
608  return false;
609  }
610  int64_t value = 0;
611  Tag tagtype = Unset;
612  std::vector<uint8_t> binary_data;
613  switch (Type(type)) {
614  case Type_uint8:
615  if (length == sizeof(uint8_t)) {
616  tagtype = GetTag(tag, length, read_ptr, &value);
617  } else {
618  return false;
619  }
620  break;
621  case Type_int8:
622  if (length == sizeof(int8_t)) {
623  tagtype = GetTag(tag, length, read_ptr, &value);
624  } else {
625  return false;
626  }
627  break;
628  case Type_uint16:
629  if (length == sizeof(uint16_t)) {
630  tagtype = GetTag(tag, length, read_ptr, &value);
631  } else {
632  return false;
633  }
634  break;
635  case Type_int16:
636  if (length == sizeof(int16_t)) {
637  tagtype = GetTag(tag, length, read_ptr, &value);
638  } else {
639  return false;
640  }
641  break;
642  case Type_uint32:
643  if (length == sizeof(uint32_t)) {
644  tagtype = GetTag(tag, length, read_ptr, &value);
645  } else {
646  return false;
647  }
648  break;
649  case Type_int32:
650  if (length == sizeof(int32_t)) {
651  tagtype = GetTag(tag, length, read_ptr, &value);
652  } else {
653  return false;
654  }
655  break;
656  case Type_uint64:
657  if (length == sizeof(uint64_t)) {
658  tagtype = GetTag(tag, length, read_ptr, &value);
659  } else {
660  return false;
661  }
662  break;
663  case Type_int64:
664  if (length == sizeof(int64_t)) {
665  tagtype = GetTag(tag, length, read_ptr, &value);
666  } else {
667  return false;
668  }
669  break;
670  case Type_string:
671  case Type_BinaryData:
672  binary_data.assign(read_ptr, read_ptr + length);
673  tagtype = Tag(tag);
674  break;
675  default:
676  break;
677  }
678 
679  switch (tagtype) {
680  case TrackDuration:
681  track_duration = value;
682  break;
683  case TrackTrickPlayFactor:
684  trick_play_factor = value;
685  break;
686  case VideoStreamId:
687  video_pes_stream_id = value;
688  break;
689  case AudioStreamId:
690  audio_pes_stream_id = value;
691  break;
692  case VideoWidth:
693  video_width = (uint16_t)value;
694  break;
695  case VideoHeight:
696  video_height = (uint16_t)value;
697  break;
698  case AudioNumChannels:
699  num_channels = (uint8_t)value;
700  break;
701  case VideoType:
702  has_video = true;
703  break;
704  case AudioType:
705  has_audio = true;
706  break;
707  case VideoPixelWidth:
708  pixel_width = static_cast<uint32_t>(value);
709  break;
710  case VideoPixelHeight:
711  pixel_height = static_cast<uint32_t>(value);
712  break;
713  case Audio_EsDescriptor: {
714  ESDescriptor descriptor;
715  if (!descriptor.Parse(binary_data)) {
716  LOG(ERROR) <<
717  "Could not extract AudioSpecificConfig from ES_Descriptor";
718  return false;
719  }
720  audio_codec_config = descriptor.decoder_specific_info();
721  break;
722  }
723  case Audio_EC3SpecificData:
724  case Audio_DtsSpecificData:
725  case Audio_AC3SpecificData:
726  LOG(ERROR) << "Audio type not supported.";
727  return false;
728  case Video_AVCDecoderConfigurationRecord:
729  video_codec_config = binary_data;
730  break;
731  default:
732  break;
733  }
734 
735  read_ptr += length;
736  index_metadata_max_size -= length;
737  }
738  // End Index metadata
739  index_size = read_ptr - index_data_.data();
740 
741  if (has_video) {
742  stream_infos_.emplace_back(new VideoStreamInfo(
743  stream_id_count_, time_scale, track_duration, kCodecH264,
744  byte_to_unit_stream_converter_.stream_format(), std::string(),
745  video_codec_config.data(), video_codec_config.size(), video_width,
746  video_height, pixel_width, pixel_height, trick_play_factor,
747  nalu_length_size, std::string(),
748  decryption_key_source_ ? false : true));
749  program_demux_stream_map_[base::UintToString(index_program_id_) + ":" +
750  base::UintToString(
751  video_pes_stream_id
752  ? video_pes_stream_id
753  : kDefaultVideoStreamId)] =
754  stream_id_count_++;
755  }
756  if (has_audio) {
757  const Codec audio_codec = kCodecAAC;
758  // TODO(beil): Pass in max and average bitrate in wvm container.
759  stream_infos_.emplace_back(new AudioStreamInfo(
760  stream_id_count_, time_scale, track_duration, audio_codec,
761  std::string(), audio_codec_config.data(), audio_codec_config.size(),
762  kAacSampleSizeBits, num_channels, sampling_frequency,
763  0 /* seek preroll */, 0 /* codec delay */, 0 /* max bitrate */,
764  0 /* avg bitrate */, std::string(),
765  decryption_key_source_ ? false : true));
766  program_demux_stream_map_[base::UintToString(index_program_id_) + ":" +
767  base::UintToString(
768  audio_pes_stream_id
769  ? audio_pes_stream_id
770  : kDefaultAudioStreamId)] =
771  stream_id_count_++;
772  }
773  }
774 
775  index_program_id_++;
776  index_data_.clear();
777  return true;
778 }
779 
780 bool WvmMediaParser::DemuxNextPes(bool is_program_end) {
781  bool output_encrypted_sample = false;
782  if (!sample_data_.empty() && (prev_pes_flags_1_ & kScramblingBitsMask)) {
783  // Decrypt crypto unit.
784  if (!content_decryptor_) {
785  output_encrypted_sample = true;
786  } else {
787  content_decryptor_->Crypt(&sample_data_[crypto_unit_start_pos_],
788  sample_data_.size() - crypto_unit_start_pos_,
789  &sample_data_[crypto_unit_start_pos_]);
790  }
791  }
792  // Demux media sample if we are at program end or if we are not at a
793  // continuation PES.
794  if ((pes_flags_2_ & kPesOptPts) || is_program_end) {
795  if (!sample_data_.empty()) {
796  if (!Output(output_encrypted_sample)) {
797  return false;
798  }
799  }
800  StartMediaSampleDemux();
801  }
802 
803  crypto_unit_start_pos_ = sample_data_.size();
804  return true;
805 }
806 
807 void WvmMediaParser::StartMediaSampleDemux() {
808  bool is_key_frame = ((pes_flags_1_ & kPesOptAlign) != 0);
809  media_sample_ = MediaSample::CreateEmptyMediaSample();
810  media_sample_->set_dts(dts_);
811  media_sample_->set_pts(pts_);
812  media_sample_->set_is_key_frame(is_key_frame);
813 
814  sample_data_.clear();
815 }
816 
817 bool WvmMediaParser::Output(bool output_encrypted_sample) {
818  if (output_encrypted_sample) {
819  media_sample_->set_data(sample_data_.data(), sample_data_.size());
820  media_sample_->set_is_encrypted(true);
821  } else {
822  if ((prev_pes_stream_id_ & kPesStreamIdVideoMask) == kPesStreamIdVideo) {
823  // Convert video stream to unit stream and get config.
824  std::vector<uint8_t> nal_unit_stream;
825  if (!byte_to_unit_stream_converter_.ConvertByteStreamToNalUnitStream(
826  sample_data_.data(), sample_data_.size(), &nal_unit_stream)) {
827  LOG(ERROR) << "Could not convert h.264 byte stream sample";
828  return false;
829  }
830  media_sample_->set_data(nal_unit_stream.data(), nal_unit_stream.size());
831  if (!is_initialized_) {
832  // Set extra data for video stream from AVC Decoder Config Record.
833  // Also, set codec string from the AVC Decoder Config Record.
834  std::vector<uint8_t> decoder_config_record;
835  byte_to_unit_stream_converter_.GetDecoderConfigurationRecord(
836  &decoder_config_record);
837  for (uint32_t i = 0; i < stream_infos_.size(); i++) {
838  if (stream_infos_[i]->stream_type() == kStreamVideo &&
839  stream_infos_[i]->codec_string().empty()) {
840  const std::vector<uint8_t>* stream_config;
841  if (stream_infos_[i]->codec_config().empty()) {
842  // Decoder config record not available for stream. Use the one
843  // computed from the first video stream.
844  stream_infos_[i]->set_codec_config(decoder_config_record);
845  stream_config = &decoder_config_record;
846  } else {
847  // Use stream-specific config record.
848  stream_config = &stream_infos_[i]->codec_config();
849  }
850  DCHECK(stream_config);
851 
852  VideoStreamInfo* video_stream_info =
853  reinterpret_cast<VideoStreamInfo*>(stream_infos_[i].get());
854  AVCDecoderConfigurationRecord avc_config;
855  if (!avc_config.Parse(*stream_config)) {
856  LOG(WARNING) << "Failed to parse AVCDecoderConfigurationRecord. "
857  "Using computed configuration record instead.";
858  video_stream_info->set_codec_config(decoder_config_record);
859  if (!avc_config.Parse(decoder_config_record)) {
860  LOG(ERROR) << "Failed to parse AVCDecoderConfigurationRecord.";
861  return false;
862  }
863  }
864  const FourCC codec_fourcc =
865  byte_to_unit_stream_converter_.stream_format() ==
866  H26xStreamFormat::kNalUnitStreamWithParameterSetNalus
867  ? FOURCC_avc3
868  : FOURCC_avc1;
869  video_stream_info->set_codec_string(
870  avc_config.GetCodecString(codec_fourcc));
871 
872  if (avc_config.pixel_width() != video_stream_info->pixel_width() ||
873  avc_config.pixel_height() !=
874  video_stream_info->pixel_height()) {
875  LOG_IF(WARNING, video_stream_info->pixel_width() != 0 ||
876  video_stream_info->pixel_height() != 0)
877  << "Pixel aspect ratio in WVM metadata ("
878  << video_stream_info->pixel_width() << ","
879  << video_stream_info->pixel_height()
880  << ") does not match with SAR in "
881  "AVCDecoderConfigurationRecord ("
882  << avc_config.pixel_width() << ","
883  << avc_config.pixel_height()
884  << "). Use AVCDecoderConfigurationRecord.";
885  video_stream_info->set_pixel_width(avc_config.pixel_width());
886  video_stream_info->set_pixel_height(avc_config.pixel_height());
887  }
888  if (avc_config.coded_width() != video_stream_info->width() ||
889  avc_config.coded_height() != video_stream_info->height()) {
890  LOG(WARNING) << "Resolution in WVM metadata ("
891  << video_stream_info->width() << ","
892  << video_stream_info->height()
893  << ") does not match with resolution in "
894  "AVCDecoderConfigurationRecord ("
895  << avc_config.coded_width() << ","
896  << avc_config.coded_height()
897  << "). Use AVCDecoderConfigurationRecord.";
898  video_stream_info->set_width(avc_config.coded_width());
899  video_stream_info->set_height(avc_config.coded_height());
900  }
901  }
902  }
903  }
904  } else if ((prev_pes_stream_id_ & kPesStreamIdAudioMask) ==
905  kPesStreamIdAudio) {
906  // Set data on the audio stream.
907  int frame_size = static_cast<int>(mp2t::AdtsHeader::GetAdtsFrameSize(
908  sample_data_.data(), kAdtsHeaderMinSize));
909  mp2t::AdtsHeader adts_header;
910  const uint8_t* frame_ptr = sample_data_.data();
911  if (!adts_header.Parse(frame_ptr, frame_size)) {
912  LOG(ERROR) << "Could not parse ADTS header";
913  return false;
914  }
915  size_t header_size = adts_header.GetAdtsHeaderSize(frame_ptr,
916  frame_size);
917  media_sample_->set_data(frame_ptr + header_size,
918  frame_size - header_size);
919  if (!is_initialized_) {
920  for (uint32_t i = 0; i < stream_infos_.size(); i++) {
921  if (stream_infos_[i]->stream_type() == kStreamAudio &&
922  stream_infos_[i]->codec_string().empty()) {
923  AudioStreamInfo* audio_stream_info =
924  reinterpret_cast<AudioStreamInfo*>(stream_infos_[i].get());
925  if (audio_stream_info->codec_config().empty()) {
926  // Set AudioStreamInfo fields using information from the ADTS
927  // header.
928  audio_stream_info->set_sampling_frequency(
929  adts_header.GetSamplingFrequency());
930  std::vector<uint8_t> audio_specific_config;
931  if (!adts_header.GetAudioSpecificConfig(&audio_specific_config)) {
932  LOG(ERROR) << "Could not compute AACAudiospecificconfig";
933  return false;
934  }
935  audio_stream_info->set_codec_config(audio_specific_config);
936  audio_stream_info->set_codec_string(
938  kCodecAAC, adts_header.GetObjectType()));
939  } else {
940  // Set AudioStreamInfo fields using information from the
941  // AACAudioSpecificConfig record.
942  AACAudioSpecificConfig aac_config;
943  if (!aac_config.Parse(stream_infos_[i]->codec_config())) {
944  LOG(ERROR) << "Could not parse AACAudioSpecificconfig";
945  return false;
946  }
947  audio_stream_info->set_sampling_frequency(
948  aac_config.GetSamplesPerSecond());
949  audio_stream_info->set_codec_string(
951  kCodecAAC, aac_config.GetAudioObjectType()));
952  }
953  }
954  }
955  }
956  }
957  }
958 
959  if (!is_initialized_) {
960  bool all_streams_have_config = true;
961  // Check if all collected stream infos have codec_config set.
962  for (uint32_t i = 0; i < stream_infos_.size(); i++) {
963  if (stream_infos_[i]->codec_string().empty()) {
964  all_streams_have_config = false;
965  break;
966  }
967  }
968  if (all_streams_have_config) {
969  init_cb_.Run(stream_infos_);
970  is_initialized_ = true;
971  }
972  }
973 
974  DCHECK_GT(media_sample_->data_size(), 0UL);
975  std::string key = base::UintToString(current_program_id_).append(":")
976  .append(base::UintToString(prev_pes_stream_id_));
977  std::map<std::string, uint32_t>::iterator it =
978  program_demux_stream_map_.find(key);
979  if (it == program_demux_stream_map_.end()) {
980  // TODO(ramjic): Log error message here and in other error cases through
981  // this method.
982  return false;
983  }
984  DemuxStreamIdMediaSample demux_stream_media_sample;
985  demux_stream_media_sample.parsed_audio_or_video_stream_id =
986  prev_pes_stream_id_;
987  demux_stream_media_sample.demux_stream_id = (*it).second;
988  demux_stream_media_sample.media_sample = media_sample_;
989  // Check if sample can be emitted.
990  if (!is_initialized_) {
991  media_sample_queue_.push_back(demux_stream_media_sample);
992  } else {
993  // flush the sample queue and emit all queued samples.
994  while (!media_sample_queue_.empty()) {
995  if (!EmitPendingSamples())
996  return false;
997  }
998  // Emit current sample.
999  if (!EmitSample(prev_pes_stream_id_, (*it).second, media_sample_, false))
1000  return false;
1001  }
1002  return true;
1003 }
1004 
1005 bool WvmMediaParser::EmitSample(uint32_t parsed_audio_or_video_stream_id,
1006  uint32_t stream_id,
1007  const std::shared_ptr<MediaSample>& new_sample,
1008  bool isLastSample) {
1009  DCHECK(new_sample);
1010  if (isLastSample) {
1011  if ((parsed_audio_or_video_stream_id & kPesStreamIdVideoMask) ==
1012  kPesStreamIdVideo) {
1013  new_sample->set_duration(prev_media_sample_data_.video_sample_duration);
1014  } else if ((parsed_audio_or_video_stream_id & kPesStreamIdAudioMask) ==
1015  kPesStreamIdAudio) {
1016  new_sample->set_duration(prev_media_sample_data_.audio_sample_duration);
1017  }
1018  if (!new_sample_cb_.Run(stream_id, new_sample)) {
1019  LOG(ERROR) << "Failed to process the last sample.";
1020  return false;
1021  }
1022  return true;
1023  }
1024 
1025  // Cannot emit current sample. Compute duration first and then,
1026  // emit previous sample.
1027  if ((parsed_audio_or_video_stream_id & kPesStreamIdVideoMask) ==
1028  kPesStreamIdVideo) {
1029  if (prev_media_sample_data_.video_sample == NULL) {
1030  prev_media_sample_data_.video_sample = new_sample;
1031  prev_media_sample_data_.video_stream_id = stream_id;
1032  return true;
1033  }
1034  prev_media_sample_data_.video_sample->set_duration(
1035  new_sample->dts() - prev_media_sample_data_.video_sample->dts());
1036  prev_media_sample_data_.video_sample_duration =
1037  prev_media_sample_data_.video_sample->duration();
1038  if (!new_sample_cb_.Run(prev_media_sample_data_.video_stream_id,
1039  prev_media_sample_data_.video_sample)) {
1040  LOG(ERROR) << "Failed to process the video sample.";
1041  return false;
1042  }
1043  prev_media_sample_data_.video_sample = new_sample;
1044  prev_media_sample_data_.video_stream_id = stream_id;
1045  } else if ((parsed_audio_or_video_stream_id & kPesStreamIdAudioMask) ==
1046  kPesStreamIdAudio) {
1047  if (prev_media_sample_data_.audio_sample == NULL) {
1048  prev_media_sample_data_.audio_sample = new_sample;
1049  prev_media_sample_data_.audio_stream_id = stream_id;
1050  return true;
1051  }
1052  prev_media_sample_data_.audio_sample->set_duration(
1053  new_sample->dts() - prev_media_sample_data_.audio_sample->dts());
1054  prev_media_sample_data_.audio_sample_duration =
1055  prev_media_sample_data_.audio_sample->duration();
1056  if (!new_sample_cb_.Run(prev_media_sample_data_.audio_stream_id,
1057  prev_media_sample_data_.audio_sample)) {
1058  LOG(ERROR) << "Failed to process the audio sample.";
1059  return false;
1060  }
1061  prev_media_sample_data_.audio_sample = new_sample;
1062  prev_media_sample_data_.audio_stream_id = stream_id;
1063  }
1064  return true;
1065 }
1066 
1067 bool WvmMediaParser::GetAssetKey(const uint8_t* asset_id,
1068  EncryptionKey* encryption_key) {
1069  DCHECK(decryption_key_source_);
1070  Status status = decryption_key_source_->FetchKeys(
1071  EmeInitDataType::WIDEVINE_CLASSIC,
1072  std::vector<uint8_t>(asset_id, asset_id + sizeof(uint32_t)));
1073  if (!status.ok()) {
1074  LOG(ERROR) << "Fetch Key(s) failed for AssetID = "
1075  << ntohlFromBuffer(asset_id) << ", error = " << status;
1076  return false;
1077  }
1078 
1079  const char kHdStreamLabel[] = "HD";
1080  status = decryption_key_source_->GetKey(kHdStreamLabel, encryption_key);
1081  if (!status.ok()) {
1082  LOG(ERROR) << "Fetch Key(s) failed for AssetID = "
1083  << ntohlFromBuffer(asset_id) << ", error = " << status;
1084  return false;
1085  }
1086 
1087  return true;
1088 }
1089 
1090 bool WvmMediaParser::ProcessEcm() {
1091  // An error will be returned later if the samples need to be decrypted.
1092  if (!decryption_key_source_)
1093  return true;
1094 
1095  if (current_program_id_ > 0) {
1096  return true;
1097  }
1098  if (ecm_.size() != kEcmSizeBytes) {
1099  LOG(ERROR) << "Unexpected ECM size = " << ecm_.size()
1100  << ", expected size = " << kEcmSizeBytes;
1101  return false;
1102  }
1103  const uint8_t* ecm_data = ecm_.data();
1104  DCHECK(ecm_data);
1105  ecm_data += sizeof(uint32_t); // old version field - skip.
1106  ecm_data += sizeof(uint32_t); // clear lead - skip.
1107  ecm_data += sizeof(uint32_t); // system id(includes ECM version) - skip.
1108  EncryptionKey encryption_key;
1109  if (!GetAssetKey(ecm_data, &encryption_key)) {
1110  return false;
1111  }
1112  if (encryption_key.key.size() < kAssetKeySizeBytes) {
1113  LOG(ERROR) << "Asset Key size of " << encryption_key.key.size()
1114  << " for AssetID = " << ntohlFromBuffer(ecm_data)
1115  << " is less than minimum asset key size.";
1116  return false;
1117  }
1118  ecm_data += sizeof(uint32_t); // asset_id.
1119  // Legacy WVM content may have asset keys > 16 bytes.
1120  // Use only the first 16 bytes of the asset key to get
1121  // the content key.
1122  std::vector<uint8_t> asset_key(
1123  encryption_key.key.begin(),
1124  encryption_key.key.begin() + kAssetKeySizeBytes);
1125  // WVM format always uses all zero IV.
1126  std::vector<uint8_t> zero_iv(kInitializationVectorSizeBytes, 0);
1127  AesCbcDecryptor asset_decryptor(kCtsPadding, AesCryptor::kUseConstantIv);
1128  if (!asset_decryptor.InitializeWithIv(asset_key, zero_iv)) {
1129  LOG(ERROR) << "Failed to initialize asset_decryptor.";
1130  return false;
1131  }
1132 
1133  const size_t content_key_buffer_size =
1134  kEcmFlagsSizeBytes + kEcmContentKeySizeBytes +
1135  kEcmPaddingSizeBytes; // flags + contentKey + padding.
1136  std::vector<uint8_t> content_key_buffer(content_key_buffer_size);
1137  CHECK(asset_decryptor.Crypt(ecm_data, content_key_buffer_size,
1138  content_key_buffer.data()));
1139 
1140  std::vector<uint8_t> decrypted_content_key_vec(
1141  content_key_buffer.begin() + 4,
1142  content_key_buffer.begin() + 20);
1143  std::unique_ptr<AesCbcDecryptor> content_decryptor(
1144  new AesCbcDecryptor(kCtsPadding, AesCryptor::kUseConstantIv));
1145  if (!content_decryptor->InitializeWithIv(decrypted_content_key_vec,
1146  zero_iv)) {
1147  LOG(ERROR) << "Failed to initialize content decryptor.";
1148  return false;
1149  }
1150 
1151  content_decryptor_ = std::move(content_decryptor);
1152  return true;
1153 }
1154 
1155 DemuxStreamIdMediaSample::DemuxStreamIdMediaSample() :
1156  demux_stream_id(0),
1157  parsed_audio_or_video_stream_id(0) {}
1158 
1159 DemuxStreamIdMediaSample::~DemuxStreamIdMediaSample() {}
1160 
1161 PrevSampleData::PrevSampleData() {
1162  Reset();
1163 }
1164 
1165 PrevSampleData::~PrevSampleData() {}
1166 
1167 void PrevSampleData::Reset() {
1168  audio_sample = NULL;
1169  video_sample = NULL;
1170  audio_stream_id = 0;
1171  video_stream_id = 0;
1172  audio_sample_duration = 0;
1173  video_sample_duration = 0;
1174 }
1175 
1176 } // namespace wvm
1177 } // namespace media
1178 } // namespace shaka
static std::shared_ptr< MediaSample > CreateEmptyMediaSample()
Create a MediaSample object with default members.
static size_t GetAdtsFrameSize(const uint8_t *data, size_t num_bytes)
Definition: adts_header.cc:23
static std::string GetCodecString(Codec codec, uint8_t audio_object_type)
KeySource is responsible for encryption key acquisition.
Definition: key_source.h:45