1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "sllog.h"
18 #include <utils/Log.h>
19 
20 #include "android/include/AacAdtsExtractor.h"
21 #include "include/avc_utils.h"
22 
23 
24 namespace android {
25 
26 #define ADTS_HEADER_LENGTH 7
27 // ADTS header size is 7, but frame size information ends on byte 6 (when counting from byte 1)
28 #define ADTS_HEADER_SIZE_UP_TO_FRAMESIZE 6
29 
30 ////////////////////////////////////////////////////////////////////////////////
31 
32 // Returns the sample rate based on the sampling frequency index
get_sample_rate(const uint8_t sf_index)33 static uint32_t get_sample_rate(const uint8_t sf_index)
34 {
35     static const uint32_t sample_rates[] =
36     {
37         96000, 88200, 64000, 48000, 44100, 32000,
38         24000, 22050, 16000, 12000, 11025, 8000
39     };
40 
41     if (sf_index < sizeof(sample_rates) / sizeof(sample_rates[0])) {
42         return sample_rates[sf_index];
43     }
44 
45     return 0;
46 }
47 
getFrameSize(const sp<DataSource> & source,off64_t offset)48 static size_t getFrameSize(const sp<DataSource> &source, off64_t offset) {
49     size_t frameSize = 0;
50 
51     uint8_t syncHeader[ADTS_HEADER_SIZE_UP_TO_FRAMESIZE];
52     const uint8_t *syncword = syncHeader;
53     const uint8_t *header = syncHeader + 3;
54 
55     ssize_t readSize = source->readAt(offset, &syncHeader, ADTS_HEADER_SIZE_UP_TO_FRAMESIZE);
56     if (readSize == 0) {
57         // EOS is normal, not an error
58         SL_LOGV("AacAdtsExtractor::getFrameSize EOS");
59         return 0;
60     }
61     if (readSize != ADTS_HEADER_SIZE_UP_TO_FRAMESIZE) {
62         SL_LOGE("AacAdtsExtractor:: getFrameSize() returns %d (syncword and header read error)",
63                 (int) readSize);
64         return 0;
65     }
66 
67     if ((syncword[0] != 0xff) || ((syncword[1] & 0xf6) != 0xf0)) {
68         SL_LOGE("AacAdtsExtractor:: getFrameSize() returns 0 (syncword pb)");
69         return 0;
70     }
71 
72     const uint8_t protectionAbsent = syncword[1] & 0x1;
73 
74     frameSize = (header[0] & 0x3) << 11 | header[1] << 3 | header[2] >> 5;
75     // the frame size read already contains the size of the ADTS header, so no need to add it here
76 
77     // protectionAbsent is 0 if there is CRC
78     static const size_t kAdtsHeaderLengthNoCrc = 7;
79     static const size_t kAdtsHeaderLengthWithCrc = 9;
80     size_t headSize = protectionAbsent ? kAdtsHeaderLengthNoCrc : kAdtsHeaderLengthWithCrc;
81     if (headSize > frameSize) {
82         SL_LOGE("AacAdtsExtractor:: getFrameSize() returns 0 (frameSize %zu < headSize %zu)",
83                 frameSize, headSize);
84         return 0;
85     }
86 
87     //SL_LOGV("AacAdtsExtractor:: getFrameSize() returns %u", frameSize);
88 
89     return frameSize;
90 }
91 
92 
AacAdtsExtractor(const sp<DataSource> & source)93 AacAdtsExtractor::AacAdtsExtractor(const sp<DataSource> &source)
94     : mDataSource(source),
95       mInitCheck(NO_INIT),
96       mFrameDurationUs(0) {
97 
98     // difference with framework's AAC Extractor: we have already validated the data
99     // upon enqueueing, so no need to sniff the data:
100     //    String8 mimeType;
101     //    float confidence;
102     //    if (!SniffAAC(mDataSource, &mimeType, &confidence, NULL)) {
103     //        return;
104     //    }
105 
106     uint8_t profile, sf_index, channel, header[2];
107     ssize_t readSize = mDataSource->readAt(2, &header, 2);
108     if (readSize != 2) {
109         SL_LOGE("Unable to determine sample rate");
110         return;
111     }
112 
113     profile = (header[0] >> 6) & 0x3;
114     sf_index = (header[0] >> 2) & 0xf;
115     uint32_t sr = get_sample_rate(sf_index);
116 
117     if (sr == 0) {
118         SL_LOGE("Invalid sample rate");
119         return;
120     }
121     channel = (header[0] & 0x1) << 2 | (header[1] >> 6);
122 
123     SL_LOGV("AacAdtsExtractor has found sr=%d channel=%d", sr, channel);
124 
125     // Never fails
126     mMeta = MakeAACCodecSpecificData(profile, sf_index, channel);
127 
128     // Round up and get the duration of each frame
129     mFrameDurationUs = (1024 * 1000000ll + (sr - 1)) / sr;
130 
131     off64_t streamSize;
132     if (mDataSource->getSize(&streamSize) == OK) {
133         off64_t offset = 0, numFrames = 0;
134         while (offset < streamSize) {
135             size_t frameSize;
136             if ((frameSize = getFrameSize(mDataSource, offset)) == 0) {
137                 // Usually frameSize == 0 due to EOS is benign (and getFrameSize() doesn't SL_LOGE),
138                 // but in this case we were told the total size of the data source and so an EOS
139                 // should not happen.
140                 SL_LOGE("AacAdtsExtractor() failed querying framesize at offset=%lld", (long long) offset);
141                 return;
142             }
143 
144             offset += frameSize;
145             if (offset > streamSize) {
146                 SL_LOGE("AacAdtsExtractor() frame of size %zu at offset=%lld is beyond EOF %lld",
147                         frameSize, (long long) offset, (long long) streamSize);
148                 return;
149             }
150             numFrames ++;
151         }
152 
153         // Compute total duration
154         int64_t duration = numFrames * mFrameDurationUs;
155         mMeta->setInt64(kKeyDuration, duration);
156     }
157 
158     // Any earlier "return" would leave mInitCheck as NO_INIT, causing later methods to fail quickly
159     mInitCheck = OK;
160 
161 }
162 
163 
~AacAdtsExtractor()164 AacAdtsExtractor::~AacAdtsExtractor() {
165 }
166 
167 
getMetaData()168 sp<MetaData> AacAdtsExtractor::getMetaData() {
169     sp<MetaData> meta = new MetaData;
170 
171     if (mInitCheck != OK) {
172         return meta;
173     }
174 
175     meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC_ADTS);
176 
177     return meta;
178 }
179 
180 
countTracks()181 size_t AacAdtsExtractor::countTracks() {
182     return mInitCheck == OK ? 1 : 0;
183 }
184 
185 
getTrack(size_t index)186 sp<MediaSource> AacAdtsExtractor::getTrack(size_t index) {
187     if (mInitCheck != OK || index != 0) {
188         return NULL;
189     }
190 
191     return new AacAdtsSource(mDataSource, mMeta, mFrameDurationUs);
192 }
193 
194 
getTrackMetaData(size_t index,uint32_t flags)195 sp<MetaData> AacAdtsExtractor::getTrackMetaData(size_t index, uint32_t flags) {
196     if (mInitCheck != OK || index != 0) {
197         return NULL;
198     }
199 
200     return mMeta;
201 }
202 
203 
204 ////////////////////////////////////////////////////////////////////////////////
205 
206 // 8192 = 2^13, 13bit AAC frame size (in bytes)
207 const size_t AacAdtsSource::kMaxFrameSize = 8192;
208 
AacAdtsSource(const sp<DataSource> & source,const sp<MetaData> & meta,int64_t frame_duration_us)209 AacAdtsSource::AacAdtsSource(
210         const sp<DataSource> &source, const sp<MetaData> &meta,
211         int64_t frame_duration_us)
212     : mDataSource(source),
213       mMeta(meta),
214       mOffset(0),
215       mCurrentTimeUs(0),
216       mStarted(false),
217       mGroup(NULL),
218       mFrameDurationUs(frame_duration_us) {
219 }
220 
221 
~AacAdtsSource()222 AacAdtsSource::~AacAdtsSource() {
223     if (mStarted) {
224         stop();
225     }
226 }
227 
228 
start(MetaData * params)229 status_t AacAdtsSource::start(MetaData *params) {
230     CHECK(!mStarted);
231 
232     mOffset = 0;
233     mCurrentTimeUs = 0;
234     mGroup = new MediaBufferGroup;
235     mGroup->add_buffer(new MediaBuffer(kMaxFrameSize));
236     mStarted = true;
237 
238     return OK;
239 }
240 
241 
stop()242 status_t AacAdtsSource::stop() {
243     CHECK(mStarted);
244 
245     delete mGroup;
246     mGroup = NULL;
247 
248     mStarted = false;
249     return OK;
250 }
251 
252 
getFormat()253 sp<MetaData> AacAdtsSource::getFormat() {
254     return mMeta;
255 }
256 
257 
read(MediaBuffer ** out,const ReadOptions * options)258 status_t AacAdtsSource::read(
259         MediaBuffer **out, const ReadOptions *options) {
260     *out = NULL;
261 
262     int64_t seekTimeUs;
263     ReadOptions::SeekMode mode;
264     if (options && options->getSeekTo(&seekTimeUs, &mode)) {
265         // difference with framework's AAC Extractor: no seeking
266         SL_LOGE("Can't seek in AAC ADTS buffer queue");
267     }
268 
269     size_t frameSize, frameSizeWithoutHeader;
270     SL_LOGV("AacAdtsSource::read() offset=%lld", mOffset);
271     if ((frameSize = getFrameSize(mDataSource, mOffset)) == 0) {
272         // EOS is normal, not an error
273         SL_LOGV("AacAdtsSource::read() returns EOS");
274         return ERROR_END_OF_STREAM;
275     }
276 
277     MediaBuffer *buffer;
278     status_t err = mGroup->acquire_buffer(&buffer);
279     if (err != OK) {
280         return err;
281     }
282 
283     frameSizeWithoutHeader = frameSize - ADTS_HEADER_LENGTH;
284     ssize_t readSize = mDataSource->readAt(mOffset + ADTS_HEADER_LENGTH, buffer->data(),
285             frameSizeWithoutHeader);
286     //SL_LOGV("AacAdtsSource::read() readAt returned %u bytes", readSize);
287     if (readSize != (ssize_t)frameSizeWithoutHeader) {
288         SL_LOGW("AacAdtsSource::read() readSize != frameSizeWithoutHeader");
289         buffer->release();
290         buffer = NULL;
291         return ERROR_IO;
292     }
293 
294     buffer->set_range(0, frameSizeWithoutHeader);
295     buffer->meta_data()->setInt64(kKeyTime, mCurrentTimeUs);
296     buffer->meta_data()->setInt32(kKeyIsSyncFrame, 1);
297 
298     mOffset += frameSize;
299     mCurrentTimeUs += mFrameDurationUs;
300 
301     *out = buffer;
302     return OK;
303 }
304 
305 }  // namespace android
306