Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / media / formats / mp2t / es_parser_adts.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 "media/formats/mp2t/es_parser_adts.h"
6
7 #include <list>
8
9 #include "base/basictypes.h"
10 #include "base/logging.h"
11 #include "base/strings/string_number_conversions.h"
12 #include "media/base/audio_timestamp_helper.h"
13 #include "media/base/bit_reader.h"
14 #include "media/base/buffers.h"
15 #include "media/base/channel_layout.h"
16 #include "media/base/stream_parser_buffer.h"
17 #include "media/formats/mp2t/mp2t_common.h"
18 #include "media/formats/mpeg/adts_constants.h"
19
20 namespace media {
21
22 static int ExtractAdtsFrameSize(const uint8* adts_header) {
23   return ((static_cast<int>(adts_header[5]) >> 5) |
24           (static_cast<int>(adts_header[4]) << 3) |
25           ((static_cast<int>(adts_header[3]) & 0x3) << 11));
26 }
27
28 static size_t ExtractAdtsFrequencyIndex(const uint8* adts_header) {
29   return ((adts_header[2] >> 2) & 0xf);
30 }
31
32 static size_t ExtractAdtsChannelConfig(const uint8* adts_header) {
33   return (((adts_header[3] >> 6) & 0x3) |
34           ((adts_header[2] & 0x1) << 2));
35 }
36
37 // Return true if buf corresponds to an ADTS syncword.
38 // |buf| size must be at least 2.
39 static bool isAdtsSyncWord(const uint8* buf) {
40   return (buf[0] == 0xff) && ((buf[1] & 0xf6) == 0xf0);
41 }
42
43 // Look for an ADTS syncword.
44 // |new_pos| returns
45 // - either the byte position of the ADTS frame (if found)
46 // - or the byte position of 1st byte that was not processed (if not found).
47 // In every case, the returned value in |new_pos| is such that new_pos >= pos
48 // |frame_sz| returns the size of the ADTS frame (if found).
49 // Return whether a syncword was found.
50 static bool LookForSyncWord(const uint8* raw_es, int raw_es_size,
51                             int pos,
52                             int* new_pos, int* frame_sz) {
53   DCHECK_GE(pos, 0);
54   DCHECK_LE(pos, raw_es_size);
55
56   int max_offset = raw_es_size - kADTSHeaderMinSize;
57   if (pos >= max_offset) {
58     // Do not change the position if:
59     // - max_offset < 0: not enough bytes to get a full header
60     //   Since pos >= 0, this is a subcase of the next condition.
61     // - pos >= max_offset: might be the case after reading one full frame,
62     //   |pos| is then incremented by the frame size and might then point
63     //   to the end of the buffer.
64     *new_pos = pos;
65     return false;
66   }
67
68   for (int offset = pos; offset < max_offset; offset++) {
69     const uint8* cur_buf = &raw_es[offset];
70
71     if (!isAdtsSyncWord(cur_buf))
72       // The first 12 bits must be 1.
73       // The layer field (2 bits) must be set to 0.
74       continue;
75
76     int frame_size = ExtractAdtsFrameSize(cur_buf);
77     if (frame_size < kADTSHeaderMinSize) {
78       // Too short to be an ADTS frame.
79       continue;
80     }
81
82     // Check whether there is another frame
83     // |size| apart from the current one.
84     int remaining_size = raw_es_size - offset;
85     if (remaining_size >= frame_size + 2 &&
86         !isAdtsSyncWord(&cur_buf[frame_size])) {
87       continue;
88     }
89
90     *new_pos = offset;
91     *frame_sz = frame_size;
92     return true;
93   }
94
95   *new_pos = max_offset;
96   return false;
97 }
98
99 namespace mp2t {
100
101 EsParserAdts::EsParserAdts(
102     const NewAudioConfigCB& new_audio_config_cb,
103     const EmitBufferCB& emit_buffer_cb,
104     bool sbr_in_mimetype)
105   : new_audio_config_cb_(new_audio_config_cb),
106     emit_buffer_cb_(emit_buffer_cb),
107     sbr_in_mimetype_(sbr_in_mimetype) {
108 }
109
110 EsParserAdts::~EsParserAdts() {
111 }
112
113 bool EsParserAdts::Parse(const uint8* buf, int size,
114                          base::TimeDelta pts,
115                          base::TimeDelta dts) {
116   int raw_es_size;
117   const uint8* raw_es;
118
119   // The incoming PTS applies to the access unit that comes just after
120   // the beginning of |buf|.
121   if (pts != kNoTimestamp()) {
122     es_byte_queue_.Peek(&raw_es, &raw_es_size);
123     pts_list_.push_back(EsPts(raw_es_size, pts));
124   }
125
126   // Copy the input data to the ES buffer.
127   es_byte_queue_.Push(buf, size);
128   es_byte_queue_.Peek(&raw_es, &raw_es_size);
129
130   // Look for every ADTS frame in the ES buffer starting at offset = 0
131   int es_position = 0;
132   int frame_size;
133   while (LookForSyncWord(raw_es, raw_es_size, es_position,
134                          &es_position, &frame_size)) {
135     DVLOG(LOG_LEVEL_ES)
136         << "ADTS syncword @ pos=" << es_position
137         << " frame_size=" << frame_size;
138     DVLOG(LOG_LEVEL_ES)
139         << "ADTS header: "
140         << base::HexEncode(&raw_es[es_position], kADTSHeaderMinSize);
141
142     // Do not process the frame if this one is a partial frame.
143     int remaining_size = raw_es_size - es_position;
144     if (frame_size > remaining_size)
145       break;
146
147     // Update the audio configuration if needed.
148     DCHECK_GE(frame_size, kADTSHeaderMinSize);
149     if (!UpdateAudioConfiguration(&raw_es[es_position]))
150       return false;
151
152     // Get the PTS & the duration of this access unit.
153     while (!pts_list_.empty() &&
154            pts_list_.front().first <= es_position) {
155       audio_timestamp_helper_->SetBaseTimestamp(pts_list_.front().second);
156       pts_list_.pop_front();
157     }
158
159     base::TimeDelta current_pts = audio_timestamp_helper_->GetTimestamp();
160     base::TimeDelta frame_duration =
161         audio_timestamp_helper_->GetFrameDuration(kSamplesPerAACFrame);
162
163     // Emit an audio frame.
164     bool is_key_frame = true;
165
166     // TODO(wolenetz/acolwell): Validate and use a common cross-parser TrackId
167     // type and allow multiple audio tracks. See https://crbug.com/341581.
168     scoped_refptr<StreamParserBuffer> stream_parser_buffer =
169         StreamParserBuffer::CopyFrom(
170             &raw_es[es_position],
171             frame_size,
172             is_key_frame,
173             DemuxerStream::AUDIO, 0);
174     stream_parser_buffer->SetDecodeTimestamp(current_pts);
175     stream_parser_buffer->set_timestamp(current_pts);
176     stream_parser_buffer->set_duration(frame_duration);
177     emit_buffer_cb_.Run(stream_parser_buffer);
178
179     // Update the PTS of the next frame.
180     audio_timestamp_helper_->AddFrames(kSamplesPerAACFrame);
181
182     // Skip the current frame.
183     es_position += frame_size;
184   }
185
186   // Discard all the bytes that have been processed.
187   DiscardEs(es_position);
188
189   return true;
190 }
191
192 void EsParserAdts::Flush() {
193 }
194
195 void EsParserAdts::Reset() {
196   es_byte_queue_.Reset();
197   pts_list_.clear();
198   last_audio_decoder_config_ = AudioDecoderConfig();
199 }
200
201 bool EsParserAdts::UpdateAudioConfiguration(const uint8* adts_header) {
202   size_t frequency_index = ExtractAdtsFrequencyIndex(adts_header);
203   if (frequency_index >= kADTSFrequencyTableSize) {
204     // Frequency index 13 & 14 are reserved
205     // while 15 means that the frequency is explicitly written
206     // (not supported).
207     return false;
208   }
209
210   size_t channel_configuration = ExtractAdtsChannelConfig(adts_header);
211   if (channel_configuration == 0 ||
212       channel_configuration >= kADTSChannelLayoutTableSize) {
213     // TODO(damienv): Add support for inband channel configuration.
214     return false;
215   }
216
217   // TODO(damienv): support HE-AAC frequency doubling (SBR)
218   // based on the incoming ADTS profile.
219   int samples_per_second = kADTSFrequencyTable[frequency_index];
220   int adts_profile = (adts_header[2] >> 6) & 0x3;
221
222   // The following code is written according to ISO 14496 Part 3 Table 1.11 and
223   // Table 1.22. (Table 1.11 refers to the capping to 48000, Table 1.22 refers
224   // to SBR doubling the AAC sample rate.)
225   // TODO(damienv) : Extend sample rate cap to 96kHz for Level 5 content.
226   int extended_samples_per_second = sbr_in_mimetype_
227       ? std::min(2 * samples_per_second, 48000)
228       : samples_per_second;
229
230   // The following code is written according to ISO 14496 Part 3 Table 1.13 -
231   // Syntax of AudioSpecificConfig.
232   uint16 extra_data_int =
233       // Note: adts_profile is in the range [0,3], since the ADTS header only
234       // allows two bits for its value.
235       ((adts_profile + 1) << 11) +
236       (frequency_index << 7) +
237       (channel_configuration << 3);
238   uint8 extra_data[2] = {
239       static_cast<uint8>(extra_data_int >> 8),
240       static_cast<uint8>(extra_data_int & 0xff)
241   };
242
243   AudioDecoderConfig audio_decoder_config(
244       kCodecAAC,
245       kSampleFormatS16,
246       kADTSChannelLayoutTable[channel_configuration],
247       extended_samples_per_second,
248       extra_data,
249       arraysize(extra_data),
250       false);
251
252   if (!audio_decoder_config.Matches(last_audio_decoder_config_)) {
253     DVLOG(1) << "Sampling frequency: " << samples_per_second;
254     DVLOG(1) << "Extended sampling frequency: " << extended_samples_per_second;
255     DVLOG(1) << "Channel config: " << channel_configuration;
256     DVLOG(1) << "Adts profile: " << adts_profile;
257     // Reset the timestamp helper to use a new time scale.
258     if (audio_timestamp_helper_) {
259       base::TimeDelta base_timestamp = audio_timestamp_helper_->GetTimestamp();
260       audio_timestamp_helper_.reset(
261         new AudioTimestampHelper(samples_per_second));
262       audio_timestamp_helper_->SetBaseTimestamp(base_timestamp);
263     } else {
264       audio_timestamp_helper_.reset(
265           new AudioTimestampHelper(samples_per_second));
266     }
267     // Audio config notification.
268     last_audio_decoder_config_ = audio_decoder_config;
269     new_audio_config_cb_.Run(audio_decoder_config);
270   }
271
272   return true;
273 }
274
275 void EsParserAdts::DiscardEs(int nbytes) {
276   DCHECK_GE(nbytes, 0);
277   if (nbytes <= 0)
278     return;
279
280   // Adjust the ES position of each PTS.
281   for (EsPtsList::iterator it = pts_list_.begin(); it != pts_list_.end(); ++it)
282     it->first -= nbytes;
283
284   // Discard |nbytes| of ES.
285   es_byte_queue_.Pop(nbytes);
286 }
287
288 }  // namespace mp2t
289 }  // namespace media
290