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