NdkMediaExtractor.cpp revision e419d7cd5c62b4b5866a45d59c5770bb470193c1
1/*
2 * Copyright (C) 2014 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#define LOG_NDEBUG 0
18#define LOG_TAG "NdkMediaExtractor"
19
20
21#include "NdkMediaError.h"
22#include "NdkMediaExtractor.h"
23#include "NdkMediaFormatPriv.h"
24
25
26#include <utils/Log.h>
27#include <utils/StrongPointer.h>
28#include <media/hardware/CryptoAPI.h>
29#include <media/stagefright/foundation/ABuffer.h>
30#include <media/stagefright/foundation/AMessage.h>
31#include <media/stagefright/MetaData.h>
32#include <media/stagefright/NuMediaExtractor.h>
33#include <media/IMediaHTTPService.h>
34#include <android_runtime/AndroidRuntime.h>
35#include <android_util_Binder.h>
36
37#include <jni.h>
38
39using namespace android;
40
41static media_status_t translate_error(status_t err) {
42    if (err == OK) {
43        return AMEDIA_OK;
44    }
45    ALOGE("sf error code: %d", err);
46    return AMEDIA_ERROR_UNKNOWN;
47}
48
49struct AMediaExtractor {
50    sp<NuMediaExtractor> mImpl;
51    sp<ABuffer> mPsshBuf;
52
53};
54
55extern "C" {
56
57EXPORT
58AMediaExtractor* AMediaExtractor_new() {
59    ALOGV("ctor");
60    AMediaExtractor *mData = new AMediaExtractor();
61    mData->mImpl = new NuMediaExtractor();
62    return mData;
63}
64
65EXPORT
66media_status_t AMediaExtractor_delete(AMediaExtractor *mData) {
67    ALOGV("dtor");
68    delete mData;
69    return AMEDIA_OK;
70}
71
72EXPORT
73media_status_t AMediaExtractor_setDataSourceFd(AMediaExtractor *mData, int fd, off64_t offset, off64_t length) {
74    ALOGV("setDataSource(%d, %lld, %lld)", fd, offset, length);
75    return translate_error(mData->mImpl->setDataSource(fd, offset, length));
76}
77
78EXPORT
79media_status_t AMediaExtractor_setDataSource(AMediaExtractor *mData, const char *location) {
80    ALOGV("setDataSource(%s)", location);
81    // TODO: add header support
82
83    JNIEnv *env = AndroidRuntime::getJNIEnv();
84    jobject service = NULL;
85    if (env == NULL) {
86        ALOGE("setDataSource(path) must be called from Java thread");
87        env->ExceptionClear();
88        return AMEDIA_ERROR_UNSUPPORTED;
89    }
90
91    jclass mediahttpclass = env->FindClass("android/media/MediaHTTPService");
92    if (mediahttpclass == NULL) {
93        ALOGE("can't find MediaHttpService");
94        env->ExceptionClear();
95        return AMEDIA_ERROR_UNSUPPORTED;
96    }
97
98    jmethodID mediaHttpCreateMethod = env->GetStaticMethodID(mediahttpclass,
99            "createHttpServiceBinderIfNecessary", "(Ljava/lang/String;)Landroid/os/IBinder;");
100    if (mediaHttpCreateMethod == NULL) {
101        ALOGE("can't find method");
102        env->ExceptionClear();
103        return AMEDIA_ERROR_UNSUPPORTED;
104    }
105
106    jstring jloc = env->NewStringUTF(location);
107
108    service = env->CallStaticObjectMethod(mediahttpclass, mediaHttpCreateMethod, jloc);
109    env->DeleteLocalRef(jloc);
110
111    sp<IMediaHTTPService> httpService;
112    if (service != NULL) {
113        sp<IBinder> binder = ibinderForJavaObject(env, service);
114        httpService = interface_cast<IMediaHTTPService>(binder);
115    }
116
117    status_t err = mData->mImpl->setDataSource(httpService, location, NULL);
118    env->ExceptionClear();
119    return translate_error(err);
120}
121
122EXPORT
123size_t AMediaExtractor_getTrackCount(AMediaExtractor *mData) {
124    return mData->mImpl->countTracks();
125}
126
127EXPORT
128AMediaFormat* AMediaExtractor_getTrackFormat(AMediaExtractor *mData, size_t idx) {
129    sp<AMessage> format;
130    mData->mImpl->getTrackFormat(idx, &format);
131    return AMediaFormat_fromMsg(&format);
132}
133
134EXPORT
135media_status_t AMediaExtractor_selectTrack(AMediaExtractor *mData, size_t idx) {
136    ALOGV("selectTrack(%z)", idx);
137    return translate_error(mData->mImpl->selectTrack(idx));
138}
139
140EXPORT
141media_status_t AMediaExtractor_unselectTrack(AMediaExtractor *mData, size_t idx) {
142    ALOGV("unselectTrack(%z)", idx);
143    return translate_error(mData->mImpl->unselectTrack(idx));
144}
145
146EXPORT
147bool AMediaExtractor_advance(AMediaExtractor *mData) {
148    //ALOGV("advance");
149    return mData->mImpl->advance();
150}
151
152EXPORT
153ssize_t AMediaExtractor_readSampleData(AMediaExtractor *mData, uint8_t *buffer, size_t capacity) {
154    //ALOGV("readSampleData");
155    sp<ABuffer> tmp = new ABuffer(buffer, capacity);
156    if (mData->mImpl->readSampleData(tmp) == OK) {
157        return tmp->size();
158    }
159    return -1;
160}
161
162EXPORT
163uint32_t AMediaExtractor_getSampleFlags(AMediaExtractor *mData) {
164    int sampleFlags = 0;
165    sp<MetaData> meta;
166    status_t err = mData->mImpl->getSampleMeta(&meta);
167    if (err != OK) {
168        return -1;
169    }
170    int32_t val;
171    if (meta->findInt32(kKeyIsSyncFrame, &val) && val != 0) {
172        sampleFlags |= AMEDIAEXTRACTOR_SAMPLE_FLAG_SYNC;
173    }
174
175    uint32_t type;
176    const void *data;
177    size_t size;
178    if (meta->findData(kKeyEncryptedSizes, &type, &data, &size)) {
179        sampleFlags |= AMEDIAEXTRACTOR_SAMPLE_FLAG_ENCRYPTED;
180    }
181    return sampleFlags;
182}
183
184EXPORT
185int AMediaExtractor_getSampleTrackIndex(AMediaExtractor *mData) {
186    size_t idx;
187    if (mData->mImpl->getSampleTrackIndex(&idx) != OK) {
188        return -1;
189    }
190    return idx;
191}
192
193EXPORT
194int64_t AMediaExtractor_getSampletime(AMediaExtractor *mData) {
195    int64_t time;
196    if (mData->mImpl->getSampleTime(&time) != OK) {
197        return -1;
198    }
199    return time;
200}
201
202EXPORT
203PsshInfo* AMediaExtractor_getPsshInfo(AMediaExtractor *ex) {
204
205    if (ex->mPsshBuf != NULL) {
206        return (PsshInfo*) ex->mPsshBuf->data();
207    }
208
209    sp<AMessage> format;
210    ex->mImpl->getFileFormat(&format);
211    sp<ABuffer> buffer;
212    if(!format->findBuffer("pssh", &buffer)) {
213        return NULL;
214    }
215
216    // the format of the buffer is 1 or more of:
217    //    {
218    //        16 byte uuid
219    //        4 byte data length N
220    //        N bytes of data
221    //    }
222
223    // Determine the number of entries in the source data.
224    // Since we got the data from stagefright, we trust it is valid and properly formatted.
225    const uint8_t* data = buffer->data();
226    size_t len = buffer->size();
227    size_t numentries = 0;
228    while (len > 0) {
229        numentries++;
230
231        // skip uuid
232        data += 16;
233        len -= 16;
234
235        // get data length
236        uint32_t datalen = *((uint32_t*)data);
237        data += 4;
238        len -= 4;
239
240        // skip the data
241        data += datalen;
242        len -= datalen;
243    }
244
245    // there are <numentries> in the buffer, we need
246    // (source buffer size) + 4 + (4 * numentries) bytes for the PsshInfo structure
247    size_t newsize = buffer->size() + 4 + (4 * numentries);
248    ex->mPsshBuf = new ABuffer(newsize);
249    ex->mPsshBuf->setRange(0, newsize);
250
251    // copy data
252    const uint8_t* src = buffer->data();
253    uint8_t* dst = ex->mPsshBuf->data();
254    uint8_t* dstdata = dst + 4 + numentries * sizeof(PsshEntry);
255    *((uint32_t*)dst) = numentries;
256    dst += 4;
257    for (size_t i = 0; i < numentries; i++) {
258        // copy uuid
259        memcpy(dst, src, 16);
260        src += 16;
261        dst += 16;
262
263        // get/copy data length
264        uint32_t datalen = *((uint32_t*)src);
265        memcpy(dst, src, 4);
266        src += 4;
267        dst += 4;
268
269        // the next entry in the destination is a pointer to the actual data, which we store
270        // after the array of PsshEntry
271        memcpy(dst, &dstdata, sizeof(dstdata));
272        dst += 4;
273
274        // copy the actual data
275        memcpy(dstdata, src, datalen);
276        dstdata += datalen;
277        src += datalen;
278    }
279
280    return (PsshInfo*) ex->mPsshBuf->data();
281}
282
283EXPORT
284AMediaCodecCryptoInfo *AMediaExtractor_getSampleCryptoInfo(AMediaExtractor *ex) {
285    sp<MetaData> meta;
286    if(ex->mImpl->getSampleMeta(&meta) != 0) {
287        return NULL;
288    }
289
290    uint32_t type;
291    const void *crypteddata;
292    size_t cryptedsize;
293    if (!meta->findData(kKeyEncryptedSizes, &type, &crypteddata, &cryptedsize)) {
294        return NULL;
295    }
296    size_t numSubSamples = cryptedsize / sizeof(size_t);
297
298    const void *cleardata;
299    size_t clearsize;
300    if (meta->findData(kKeyPlainSizes, &type, &cleardata, &clearsize)) {
301        if (clearsize != cryptedsize) {
302            // The two must be of the same length.
303            return NULL;
304        }
305    }
306
307    const void *key;
308    size_t keysize;
309    if (meta->findData(kKeyCryptoIV, &type, &key, &keysize)) {
310        if (keysize != 16) {
311            // IVs must be 16 bytes in length.
312            return NULL;
313        }
314    }
315
316    const void *iv;
317    size_t ivsize;
318    if (meta->findData(kKeyCryptoIV, &type, &iv, &ivsize)) {
319        if (ivsize != 16) {
320            // IVs must be 16 bytes in length.
321            return NULL;
322        }
323    }
324
325    int32_t mode;
326    if (!meta->findInt32(kKeyCryptoMode, &mode)) {
327        mode = CryptoPlugin::kMode_AES_CTR;
328    }
329
330    return AMediaCodecCryptoInfo_new(
331            numSubSamples,
332            (uint8_t*) key,
333            (uint8_t*) iv,
334            mode,
335            (size_t*) cleardata,
336            (size_t*) crypteddata);
337}
338
339
340} // extern "C"
341
342