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