• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <media/NdkMediaError.h>
22 #include <media/NdkMediaExtractor.h>
23 #include <media/NdkMediaErrorPriv.h>
24 #include <media/NdkMediaFormatPriv.h>
25 #include "NdkJavaVMHelperPriv.h"
26 #include "NdkMediaDataSourcePriv.h"
27 
28 
29 #include <inttypes.h>
30 #include <utils/Log.h>
31 #include <utils/StrongPointer.h>
32 #include <media/hardware/CryptoAPI.h>
33 #include <media/stagefright/foundation/ABuffer.h>
34 #include <media/stagefright/foundation/AMessage.h>
35 #include <media/stagefright/MetaData.h>
36 #include <media/stagefright/NuMediaExtractor.h>
37 #include <media/IMediaHTTPService.h>
38 #include <android_util_Binder.h>
39 
40 #include <jni.h>
41 
42 using namespace android;
43 
44 struct AMediaExtractor {
45     sp<NuMediaExtractor> mImpl;
46     sp<ABuffer> mPsshBuf;
47 };
48 
U32ArrayToSizeBuf(size_t numSubSamples,uint32_t * data)49 sp<ABuffer> U32ArrayToSizeBuf(size_t numSubSamples, uint32_t *data) {
50     if (numSubSamples >  SIZE_MAX / sizeof(size_t)) {
51         return NULL;
52     }
53     sp<ABuffer> sizebuf = new ABuffer(numSubSamples * sizeof(size_t));
54     size_t *sizes = (size_t *)sizebuf->data();
55     for (size_t i = 0; sizes != NULL && i < numSubSamples; i++) {
56         sizes[i] = data[i];
57     }
58     return sizebuf;
59 }
60 
61 extern "C" {
62 
63 EXPORT
AMediaExtractor_new()64 AMediaExtractor* AMediaExtractor_new() {
65     ALOGV("ctor");
66     AMediaExtractor *mData = new AMediaExtractor();
67     mData->mImpl = new NuMediaExtractor(
68         NdkJavaVMHelper::getJNIEnv() != nullptr
69                 ? NuMediaExtractor::EntryPoint::NDK_WITH_JVM
70                 : NuMediaExtractor::EntryPoint::NDK_NO_JVM );
71     return mData;
72 }
73 
74 EXPORT
AMediaExtractor_delete(AMediaExtractor * mData)75 media_status_t AMediaExtractor_delete(AMediaExtractor *mData) {
76     ALOGV("dtor");
77     delete mData;
78     return AMEDIA_OK;
79 }
80 
81 EXPORT
AMediaExtractor_setDataSourceFd(AMediaExtractor * mData,int fd,off64_t offset,off64_t length)82 media_status_t AMediaExtractor_setDataSourceFd(AMediaExtractor *mData, int fd, off64_t offset,
83         off64_t length) {
84     ALOGV("setDataSource(%d, %" PRId64 ", %" PRId64 ")", fd, offset, length);
85     return translate_error(mData->mImpl->setDataSource(fd, offset, length));
86 }
87 
AMediaExtractor_setDataSourceWithHeaders(AMediaExtractor * mData,const char * uri,int numheaders,const char * const * keys,const char * const * values)88 media_status_t AMediaExtractor_setDataSourceWithHeaders(AMediaExtractor *mData,
89         const char *uri,
90         int numheaders,
91         const char * const *keys,
92         const char * const *values) {
93 
94     ALOGV("setDataSource(%s)", uri);
95 
96     sp<MediaHTTPService> httpService = createMediaHttpService(uri);
97     if (httpService == NULL) {
98         ALOGE("can't create http service");
99         return AMEDIA_ERROR_UNSUPPORTED;
100     }
101 
102     KeyedVector<String8, String8> headers;
103     for (int i = 0; i < numheaders; ++i) {
104         String8 key8(keys[i]);
105         String8 value8(values[i]);
106         headers.add(key8, value8);
107     }
108 
109     status_t err;
110     err = mData->mImpl->setDataSource(httpService, uri, numheaders > 0 ? &headers : NULL);
111     return translate_error(err);
112 }
113 
114 EXPORT
AMediaExtractor_setDataSource(AMediaExtractor * mData,const char * location)115 media_status_t AMediaExtractor_setDataSource(AMediaExtractor *mData, const char *location) {
116     return AMediaExtractor_setDataSourceWithHeaders(mData, location, 0, NULL, NULL);
117 }
118 
119 EXPORT
AMediaExtractor_setDataSourceCustom(AMediaExtractor * mData,AMediaDataSource * src)120 media_status_t AMediaExtractor_setDataSourceCustom(AMediaExtractor* mData, AMediaDataSource *src) {
121     return translate_error(mData->mImpl->setDataSource(new NdkDataSource(src)));
122 }
123 
124 EXPORT
AMediaExtractor_getFileFormat(AMediaExtractor * mData)125 AMediaFormat* AMediaExtractor_getFileFormat(AMediaExtractor *mData) {
126     sp<AMessage> format;
127     mData->mImpl->getFileFormat(&format);
128     return AMediaFormat_fromMsg(&format);
129 }
130 
131 EXPORT
AMediaExtractor_getTrackCount(AMediaExtractor * mData)132 size_t AMediaExtractor_getTrackCount(AMediaExtractor *mData) {
133     return mData->mImpl->countTracks();
134 }
135 
136 EXPORT
AMediaExtractor_getTrackFormat(AMediaExtractor * mData,size_t idx)137 AMediaFormat* AMediaExtractor_getTrackFormat(AMediaExtractor *mData, size_t idx) {
138     sp<AMessage> format;
139     mData->mImpl->getTrackFormat(idx, &format);
140     return AMediaFormat_fromMsg(&format);
141 }
142 
143 EXPORT
AMediaExtractor_selectTrack(AMediaExtractor * mData,size_t idx)144 media_status_t AMediaExtractor_selectTrack(AMediaExtractor *mData, size_t idx) {
145     ALOGV("selectTrack(%zu)", idx);
146     return translate_error(mData->mImpl->selectTrack(idx));
147 }
148 
149 EXPORT
AMediaExtractor_unselectTrack(AMediaExtractor * mData,size_t idx)150 media_status_t AMediaExtractor_unselectTrack(AMediaExtractor *mData, size_t idx) {
151     ALOGV("unselectTrack(%zu)", idx);
152     return translate_error(mData->mImpl->unselectTrack(idx));
153 }
154 
155 EXPORT
AMediaExtractor_advance(AMediaExtractor * mData)156 bool AMediaExtractor_advance(AMediaExtractor *mData) {
157     //ALOGV("advance");
158     status_t err = mData->mImpl->advance();
159     if (err == ERROR_END_OF_STREAM) {
160         return false;
161     } else if (err != OK) {
162         ALOGE("sf error code: %d", err);
163         return false;
164     }
165     return true;
166 }
167 
168 EXPORT
AMediaExtractor_seekTo(AMediaExtractor * ex,int64_t seekPosUs,SeekMode mode)169 media_status_t AMediaExtractor_seekTo(AMediaExtractor *ex, int64_t seekPosUs, SeekMode mode) {
170     android::MediaSource::ReadOptions::SeekMode sfmode;
171     if (mode == AMEDIAEXTRACTOR_SEEK_PREVIOUS_SYNC) {
172         sfmode = android::MediaSource::ReadOptions::SEEK_PREVIOUS_SYNC;
173     } else if (mode == AMEDIAEXTRACTOR_SEEK_CLOSEST_SYNC) {
174         sfmode = android::MediaSource::ReadOptions::SEEK_CLOSEST_SYNC;
175     } else {
176         sfmode = android::MediaSource::ReadOptions::SEEK_NEXT_SYNC;
177     }
178 
179     return translate_error(ex->mImpl->seekTo(seekPosUs, sfmode));
180 }
181 
182 EXPORT
AMediaExtractor_readSampleData(AMediaExtractor * mData,uint8_t * buffer,size_t capacity)183 ssize_t AMediaExtractor_readSampleData(AMediaExtractor *mData, uint8_t *buffer, size_t capacity) {
184     //ALOGV("readSampleData");
185     sp<ABuffer> tmp = new ABuffer(buffer, capacity);
186     if (mData->mImpl->readSampleData(tmp) == OK) {
187         return tmp->size();
188     }
189     return -1;
190 }
191 
192 EXPORT
AMediaExtractor_getSampleSize(AMediaExtractor * mData)193 ssize_t AMediaExtractor_getSampleSize(AMediaExtractor *mData) {
194     size_t sampleSize;
195     status_t err = mData->mImpl->getSampleSize(&sampleSize);
196     if (err != OK) {
197         return -1;
198     }
199     return sampleSize;
200 }
201 
202 EXPORT
AMediaExtractor_getSampleFlags(AMediaExtractor * mData)203 uint32_t AMediaExtractor_getSampleFlags(AMediaExtractor *mData) {
204     int sampleFlags = 0;
205     sp<MetaData> meta;
206     status_t err = mData->mImpl->getSampleMeta(&meta);
207     if (err != OK) {
208         return -1;
209     }
210     int32_t val;
211     if (meta->findInt32(kKeyIsSyncFrame, &val) && val != 0) {
212         sampleFlags |= AMEDIAEXTRACTOR_SAMPLE_FLAG_SYNC;
213     }
214 
215     uint32_t type;
216     const void *data;
217     size_t size;
218     if (meta->findData(kKeyEncryptedSizes, &type, &data, &size)) {
219         sampleFlags |= AMEDIAEXTRACTOR_SAMPLE_FLAG_ENCRYPTED;
220     }
221     return sampleFlags;
222 }
223 
224 EXPORT
AMediaExtractor_getSampleTrackIndex(AMediaExtractor * mData)225 int AMediaExtractor_getSampleTrackIndex(AMediaExtractor *mData) {
226     size_t idx;
227     if (mData->mImpl->getSampleTrackIndex(&idx) != OK) {
228         return -1;
229     }
230     return idx;
231 }
232 
233 EXPORT
AMediaExtractor_getSampleTime(AMediaExtractor * mData)234 int64_t AMediaExtractor_getSampleTime(AMediaExtractor *mData) {
235     int64_t time;
236     if (mData->mImpl->getSampleTime(&time) != OK) {
237         return -1;
238     }
239     return time;
240 }
241 
242 EXPORT
AMediaExtractor_getPsshInfo(AMediaExtractor * ex)243 PsshInfo* AMediaExtractor_getPsshInfo(AMediaExtractor *ex) {
244 
245     if (ex->mPsshBuf != NULL) {
246         return (PsshInfo*) ex->mPsshBuf->data();
247     }
248 
249     sp<AMessage> format;
250     ex->mImpl->getFileFormat(&format);
251     sp<ABuffer> buffer;
252     if(!format->findBuffer("pssh", &buffer)) {
253         return NULL;
254     }
255 
256     // the format of the buffer is 1 or more of:
257     //    {
258     //        16 byte uuid
259     //        4 byte data length N
260     //        N bytes of data
261     //    }
262 
263     // Determine the number of entries in the source data.
264     // Since we got the data from stagefright, we trust it is valid and properly formatted.
265     const uint8_t* data = buffer->data();
266     size_t len = buffer->size();
267     size_t numentries = 0;
268     while (len > 0) {
269         numentries++;
270 
271         if (len < 16) {
272             ALOGE("invalid PSSH data");
273             return NULL;
274         }
275         // skip uuid
276         data += 16;
277         len -= 16;
278 
279         // get data length
280         if (len < 4) {
281             ALOGE("invalid PSSH data");
282             return NULL;
283         }
284         uint32_t datalen = *((uint32_t*)data);
285         data += 4;
286         len -= 4;
287 
288         if (len < datalen) {
289             ALOGE("invalid PSSH data");
290             return NULL;
291         }
292         // skip the data
293         data += datalen;
294         len -= datalen;
295     }
296 
297     // there are <numentries> in the source buffer, we need
298     // (source buffer size) - (sizeof(uint32_t) * numentries) + sizeof(size_t)
299     //  + ((sizeof(void*) + sizeof(size_t)) * numentries) bytes for the PsshInfo structure
300     // Or in other words, the data lengths in the source structure are replaced by size_t
301     // (which may be the same size or larger, for 64 bit), and in addition there is an
302     // extra pointer for each entry, and an extra size_t for the entire PsshInfo.
303     size_t newsize = buffer->size() - (sizeof(uint32_t) * numentries) + sizeof(size_t)
304             + ((sizeof(void*) + sizeof(size_t)) * numentries);
305     if (newsize <= buffer->size()) {
306         ALOGE("invalid PSSH data");
307         return NULL;
308     }
309     ex->mPsshBuf = new ABuffer(newsize);
310     ex->mPsshBuf->setRange(0, newsize);
311 
312     // copy data
313     const uint8_t* src = buffer->data();
314     uint8_t* dst = ex->mPsshBuf->data();
315     uint8_t* dstdata = dst + sizeof(size_t) + numentries * sizeof(PsshEntry);
316     *((size_t*)dst) = numentries;
317     dst += sizeof(size_t);
318     for (size_t i = 0; i < numentries; i++) {
319         // copy uuid
320         memcpy(dst, src, 16);
321         src += 16;
322         dst += 16;
323 
324         // get/copy data length
325         uint32_t datalen = *((uint32_t*)src);
326         *((size_t*)dst) = datalen;
327         src += sizeof(uint32_t);
328         dst += sizeof(size_t);
329 
330         // the next entry in the destination is a pointer to the actual data, which we store
331         // after the array of PsshEntry
332         *((void**)dst) = dstdata;
333         dst += sizeof(void*);
334 
335         // copy the actual data
336         memcpy(dstdata, src, datalen);
337         dstdata += datalen;
338         src += datalen;
339     }
340 
341     return (PsshInfo*) ex->mPsshBuf->data();
342 }
343 
344 EXPORT
AMediaExtractor_getSampleCryptoInfo(AMediaExtractor * ex)345 AMediaCodecCryptoInfo *AMediaExtractor_getSampleCryptoInfo(AMediaExtractor *ex) {
346     sp<MetaData> meta;
347     if(ex->mImpl->getSampleMeta(&meta) != 0) {
348         return NULL;
349     }
350 
351     uint32_t type;
352     const void *crypteddata;
353     size_t cryptedsize;
354     if (!meta->findData(kKeyEncryptedSizes, &type, &crypteddata, &cryptedsize)) {
355         return NULL;
356     }
357     size_t numSubSamples = cryptedsize / sizeof(uint32_t);
358 
359     const void *cleardata;
360     size_t clearsize;
361     if (meta->findData(kKeyPlainSizes, &type, &cleardata, &clearsize)) {
362         if (clearsize != cryptedsize) {
363             // The two must be of the same length.
364             return NULL;
365         }
366     }
367 
368     const void *key;
369     size_t keysize;
370     if (meta->findData(kKeyCryptoKey, &type, &key, &keysize)) {
371         if (keysize != 16) {
372             // Keys must be 16 bytes in length.
373             return NULL;
374         }
375     }
376 
377     const void *iv;
378     size_t ivsize;
379     if (meta->findData(kKeyCryptoIV, &type, &iv, &ivsize)) {
380         if (ivsize != 16) {
381             // IVs must be 16 bytes in length.
382             return NULL;
383         }
384     }
385 
386     int32_t mode;
387     if (!meta->findInt32(kKeyCryptoMode, &mode)) {
388         mode = CryptoPlugin::kMode_AES_CTR;
389     }
390 
391     if (sizeof(uint32_t) != sizeof(size_t)) {
392         sp<ABuffer> clearbuf   = U32ArrayToSizeBuf(numSubSamples, (uint32_t *)cleardata);
393         sp<ABuffer> cryptedbuf = U32ArrayToSizeBuf(numSubSamples, (uint32_t *)crypteddata);
394         cleardata   = clearbuf    == NULL ? NULL : clearbuf->data();
395         crypteddata = crypteddata == NULL ? NULL : cryptedbuf->data();
396         if(crypteddata == NULL || cleardata == NULL) {
397             return NULL;
398         }
399     }
400 
401     return AMediaCodecCryptoInfo_new(
402             numSubSamples,
403             (uint8_t*) key,
404             (uint8_t*) iv,
405             (cryptoinfo_mode_t) mode,
406             (size_t*) cleardata,
407             (size_t*) crypteddata);
408 }
409 
410 EXPORT
AMediaExtractor_getCachedDuration(AMediaExtractor * ex)411 int64_t AMediaExtractor_getCachedDuration(AMediaExtractor *ex) {
412     bool eos;
413     int64_t durationUs;
414     if (ex->mImpl->getCachedDuration(&durationUs, &eos)) {
415         return durationUs;
416     }
417     return -1;
418 }
419 
420 EXPORT
AMediaExtractor_getSampleFormat(AMediaExtractor * ex,AMediaFormat * fmt)421 media_status_t AMediaExtractor_getSampleFormat(AMediaExtractor *ex, AMediaFormat *fmt) {
422     ALOGV("AMediaExtractor_getSampleFormat");
423     if (fmt == NULL) {
424         return AMEDIA_ERROR_INVALID_PARAMETER;
425     }
426 
427     sp<MetaData> sampleMeta;
428     status_t err = ex->mImpl->getSampleMeta(&sampleMeta);
429     if (err != OK) {
430         return translate_error(err);
431     }
432 #ifdef LOG_NDEBUG
433     sampleMeta->dumpToLog();
434 #endif
435 
436     sp<AMessage> meta;
437     AMediaFormat_getFormat(fmt, &meta);
438     meta->clear();
439 
440     int32_t layerId;
441     if (sampleMeta->findInt32(kKeyTemporalLayerId, &layerId)) {
442         meta->setInt32(AMEDIAFORMAT_KEY_TEMPORAL_LAYER_ID, layerId);
443     }
444 
445     size_t trackIndex;
446     err = ex->mImpl->getSampleTrackIndex(&trackIndex);
447     if (err == OK) {
448         meta->setInt32(AMEDIAFORMAT_KEY_TRACK_INDEX, trackIndex);
449         sp<AMessage> trackFormat;
450         AString mime;
451         err = ex->mImpl->getTrackFormat(trackIndex, &trackFormat);
452         if (err == OK
453                 && trackFormat != NULL
454                 && trackFormat->findString(AMEDIAFORMAT_KEY_MIME, &mime)) {
455             meta->setString(AMEDIAFORMAT_KEY_MIME, mime);
456         }
457     }
458 
459     int64_t durationUs;
460     if (sampleMeta->findInt64(kKeyDuration, &durationUs)) {
461         meta->setInt64(AMEDIAFORMAT_KEY_DURATION, durationUs);
462     }
463 
464     uint32_t dataType; // unused
465     const void *seiData;
466     size_t seiLength;
467     if (sampleMeta->findData(kKeySEI, &dataType, &seiData, &seiLength)) {
468         sp<ABuffer> sei = ABuffer::CreateAsCopy(seiData, seiLength);;
469         meta->setBuffer(AMEDIAFORMAT_KEY_SEI, sei);
470     }
471 
472     const void *mpegUserDataPointer;
473     size_t mpegUserDataLength;
474     if (sampleMeta->findData(
475             kKeyMpegUserData, &dataType, &mpegUserDataPointer, &mpegUserDataLength)) {
476         sp<ABuffer> mpegUserData = ABuffer::CreateAsCopy(mpegUserDataPointer, mpegUserDataLength);
477         meta->setBuffer(AMEDIAFORMAT_KEY_MPEG_USER_DATA, mpegUserData);
478     }
479 
480     const void *audioPresentationsPointer;
481     size_t audioPresentationsLength;
482     if (sampleMeta->findData(
483             kKeyAudioPresentationInfo, &dataType,
484             &audioPresentationsPointer, &audioPresentationsLength)) {
485         sp<ABuffer> audioPresentationsData = ABuffer::CreateAsCopy(
486                 audioPresentationsPointer, audioPresentationsLength);
487         meta->setBuffer(AMEDIAFORMAT_KEY_AUDIO_PRESENTATION_INFO, audioPresentationsData);
488     }
489 
490     int64_t val64;
491     if (sampleMeta->findInt64(kKeySampleFileOffset, &val64)) {
492         meta->setInt64("sample-file-offset", val64);
493         ALOGV("SampleFileOffset Found");
494     }
495     if (sampleMeta->findInt64(kKeyLastSampleIndexInChunk, &val64)) {
496         meta->setInt64("last-sample-index-in-chunk" /*AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK*/,
497                        val64);
498         ALOGV("kKeyLastSampleIndexInChunk Found");
499     }
500 
501     ALOGV("AMediaFormat_toString:%s", AMediaFormat_toString(fmt));
502 
503     return AMEDIA_OK;
504 }
505 
506 } // extern "C"
507 
508