1 /*
2  * Copyright (C) 2020 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 #include <NdkMediaExtractor.h>
17 #include <android/asset_manager.h>
18 #include <android/asset_manager_jni.h>
19 #include <jni.h>
20 #include <nativehelper/ScopedUtfChars.h>
21 #include <thread>
22 
23 extern "C" JNIEXPORT void JNICALL
Java_android_media_cts_MediaExtractorDeviceSideTest_extractUsingNdkMediaExtractor(JNIEnv * env,jobject,jobject assetManager,jstring assetPath,jboolean withAttachedJvm)24 Java_android_media_cts_MediaExtractorDeviceSideTest_extractUsingNdkMediaExtractor(
25         JNIEnv* env, jobject, jobject assetManager, jstring assetPath, jboolean withAttachedJvm) {
26     ScopedUtfChars scopedPath(env, assetPath);
27 
28     AAssetManager* nativeAssetManager = AAssetManager_fromJava(env, assetManager);
29     AAsset* asset = AAssetManager_open(nativeAssetManager, scopedPath.c_str(), AASSET_MODE_RANDOM);
30     off_t start;
31     off_t length;
32     int fd = AAsset_openFileDescriptor(asset, &start, &length);
33 
34     auto mediaExtractorTask = [=]() {
35         AMediaExtractor* mediaExtractor = AMediaExtractor_new();
36         AMediaExtractor_setDataSourceFd(mediaExtractor, fd, start, length);
37         AMediaExtractor_delete(mediaExtractor);
38     };
39 
40     if (withAttachedJvm) {
41         // The currently running thread is a Java thread so it has an attached JVM.
42         mediaExtractorTask();
43     } else {
44         // We want to run the MediaExtractor calls on a thread with no JVM, so we spawn a new native
45         // thread which will not have an associated JVM. We execute the MediaExtractor calls on the
46         // new thread, and immediately join its execution so as to wait for its completion.
47         std::thread(mediaExtractorTask).join();
48     }
49     // TODO: Make resource management automatic through scoped handles.
50     close(fd);
51     AAsset_close(asset);
52 }
53