using the android native development kit (ndk)

70
Using the Android* Native Development Kit (NDK) Xavier Hallade, Technical Marketing Engineer @ph0b - ph0b.com

Upload: ph0b

Post on 28-Nov-2014

2.632 views

Category:

Technology


0 download

DESCRIPTION

Learn how to use the Android NDK and integrate C/C++ code in your Android apps.

TRANSCRIPT

Page 1: Using the Android Native Development Kit (NDK)

Using the Android* Native Development Kit

(NDK)

Xavier Hallade, Technical Marketing Engineer

@ph0b - ph0b.com

Page 2: Using the Android Native Development Kit (NDK)

3

Agenda

• The Android* Native Development Kit (NDK)

• Developing an application that uses the NDK

• Supporting several CPU architectures

• Summary and Q&A

Break

• Debugging

• Optimizing

• Intel® Tools and Libraries

• Summary and Q&A

Page 3: Using the Android Native Development Kit (NDK)

4

Agenda

• The Android* Native Development Kit (NDK)

• Developing an application that uses the NDK

• Supporting several CPU architectures

• Summary and Q&A

Break

• Debugging

• Optimizing

• Intel® Tools and Libraries

• Summary and Q&A

Page 4: Using the Android Native Development Kit (NDK)

5

Android* Native Development Kit (NDK)

What is it?

Build scripts/toolkit to incorporate native code in Android* apps via the Java Native Interface (JNI)

Why use it?

Performance

e.g., complex algorithms, multimedia applications, games

Differentiation

app that takes advantage of direct CPU/HW access

e.g., using SSSE3 for optimization

Fluid and lag-free animations

Software code reuse

Why not use it?

Performance improvement isn’t alwaysguaranteed, in contrary to the added complexity

Page 5: Using the Android Native Development Kit (NDK)

6

C/C++Code

Makefilendk-build

Mix with Java*

GDB debug

Java Framework

Java Application

SDK APIs

JNI

Native Libs

Android* Applications

NDK APIs

Bionic C Library

NDK Application Development

Using JNI

Page 6: Using the Android Native Development Kit (NDK)

7

NDK Platform

Android* NDK Application

Dalvik* Application

Android app

Class

Java Source

Compile with

Javac

Java Native

Library Class

Java* Native

Library

Compile with

Javac

Create C header with

javah -jni

Header file C/C++ Source

Code

Compile and Link C

Code

Dynamic

Library

Application

Files

Makefile

Optional thanks to

JNI_Onload

Page 7: Using the Android Native Development Kit (NDK)

8

Compatibility with Standard C/C++

Bionic C Library:

Lighter than standard GNU C Library

Not POSIX compliant

pthread support included, but limited

No System-V IPCs

Access to Android* system properties

Bionic is not binary-compatible with the standard C library

It means you generally need to (re)compile everything using the Android NDK toolchain

Page 8: Using the Android Native Development Kit (NDK)

9

Android* C++ SupportBy default, libstdc++ is used. It lacks:

Standard C++ Library support (except some headers)

C++ exceptions support

RTTI support

Fortunately, you have other libs available with the NDK:

Runtime Exceptions RTTI STL

system No No No

gabi++ Yes Yes No

stlport Yes Yes Yes

gnustl Yes Yes Yes

Choose which library to compile

against in your Makefile

(Application.mk file):

APP_STL := gnustl_shared

Postfix the runtime with _static

or _shared

For using C++ features, you also need to enable these in your Makefile:LOCAL_CPP_FEATURES += exceptions rtti

Page 9: Using the Android Native Development Kit (NDK)

10

Agenda

• The Android* Native Development Kit (NDK)

• Developing an application that uses the NDK

• Supporting several CPU architectures

• Summary and Q&A

Break

• Debugging

• Optimizing

• Intel® Tools and Libraries

• Summary and Q&A

Page 10: Using the Android Native Development Kit (NDK)

11

PSI

TS

PIDs

Installing the Android* NDKNDK is a platform dependant archive:

It provides:

A build environment

Android* headers and libraries

Documentation and samples

(these are very useful)

You can integrate it with Eclipse ADT:

We’ll talk about Android studio integration later

Page 11: Using the Android Native Development Kit (NDK)

12

Standard Android* Project Structure

Native Sources - JNI Folder 1. Create JNI folder for native sources

3. Create Android.mk Makefile

4. Build Native libraries using NDK-BUILD script.

2. Reuse or create native c/c++ sources

NDK-BUILD will automatically create ABI libs folders.

Manually Adding Native Code to an Android* Project

Page 12: Using the Android Native Development Kit (NDK)

13

Adding NDK Support to your Eclipse Android*

Project

Page 13: Using the Android Native Development Kit (NDK)

14

Android* NDK Samples

Sample App Type

hello-jni Call a native function written in C from Java*.

bitmap-plasma Access an Android* Bitmap object from C.

san-angeles EGL and OpenGL* ES code in C.

hello-gl2 EGL setup in Java and OpenGL ES code in C.

native-activityC only OpenGL sample

(no Java, uses the NativeActivity class).

native-plasmaC only OpenGL sample

(also uses the NativeActivity class).

Page 14: Using the Android Native Development Kit (NDK)

15

Focus on Native Activity

Only native code in the project

android_main() entry point running in its own thread

Event loop to get input data and frame drawing messages

/**

* This is the main entry point of a native application that is using

* android_native_app_glue. It runs in its own thread, with its own

* event loop for receiving input events and doing other things.

*/

void android_main(struct android_app* state);

Page 15: Using the Android Native Development Kit (NDK)

16

PSI

TS

PIDs

Integrating Native Functions with Java*

Declare native methods in your Android* application (Java*) using the ‘native’ keyword:

public native String stringFromJNI();

Provide a native shared library built with the NDK that contains the methods used by your application:

libMyLib.so

Your application must load the shared library (before use… during class load for example):

static {

System.loadLibrary("MyLib");

}

There is two ways to associate your native code to the Java methods: javah and JNI_OnLoad

Page 16: Using the Android Native Development Kit (NDK)

17

Javah Method

“javah” helps automatically generate the appropriate JNI header stubs

based on the Java* source files from the compiled Java classes files:

Example:

> javah –d jni –classpath bin/classes \

com.example.hellojni.HelloJni

Generates com_example_hellojni_HelloJni.h file with this

definition:

JNIEXPORT jstring JNICALL

Java_com_example_hellojni_HelloJni_stringFromJNI(JNIEn

v *, jobject);

Page 17: Using the Android Native Development Kit (NDK)

18

Javah Method

C function that will be automatically mapped:jstring

Java_com_example_hellojni_HelloJni_stringFromJNI(JNIEnv* env,

jobject thiz )

{

return (*env)->NewStringUTF(env, "Hello from JNI !");

}

...

{

...

tv.setText( stringFromJNI() );

...

}

public native String stringFromJNI();

static {

System.loadLibrary("hello-jni");

}

Page 18: Using the Android Native Development Kit (NDK)

19

JNI_OnLoad Method – Why ?

Proven method

No more surprises after methods registration

Less error prone when refactoring

Add/remove native functions easily

No symbol table issue when mixing C/C++ code

Best spot to cache Java* class object references

Page 19: Using the Android Native Development Kit (NDK)

20

JNI_OnLoad Method

In your library name your functions as you wish and declare the mapping with JVM methods:

jstring stringFromJNI(JNIEnv* env, jobject thiz)

{

return env->NewStringUTF("Hello from JNI !");

}

static JNINativeMethod exposedMethods[] = {

{"stringFromJNI","()Ljava/lang/String;",(void*)stringFromJNI},

}

()Ljava/lang/String; is the JNI signature of the Java* method, you can retrieve it using the javap utility:

> javap -s -classpath bin\classes -p com.example.hellojni.HelloJni

Compiled from "HelloJni.java“

public native java.lang.String stringFromJNI();

Signature: ()Ljava/lang/String;

Page 20: Using the Android Native Development Kit (NDK)

21

JNI_OnLoad Method

JNI_OnLoad is the library entry point called during load.

Here it applies the mapping previously defined.

extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved)

{

JNIEnv* env;

if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) !=

JNI_OK)

return JNI_ERR;

jclass clazz = env->FindClass("com/example/hellojni/HelloJni");

if(clazz==NULL)

return JNI_ERR;

env->RegisterNatives(clazz, exposedMethods,

sizeof(exposedMethods)/sizeof(JNINativeMethod));

env->DeleteLocalRef(clazz);

return JNI_VERSION_1_6;

}

Page 21: Using the Android Native Development Kit (NDK)

22

Memory Handling of Java* Objects

Memory handling of Java* objects is done by the JVM:

You only deal with references to these objects

Each time you get a reference, you must not forget to delete it after use

local references are automatically deleted when the native call returns to

Java

References are local by default

Global references are only created by NewGlobalRef()

Page 22: Using the Android Native Development Kit (NDK)

23

Creating a Java* String

Memory is handled by the JVM, jstring is always a reference. You can call DeleteLocalRef() on it once you finished with it.

By the way:

Main difference with compiling JNI code in C or in C++ is the nature of “env” as you can see it here

Remember that otherwise, the API is the same

C:

jstring string =

(*env)->NewStringUTF(env, "new Java String");

C++:

jstring string = env->NewStringUTF("new Java String");

Page 23: Using the Android Native Development Kit (NDK)

24

Getting a C/C++ String from Java* String

const char *nativeString = (*env)-

>GetStringUTFChars(javaString, null);

(*env)->ReleaseStringUTFChars(env, javaString,

nativeString);

//more secure and efficient:

int tmpjstrlen = env->GetStringUTFLength(tmpjstr);

char* fname = new char[tmpjstrlen + 1];

env->GetStringUTFRegion(tmpjstr, 0, tmpjstrlen, fname);

fname[tmpjstrlen] = 0;

delete fname;

Page 24: Using the Android Native Development Kit (NDK)

25

Handling Java* Exceptions

// call to java methods may throw Java exceptions

jthrowable ex = (*env)->ExceptionOccurred(env);

if (ex!=NULL) {

(*env)->ExceptionClear(env);

// deal with exception

}

(*env)->DeleteLocalRef(env, ex);

Page 25: Using the Android Native Development Kit (NDK)

26

JNI Primitive Types

Java* Type Native Type Description

boolean jboolean unsigned 8 bits

byte jbyte signed 8 bits

char jchar unsigned 16 bits

short jshort signed 16 bits

int jint signed 32 bits

long jlong signed 64 bits

float jfloat 32 bits

double jdouble 64 bits

void void N/A

Page 26: Using the Android Native Development Kit (NDK)

27

JNI Reference Types

jobject

jclass

jstring

jarray

jobjectArray

jbooleanArray

jbyteArray

jcharArray

jshortArray

jintArray

jlongArray

jfloatArray

jdoubleArray

jthrowable

Arrays elements are manipulated using Get<type>ArrayElements()

and Get/Set<type>ArrayRegion()

Don’t forget to call ReleaseXXX() for each GetXXX() call.

Page 27: Using the Android Native Development Kit (NDK)

28

Calling Java* MethodsOn an object instance:jclass clazz = (*env)->GetObjectClass(env, obj);

jmethodID mid = (*env)->GetMethodID(env, clazz,

"methodName", "(…)…");

if (mid != NULL)

(*env)->Call<Type>Method(env, obj, mid, parameters…);

Static call:jclass clazz = (*env)->FindClass(env, "java/lang/String");

jmethodID mid = (*env)->GetStaticMethodID(env, clazz,

"methodName", "(…)…");

if (mid != NULL)

(*env)->CallStatic<Type>Method(env, clazz, mid,

parameters…);

• (…)…: method signature

• parameters: list of parameters expected by the Java* method• <Type>: Java method return type

Page 28: Using the Android Native Development Kit (NDK)

29

Throwing Java* Exceptions

jclass clazz =

(*env->FindClass(env, "java/lang/Exception");

if (clazz!=NULL)

(*env)->ThrowNew(env, clazz, "Message");

The exception will be thrown only when the JNI call returns to Java*, it

will not break the current native code execution.

Page 29: Using the Android Native Development Kit (NDK)

30

Agenda

• The Android* Native Development Kit (NDK)

• Developing an application that uses the NDK

• Supporting several CPU architectures

• Break

• Summary and Q&A

• Debugging

• Optimizing

• Intel® Tools and Libraries

• Summary and Q&A

Page 30: Using the Android Native Development Kit (NDK)

31

NDK Applications support on Intel® Platforms

Most will run w/o any recompilation…

Android NDK provides an x86 toolchain since 2011

A simple recompile using the Android NDK yields the

best performance

If there is specific processor dependent code, porting

may be necessary

Page 31: Using the Android Native Development Kit (NDK)

32

Include all ABIs by setting APP_ABI to all in jni/Application.mk:

APP_ABI=all

The NDK will generate optimized code for all target ABIs

You can also pass APP_ABI variable to ndk-build, and specify each ABI:

ndk-build APP_ABI=x86

Configuring NDK Target ABIs

Build ARM v7a libs

Build ARM v5 libs

Build x86 libs

Build mips libs

Page 32: Using the Android Native Development Kit (NDK)

33

Fat Binaries

By default, an APK contains libraries for every supported ABIs.

Use lib/armeabi libraries

Use lib/armeabi-v7a

libraries

Use lib/x86

libraries

libs/armeabi-v7a

libs/x86

libs/armeabi

Android project

The application will be filtered during installation (after download)

Page 33: Using the Android Native Development Kit (NDK)

34

Multiple APKs

Google Play* supports multiple APKs for the same application.

What compatible APK will be chosen for a device entirely depends on the android:VersionCode

If you have multiple APKs for multiple ABIs, best is to simply prefix your current version code with a digit representing the ABI:

2310 6310

You can have more options for multiple APKs, here is a convention that will work

if you’re using all of these:

x86ARMv7

Page 34: Using the Android Native Development Kit (NDK)

35

Uploading Multiple APKs to the store

Switch to Advanced mode before

uploading the second APK.

The interface almost doesn’t change.

But if you upload a new apk in

simple mode, it will overwrite the

former one.

You can get the same screen than on

the right. even if the new package

will not overwrite the previous one.

Page 35: Using the Android Native Development Kit (NDK)

36

Uploading Multiple APKs to the store

Don’t forget to use different version codes for your different APKs.

Page 36: Using the Android Native Development Kit (NDK)

37

Memory AlignmentBy default

Easy fix

struct TestStruct {

int mVar1;

long long mVar2;

int mVar3;

};

struct TestStruct {

int mVar1;

long long mVar2 __attribute__ ((aligned(8)));

int mVar3;

};

Page 37: Using the Android Native Development Kit (NDK)

38

SIMD InstructionsNEON* instruction set on ARM* platforms

MMX™, Intel® SSE, SSE2, SSE3, SSSE3 on Intel® Atom™ processor based platforms

http://intel.ly/10JjuY4 - NEONvsSSE.h : wrap NEON functions and intrinsics to

SSE3 – 100% covered

Optimization Notice

Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors. These optimizations include SSE2, SSE3, and SSSE3 instruction sets and other optimizations. Intel does not guarantee the availability, functionality, or effectiveness of any optimization on microprocessors not manufactured by Intel. Microprocessor-dependent optimizations in this product are intended for use with Intel microprocessors. Certain optimizations not specific to Intel microarchitecture are reserved for Intel microprocessors. Please refer to the applicable product User and Reference Guides for more information regarding the specific instruction sets covered by this notice.

Notice revision #20110804

//******* definition sample *****************

int8x8_t vadd_s8(int8x8_t a, int8x8_t b); // VADD.I8 d0,d0,d0

#ifdef USE_MMX

#define vadd_s8 _mm_add_pi8 //MMX

#else

#define vadd_s8 _mm_add_epi8

#endif

//…

Intel® Streaming SIMD Extensions (Intel® SSE)Supplemental Streaming SIMD Extensions (SSSE)

Page 38: Using the Android Native Development Kit (NDK)

39

Multiple Code Paths

Compiler macros

• Directly inside source code

• No runtime overhead

• Works with all build configurations

#ifdef __i386__

strlcat(buf, "__i386__", sizeof(buf));

#endif

#ifdef __arm__

strlcat(buf, "__arm__", sizeof(buf));

#endif

#ifdef _MIPS_ARCH

strlcat(buf, "_MIPS_ARCH", sizeof(buf));

#endif

Page 39: Using the Android Native Development Kit (NDK)

40

Multiple Code Paths

Inside Makefiles

ifeq ($(TARGET_ARCH_ABI),x86)

else

endif

Page 40: Using the Android Native Development Kit (NDK)

41

3rd party libraries x86 support

Game engines/libraries with x86 support:

• Havok Anarchy SDK: android x86 target available

• Unreal Engine 3: android x86 target available

• Marmalade: android x86 target available

• Cocos2Dx: set APP_ABI in Application.mk

• FMOD: x86 lib already included, set ABIs in Application.mk

• AppGameKit: x86 lib already included, set ABIs in Application.mk

• libgdx: x86 lib now available in latest releases

• …

No x86 support but works on consumer devices:

• Corona

• Unity

Page 41: Using the Android Native Development Kit (NDK)

42

Agenda

• The Android* Native Development Kit (NDK)

• Developing an application that uses the NDK

• Supporting several CPU architectures

• Summary and Q&A

Break

• Debugging

• Optimizing

• Intel® Tools and Libraries

• Summary and Q&A

Page 42: Using the Android Native Development Kit (NDK)

43

Debugging with logcatNDK provides log API in <android/log.h>:

Usually used through this sort of macro:

#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO,

"APPTAG", __VA_ARGS__))

Example:

LOGI("accelerometer: x=%f y=%f z=%f", x, y, z);

int __android_log_print(int prio, const char *tag,

const char *fmt, ...)

Page 43: Using the Android Native Development Kit (NDK)

44

Debugging with logcat

To get more information on native code execution:

adb shell setprop debug.checkjni 1

(already enabled by default in the emulator)

And to get memory debug information (root only):

adb shell setprop libc.debug.malloc 1

-> leak detection

adb shell setprop libc.debug.malloc 10

-> overruns detection

adb shell start/stop -> reload environment

Page 44: Using the Android Native Development Kit (NDK)

45

Debugging with GDB and EclipseNative support must be added to your project

Pass NDK_DEBUG=1 to the ndk-build command, from the project

properties:

NDK_DEBUG flag is supposed to be automatically set for a debug

build, but this is not currently the case.

Page 45: Using the Android Native Development Kit (NDK)

46

Debugging with GDB and Eclipse*

When NDK_DEBUG=1 is specified, a “gdbserver” file is added to your

libraries

Page 46: Using the Android Native Development Kit (NDK)

47

Debugging with GDB and Eclipse*

Debug your project as a native Android* application:

Page 47: Using the Android Native Development Kit (NDK)

48

Debugging with GDB and Eclipse

From Eclipse “Debug” perspective, you can manipulate breakpoints and debug your project

Your application will run before the debugger is attached, hence breakpoints you set near application launch will be ignored

Page 48: Using the Android Native Development Kit (NDK)

49

ValgrindThe Valgrind tool suite provides a number of debugging and profiling tools that help you make your

programs faster and more correct.

Memcheck : It can detect many memory-related errors that are common in C and C++ programs and

that can lead to crashes and unpredictable behavior.

Setting up Valgrind

Download latest version on Valgrind from http://valgrind.org/downloads/

./configure

Make

Sudo make install

Steps above should install valgrind.

Compile your program with -g to include debugging information so that Memcheck's error messages

include exact line numbers.

gcc myprog.c

valgrind --leak-check=yes myprog arg1 arg2 ; Memcheck is the default tool. The --leak-check option

turns on the detailed memory leak detector. You can also invoke the leak check like this

Valgrind ./a.out

Use “–o” to optimize the program while compiling. Any other option slows down Valgrind to a

significant extent.

Page 49: Using the Android Native Development Kit (NDK)

50

Interpreting Valgrind error messages

Example of output message from Valgrind Memcheck

==19182== Invalid write of size 4

==19182== at 0x804838F: f (example.c:6) ==19182== by 0x80483AB: main (example.c:11)

19182 : Process ID

“Invalid write..” is the error message

6 and 11 are line numbers

Add “--gen-suppressions=yes ” to suppress errors arising out of pre compiled libs and other mem leak errors that you cannot make changes to.

Memcheck cannot detect every memory error your program has. For example, it can't detect out-of-range reads or writes to arrays that are allocated statically or on the stack. But it should detect many errors that could crash your program

Suggested reading : http://valgrind.org/docs/manual/manual.html

Page 50: Using the Android Native Development Kit (NDK)

51

Valgrind on Android x86Installing Valgrind

Download this package: https://my.syncplicity.com/share/7cse0vnb43auckm/valgrind-x86-android-emulator

Unzip and enter root of the unzipped package.

Install valgrind on the emulator using these commands:

adb push Inst /

adb shell chmod 777 /data/local/Inst

adb shell chmod 755 /data/local/Inst/bin/*

adb shell chmod 755 /data/local/Inst/lib/valgrind/*

Setting up a program to be run with Valgrind

adb shell setprop wrap.com.example.hellojni "logwrapper /data/local/Inst/bin/valgrind“ #Replace package name with your package name

Next startups of your app will be wrapped by valgrind and you'll see the output inside logcat.

Please note

These binaries are compatible with Intel HAXM 4.0.3 x86 emulator, not the 4.3.

You can use any OS as host

To use valgrind on a real device, you need to recompile valgrind for it (you can read the .sh file inside the zip to get the right cmd and adapt it) and you need to be root on it.

Page 51: Using the Android Native Development Kit (NDK)

52

Agenda

• The Android* Native Development Kit (NDK)

• Developing an application that uses the NDK

• Supporting several CPU architectures

• Summary and Q&A

Break

• Debugging

• Optimizing

• Intel® Tools and Libraries

• Summary and Q&A

Page 52: Using the Android Native Development Kit (NDK)

53

VectorizationSIMD instructions up to SSSE3 available on current Intel® Atom™ processor based platforms, Intel® SSE4.2 on the Intel Silvermont Microarchitecture

On ARM*, you can get vectorization through the ARM NEON* instructions

Two classic ways to use these instructions:

Compiler auto-vectorization

Compiler intrinsics

Optimization Notice

Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors. These optimizations include SSE2, SSE3, and SSSE3 instruction sets and other optimizations. Intel does not guarantee the availability, functionality, or effectiveness of any optimization on microprocessors not manufactured by Intel. Microprocessor-dependent optimizations in this product are intended for use with Intel microprocessors. Certain optimizations not specific to Intel microarchitecture are reserved for Intel microprocessors. Please refer to the applicable product User and Reference Guides for more information regarding the specific instruction sets covered by this notice.

Notice revision #20110804

SSSE3, SSE4.2Vector size: 128 bit

Data types:

• 8, 16, 32, 64 bit integer

• 32 and 64 bit float

VL: 2, 4, 8, 16

X2

Y2

X2◦Y2

X1

Y1

X1◦Y1

X4

Y4

X4◦Y4

X3

Y3

X3◦Y3

127 0

Intel® Streaming SIMD Extensions (Intel® SSE)

Supplemental Streaming SIMD Extensions (SSSE)

Page 53: Using the Android Native Development Kit (NDK)

54

GCC Flags

ffast-math influence round-off of fp arithmetic and so breaks strict IEEE

compliance

The other optimizations are totally safe

Add -ftree-vectorizer-verbose to get a vectorization report

ifeq ($(TARGET_ARCH_ABI),x86)

LOCAL_CFLAGS += -O3 -ffast-math -mtune=atom -msse3 -mfpmath=sse

else

LOCAL_CFLAGS += ...

endif

LOCAL_CFLAGS += -O3 -ffast-math -mtune=slm -msse4.2 -mfpmath=sse

To optimize for Intel Silvermont Microarchitecture (available starting with NDK r9

gcc-4.8 toolchain):

Optimization Notice

Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors. These optimizations include SSE2, SSE3, and SSSE3 instruction sets and other optimizations. Intel does not guarantee the availability, functionality, or effectiveness of any optimization on microprocessors not manufactured by Intel. Microprocessor-dependent optimizations in this product are intended for use with Intel microprocessors. Certain optimizations not specific to Intel microarchitecture are reserved for Intel microprocessors. Please refer to the applicable product User and Reference Guides for more information regarding the specific instruction sets covered by this notice.

Notice revision #20110804

Page 54: Using the Android Native Development Kit (NDK)

55

Agenda

• The Android* Native Development Kit (NDK)

• Developing an application that uses the NDK

• Supporting several CPU architectures

• Summary and Q&A

Break

• Debugging

• Optimizing

• Intel® Tools and Libraries

• Summary and Q&A

Page 55: Using the Android Native Development Kit (NDK)

56

Intel x86 Emulator

Accelerator

Intel x86 Atom

System Image

Faster Android* Emulation on Intel® Architecture

Based Host PCPre-built Intel® Atom™ Processor Images

Android* SDK manager has x86 emulation images built-in

To emulate an Intel Atom processor based Android phone, install the “Intel Atom x86 System Image” available in the Android SDK Manager

Much Faster Emulation

Intel® Hardware Accelerated Execution Manager (Intel® HAXM) for Mac and Windows uses Intel®

Virtualization Technology (Intel® VT) to accelerate Android emulator

Intel VT is already supported in Linux* by KVM

Page 56: Using the Android Native Development Kit (NDK)

57

Intel® Threading Building Blocks (Intel® TBB)

Specify tasks instead of manipulating threads

Intel® Threading Building Blocks (Intel® TBB) maps your logical tasks onto threads with

full support for nested parallelism

Targets threading for scalable performance

Uses proven efficient parallel patterns

Uses work-stealing to support the load balance of unknown execution time for tasks

Open source and licensed versions available on:

Linux*, Windows*, Mac OS X* and… Android*

Open Source version available on:

http://threadingbuildingblocks.org/

Licensed version available on:

http://software.intel.com/en-us/intel-tbb

Page 57: Using the Android Native Development Kit (NDK)

58

Components of TBB (version 4.2)

Synchronization primitivesatomic operations

mutexes : classic, recursive, spin, queuing

rw_mutexes : spin, queuing

Parallel algorithmsparallel_for

parallel_for_each

parallel_reduce

parallel_do

parallel_scan

parallel_pipeline & filters

parallel_sort

parallel_invoke

Concurrent containersconcurrent_hash_map

concurrent_queue

concurrent_bounded_queue

concurrent_priority_queue

concurrent_vector

concurrent_unordered_map

concurrent_unordered_set

Task scheduler

Memory allocatorstbb_allocator, cache_aligned_allocator, scalable_allocator

Thread Local Storagecombinable

enumerable_thread_specific

flattened2d

Ranges and

partitioners

Flow Graphsfunctional nodes

(source, continue, function)

buffering nodes

(buffer, queue, sequencer)

split/join nodes

other nodes

Tasks & Task groups

Page 58: Using the Android Native Development Kit (NDK)

59

Intel® TBB – Integration

#for including tbb in your project:

include $(CLEAR_VARS)

LOCAL_MODULE := tbb

LOCAL_SRC_FILES := $(TBB_PATH)/lib/android/libtbb.so

LOCAL_EXPORT_C_INCLUDES := $(TBB_PATH)/include

include $(PREBUILT_SHARED_LIBRARY)

#for calling tbb from your lib:

LOCAL_CPP_FEATURES := rtti exceptions

LOCAL_SHARED_LIBRARIES += tbb

LOCAL_CFLAGS += -DTBB_USE_GCC_BUILTINS -std=c++11

Android.mk

APP_STL := gnustl_shared Application.mk

System.loadLibrary("gnustl_shared");

System.loadLibrary("tbb");

System.loadLibrary("YourLib");

Java

Page 59: Using the Android Native Development Kit (NDK)

60

Intel® Threading Building Blocks (Intel® TBB) -

Example#include <tbb/parallel_reduce.h>

#include <tbb/blocked_range.h>

double getPi() {

const int num_steps = 10000000;

const double step = 1./num_steps;

double pi = tbb::parallel_reduce(

tbb::blocked_range<int>(0, num_steps), //Range

double(0), //Value

//function

[&](const tbb::blocked_range<int>& r, double current_sum ) ->

double {

for (size_t i=r.begin(); i!=r.end(); ++i) {

double x = (i+0.5)*step;

current_sum += 4.0/(1.0 + x*x);

}

return current_sum; // updated value of the accumulator

},

[]( double s1, double s2 ) { //Reduction

return s1+s2;

}

);

return pi*step;

}

Computes reduction

over a range

Defining a one-

dimensional range

Lambda function with

range and initial value as

parm

Calculating a part of Pi

within the range r

Defining a reduction

function

Page 60: Using the Android Native Development Kit (NDK)

61

Intel® Graphics Performance Analyzer

(Intel® GPA): System Analyzer

Profiles performance and Power

Real-time charts of CPU, GPU and power

metrics

Conduct real-time experiments with

OpenGL-ES* (with state overrides) to help

narrow down problems

Triage system-level performance with

CPU, GPU and Power metrics

Available freely on intel.com/software/gpa

Page 61: Using the Android Native Development Kit (NDK)

62

1. Install APK, and

connect to Host PC via

adb

2. Run Intel® GPA System Analyzer

on development machine3. View Profile

Intel® Graphics Performance Analyzer (Intel® GPA):

How to Use the System Analyzer

Page 62: Using the Android Native Development Kit (NDK)

63

Intel® C++ Compiler for Android*

• Based on Intel® C/C++ Compiler XE 14.0 for Linux*

• Integrates into the Android* NDK as additional toolchain

• Supports Intel® Atom™ processor optimization

• 79.95$

Available on http://software.intel.com/c-compiler-android

Page 63: Using the Android Native Development Kit (NDK)

64

http://www.projectanarchy.com/

Project Anarchy*

• Complete mobile game engine that includes Havok Vision Engine, Physics, Animation Studio and AI

• Free to publish on Android (ARM and x86), iOS, and Tizen

• C++ development environment

• Efficient asset management system

• LUA scripting and debugging

• Extensible source code and full library of sample materials

• Remote debugging

• File serving for live asset updates

• Remote input

• Visual debugger

Page 64: Using the Android Native Development Kit (NDK)

65

Summary

Use the NDK for performance critical applications and code reuse

It is easy to target multiple architectures

Our tools can help you getting most out of it

Page 65: Using the Android Native Development Kit (NDK)

66

Where to Get More Info

Intel® Developer Zone (Intel® DZ)• Real developers sharing knowledge and offering

help• Dedicated communities and forums focused on

your interests• Worldwide reach• News and insights on cutting edge technology

Android Developer on Intel Website• Great content you won’t find anywhere else• Technical articles, tools, and guides• Native app porting tips & case studies• Info on x86 emulator and Intel® Hardware Accelerated

Execution Manager• Active forums and blogs written by Intel and

community experts

Getting Started

Technical Content

Android Blogs

Support Forums

www.intel.com/software/android

Page 66: Using the Android Native Development Kit (NDK)

67

Resources

http://developer.android.com/tools/sdk/ndk/index.html - NDK

http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/intro.html - JNI documentation

http://software.intel.com/en-us/blogs/2012/12/12/from-arm-neon-to-intel-mmxsse-automatic-porting-

solution-tips-and-tricks - Automatic porting of NEON* instructions

http://software.intel.com/en-us/blogs/2012/11/28/intel-for-android-developers-learning-series - Android* learning series

http://software.intel.com/en-us/articles/android-application-development-and-optimization-on-the-intel-atom-platform - NDK Apps Development

http://software.intel.com/en-us/articles/creating-and-porting-ndk-based-android-apps-for-ia/ - NDK Apps porting

http://software.intel.com/en-us/articles/android-texture-compression - Textures Compression

http://software.intel.com/en-us/articles/how-to-debug-an-app-for-android-x86-and-the-tools-to-use/ - NDK Apps debugging

http://software.intel.com/en-us/articles/android-tutorial-writing-a-multithreaded-application-using-intel-threading-building-blocks - TBB Android* Tutorial

http://developer.android.com/training/ - Google Android* developer guide

Page 67: Using the Android Native Development Kit (NDK)

68

Legal DisclaimerINFORMATION IN THIS DOCUMENT IS PROVIDED IN CONNECTION WITH INTEL PRODUCTS. NO LICENSE, EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE, TO ANY INTELLECTUAL PROPERTY RIGHTS IS GRANTED BY THIS DOCUMENT. EXCEPT AS PROVIDED IN INTEL'S TERMS AND CONDITIONS OF SALE FOR SUCH PRODUCTS, INTEL ASSUMES NO LIABILITY WHATSOEVER AND INTEL DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY, RELATING TO SALE AND/OR USE OF INTEL PRODUCTS INCLUDING LIABILITY OR WARRANTIES RELATING TO FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR INFRINGEMENT OF ANY PATENT, COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT.A "Mission Critical Application" is any application in which failure of the Intel Product could result, directly or indirectly, in personal injury or death. SHOULD YOU PURCHASE OR USE INTEL'S PRODUCTS FOR ANY SUCH MISSION CRITICAL APPLICATION, YOU SHALL INDEMNIFY AND HOLD INTEL AND ITS SUBSIDIARIES, SUBCONTRACTORS AND AFFILIATES, AND THE DIRECTORS, OFFICERS, AND EMPLOYEES OF EACH, HARMLESS AGAINST ALLCLAIMS COSTS, DAMAGES, AND EXPENSES AND REASONABLE ATTORNEYS' FEES ARISING OUT OF, DIRECTLY OR INDIRECTLY, ANY CLAIM OF PRODUCT LIABILITY, PERSONAL INJURY, OR DEATH ARISING IN ANY WAY OUT OF SUCH MISSION CRITICAL APPLICATION, WHETHER OR NOT INTEL OR ITSSUBCONTRACTOR WAS NEGLIGENT IN THE DESIGN, MANUFACTURE, OR WARNING OF THE INTEL PRODUCT OR ANY OF ITS PARTS.Intel may make changes to specifications and product descriptions at any time, without notice. Designers must not rely on the absence or characteristics of any features or instructions marked "reserved" or "undefined". Intel reserves these for future definition and shall have no responsibility whatsoever for conflicts or incompatibilities arising from future changes to them. The information here is subject to change without notice. Do not finalize a design with this information.The products described in this document may contain design defects or errors known as errata which may cause the product to deviate from published specifications. Current characterized errata are available on request.Contact your local Intel sales office or your distributor to obtain the latest specifications and before placing your product order.Copies of documents which have an order number and are referenced in this document, or other Intel literature, may be obtained by calling 1-800-548-4725, or go to: http://www.intel.com/design/literature.htm

Silvermont and other code names featured are used internally within Intel to identify products that are in development and not yet publicly announced for release. Customers, licensees and other third parties are not authorized by Intel to use code names in advertising, promotion or marketing of any product or services and any such use of Intel's internal code names is at the sole risk of the user.

Intel, Atom, Look Inside and the Intel logo are trademarks of Intel Corporation in the United States and other countries.

*Other names and brands may be claimed as the property of others.Copyright ©2013 Intel Corporation.

Page 68: Using the Android Native Development Kit (NDK)

69

Legal DisclaimerRoadmap Notice: All products, computer systems, dates and figures specified are preliminary based on current expectations, and are subject to change

without notice.Intel® Virtualization Technology (Intel® VT) requires a computer system with an enabled Intel® processor, BIOS, and virtual machine monitor

(VMM). Functionality, performance or other benefits will vary depending on hardware and software configurations. Software applications may not be compatible with all operating systems. Consult your PC manufacturer. For more information, visit http://www.intel.com/go/virtualization.

Software Source Code Disclaimer: Any software source code reprinted in this document is furnished under a software license and may only be used or copied in accordance with the terms of that license. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Page 69: Using the Android Native Development Kit (NDK)

70

Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors. These optimizations include SSE2, SSE3, and SSE3 instruction sets and other optimizations. Intel does not guarantee the availability, functionality, or effectiveness of any optimization on microprocessors not manufactured by Intel.

Microprocessor-dependent optimizations in this product are intended for use with Intel microprocessors. Certain optimizations not specific to Intel microarchitecture are reserved for Intel microprocessors. Please refer to the applicable product User and Reference Guides for more information regarding the specific instruction sets covered by this notice.

Notice revision #20110804

Page 70: Using the Android Native Development Kit (NDK)

71

Risk FactorsThe above statements and any others in this document that refer to plans and expectations for the third quarter, the year and the future are forward-looking

statements that involve a number of risks and uncertainties. Words such as “anticipates,” “expects,” “intends,” “plans,” “believes,” “seeks,” “estimates,” “may,” “will,” “should”

and their variations identify forward-looking statements. Statements that refer to or are based on projections, uncertain events or assumptions also identify forward-

looking statements. Many factors could affect Intel’s actual results, and variances from Intel’s current expectations regarding such factors could cause actual results to

differ materially from those expressed in these forward-looking statements. Intel presently considers the following to be the important factors that could cause actual

results to differ materially from the company’s expectations. Demand could be different from Intel's expectations due to factors including changes in business and

economic conditions; customer acceptance of Intel’s and competitors’ products; supply constraints and other disruptions affecting customers; changes in customer order

patterns including order cancellations; and changes in the level of inventory at customers. Uncertainty in global economic and financial conditions poses a risk that

consumers and businesses may defer purchases in response to negative financial events, which could negatively affect product demand and other related matters. Intel

operates in intensely competitive industries that are characterized by a high percentage of costs that are fixed or difficult to reduce in the short term and product

demand that is highly variable and difficult to forecast. Revenue and the gross margin percentage are affected by the timing of Intel product introductions and the

demand for and market acceptance of Intel's products; actions taken by Intel's competitors, including product offerings and introductions, marketing programs and

pricing pressures and Intel’s response to such actions; and Intel’s ability to respond quickly to technological developments and to incorporate new features into its

products. The gross margin percentage could vary significantly from expectations based on capacity utilization; variations in inventory valuation, including variations

related to the timing of qualifying products for sale; changes in revenue levels; segment product mix; the timing and execution of the manufacturing ramp and

associated costs; start-up costs; excess or obsolete inventory; changes in unit costs; defects or disruptions in the supply of materials or resources; product

manufacturing quality/yields; and impairments of long-lived assets, including manufacturing, assembly/test and intangible assets. Intel's results could be affected by

adverse economic, social, political and physical/infrastructure conditions in countries where Intel, its customers or its suppliers operate, including military conflict and

other security risks, natural disasters, infrastructure disruptions, health concerns and fluctuations in currency exchange rates. Expenses, particularly certain marketing

and compensation expenses, as well as restructuring and asset impairment charges, vary depending on the level of demand for Intel's products and the level of revenue

and profits. Intel’s results could be affected by the timing of closing of acquisitions and divestitures. Intel's results cou ld be affected by adverse effects associated with

product defects and errata (deviations from published specifications), and by litigation or regulatory matters involving intellectual property, stockholder, consumer,

antitrust, disclosure and other issues, such as the litigation and regulatory matters described in Intel's SEC reports. An unfavorable ruling could include monetary

damages or an injunction prohibiting Intel from manufacturing or selling one or more products, precluding particular business practices, impacting Intel’s ability to design

its products, or requiring other remedies such as compulsory licensing of intellectual property. A detailed discussion of these and other factors that could affect Intel’s

results is included in Intel’s SEC filings, including the company’s most recent reports on Form 10-Q, Form 10-K and earnings release.

Rev. 7/17/13