<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anshul Saraf on Medium]]></title>
        <description><![CDATA[Stories by Anshul Saraf on Medium]]></description>
        <link>https://medium.com/@sarafanshul?source=rss-597842d45fa4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yuLYWc5mjHo2d4-lqWERFg.png</url>
            <title>Stories by Anshul Saraf on Medium</title>
            <link>https://medium.com/@sarafanshul?source=rss-597842d45fa4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 07:10:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sarafanshul/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Android GPU Profiling: A (Not So) Serious Guide ]]></title>
            <link>https://medium.com/@sarafanshul/android-gpu-profiling-a-not-so-serious-guide-fb2247aa6b44?source=rss-597842d45fa4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb2247aa6b44</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[opengl]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[profiling]]></category>
            <dc:creator><![CDATA[Anshul Saraf]]></dc:creator>
            <pubDate>Wed, 30 Aug 2023 15:51:14 GMT</pubDate>
            <atom:updated>2023-08-30T15:51:14.758Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qwtM1lAsQzTVTNTY.png" /></figure><p>Performance is a key design criteria when developing high quality applications and games for mobile devices. Players expect high frame rates, stutter-free rendering, and that important all-day battery life.</p><p>The GPU is a powerful piece of hardware that can make your Android apps fly. But sometimes, it can also be a bit grumpy. That’s where GPU profiling comes in. GPU profiling is a way to track what the GPU is doing, so you can find the bottlenecks and make your apps faster.</p><p>For all the folks working on Windows/Linux, RenderDoc is a goto software (AGI only supports &lt;5% devices, and for me <em>angle</em> messes things up 🫠), this blog will target all the folks (including the ones on <strong>MacOs 😉</strong>).</p><p>We will use <a href="https://developer.arm.com/Tools%20and%20Software/Arm%20Mobile%20Studio">Arm Mobile Studio</a> since this works on all the <em>arm</em> supported devices and most of the other devices too 😅.</p><p>For this blog I’ll be using the <a href="https://github.com/android/ndk-samples/tree/main/gles3jni">ndk-sample/gles3-jni</a> as a base project.</p><h3>Lets Get Started</h3><p>First of all you’ll need to get the <a href="https://developer.arm.com/Tools%20and%20Software/Arm%20Mobile%20Studio">Arm Mobile Studio</a></p><p>Configure it with ADB paths and some other basic requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*ls6kIRVadoxo_LYHGSaJ1g.png" /></figure><p>The UI (Brief)</p><ul><li>First 3 buttons toggles connection with device, you connect/disconnect to device via them</li><li>The Play/Pause button toggles the execution of application 🤯</li><li>The Camera Button captures the frame to trace</li><li>Next buttons enables: <strong>FrameBuffer</strong> Capture, <strong>Shader Overdraw</strong> Capture, <strong>ShaderMap</strong>, and <strong>Fragment count</strong> stats respectively</li></ul><p>When the device is connected we’ll launch the app to trace via above toolbar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BcghtbCmH6ItcpZpOHoLyA.png" /><figcaption>selecting the project to trace</figcaption></figure><p>Once trace app is selected, it’ll launch the application, just like how Android Studio does for Memory debugging, then you can navigate to the section of app you want to trace/profile.</p><p>Currently we are Capturing FrameBuffer Data, so we toggle it from tool bar, when clicked capture we can navigate to our captured frame from the frame tree in left,</p><p>With this we can now trace our GL calls step by step,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rth74LeRZv166uVh9v3T_g.gif" /><figcaption>trace</figcaption></figure><p>We can also peek at the attached program and it’s source</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mh0hsU-M3_fVrGEO7eCwZg.png" /></figure><p>Since OpenGL is a state machine, we can also check the state values w.r.t current trace (gl-call)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9vPtdVsc3eS16mfXHBAUw.png" /><figcaption>state of the machine</figcaption></figure><p>And the VAO data 🤯🤯🤯:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tV-v1jHaI2WfHUYkOYuYrA.gif" /><figcaption>VBO/EBO data, (visualised)</figcaption></figure><h3>Conclusion</h3><p>No matter which method you use, GPU profiling can be a helpful tool for making your Android apps faster. So if your app is feeling a bit grumpy, give GPU profiling a try. You might be surprised at how much faster it can make your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*xnu1u4GxorU1VL6W.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb2247aa6b44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JNI-201 — Dynamic Registration]]></title>
            <link>https://medium.com/@sarafanshul/jni-201-dynamic-registration-a1ad7fa50b21?source=rss-597842d45fa4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1ad7fa50b21</guid>
            <dc:creator><![CDATA[Anshul Saraf]]></dc:creator>
            <pubDate>Mon, 26 Jun 2023 18:46:12 GMT</pubDate>
            <atom:updated>2023-06-26T18:46:12.953Z</atom:updated>
            <content:encoded><![CDATA[<h3>JNI-201 — Dynamic Registration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/0*hr5pOUr1Oibsf2ZT.png" /></figure><p>Here we pick up from the last post about JNI, if you missed it — <a href="https://medium.com/@sarafanshul/jni-101-introduction-to-java-native-interface-8a1256ca4d8e"><em>have a look</em></a><em>. </em>The java layer calls the JNI method with the native keyword. It needs to register the correspondence between the java layer and the native layer.</p><p><strong>The JVM has two ways to find and link native methods with Java code.</strong> The first one is to <strong>call a native function in a specific way</strong> so that the JVM can find it (<strong>Static Registration</strong>). Another way is to <strong>use the JNI <em>RegisterNatives()</em> method</strong>.</p><p>As the name suggests, <em>RegisterNatives() </em>registers native methods with the class passed as an argument. <strong>By using this approach, we can name our C++ functions whatever we want, </strong>this comes under<strong> Dynamic registration</strong>.</p><h3>Static Registration</h3><p>This registration method is often used by small projects and is relatively common. This is generally used by the application layer, binding package <em>name + class name + method name</em>. When calling the JNI method, the corresponding function is searched through the class loader.</p><p>Since we’ve covered in last blog, we know that <em>The disadvantage of static registration is that when the package name, class name or method name is modified, the jni method name of the native layer must also be modified accordingly. </em>This creates unwanted tech-debts 📉📉.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3S1mOdW9VLZ_a9-N" /><figcaption>static registration (visualised)</figcaption></figure><h3><strong>Dynamic Registration</strong></h3><p>Dynamic registration JNI is a technique that allows native Java code to be dynamically loaded and registered with the Java Virtual Machine (JVM). This can be useful for systems that need to be able to adapt to changing requirements or that need to be able to add new features without disrupting existing users 📈📈.</p><h4>Init 🎬</h4><p>This is not-quite-easy to setup first time, but once done, it’s easy to maintain. There are several reasons why you might want to use dynamic registration:</p><ul><li>Easier to add new features: With dynamic registration JNI, new native Java code can be dynamically loaded and registered with the JVM without having to modify the system’s source code.</li><li>Easier to update existing features: If a native Java code needs to be updated, it can simply be unregistered from the JVM and then re-registered with the updated version. This can avoid the need to restart the JVM or to recompile the system’s Java code.</li><li>More flexible: Dynamic registration JNI allows for more flexibility in the way that native Java code is loaded and registered with the JVM. This can be useful for systems that need to be able to dynamically load native Java code from different sources, such as files, JAR files, or network resources.</li></ul><h4>Registration ⚙️</h4><p>To register a native method dynamically, you need to call the RegisterNatives() method of the JNIEnv object. The RegisterNatives() method takes two arguments:</p><p>— The first argument is the class object for the Java class that contains the native method.</p><p>— The second argument is an array of JNINativeMethod structures. Each JNINativeMethod structure contains the following information:</p><ol><li>The name of the native method.</li></ol><p>2. The signature of the native method.</p><p>3. A pointer to the native method implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WSHrV_0pm8SR_T91zZLgDQ.png" /><figcaption><a href="https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/types.html">type signatures</a></figcaption></figure><pre>// Inside Constants.h <br><br>// just a random funcition (0)<br>static jfloat JniVersion(JNIEnv *env, jobject object) {<br>        return 1.4;<br>}<br><br>// just a random funcition (1)<br>static jstring OpenCVVersion(JNIEnv *env, jobject object){<br>    return env-&gt;NewStringUTF(CV_VERSION);<br>}<br><br>// this is the path of java package for the wrapper class.<br>static const char *constants = &quot;com/projectdelta/chopper/util/Constants&quot;;<br><br>static JNINativeMethod constants_methods[] = {<br>// ------- java-function-name --------- jni-signature -------- cpp-function-ptr--<br>        {&quot;nativeGetJniVersion&quot;   , &quot;()F&quot;                 , (void *) JniVersion},<br>        {&quot;nativeGetOpenCVVersion&quot;, &quot;()Ljava/lang/String;&quot;, (void *) OpenCVVersion}<br>};</pre><p>Then we need to create function with same name on java side</p><pre>class Constants { // package name: com/projectdelta/chopper/util/Constants<br>    companion object {<br>        const val CHOPPER_LIBS = &quot;chopper&quot;<br>        <br>        val coreJniVersion: Float<br>           get() = nativeGetJniVersion()<br>        <br>        val openCVVersion: String<br>           get() = nativeGetOpenCVVersion()<br>        <br>        // function name should match to JNINativeMethod::name one!!<br>        @[Keep, JvmStatic]<br>        private external fun nativeGetJniVersion(): Float<br>        <br>        @[Keep, JvmStatic]<br>        private external fun nativeGetOpenCVVersion(): String<br>    }<br>}</pre><p>For starters we will call this RegisterNatives method from JNI_OnLoad</p><pre>// Inside chopper_jni.h class<br><br>typedef union {<br>    JNIEnv *env;<br>    void *venv;<br>} UnionJNIEnvToVoid;<br><br>/*<br> * Register several native methods for one class.<br> */<br>static int registerNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *gMethods,<br>                                 int numMethods) {<br>    jclass clazz;<br>    clazz = env-&gt;FindClass(className); // here identifies from reflection -&gt; slow :(<br>    if (clazz == NULL) {<br>        ALOGE(&quot;Native registration unable to find class &#39;%s&#39;&quot;, className);<br>        return JNI_FALSE;<br>    }<br>    if (env-&gt;RegisterNatives(clazz, gMethods, numMethods) &lt; 0) { // main/imp method<br>        ALOGE(&quot;RegisterNatives failed for &#39;%s&#39;&quot;, className);<br>        return JNI_FALSE; // rip!<br>    }<br>    return JNI_TRUE;<br>}<br><br>/*<br> * Register native methods for all classes we know about.<br> * returns: JNI_TRUE on success.<br> */<br>static int registerNatives(JNIEnv *env) {<br>    if (!registerNativeMethods(env, <br>        constants , // included from Constants.h<br>        constants_methods, // included from Constants.h<br>        SIZE(constants_methods))) {<br>        return JNI_FALSE;<br>    } // for constants-class<br>    return JNI_TRUE;<br>}<br><br>jint JNI_OnLoad(JavaVM *vm, void *reserved){<br><br>    UnionJNIEnvToVoid uenv;<br>    uenv.venv = nullptr;<br>    jint result = -1;<br>    JNIEnv* env;<br><br>    ALOGI(&quot;JNI_OnLoad&quot;);<br>    if (vm-&gt;GetEnv(&amp;uenv.venv, JNI_VERSION_1_4) != JNI_OK) {<br>        ALOGE(&quot;ERROR: GetEnv failed&quot;);<br>        goto bail;<br>    }<br>    env = uenv.env;<br>    if (registerNatives(env) != JNI_TRUE) {<br>        ALOGE(&quot;ERROR: registerNatives failed&quot;);<br>        goto bail; // r.i.p!<br>    }<br><br>    result = JNI_VERSION_1_4;<br><br>    bail:<br>    return result;<br>}</pre><p>ET voila now we are free of shackles of writing long-long method names.</p><h4>Disadvantages 🤯</h4><p>Here are some of the disadvantages of using dynamic registration JNI:</p><ul><li>Security: Dynamic registration JNI can introduce security risks if it is not used properly. For example, if a malicious native Java code is dynamically loaded and registered with the JVM, it could potentially exploit vulnerabilities in the JVM or in the system’s native code.</li><li>Performance: Dynamic registration JNI can have a negative impact on performance, especially if it is used to load and register a large number of native Java code modules.</li><li>Complexity: Dynamic registration JNI can be complex to implement and use. This is because it requires the developer to understand the details of how the JVM loads and registers native Java code.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*YkDANTTcs-F3P6h7.jpg" /><figcaption>Random meme to keep the mood light XD</figcaption></figure><h3>Conclusion 🫡</h3><p>Overall, dynamic registration JNI can be a useful technique for systems that need to be able to dynamically load and register native Java code. However, it is important to weigh the advantages and disadvantages before using it.</p><p><a href="https://github.com/sarafanshul/Chopper">Added a sample project for reference</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*PfFQVfIQ3xVY_r6v.jpg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1ad7fa50b21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JNI 101 - Introduction to Java Native Interface]]></title>
            <link>https://medium.com/@sarafanshul/jni-101-introduction-to-java-native-interface-8a1256ca4d8e?source=rss-597842d45fa4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a1256ca4d8e</guid>
            <category><![CDATA[c]]></category>
            <category><![CDATA[jni]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Anshul Saraf]]></dc:creator>
            <pubDate>Thu, 03 Nov 2022 22:58:07 GMT</pubDate>
            <atom:updated>2023-11-13T14:20:38.834Z</atom:updated>
            <content:encoded><![CDATA[<h3>JNI-101 — Introduction to Java Native Interface</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/0*lc4LdtqQipW74Mh_.jpg" /></figure><h3>What is JNI ?</h3><p>If you haven’t heard about this technology, <strong>Java Native Interface</strong> or <strong>JNI</strong> is a standard Java mechanism that allows Java code to interact with C and C++ code. Wikipedia says “JNI enables programmers to write native methods to handle situations when an application cannot be written entirely in the Java programming language, e.g. when the standard Java class library does not support the platform-specific features or program library” which means that in an Android application we can use a C++ library we need and interact with it directly from Java code and vice-versa.</p><p>From the viewpoint of a JVM, there are two types of code: “Java” and “native”. The Java Native Interface (JNI) establishes a well-defined and <strong><em>platform-independent</em></strong> interface between the two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wOxO2Yc_WAUu5N3F.png" /></figure><p>JNI defines a way for the bytecode that Android compiles from managed code (written in the Java or Kotlin programming languages) to interact with native code (written in C/C++).</p><h3>Why JNI then ?</h3><p>JNI is <strong><em>vendor-neutral</em></strong>, has support for loading code from <strong><em>dynamic shared libraries</em></strong>, and while cumbersome at times is reasonably <strong><em>efficient</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*mBm21TOxDYj7cMrOyUymdg.gif" /></figure><p>JNI makes some processes that aren’t implemented in Java possible. Like hardware-sensitive or direct OS API commands, for example. For Android Devs, it opens a lot of opportunities outside Dalvik. Compiled C/C++ code will work on any Java device because JNI is independent from Dalvik as it was designed for JVM.</p><h3>Hello World</h3><p><strong>Let’s look at how JNI works in practice.</strong></p><p>In this tutorial, we’ll use Kotlin, C++ as the native language and G++ as compiler and linker.</p><p>We will start with Android Studio Native C++ Project (<em>Easiest way to dive into JNI</em> , no manually compiling, building, etc. just hit run)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cs-cbcEMD--gTZK_4syFUA.png" /></figure><p>Setting up the project, I believe we are past that 😉</p><h4>1. Creating a Kotlin class</h4><pre>class <strong>MyFirstJNI</strong> {<br><br>    companion object {<br>        System.loadLibrary(&quot;test_jni&quot;)<br>    }<br>    <br>    fun <strong>main</strong>() {<br>        <strong>MyFirstJNI</strong>.printSomething()<br>    }<br><br>    private external fun printSomething();<br>}</pre><p>As we can see, <strong>we load the shared library in a static block</strong>. This ensures that it will be ready when we need it and from wherever we need it.</p><p>Alternatively, in this trivial program, we could instead load the library just before calling our native method because we’re not using the native library anywhere else.</p><h4>2. Registering our method in C++</h4><p>The java layer calls the JNI method with the native keyword. It needs to register the correspondence between the java layer and the native layer. There are two ways: <strong>static registration</strong> and <strong>dynamic registration</strong>.</p><p>Static registration is generally used by the application layer, binding package <em>name + class name + method name</em>. When calling the JNI method, the corresponding function is searched through the class loader.</p><p>Dynamic registration is generally used by the framework layer. When the JNI_OnLoad() callback is made, the JNINativeMethod is registered to the function table. <em>The disadvantage of static registration is that when the package name, class name or method name is modified, the jni method name of the native layer must also be modified accordingly.</em></p><p>Example of static registration (if it is a c++ file (.cpp/.cc/.cxx), you need to add the extern “C” keyword):</p><pre>#ifdef __cplusplus<br>extern &quot;C&quot; {<br>#endif</pre><pre>JNIEXPORT <strong>void</strong> JNICALL <strong>Java_com_package_name_</strong><strong>MyFirstJNI_</strong>printSomething(JNIEnv *, jobject);</pre><pre>#ifdef __cplusplus<br>}<br>#endif</pre><p>And for source cpp file,</p><pre>#ifdef __cplusplus<br>extern &quot;C&quot; {<br>#endif</pre><pre>JNIEXPORT <strong>void</strong> JNICALL <strong>Java_com_package_name_</strong><strong>MyFirstJNI_</strong><strong>printSomething</strong>(JNIEnv* env, jobject thisObject) {     <br>    std::cout &lt;&lt; &quot;Something from C++ !! XD&quot; &lt;&lt; std::endl; <br>}</pre><pre>#ifdef __cplusplus<br>}<br>#endif</pre><p><em>Dynamic registration is something JNI 102 will cover.</em></p><h4>3. Hit Run</h4><p>After initial compile and build, you’ll able to see the required string in logcat.</p><h3>Adding Parameters To Our Native Methods</h3><p>Saying hello is nice but not very useful. <strong>Usually, we would like to exchange data between Java and C++ code and manage this data in our program.</strong></p><p>We’ll add some parameters to our native methods. Let’s create a new class called <em>ExampleParametersJNI</em> with two native methods using parameters and returns of different types:</p><pre>private external fun isOdd(int x) : Boolean;</pre><p>Now create the corresponding implementation of the new C++ method:</p><pre>JNIEXPORT jboolean JNICALL <strong>Java_com_package_name_</strong><strong>MyFirstJNI_isOdd</strong>(JNIEnv* env, jobject obj, jint x) {     <br>    return x % 2 == 1; <br>}</pre><p>And then we test if -1 is odd or not 💀💀.</p><h3>Advantages</h3><ul><li>JNI makes some processes that aren’t implemented in Java possible. Like hardware-sensitive or direct OS API commands, for example. For Android devs, it opens a lot of opportunities outside Dalvik. Compiled C/C++ code will work on any Java device because JNI is independent from Dalvik as it was designed for JVM.</li><li>Ability to increase app performance with the help of low-level libraries for things like graphics, calculations, different types of rendering, etc.</li><li>Huge number of libraries has already been written for all the different tasks. And being able to reuse the code without rewriting it in other language makes a developer’s life much easier. This way such popular libraries as <strong>FFmpeg</strong> and <strong>OpenCV</strong> become available for Android developers.</li></ul><h3>Concerns</h3><p><em>Some things to keep in mind</em></p><p>JNI not only adds a layer of complexity to our program. <strong>It also adds a costly layer of communication</strong> between the code running into the JVM and our native code: we need to convert the data exchanged in both ways between Java and C++ in a marshaling/unmarshaling process.</p><ul><li>Function calls to JNI methods are expensive, especially when calling a method repeatedly.</li><li>Native methods are not inlined by the JVM, nor can the method be JIT compiled, as the method is already compiled.</li><li>A Java array may be copied for access in native code, and later copied back. The cost can be linear in the size of the array.</li><li>If the method is passed an object, or needs to make a callback, then the native method will likely be making its own calls to the JVM.</li><li>Accessing Java fields, methods and types from the native code requires something similar to reflection. Signatures are specified in strings and queried from the JVM. This is both slow and error-prone.</li><li>Java Strings are objects, have length and are encoded. Accessing or creating a string may require an O(n) copy.</li></ul><h3>Conclusion</h3><p>Regardless of all its flaws (nobody’s perfect), this technology makes it useful when we need to speed up a demanding process, (trigger warning) because we all know that C++ is faster, we can increase app performance with the help of low-level libraries for things like <strong>Graphics</strong>, <strong>Calculations</strong>, different types of <strong>Rendering.</strong></p><p><a href="https://medium.com/@sarafanshul/jni-201-dynamic-registration-a1ad7fa50b21"><strong>Want more ??, Part 2</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/0*5q2MWIO2YityGU8J" /><figcaption>Started with a meme so ended with a meme, -symmetry</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a1256ca4d8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>