<?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 Petros Douvantzis on Medium]]></title>
        <description><![CDATA[Stories by Petros Douvantzis on Medium]]></description>
        <link>https://medium.com/@petrakeas?source=rss-1516935fe5ab------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Zr7bc-ZwzWsVhBIY.jpg</url>
            <title>Stories by Petros Douvantzis on Medium</title>
            <link>https://medium.com/@petrakeas?source=rss-1516935fe5ab------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 15:35:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@petrakeas/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[DLSS Image Quality: they have been testing it wrong!]]></title>
            <link>https://petrakeas.medium.com/dlss-image-quality-they-have-been-testing-it-wrong-3aa3d07c4c3e?source=rss-1516935fe5ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/3aa3d07c4c3e</guid>
            <category><![CDATA[image-upscaling]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[comparison-tool]]></category>
            <category><![CDATA[gaming]]></category>
            <dc:creator><![CDATA[Petros Douvantzis]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 23:37:21 GMT</pubDate>
            <atom:updated>2025-02-05T00:17:33.448Z</atom:updated>
            <content:encoded><![CDATA[<p>DLSS Image Quality: they have been testing it wrong!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*XNSRJ7-475S2J2o8Qh41LQ.gif" /><figcaption>The right video is a stabilized version of the left video</figcaption></figure><p>Now that the transformer DLSS model is out, I used <a href="https://github.com/beeradmoore/dlss-swapper">DLSS Swapper </a>to test in on Talos Principle 2, which is the game I play lately and is famous for its blurry Unreal Engine 5 nature. The transformer model made everything look so clear in motion, unlike the CNN model. The latter felt like motion blur was applied when moving the camera, only to clear up a few milliseconds after I stopped the mouse movement.</p><p>The image quality under motion is something I have never seen discussed or demonstrated properly in upscaler comparison videos, even in the really well made ones by <a href="https://www.youtube.com/watch?v=PneArHayDv4&amp;">Digital Foundry</a>. Then, I had this idea… Let me introduce to what I call “the Stabilized Motion Test”.</p><blockquote>The idea is to stabilize the video in such a way that the camera orientation remains unchanged. This way the pixels of each frame align with the ones of the next one making the comparison obvious.</blockquote><p>So, I captured some footage with both DLSS models, processed them and uploaded them (along with the raw footage) in this <a href="http://bit.ly/40IN0Ds">Google Drive link</a>. You can also see the comparison in this 1080p YouTube video below, but the quality due to compression will not be that good .</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fen7PUgj5eYg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Den7PUgj5eYg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fen7PUgj5eYg%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7db55624ffc0973cca4a8af1ae0b44ee/href">https://medium.com/media/7db55624ffc0973cca4a8af1ae0b44ee/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*2EjjPxbedIk1np7sPDULGw.gif" /><figcaption>Stabilized motion test: CNN vs Transformer</figcaption></figure><p>You can see the CNN model getting blurry the moment the camera starts moving (this is when the white dot starts moving). The statue and the tree branches lose resolution. There is also more visual noise and less temporal stability on the stone road. The transformer model on the other hand remains crisp. If you pay close attention, you can see it losing the ability to reconstruct the smaller tree branches, but what it can reconstruct remain sharp. The moment the camera stops, the CNN models gets progressively sharper.</p><p>Now, you might argue that if we have to go through all of that effort to demonstrate the difference, does this mean it’s not observable when actually gaming? And the answer is that your eyes and brain will tell you the difference. The transformer model does not tire you and even though you can’t see at pixel level when moving the camera like that, your brain can actually reconstruct the geometry edges much better without giving you a headache.</p><p>I also took some screenshots when still, when moving the camera and when strafing and uploaded them to imgsli: <a href="https://imgsli.com/MzQ1MTYz/1/3">1080p look</a>,<a href="https://imgsli.com/MzQ1MTY1/1/3">1440p look</a>, <a href="https://imgsli.com/MzQ1MTk5/1/3">1440p strafe</a>. As usual, please open the images in native resolution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p4my_BQKVigHtoBbu7EniQ.jpeg" /><figcaption>imgsli: looking around @ 1080p</figcaption></figure><p>As you can see, the DLSS transformer model has much better clarity in motion. The CNN model struggles on the pebble stone road. It gets blurry and unstable. The tree branches and the statue on the center lose definition and it’s like seeing the actual native low resolution behind the upscaler.</p><p>I hope this topic gets more attention by the review community. Disocclusion fizzle, trails and artifacts are important, but motion clarity is how clear the game actually feels when gaming. We are not moving the camera in slow pace in “real” life.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3aa3d07c4c3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analyze HDR videos like a pro]]></title>
            <link>https://petrakeas.medium.com/analyze-hdr-videos-like-a-pro-325b44954099?source=rss-1516935fe5ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/325b44954099</guid>
            <dc:creator><![CDATA[Petros Douvantzis]]></dc:creator>
            <pubDate>Sun, 12 Nov 2023 12:14:39 GMT</pubDate>
            <atom:updated>2023-11-12T12:14:39.218Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered how many nits an HDR movie reaches in a specific scene? How bright the sun or that tiny specular reflection is? Or if the movie is using the BT.2020 or P3 color space?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1L1tZ-2oHWLuVEpvBRDL8w.png" /><figcaption>Dune 4K Blu-ray release rocking BT2020 color space</figcaption></figure><p>Or you may haved played an HDR game in your console and you wonder what’s the average CLL or how the game tonemaps after you perform the HDR calibration in PS5 and Xbox Series.</p><p>I’m going to show you a way that’s far better than importing the video in DaVinci Resolve and using its scopes. You will be able to play the video normally, seek as fast you want and even use your mouse to get the nits wherever you want. Ready for it???</p><h4>Setting everything up</h4><p>Here it goes! We are going to use a tool that was meant to be used in video games, but we will apply it to a video player: that’s <a href="https://reshade.me/#download">ReShade</a>. We will also add <a href="https://github.com/EndlesslyFlowering/ReShade_HDR_shaders">EndlesslyFlowering’s HDR shaders.</a> These tools have everything I would ever want in terms of scopes, functionality etc. The UI is also really easy and powerful. And don’t forget that it runs under ReShade, inside an app that was not meant for that.</p><p>Even though ReShade was build to be injected in DirectX games, we will use it on a video player and more specifically in its renderer!</p><p>You will have to download <a href="https://github.com/clsid2/mpc-hc/releases">mpc-hc</a>. We will use the word’s best renderer: <a href="https://www.videohelp.com/software/madVR">madVR</a>. You can either install it by itself or from a codec pack such as <a href="https://codecguide.com/download_kl.htm">K-Lite</a>.</p><p>Make sure that mpc-hc is configured to use madVR. We will now have to inject ReShare to it. Run ReShade’s setup, pick the mpc-hc executable and select DX9. Download the <a href="https://github.com/EndlesslyFlowering/ReShade_HDR_shaders/releases">HDR Shaders</a> and copy the <em>shaders </em>and textures directories to <em>mpc-hc\reshade-shaders.</em></p><p>Open mpc-hc and change the “start from beginning” shortcut to be something different than “home key”, as this is the key that shows the ReShade GUI.</p><p>Open madVR settings from the Windows start up menu. Go to “user interface-&gt;keyboard shortcuts” and uncheck “use only if media player has keyboard focus”. This will allow its keyboard shortcuts to continue to work properly with ReShade.</p><p>Time for testing! Enable HDR in Windows. This step requires that you have an HDR screen. You can also try the following shortcut: “<em>Windows+Alt+B”. </em>Open an HDR video with mpc-hc. You will see ReShade on top. Press the home key to have the ReShade GUI appear. Enable “Lilium’s HDR analysis”. If everything worked properly you will now be able to see something similar as the top photo of the post. You can now play with the shader’s settings.</p><p>Here are some tips to increase accuracy:</p><ul><li>madVR’s filters for upscaling/downscaling (under “Scaling algorithms” menu) can affect the HDR histogram, as interpolating between pixel values will result to different ones. This is not ideal when analyzing a video. Nearest neighbor is the best option for not affecting the pixel values. You can also right click select “Video Frame-&gt;Normal Size” to avoid resizing the video.</li><li>you may want to disable madVR’s dithering as it will make the <em>cursorCLL </em>value to change rapidly. You can use a keyboard shortcut to toggle it.</li></ul><p>And here are some limitations:</p><ul><li>if you use the madVR shortcut key to change bit levels between “10,9,8,7,6”, it won’t go back to 10 bit</li><li>when resizing mpc-hc, the ReShade shaders are compiled from scratch and this can take some time. You can uninstall all shaders except “Lilium’s HDR analysis” for faster recompiling</li><li>even though madVR can use an Nvidia API to switch your display to HDR, when paying an HDR video, even when Windows are in SDR mode, “Lilium’s HDR analysis” requires Windows HDR to work</li><li>sometimes the madVR keyboard shortcuts stop working</li></ul><h4>Playing with it</h4><p>After I got everything working, I wanted to experiment with some HDR calibration patters I had.</p><p>There was an 10-bit pattern clip, from <a href="https://www.avsforum.com/threads/hdr10-test-patterns-set.2943380/">Mehanic</a> test patterns set, that showed different shades of grey in 10 bit precision. madVR supports 10-bit and I wanted to verify via the “Lilium’s HDR analysis” tool that it does send different values at 10-bit precision to the screen.</p><p>In fact, it does as you can see in the following gif:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KBtSUasI2CZDeOnBgN42dQ.gif" /><figcaption>C260 and C261 are rendered with different nits; 10-bit precision is kept intact</figcaption></figure><p>Another thing I wanted to test was to compare how “God of War Ragnarok” changes the image according to PS5’s system level calibration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xe-SQPql7vmGQDlO28bL5g.gif" /><figcaption>God of War Ragnarok: uncalibrated vs calibrated at 853 nits</figcaption></figure><p>The game uses the full BT.2020 color gamut. This is more apparent in some other scenes of the game.</p><p>The uncalibrated image, shows that God of War is mastered for 4.000 nits. maxCLL shows 9134 but this is due to some pixel overshoots. The calibrated image was captured after performing 14 clicks in the PS5 system calibration, which results to 853 nits. Indeed, the game adheres to the restriction. I measured the brightest part in the image to be 841 nits. It’s the left part of the cave. The calibrated image, lifts the near black a bit.</p><p>In my opinion, the game tonemaps the highlights too aggressively in order to keep the details in some super bright areas. Even the SDR range up to 100 nits is affected, which normally should be kept as is.</p><p>“Lilium’s HDR analysis” allows you to crop a region and only analyze this one. In the following comparison, I have cropped the region around the fire.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JLIK4F0FdNwmBSk1UTeE-g.gif" /><figcaption>Color saturation change in uncalibrated vs calibrated</figcaption></figure><p>In the calibrated image, you can see that some red tones have moved towards the center of the CIE diagram (check out the blue circle), which means that they are less saturated. It seems that the game’s tonemapping does not only tonemap the luminance levels but also reduces the game’s saturation.</p><p>I am only scratching the surface of what’s possible to analyze here and I should be making a full post or even an HDR video about this if I find the willpower to go down that road</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=325b44954099" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Intent security vulnerabilities]]></title>
            <link>https://petrakeas.medium.com/android-intent-security-vulnerabilities-6a4df3f6c45e?source=rss-1516935fe5ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a4df3f6c45e</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[intent]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Petros Douvantzis]]></dc:creator>
            <pubDate>Wed, 20 Apr 2022 12:48:22 GMT</pubDate>
            <atom:updated>2022-07-28T14:55:16.602Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://developer.android.com/reference/android/content/Intent">Intents</a> are a primary element of Android architecture. They can be used used to start activities, services, enable IPC (Inter-process communication), pass messages from one part of the app to the other, enable functionality via notifications (such as inline-reply in a messaging app) etc.</p><p>If not implemented correctly, they can enable other apps to read information you though was private or let a malicious app affect your app’s functionality. You would be surprised to find out that most probably one or both of these issues can be exploited in your app.</p><p>This article will focus on broadcast intents and broadcast receivers and assumes that you are familiar with basic usage. It will tap into the topics explained in Google’s excellent article and dive a bit deeper: <a href="https://developer.android.com/guide/components/broadcasts">https://developer.android.com/guide/components/broadcasts</a></p><h3>The 2 questions/requirements</h3><p>When implementing a broadcast-receiver scheme, there are 2 questions you should ask yourself:</p><ol><li>Do you know who the receiver(s) of your broadcast is? In other words, can an unwanted app be listening to your broadcasts?</li><li>Do you know who the sender(s) of a received broadcast is? In other words, can an unwanted app be sending you broadcasts?</li></ol><p>We will try to see how the different types of broadcast receivers and setups can affect the outcome of these 2 questions.</p><h3>Broadcast receiver types</h3><p>There are 2 types of <a href="https://developer.android.com/reference/android/content/BroadcastReceiver">broadcast receivers</a>: manifest-declared receivers and context-registered receivers.</p><p>A context-registered receiver has the advantage that you can programmatically register it and unregister it. Your app should be running for the receiver to work. It can be used only for subscribing <strong>to implicit intents</strong>. It is always exported (and possibly accessed by other apps).</p><p>A manifest-declared receiver will always receive updates. Android can even launch your app so that your receiver gets the broadcast. <a href="https://developer.android.com/guide/components/broadcasts#android_80">Starting from</a> Android 8, you can’t use such a receiver for implicit intents. It can be used only for subscribing <strong>to explicit intents</strong>. It can be declared as exported or non exported.</p><h3>A naive implementation</h3><p>The simplest way to send an intent is creating an implicit intent. Even though Google encourages the use of your package name, the string of the intent can literally be whatever you want.</p><pre>Intent intent = new Intent();<br>intent.setAction(&quot;com.whatever.SOME_NOTIFICATION&quot;);</pre><p>On the receiving side, you will create a context-register receiver using</p><pre>IntentFilter filter = new IntentFilter<strong>(</strong>&quot;com.whatever.SOME_NOTIFICATION&quot;<strong>)</strong>;</pre><p>Even though this can work, it fails on both of the requirements stated earlier. A third party-app can also register to this intent, if it knows its name. Also, a third-party app can broadcast this intent, resulting on your app receiving it.</p><p>Here are some possible solutions:</p><h4><a href="https://developer.android.com/reference/androidx/localbroadcastmanager/content/LocalBroadcastManager#sendBroadcast(android.content.Intent)">LocalBroadcastManager</a></h4><p>If your intent (pun intended) is to pass messages from one part of your app to the other, you should simply use <a href="https://developer.android.com/reference/androidx/localbroadcastmanager/content/LocalBroadcastManager#sendBroadcast(android.content.Intent)">LocalBroadcastManager</a>. It’s a simpler implementation that doesn’t involve IPC and thus is secure and lightweight.</p><p>You can dynamically register or unregister a receiver. Ordered broadcasts are not supported unfortunately out of the box, but you can find implementations that work around this.</p><h4>Non exported receiver</h4><p>Declare a receiver in the manifest (and implement the receiver class).</p><pre><strong>&lt;receiver android:name=&quot;.SomeReceiver&quot; /&gt;</strong></pre><p>Broadcast an explicit intent to that receiver:</p><pre>Intent intent = new Intent<strong>()</strong>;<br>intent.setClassName<strong>(</strong>&quot;com.yourpackagename.yourappname&quot;, &quot;com.yourpackagename.yourappname.SomeReceiver&quot;<strong>)</strong>;</pre><p>This way there can be only one receiver (we met the first requirement). However, another app can still send a broadcast to your receiver if it knows the package name and class name.</p><p>A simple solution to that, is to define `<em>android:exported=”false”` </em>to your receiver declaration in the manifest.</p><pre><strong>&lt;receiver android:name=&quot;.SomeReceiver&quot; <br>    android:exported=&quot;false&quot;/&gt;</strong></pre><p>This way we have also met the second requirement.</p><p>This setup is useful for creating <a href="https://developer.android.com/reference/android/app/PendingIntent">PendingIntents</a> to pass for example to the <a href="https://developer.android.com/reference/android/app/AlarmManager">AlarmManager</a> or to a <a href="https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder#addAction(int,java.lang.CharSequence,android.app.PendingIntent)">Notification</a>. The only downside to this approach is that you have no way of unsubscribing. You can work around this by using LocalBroadcastManager to forward the intent from your receiver class to the actual place it needs to be delivered to.</p><h3>Permissions</h3><p>If you want to have a way to send broadcasts between two apps that you own, the previous answers will be of no use. Using <a href="https://developer.android.com/guide/components/broadcasts#restrict-broadcasts-permissions">permissions</a> may help you in this case. The permission can use `<em>android:protectionLevel=”signature”</em>` so that only the apps that are signed with the same signature, can use them. Declaring a permission without a protection level does not offer any security benefits.</p><p>In the following paragraphs, we won’t go through the exact way to use permissions as you can read that in the linked Android article above. Instead, we will go in depth into the implications of using permissions.</p><h4>Sending with permissions</h4><p>The sending side includes programmatically the name of the permission when sending the broadcast. It can be an implicit or explicit intent.</p><p>The receiving side uses the permission in its manifest. It can use a manifest-declared (for explicit intents) or context-registered (for implicit intents) receiver.</p><p>Only apps that use this permission in their manifest will have their receivers triggered by our broadcast. However, these receivers can also be triggered by broadcasts that don’t use the permission.</p><blockquote>So, when sending with permission, we know who the receiver will be. We don’t know who the sender(s) will be.</blockquote><p>This method fulfills the first requirement but fails on the second one.</p><h4>Receiving with permissions</h4><p>The sending side uses the permission in its manifest. It can send an implicit or explicit intent (without specifying the permission name when sending).</p><p>The receiving side includes the permission programmatically in its context-registered receiver or when declaring its manifest-based receiver.</p><p>Only senders that use the permission can send to our receiver. However, receivers of other apps will be able to receive the broadcast of the sender.</p><blockquote>So, when receiving with permission, we know who the sender will be. We don’t know who the receiver(s) will be.</blockquote><p>This method fulfils the second requirement correctly but fails on the first one.</p><p>Depending on your use case, this may be enough. If you use an explicit intent and “receiving with permissions”, you can manage to fulfil both requirements.</p><h4>Receiving and sending with permissions in 1 way communication</h4><p>This is not mentioned in Android’s article, but you can combine the two previous methods.</p><p>The sending side uses the permission in its manifest. It includes programmatically the name of the permission when sending the broadcast.</p><p>The receiving side uses the permission in its manifest. It includes the permission programmatically in its context-registered receiver or when declaring its manifest-based receiver.</p><blockquote>By sending and receiving with permissions, we know who the sender will be and who the receiver will be.</blockquote><h4>Receiving and sending with permissions in 2 way communication</h4><p>In the previous scenario there was a sending app and a receiving app. In this scenario, both apps are able receive and send broadcasts in a secure manner.</p><p>Both apps use the permission in their manifest. The receiving side (of each app) includes the permission programmatically in its context-registered receiver or when declaring its manifest-based receiver. The sending side (of each app) includes programmatically the name of the permission when sending the broadcast.</p><h4>Installation order</h4><p>Note that when using a permission, the app installation order matters.</p><p>The app that declares the permission in its manifest (it can be the receiver, the sender or even a third-party app), <strong>has to be installed before</strong> the app that uses the permission in its manifest.</p><p>Two apps can declare the same permission if they have the same signature. Otherwise, the second app will fail to install.</p><h3>Conclusion</h3><p>According to your use case and restrictions, you can make use of some of the methods explained. In either case, you should always try to check if your implementation meets the 2 requirements:</p><ul><li>Unwanted apps should not be able to listen to your broadcasts</li><li>Unwanted apps should not be able to send broadcasts to your app</li></ul><p>And don’t stay in theory but test it as well! Create a testing app that tries to receive your broadcast or send a broadcast to your app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a4df3f6c45e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Publish a multi-module Java/Android library to Maven Central + GitHub CI automation at  2021]]></title>
            <link>https://petrakeas.medium.com/publish-a-multi-module-java-android-library-to-maven-central-github-ci-automation-at-2021-4f98a311df2a?source=rss-1516935fe5ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f98a311df2a</guid>
            <category><![CDATA[publishing]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[maven]]></category>
            <dc:creator><![CDATA[Petros Douvantzis]]></dc:creator>
            <pubDate>Thu, 22 Apr 2021 16:44:18 GMT</pubDate>
            <atom:updated>2021-04-22T16:59:01.269Z</atom:updated>
            <content:encoded><![CDATA[<h3>Publish a multi-module Java/Android library to Maven Central + GitHub CI automation at 2021</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GBYzY3jt3tFSj67uXs7IdQ.png" /></figure><p>As an Android developer, I have to fiddle with <a href="https://gradle.org/">Gradle</a> from time to time, but I never quite managed to get to a point where my thoughts resulted to a working Gradle configuration. My experience was always a frustrating process of extreme Googling ,trying things out and asking questions to the Gradle forums (which most of the times got answered). Publishing a library to <a href="https://mvnrepository.com/">Maven</a> is not a trivial task, even though the situation has become as lot easier than what it used to be.</p><p>In my case, I had an Android Studio project that contained a pure Java module and an Android library module that depended on the pure Java module. My goal was to publish them in Maven, including their Javadoc and source code. Even if your project does not match exactly mine, I am sure that the following guide will help you at some extent.</p><p>This is a lengthy process and can be broken down to these steps (where each step relies on the previous one):</p><ul><li>Publish to <a href="https://www.baeldung.com/maven-local-repository">Maven local</a></li><li>Publish to <a href="https://search.maven.org/">Maven Central</a> from your computer</li><li>Prepare for GitHub</li><li>Build a <a href="https://docs.github.com/en/actions">GitHub workflow</a> that calls the publish Gradle task</li></ul><h4>Publish to Maven local</h4><p>We are going to use the <a href="https://docs.gradle.org/current/userguide/publishing_maven.html">Maven Publish plugin</a> for publishing our library module to Maven. Since we have more than one modules that we want published, we will create a publish-helper.gradle file to our root folder and we will include it in each module. Here’s our helper file:</p><pre>apply plugin: &#39;maven-publish&#39;<br><br>task androidJavadoc<strong>(</strong>type: Javadoc<strong>) {<br>    </strong>source = android.sourceSets.main.java.srcDirs<br>    classpath += project.files<strong>(</strong>android.getBootClasspath<strong>()</strong>.join<strong>(</strong>File.<strong><em>pathSeparator</em>))<br>    </strong>android.libraryVariants.all <strong>{ </strong>variant <strong>-&gt;<br>        if (</strong>variant.name == &#39;release&#39;<strong>) {<br>            </strong>owner.classpath += variant.javaCompileProvider.get<strong>()</strong>.classpath<br>        <strong>}<br>    }<br><br>    </strong>exclude &#39;**/R.html&#39;, &#39;**/R.*.html&#39;, &#39;**/index.html&#39;<br>    options.encoding &#39;utf-8&#39;<br>    options <strong>{<br>        </strong>addStringOption &#39;docencoding&#39;, &#39;utf-8&#39;<br>        addStringOption &#39;charset&#39;, &#39;utf-8&#39;<br>        links &#39;https://docs.oracle.com/javase/7/docs/api/&#39;<br>        links &#39;https://d.android.com/reference&#39;<br>        links &#39;https://developer.android.com/reference/androidx/&#39;<br>    <strong>}<br>}<br><br></strong>task androidJavadocJar<strong>(</strong>type: Jar, dependsOn: androidJavadoc<strong>) {<br>    </strong>archiveClassifier.set<strong>(</strong>&#39;javadoc&#39;<strong>)<br>    </strong>from androidJavadoc.destinationDir<br>    <br>    preserveFileTimestamps = <strong>false<br>    </strong>reproducibleFileOrder = <strong>true<br>}<br><br></strong>task javaSourcesJar<strong>(</strong>type: Jar<strong>) {<br>    </strong>archiveClassifier.set<strong>(</strong>&#39;sources&#39;<strong>)<br>    </strong>from android.sourceSets.main.java.srcDirs<br><br>    preserveFileTimestamps = <strong>false<br>    </strong>reproducibleFileOrder = <strong>true<br>}<br><br></strong>afterEvaluate <strong>{<br>    </strong>publishing <strong>{<br>        </strong>publications <strong>{</strong><br>            release<strong>(</strong>MavenPublication<strong>) {<br>                    <br>                </strong>from components.release<br><br>                artifact androidJavadocJar<br>                artifact javaSourcesJar<br><br>                groupId &#39;&#39;<br>                version &#39;&#39;<br>                pom <strong>{<br>                    </strong>name = artifactId<br>                    description = &#39;&#39;<br>                    url = &#39;&#39;<br>                    licenses <strong>{<br>                        </strong>license <strong>{<br>                            </strong>name = &#39;&#39;<br>                            url = &#39;&#39;<br>                        <strong>}<br>                    }<br>                    </strong>scm <strong>{<br>                        </strong>connection = &#39;&#39;<br>                        url = &#39;&#39;<br>                    <strong>}<br>                    </strong>developers <strong>{<br>                        </strong>developer <strong>{<br>                            </strong>id = &#39;&#39;<br>                            name = &#39;&#39;<br>                            email = &#39;&#39;<br>                        <strong>}<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</strong></pre><p>Most of this code was taken from <a href="https://gist.github.com/Robyer/a6578e60127418b380ca133a1291f017">here</a>. The preserveFileTimestamps and reproducibleFileOrder arguments were added so that our source code jar and Javadoc jar result in the same hash every time we generate them, unless the source code has actually changed. Extra arguments have been added in the Javadoc generation task, so that any UTF-8 characters contained in your source code appear correctly to the final Javadoc (yeah, it requires 3 arguments to make this right). At the end, we have to specify some metadata that will be required when publishing to Maven. In this example, empty strings have been added as placeholders.</p><p>We can now include this file to the end of the Android Library’s build.gradle file:</p><pre>apply from: &#39;../publish-helper.gradle&#39;</pre><p>We can also override default values like so:</p><pre>apply from: &#39;../publish-helper.gradle&#39;<br><br>afterEvaluate <strong>{<br>    </strong>publishing <strong>{<br>        </strong>publications <strong>{<br>            </strong>release<strong>(</strong>MavenPublication<strong>) {<br>                </strong>// Specify custom artifactId if needed,<br>                // otherwise it will use module&#39;s name by default.<br>                artifactId = &quot;our library name&quot;<br>            <strong>}<br>        }<br>    }</strong></pre><p>Let Gradle sync, and open the Gradle pane on the right of Android Studio and find the publishReleasePublicationToMavenLocal task. If you run it, your Android Library will be published locally to the .m2 folder under your user directory .</p><p>If your Android Library depends on another module, you will have to include the publish-helper.gradle to that module as well. The maven-publish plugin will publish both of the modules and the generated pom file (the file that mentions your dependencies) will list the dependent module using its group id and artifact id. If you used api for the dependency, it will be converted to compile. If you used implementation, it will be converted to runtime.</p><p>It’s time to make a test project that consumes the locally published library and test that your library works as expected. In the project’s build.gradle add the maven local repository:</p><pre>allprojects <strong>{<br>    </strong>repositories <strong>{<br>        </strong>mavenLocal<strong>() </strong>// add it here<br>        google<strong>()<br>        </strong>jcenter<strong>()<br>    }<br>}</strong></pre><p>You can now add your published library as a dependency, like you would normally do.</p><p>In case your published library is a pure Java library (it uses the java or the java-library plugin), we have to make some adjustments when building the Javadoc and source code. Instead of creating a different publish helper file for each file, we will use if (plugins.hasPlugin()) to differentiate between the two as explained <a href="https://dzone.com/articles/publishing-multi-module-android-libraries">here</a>. So, our publish-helper.gradle file becomes:</p><pre>apply plugin: &#39;maven-publish&#39;<br><br>task androidJavadoc<strong>(</strong>type: Javadoc<strong>) {<br>    if (</strong>plugins.hasPlugin<strong>(</strong>&#39;android-library&#39;<strong>)) {<br>        </strong>source = android.sourceSets.main.java.srcDirs<br>        classpath += project.files<strong>(</strong>android.getBootClasspath<strong>()</strong>.join<strong>(</strong>File.<strong><em>pathSeparator</em>))<br>        </strong>android.libraryVariants.all <strong>{ </strong>variant <strong>-&gt;<br>            if (</strong>variant.name == &#39;release&#39;<strong>) {<br>                </strong>owner.classpath += variant.javaCompileProvider.get<strong>()</strong>.classpath<br>            <strong>}<br>        }<br>    }<br>    else {<br>        </strong>source = sourceSets.main.allJava<br>        classpath += configurations.runtimeClasspath<br>        classpath += configurations.compileClasspath<br>    <strong>}<br>    </strong>exclude &#39;**/R.html&#39;, &#39;**/R.*.html&#39;, &#39;**/index.html&#39;<br>    options.encoding &#39;utf-8&#39;<br>    options <strong>{<br>        </strong>addStringOption &#39;docencoding&#39;, &#39;utf-8&#39;<br>        addStringOption &#39;charset&#39;, &#39;utf-8&#39;<br>        links &#39;https://docs.oracle.com/javase/7/docs/api/&#39;<br>        links &#39;https://d.android.com/reference&#39;<br>        links &#39;https://developer.android.com/reference/androidx/&#39;<br>    <strong>}<br>}<br><br></strong>task androidJavadocJar<strong>(</strong>type: Jar, dependsOn: androidJavadoc<strong>) {<br>    </strong>archiveClassifier.set<strong>(</strong>&#39;javadoc&#39;<strong>)<br>    </strong>from androidJavadoc.destinationDir<br>    preserveFileTimestamps = <strong>false<br>    </strong>reproducibleFileOrder = <strong>true<br>}<br><br></strong>task javaSourcesJar<strong>(</strong>type: Jar<strong>) {<br>    </strong>archiveClassifier.set<strong>(</strong>&#39;sources&#39;<strong>)<br>    if (</strong>plugins.hasPlugin<strong>(</strong>&#39;android-library&#39;<strong>)) {<br>        </strong>from android.sourceSets.main.java.srcDirs<br>    <strong>}<br>    else {<br>        </strong>from sourceSets.main.allSource<br>    <strong>}<br>    </strong>preserveFileTimestamps = <strong>false<br>    </strong>reproducibleFileOrder = <strong>true<br>}<br><br></strong>afterEvaluate <strong>{<br>    </strong>publishing <strong>{<br>        </strong>publications <strong>{<br>            </strong>release<strong>(</strong>MavenPublication<strong>) {<br>                if (</strong>plugins.hasPlugin<strong>(</strong>&#39;android-library&#39;<strong>)) {<br>                    </strong>from components.release<br>                <strong>}<br>                else if (</strong>plugins.hasPlugin<strong>(</strong>&#39;java&#39;<strong>)) {<br>                    </strong>from components.java<br>                    jar.preserveFileTimestamps = <strong>false<br>                    </strong>jar.reproducibleFileOrder = <strong>true<br>                }<br><br>                </strong>artifact androidJavadocJar<br>                artifact javaSourcesJar<br><br>                groupId &#39;&#39;<br>                version &#39;&#39;<br>                pom <strong>{<br>                    </strong>name = artifactId<br>                    description = &#39;&#39;<br>                    url = &#39;&#39;<br>                    licenses <strong>{<br>                        </strong>license <strong>{<br>                            </strong>name = &#39;&#39;<br>                            url = &#39;&#39;<br>                        <strong>}<br>                    }<br>                    </strong>scm <strong>{<br>                        </strong>connection = &#39;&#39;<br>                        url = &#39;&#39;<br>                    <strong>}<br>                    </strong>developers <strong>{<br>                        </strong>developer <strong>{<br>                            </strong>id = &#39;&#39;<br>                            name = &#39;&#39;<br>                            email = &#39;&#39;<br>                        <strong>}<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</strong></pre><h4>Publish to Maven Central from your computer</h4><p>So far, we have managed to publish the library locally, but we want to publish it to Maven Central. The steps needed are:</p><ul><li>Create a ticket with Sonatype</li><li>Create a GPG key (I recommend using <a href="https://www.openpgp.org/software/kleopatra/">Kleopatra</a>)</li><li>Upload Public Key To Directory Service</li><li>Configure gradle for signing and publishing</li></ul><p>You can find details on the first three steps in these guides: <a href="https://blog.autsoft.hu/publishing-an-android-library-to-mavencentral-in-2019/">1</a>, <a href="https://proandroiddev.com/publishing-your-first-android-library-to-mavencentral-be2c51330b88">2</a> You can also read the<a href="https://central.sonatype.org/publish/publish-guide/"> official Sonaytpe guidelines</a>. Let’s jump to configuring gradle.</p><p>Place the following to your project’s build.gradle:</p><pre>File secretPropsFile = project.rootProject.file<strong>(</strong>&#39;local.properties&#39;<strong>)<br>if (</strong>secretPropsFile.exists<strong>()) {<br>    </strong>Properties p = <strong>new </strong>Properties<strong>()<br>    </strong>p.load<strong>(new </strong>FileInputStream<strong>(</strong>secretPropsFile<strong>))<br>    </strong>p.each <strong>{ </strong>name, value <strong>-&gt;<br>        </strong>ext<strong>[</strong>name<strong>] </strong>= value<br>    <strong>}<br>}</strong></pre><p>Open your local.properties and populate the following values:</p><pre>signing.keyId=<br>signing.password=<br>signing.secretKeyRingFile=<br>ossrhUsername=<br>ossrhPassword=</pre><p>The first 3 values are related to your key. signing.secretKeyRingFile is the file path to your private key. The ossrhUsername and ossrhPassword are the ones used to login to Sonaytpe. Instead of placing your actual credentials, you can generate tokens as explained <a href="https://help.sonatype.com/iqserver/managing/user-management/user-tokens">here</a>. Note that by default, the local.properties file is not added to Git. Make sure that this is the case for your case as well.</p><p>We need to make the following changes to our publish-helper.gradle. Add the signing plugin:</p><pre>apply plugin: &#39;maven-publish&#39;<br>apply plugin: &#39;signing&#39;</pre><p>Add this to the end (even though we will remove the “repositories” part later):</p><pre>afterEvaluate <strong>{<br>    </strong>publishing <strong>{<br>        </strong>publications <strong>{<br>            </strong>...<br>        <strong>}<br>        </strong>repositories <strong>{<br>            </strong>maven <strong>{<br>                </strong>name = &quot;sonatype&quot;<br><br>                <strong>def </strong>releasesRepoUrl = &quot;https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/&quot;<br>                <strong>def </strong>snapshotsRepoUrl = &quot;https://s01.oss.sonatype.org/content/repositories/snapshots/&quot;<br>                url = version.endsWith<strong>(</strong>&#39;SNAPSHOT&#39;<strong>) </strong>? snapshotsRepoUrl : releasesRepoUrl<br><br>                credentials <strong>{<br>                    </strong>username ossrhUsername<br>                    password ossrhPassword<br>                <strong>}<br>            }<br>        }<br>    }<br>}<br><br></strong>signing <strong>{<br>    </strong>sign publishing.publications<br><strong>}</strong></pre><p>This configuration enables uploading SNAPSHOT versions of your library. You will just have to name the version to something like: 1.0.0-SNAPSHOT and it will be released to Maven’s snapshot repo.</p><p>Go to the Gradle pane on the right and run the publishReleasePublicationToSonatypeRepository task. This will publish your library to the staging repo, which you can <a href="https://s01.oss.sonatype.org/#stagingRepositories">find here</a>. Check that everything’s ok and close the repository. You can now release the repository (and check “automatically drop”). If this was your first release, you should go back to the Jira ticket and comment to let them know that your repository setup and publication is working. The library will eventually become public.</p><h4>Prepare for GitHub</h4><p>We need to make a couple of adjustments so that our Gradle tasks can be run by GitHub.</p><p>Instead of manually going to Sonaytpe to release the staging repo every time, we will use the <a href="https://github.com/gradle-nexus/publish-plugin">gradle-nexus.publish-plugin</a>. Place the plugin to your project’s build.gradle :</p><pre>plugins <strong>{<br>    </strong>id &quot;io.github.gradle-nexus.publish-plugin&quot; version &quot;1.0.0&quot;<br><strong>}</strong></pre><p>and configure it:</p><pre>nexusPublishing <strong>{<br>    </strong>repositories <strong>{<br>        </strong>sonatype <strong>{<br>            </strong>stagingProfileId = &#39;&#39;<br>            nexusUrl.set<strong>(</strong>uri<strong>(</strong>&quot;https://s01.oss.sonatype.org/service/local/&quot;<strong>))<br>            </strong>snapshotRepositoryUrl.set<strong>(</strong>uri<strong>(</strong>&quot;https://s01.oss.sonatype.org/content/repositories/snapshots/&quot;<strong>))<br>            </strong>username = ossrhUsername<br>            password = ossrhPassword<br>            version = &#39;&#39;<br>        <strong>}<br>    }<br>}</strong></pre><p>You can get your stagingProfileId by logging in Sonatype and selecting “Staging Profiles” on the left sidebar. You find the id on the URL.</p><p>We should also remove the repository configuration we added in our publish-helper.gradle in the previous step. The publishing plugin will take care of that now. Otherwise, we will end up with 2 similarly named Gradle tasks.</p><p>Let Gradle sync. Some new tasks will appear in he publishing section. In order to publish your library and close &amp; release the corresponding staging repository, run from the console:</p><pre>./gradlew publishReleasePublicationToSonatypeRepository closeAndReleaseSonatypeStagingRepository</pre><p>As a final preparation step, we have to read all the variables from environmental variables. This is because sensitive information can be store to GitHub secrets, which can be exposed to scripts as environmental variables. We also need to to write the private key to a file, since we will read its contents in base64 from an environmental variable. So, the project’s build.gradle will be updated as:</p><pre>// Initialize publishing/signing extra properties with environmental vars<br>ext<strong>[</strong>&#39;signing.keyId&#39;<strong>] </strong>= System.getenv<strong>(</strong>&#39;SIGNING_KEY_ID&#39;<strong>) </strong>?: &#39;&#39;<br>ext<strong>[</strong>&#39;signing.password&#39;<strong>] </strong>= System.getenv<strong>(</strong>&#39;SIGNING_PASSWORD&#39;<strong>) </strong>?: &#39;&#39;<br>ext<strong>[</strong>&#39;signing.secretKeyRingFile&#39;<strong>] </strong>= System.getenv<strong>(</strong>&#39;SIGNING_SECRET_KEY_RING_FILE&#39;<strong>) </strong>?: &#39;&#39;<br>ext<strong>[</strong>&#39;ossrhUsername&#39;<strong>] </strong>= System.getenv<strong>(</strong>&#39;OSSRH_USERNAME&#39;<strong>) </strong>?: &#39;&#39;<br>ext<strong>[</strong>&#39;ossrhPassword&#39;<strong>] </strong>= System.getenv<strong>(</strong>&#39;OSSRH_PASSWORD&#39;<strong>) </strong>?: &#39;&#39;<br>// Override with local.properties if available<br>File secretPropsFile = project.rootProject.file<strong>(</strong>&#39;local.properties&#39;<strong>)<br>if (</strong>secretPropsFile.exists<strong>()) {<br>    </strong>Properties p = <strong>new </strong>Properties<strong>()<br>    </strong>p.load<strong>(new </strong>FileInputStream<strong>(</strong>secretPropsFile<strong>))<br>    </strong>p.each <strong>{ </strong>name, value <strong>-&gt;<br>        </strong>ext<strong>[</strong>name<strong>] </strong>= value<br>    <strong>}<br>}<br><br></strong><br><strong>def </strong>pgpKeyContent = System.getenv<strong>(</strong>&#39;PGP_KEY_CONTENTS&#39;<strong>)<br>if (</strong>pgpKeyContent != <strong>null) {<br>    def </strong>tmpDir = <strong>new </strong>File<strong>(</strong>&quot;$rootProject.rootDir/tmp&quot;<strong>)<br>    </strong>mkdir tmpDir<br>    <strong>def </strong>keyFile = <strong>new </strong>File<strong>(</strong>&quot;$tmpDir/key.pgp&quot;<strong>)<br>    </strong>keyFile.createNewFile<strong>()<br>    def </strong>os = keyFile.newDataOutputStream<strong>()<br>    </strong>os.write<strong>(</strong>pgpKeyContent.decodeBase64<strong>())<br>    </strong>os.close<strong>()<br>    </strong>pgpKeyContent = &#39;&#39;<br><br>    ext<strong>[</strong>&#39;signing.secretKeyRingFile&#39;<strong>] </strong>= keyFile.absolutePath<br><strong>}</strong></pre><p>This configurations tries to read the required properties from environmental variables. If local.prperties is found, it uses that instead. This way, the set-up can work at GitGub and locally. Even if someone pulls your repo, without setting up these properties, they can build the project without errors. The script will also write the private key to a tmp/key.pgp .</p><h4>Build a GitHub workflow</h4><p>You can start by creating a new GitHub action using the <a href="https://github.com/marketplace/actions/gradle-command">Gradle command</a>. It’s better to also setup a cache for Gradle as explained in the guide. Our goal is to create a workflow that is triggered when a new release is published:</p><pre>on:<br>  release:<br>    types: [published]</pre><p>The step that runs our Gradle tasks can be:</p><pre>- name: Build and publish to Maven<br>      env:<br>        SIGNING_KEY_ID: ${{ secrets.SIGNING_KEY_ID }}<br>        SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }}<br>        OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }}<br>        OSSRH_PASSWORD: ${{ secrets.OSSRH_PASSWORD }}<br>        PGP_KEY_CONTENTS: ${{ secrets.PGP_KEY_CONTENTS }}<br>      run:<br>        ./gradlew publishReleasePublicationToSonatypeRepository closeAndReleaseSonatypeStagingRepository</pre><p>The secrets that are referenced have to be set in your GitHub’s repository as shown in the <a href="https://docs.github.com/en/actions/reference/encrypted-secrets">documentation</a>. PGP_KEY_CONTENTS should contain the Base64 version of your private key.</p><h4>Conclusion</h4><p>I may have skipped some steps, but I tried to reduce the guide as much as possible. If you want to see a fully working example, check my <a href="https://github.com/transifex/transifex-java/blob/master/TransifexNativeSDK/build.gradle">builde.gradle</a> and <a href="https://github.com/transifex/transifex-java/blob/master/TransifexNativeSDK/publish-helper.gradle">publish-helper.gradle</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f98a311df2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android 10 & 11 storage cheat sheet]]></title>
            <link>https://petrakeas.medium.com/android-10-11-storage-cheat-sheet-76866a989df4?source=rss-1516935fe5ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/76866a989df4</guid>
            <category><![CDATA[storage]]></category>
            <category><![CDATA[storage-access-framework]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Petros Douvantzis]]></dc:creator>
            <pubDate>Thu, 04 Mar 2021 12:15:37 GMT</pubDate>
            <atom:updated>2021-03-04T12:35:43.644Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kVeD_1dD9NpKYEhzsYvigA.png" /></figure><p>Google keeps changing the way apps can access shared files by adding and lifting restrictions to existing APIs to the point they had to write <a href="https://developer.android.com/training/data-storage/use-cases">this</a>.</p><p>The following is a simplified guide about the storage options of an app and how they differentiate between Android versions.</p><p><strong>TLDR</strong>: not much have actually changed if you’re making a camera app. If you have a gallery or file app, then you have to do some refactoring.</p><p>In Android, an app has access to:</p><ol><li>private folders that only the app can see: <a href="https://medium.com/r?url=https%3A%2F%2Fdeveloper.android.com%2Freference%2Fandroid%2Fcontent%2FContext%23getFilesDir%28%29">getFilesDir(</a>), <a href="https://developer.android.com/reference/android/content/Context#getCacheDir()">getCacheDir()</a> .<br>/data/user/0/&lt;package_name&gt;/files<br>/data/user/0/c&lt;package_name&gt;/files</li><li>app-specific folders that other apps can see. There is a generic one: <a href="https://developer.android.com/reference/android/content/Context#getExternalFilesDirs(java.lang.String)">getExternalFilesDirs(</a>) and a media one: <a href="https://developer.android.com/reference/android/content/Context#getExternalMediaDirs()">getExternalMediaDirs()</a>. These are deleted when the app is deleted. These directories have 2 variants:<br>1. those that exist in internal storage. You can get the path using the first element in the array returned by the aforementioned methods. /storage/emulated/0/Android/data/&lt;package_name&gt;/files<br>/storage/emulated/0/Android/media/&lt;package_name&gt;<br>2. those that exist in external storage such as SD card. You can get the path using the second element in the array returned by the aforementioned methods. <br>/storage/11EC-2402/Android/data/&lt;package_name&gt;/files<br>/storage/11EC-2402/Android/media/&lt;package_name&gt;</li><li>public folders that all apps can see, like DCIM, Music, Download folder etc. They can be selected by the user by starting an <a href="https://developer.android.com/training/data-storage/shared/documents-files#grant-access-directory">ACTION_OPEN_DOCUMENT_TREE</a> intent. These directories have 2 variants:<br> 1. those that exist in internal storage. Another (deprecated) way to get the path to these folders is with <a href="https://developer.android.com/reference/android/os/Environment#getExternalStoragePublicDirectory(java.lang.String)">getExternalStoragePublicDirectory()</a>. <br>/storage/emulated/0/DCIM<em> <br></em>/storage/emulated/0/Download<em><br></em>2. those that exist in external storage such as SD card. <br>/storage/11EC-2402/DCIM</li></ol><p>Note that the paths above are examples and should not be used as is.</p><p>All Android versions can write to 1, 2.1, 2.2 using the classic <a href="https://developer.android.com/reference/java/io/File">Files API</a>.</p><p>Android 10 requires asking user permission for <a href="https://developer.android.com/reference/android/Manifest.permission#WRITE_EXTERNAL_STORAGE"><em>WRITE_EXTERNAL_STORAGE</em></a>, as usual, and setting <a href="https://developer.android.com/reference/android/R.attr#requestLegacyExternalStorage">android:requestLegacyExternalStorage=”true”</a> to the manifest to access 3.1 using Files API. You can write whatever filetype you want in these folders and also delete pre-existing files or files created by other apps. 3.2 can’t be accessed this way.</p><p>Android 11 can write to 3.1 and 3.2 (no manifest flag needed) as long as the file type written matches the directory. For example, you can’t write a .mp3 file in DCIM folder. In Downloads folder, you can write whatever you want. Your app can delete only files created by it. It can’t delete pre-existing files or file created by a previous installation of the app. It can read files created by other apps. You can’t write to a random folder in the internal storage such as /storage/emulated/0/Test but you can read its contents.</p><p>Note that in Android 11 you don’t even have to declare <a href="https://developer.android.com/reference/android/Manifest.permission#WRITE_EXTERNAL_STORAGE"><em>WRITE_EXTERNAL_STORAGE</em></a><em> </em>in your manifest or ask user permission in order to write to all the aforementioned folders. If you want to read files created by other apps though, you’ll have to ask the user for <a href="https://developer.android.com/reference/android/Manifest.permission#WRITE_EXTERNAL_STORAGE"><em>WRITE_EXTERNAL_STORAGE</em></a><em> </em>or <a href="https://developer.android.com/reference/android/Manifest.permission#READ_EXTERNAL_STORAGE">READ_EXTERNAL_STORAGE</a> permission.</p><p>And here’s another small cheat sheet taken from <a href="https://developer.android.com/guide/topics/manifest/uses-sdk-element.html">here</a>:<br>Android 11 == code R == API 30 <br>Android 10 == code Q == API 29</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76866a989df4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Half-Life Alyx theory]]></title>
            <link>https://petrakeas.medium.com/half-life-alyx-theory-b2c2fbb43a10?source=rss-1516935fe5ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2c2fbb43a10</guid>
            <category><![CDATA[half-life-alyx]]></category>
            <category><![CDATA[half-life]]></category>
            <category><![CDATA[theory]]></category>
            <dc:creator><![CDATA[Petros Douvantzis]]></dc:creator>
            <pubDate>Sat, 30 Jan 2021 21:26:43 GMT</pubDate>
            <atom:updated>2021-01-30T21:36:04.755Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jg38MZH1b5tMo9f5OH_LSw.png" /></figure><p>If you haven’t played the game (or seen the ending), you better stop right here, as the following contain spoilers.</p><p>After finishing Half-Life:Alyx, the role of G-Man became clear to me and all pieces simply fell in place. This theory may not explain every bit of the Half-Life plot, but it will let us understand the basic concept behind it. If you are expecting a 100% realistic answer you may be disappointed, as this theory has a more abstract approach. If you’re familiar with David Lynch, you’ll feel right at home. The quotes below are from G-Man at the ending of Half-Life Alyx. Here it goes:</p><p><strong>The G-Man</strong>: He represents Valve, the story writers and developers, those who decide the future of Half Life. He’s the tool via whom stuff happens in the Half-Life universe. If for example a DLC needs to me made, G-Man will do what’s necessary so that the game has a plot and a reason for existence. He’s the cog between Valve and stuff happening inside the game.</p><p>You can hear him admit this:</p><p>“Some believe that the fate of this world is inflexible. My employers disagree. They authorize me to nudge things in a particular direction from time to time”.</p><p>If you think about it, whenever a new Half-Life game has to appear, G-Man does his magic on the background. For example, he’s the one who wakes up Gordon Freeman. His employers are Valve and the game developers.</p><p><strong>Gordon Freeman</strong>: He used to represent the player. All players playing the game connected with the Half Life universe via Gordon’s eyes. Between Half-Life 1 and Half -Life 2, 6 years elapsed. During this time, Gordon was in a “hibernation state” .When Half-life 2 began, his consciousness (us, the players) is brought back to life.</p><p>Gordon served the series well, but after HL episode 3, the series went on a halt. Valve worked on lots of prototypes with Gordon that led nowhere and got canceled.</p><p>This is why G-Man says:</p><p>“A previous hire has been unable to perform the tasks laid before him”</p><p>“We have struggled to find a suitable replacement. Until now”</p><p>After 13 years of effort, Valve turns to Alyx for the protagonist of a new game. And she seems to be suited for the job. She’s much more than what they originally thought. And hence Half-Life Alyx comes to life.</p><p>“You are aware that you’ve proven yourself to be of extraordinary value”.</p><p>Indeed, Alyx managed to bring back Half Life from the dead.</p><p>Alyx asks a favor from G-Man. She wants the Combine off earth. G-man can twist the plot a bit, but he can’t do this particular favor because the Half-Life series would cease to exist.</p><p>“That would be a considerably large nudge.<br>Too large, given the interests of my employers”</p><p>The interest of Valve is to make new Half Life games. If the Combine are gone, there would be no interest for a new game. So, Alyx asks to save her father. This is a nudge that can be made by G-Man. Valve has no issues with that, as it would push the plot forward and create an opportunity for a new game.</p><p>So, what about the vault where G-Man was trapped? I think that it represents a place with no time or space as the game is concerned. It’s like a simulation, closer to the game engine and the developers. If this was Matrix, it’s where the architect would be.</p><p>Until the next game is released, G-Man hibernates Alyx as he used to do for Gordon.</p><p>Subject: Alyx Vance<br>Status: hired<br>AWAITING ASSIGMENT</p><p>So probably the next game will be with Alyx??</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2c2fbb43a10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Half-Life: Alyx performance analysis (or: why low graphic settings produce a sharper image)]]></title>
            <link>https://petrakeas.medium.com/half-life-alyx-performance-analysis-or-why-low-graphic-settings-produce-a-sharper-image-4d17fb8c19bb?source=rss-1516935fe5ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d17fb8c19bb</guid>
            <category><![CDATA[valve-index]]></category>
            <category><![CDATA[vr-headset]]></category>
            <category><![CDATA[vr]]></category>
            <category><![CDATA[steamvr]]></category>
            <category><![CDATA[half-life-alyx]]></category>
            <dc:creator><![CDATA[Petros Douvantzis]]></dc:creator>
            <pubDate>Sat, 06 Jun 2020 14:53:37 GMT</pubDate>
            <atom:updated>2020-06-09T10:09:53.427Z</atom:updated>
            <content:encoded><![CDATA[<p>I have been a happy PSVR user for more than 1 year and due to Alyx, I got the Valve Index. Alyx and the Index live in the PC space and playing with it reminded me of the difference between console and PC gaming in terms of tweaking and out of the box experience.</p><p>Alyx was built to work with a variety of VR headsets and different setups in terms of computing power. It comes as no surprise that it has various graphic options to tweak, on top of those provided by Steam VR such as “render resolution” and “motion smoothing”. If you’re like me, you’ll understand why I spent my first 2 weeks with the headset playing with the settings instead of enjoying the actual game.</p><p>So, here are my findings which will can hopefully help you get a higher resolution picture from the game. I run Alyx on my PC, having a GTX1080, and on my Razer Blade Advanced 2019 model, having an RTX2080 Max-Q. I will also get into some details in the end of the article about the issues I faced when running VR from a laptop.</p><p>If you’re interested just in the tips, you can skip to the <strong>TLDR </strong>paragraph.</p><h3>Steam VR render scale</h3><p>Before diving into Alyx’s dynamic resolution implementation, we need to first look at how Steam VR handles resolution. When a game renders a frame, it isn’t sent straight to the headset. It’s handed over to Steam VR’s compositor, which applies lens correction and renders it to the headset’s native resolution. So, the game’s resolution can be different than the headset’s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_4hfKdIQ3CmwtiOiFTm6CA.gif" /><figcaption>Steam VR settings</figcaption></figure><p>In Steam VR you can set the “<strong>render resolution</strong>” per eye. Valve index has a per-eye resolution of <em>1440×1600</em>. Setting the render resolution to <em>100%</em> results in <em>2016×2440</em>.</p><blockquote>The reason it’s bigger than the headset’s native resolution is because it takes into account that lens correction will stretch out the center of the game’s rendered frame and it will need more pixels to sample from.</blockquote><p>Steam VR has a per-game resolution multiplier that when multiplied with the render resolution, produces the resolution that the game will render to. Let me give you an example.</p><p>If you use <em>120%</em> for the “render resolution”and <em>200%</em> for the per-game multiplier, the final resolution scale will be: <em>120% x 200% = 240 %</em> , producing a render resolution of <em>3122×3780</em>. Note that the percentage refers to the total amount of pixels and not the per axis increase. So, 200% will not result in a horizontal resolution of <em>2 x 2016 = 4032 </em>, but in</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/131/1*jW0IcC3p-_rvipKBQKSHTg.png" /></figure><p>The total amount of pixels (taking into account both the horizontal and vertical resolution increase) will be double, though.</p><h3>Alyx dynamic resolution</h3><p>Alyx, on the other hand, uses a dynamic resolution scheme, where Steam VR’s resolution is only used as a reference. You can check out a really interesting analysis of the game’s algorithm by <a href="https://www.gdcvault.com/play/1023522/Advanced-VR-">Alex Vlachos</a> , but I’ll explain the gist of it bellow.</p><p>Alyx uses 8 different <strong>fidelity levels </strong>(not to be confused with fidelity levels found in the game’s graphics settings menu), which result in higher or smaller render resolutions and MSAA x4. In my case, where I set the global steam VR scale to 118% (2188 x 2432), the levels are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*wjmkgkArPNAN0tYo6pU3vA.png" /><figcaption>Resolutions per fidelity level. Steam resolution is 2188 x 2432.</figcaption></figure><blockquote><strong>Level 3</strong> defaults to the Steam VR resolution. The other resolutions are calculated according to each fidelity level’s scale. For example, level 8 results to 3094 x 3439 which has double the amount of pixels than fidelity level 3.</blockquote><p>The game tries to choose the higher fidelity level possible, as long as no frame is dropped. If you run your headset at 90Hz, the GPU has a <em>11,1ms</em> window to render the frame. Alyx, will try to render it in <em>0,9*11,1 = 10 ms </em>as it leaves some time for the VR compositor to do the final render and also allows for some headroom. This means that if you get into a GPU intensive scene, Alyx will probably drop the fidelity level. On the other hand, looking at the sky, will probably reach level 8.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*rz2IftgyECO3F0yNe42QPQ.gif" /><figcaption>The algorithm chooses a higher fidelity level for less complex scenes , such as looking towards the sky</figcaption></figure><p>You can visualize the fidelity level used, by launching the game with <strong>-console -vconsole</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*i1-80uNH5F3Ic43qYU8WbA.png" /></figure><p>, pressing the<strong> </strong>tilde(~) key to open the console, typing <strong>vr_perf_hud 1 </strong>and hitting enter. There is a way to disable the automatic fidelity level algorithm and force your own. To disable it, type: <strong>vr_fidelity_level_auto 0 and </strong>to force fidelity level 8, type: <strong>vr_fidelity_level 8</strong> .</p><p>I played with the fidelity levels while gazing at City 17 from the balcony at the beginning of the game. The following gifs cycle between level 0, 3, 6, 8:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uHDz9-ncEs2soKlBIGeA3Q.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*b7lENibUDQn8a7SnrHxoCQ.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*0jkD5Dnw5h8jD0-TX1AiQg.gif" /><figcaption>Gif cycling different fidelity levels. Notice how the GPU time graph increases with the level.</figcaption></figure><p>Due to gif compression, the difference may not be that apparent. To see the difference better, you can view the in-game screenshots on a computer monitor: <a href="https://i.imgur.com/b7ZxhQl.jpg">0</a>, <a href="https://i.imgur.com/TtU2aKd.jpg">3</a>, <a href="https://i.imgur.com/CB9Dgjt.jpg">6</a>, <a href="https://i.imgur.com/JUUMnva.jpg">8</a>. Notice that the higher the fidelity level, the larger the screenshot size. This is because Alyx is handing a larger buffer to Steam VR’s compositor as fidelity level increases.</p><p>Level 8 resulted in super clear and detailed textures. I could easily make out the individual leaves of the trees at the street level and the railings of the balcony at the first floor were rendered beautifully. The geometry of the buildings far away was solid without shimmering. Level 3 on the other hand, was quite more blurry. <strong>Level 6 was a good compromise</strong>. Unfortunately, the game mostly played around level 3 with the out of the box settings.</p><p>Alyx does not give you a direct way (besides using the console) of controlling the fidelity level from the graphics options, but you can control it in an indirect way: using higher graphic presets, can result in a lower fidelity level. This is far from intuitive, but since you are stressing your GPU more at higher quality settings, the algorithm will have to drop the resolution to manage and hit those 10 ms.</p><blockquote>I noticed that in some reviews where they fiddle with the graphics options and conclude that Alyx plays well in Ultra settings even in lower-end GPUs, they don’t realize that they’re getting a blurrier image. For example, in <a href="https://game-debate.com/news/28601/half-life-alyx-pc-low-vs-ultra-graphics-comparison">this comparison</a> they attribute the bluriness of ULTRA settings to different Anti-Aliasing and not to the lower fidelity level chosen by the algorithm.</blockquote><h3>Graphics options</h3><p>Alyx has some graphics options under the “performance” menu, which can alter the quality and the effect detail level. There are some ready to use presets that vary from “low fidelity” to “high fidelity”. Even though the word “fidelity” is used, it’s not related to the “fidelity level” that controls the game’s resolution.</p><p>Here are 2 screenshots with <strong>low </strong>and <strong>ultra </strong>settings. The fidelity level has manually been forced to 6, so that we remove that from the equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nTD_FNy11OQP__lnOk29LQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZJNOQJDpZCTDEDzUd4cZbA.jpeg" /><figcaption>“low” settings on the left, “ultra” settings on the right</figcaption></figure><p>If you’re struggling to see the difference, it’s because in this particular scene there is virtually no difference. If you zoom-in you can see in the “ultra” screenshot, that the characters have an ambient shadow in their feet. This is controlled by the “character” setting. The performance implications though from “low” to “ultra” are vast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S0OBQwaZ4urMyQ9BtM41eQ.jpeg" /><figcaption>“High” settings with some tweaks</figcaption></figure><p>The “textures” setting remains at “high” regardless of the preset you use. It has almost no performance cost, unless you run low on GPU memory. The settings that can greatly affect performance are “characters”, “fog” and “shadow”. You can see exactly how they affect the image in this <a href="https://game-debate.com/news/28601/half-life-alyx-pc-low-vs-ultra-graphics-comparison">really good guide</a> (that I previously mentioned). The “shadows” setting affects the resolution of the dynamic shadows. “Character” setting does not seem to affect the character detail, but it enables something like ambient occlusion and creates a soft shadow on the character’s feet making them look more grounded.</p><p>In order to measure the performance cost of these 3 settings, I set all of them to “low” and measured GPU time with fidelity level locked to 3. I changed each setting to “medium” and “high” and measured the increase in GPU time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*JrGbbXCGLYQE6IlQrHMqaQ.png" /><figcaption>GPU time increase (in ms) per graphic setting</figcaption></figure><p>The way to read the table is for example, that an increase in “character” level from “low” to “medium” costs 0,7 ms.</p><p><strong>If you want to gain performance</strong>, set all of them to low.</p><p><strong>For a slightly better visual result</strong> set:</p><ul><li>“shadows” to “medium” or “high”</li><li>“fog” to “medium”</li></ul><h3>MSAA</h3><p>Alyx uses MSAA x4 for all fidelity levels (at least in my system). You can change (or even disable) the MSAA level, by writing in the console: <strong>vr_msaa 0</strong>.</p><p>Many gamers think that MSAA is mostly blurring the geometry edges, but that would be an oversimplification. Its effect is crucial to the visual quality in VR, image stability and geometry detail as the following screenshot shows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*1tYqQ2px1CPOf1x46vC75Q.gif" /><figcaption>MSAA level comparison (check out the tree branches)</figcaption></figure><p>MSAA x4 effectively quadruples the geometry coverage. Geometry that is driven by alpha textures such as wires and tree branches (that probably use <a href="https://medium.com/@bgolus/anti-aliased-alpha-test-the-esoteric-alpha-to-coverage-8b177335ae4f">“alpha to coverage”</a> and rely on MSAA to work correctly) have a huge improvement with MSAA enabled.</p><p>I also noticed that disabling MSAA produces a slightly brightened image. I believe that Alyx expects MSAA to be enabled before tone-mapping the final image.</p><p>What about the performance cost you may ask? Here’s a really interesting table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*1OMaiMIA3LRIQJaNxAcJQQ.png" /><figcaption>GPU time for different MSAA values and fidelity levels</figcaption></figure><p>It’s certainly not cheap. But if you consider that using MSAA x4 is similar to rendering geometry from a buffer of 2700x3000 to one of 5400x6000, it’s acceptable. Fragment shaders still run at the initial resolution. So, even though you gain more “geometry” resolution, you don’t get sharper textures.</p><p>You may be tempted to disable it though. Looking at the table, you can see that “fid. level 6, MSAA x2” has similar performance to “fil. level 8, MSAA x0”. Check out the visual comparison:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*KQ0oQvsn18Q06AGCgVnFrQ.gif" /><figcaption>fidelity level VS MSAA level</figcaption></figure><p>I think the choice between the two is obvious.</p><p>“Fid. level 6, MSAA x4” is slightly faster than “Fid. level 8, MSAA x2”. Here’s a comparison:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*o36PyzYWxk7L7Sk2JX_Tzw.gif" /></figure><p>The difference in this case is much smaller.</p><p>Here are all the screenshots. I recommend looking at them at a 100% scale in a monitor.</p><ul><li><a href="https://i.imgur.com/OYzjdpm.jpg">fidelity level 6, MSAA x</a>0</li><li><a href="https://i.imgur.com/0brvytO.jpg">fidelity level 6, MSAA x2</a></li><li><a href="https://i.imgur.com/1AFrDxI.png">fidelity level 6, MSAA x4</a></li><li><a href="https://i.imgur.com/bkp1MBl.jpg">fidelity level 8, MSAA x0</a></li><li><a href="https://i.imgur.com/seJIkyV.jpg">fidelity level 8, MSAA x2</a></li><li><a href="https://i.imgur.com/Ltzj2ju.jpg">fidelity level 8, MSAA x4</a></li></ul><h3>Motion smoothing</h3><p>Steam VR has the option of motion smoothing enabled by default. This can be useful when a game can’t deliver a frame in time. Motion smoothing takes into account the previous frames and creates a synthetic one. If enabled, it prepares<strong> </strong>a synthetic frame even if you never drop a frame, so that it’s ready if needed. <strong>This process however can increase the game’s render times by 2ms.</strong></p><blockquote>Not than unlike motion smoothing, reprojection is always running to correct the image, based on the headset’s latest orientation (not position). The performance cost of this operation is negligible. Reprojection will render a frame even if the game drops one, however it will not compensate for translation in the way “motion smoothing” does. For example, if you use locomotion, motion smoothing can make it look smooth even if the game drops frames. Timewarp can’t. Note that you won’t get motion sickness with motion smoothing disabled even if the game drops frames. You’ll just experience a bit of judder in moving objects. Reprojection, on the other hand, reduces motion sickness.</blockquote><p>Since Alyx is already varying the resolution to avoid dropping a frame, you don’t actually need “motion smoothing” enabled at the same time. So, disable it and enjoy the higher fidelity level that Alyx will choose due to the extra GPU power available to it.</p><p>If your GPU can’t reach the headset’s refresh rate, even with all the proposed optimizations applied, you can enable “forced motion smoothing” which results in halving the game’s refresh rate. In our example, Alyx will render at 45 Hz, which needs a render time of <strong>22ms</strong>. The game’s algorithm though will still try to hit <strong>10ms</strong> and probably choose a low fidelity level, which will result in a blurry picture. In this case, you can take the situation into your own hands and force a fidelity level that you like, as long as it has a render time of less than <strong>19ms. </strong>If you enter a demanding area though and it takes more than <em>19ms</em> to render the frame, the frame rate will drop to <em>90/3=30Hz</em>.</p><blockquote>It would be a great improvement if the auto fidelity algorithm targeted half the frame rate when “forced motion smoothing” was enabled.</blockquote><h3>Laptop optimization (aka: why nvidia Optimus sucks)</h3><p>Even though my Razer Blade’s RTX2080 Max Q performs similarly to my desktop’s GTX1080, the VR performance was quite bad. Fortunately, I found the reasons that caused it.</p><p>At first, I had to use Razer’s <strong>game mode</strong>, which<strong> </strong>resulted in robust performance without frame spikes. I usually don’t prefer it over <strong>balanced mode</strong>, due to the higher fan noise, but it’s mandatory for stable VR performance.</p><p>In case you are using Afterburner to lock the GPU frequency, don’t. It causes frame drops in VR.</p><p>The primary reason Alyx performed bad in my laptop though, was the spectator window. Most gaming laptops use <a href="https://www.geforce.com/hardware/technology/optimus/technology">nvidia’s Optimus technology</a>, which uses the nvidia discrete GPU for rendering and then copies the result to the integrated GPU so that it’s displayed in the monitor’s laptop. In the following screenshots, you can see the Intel integrated GPU (GPU 0), being utilized by “Desktop Window Manager” so that the VR view is rendered in the laptop’s screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XzB1iboaSgFjYH7RITnmSQ.png" /><figcaption>integrated GPU utilization when VR View is enabled in the laptop’s screen</figcaption></figure><p>In the next screenshot, I had the VR view disabled at first. The red line shows the time when I enabled the VR View. Notice that Intel’s GPU utilization increases and as a side-effect the CPU usage increases too, stealing CPU power from the game. This translates to increased render times in VR and thus frame drops.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l1-9LA0KEmNdfIbS4tjMqw.png" /><figcaption>CPU and GPU utilization increase when VR View gets enabled in laptop’s screen</figcaption></figure><p>One solution is to lower the spectator’s window resolution or even minimize it. To do that, run Alyx with <strong>-window -w 512 -h 512 </strong>. You can even disable the window entirely by running Alyx with <strong>-nowindow</strong>.</p><p>Another solution is to connect an external monitor via HDMI (or whatever output is directly connected to your discrete GPU) and set it as your main monitor. In this case, the spectator window will not cause any performance issues.</p><h4>VR View &amp; Spectator view cost in desktop systems</h4><p>The previous paragraph showed that Alyx’s spectator window has a huge performance impact on laptops with nvidia Optimus technology. How about desktops systems though(or laptops when an external monitor is used)?</p><blockquote>Hiding Alyx’s spectator window had no measurable performance difference in a desktop systems. Steam’s VR View did!</blockquote><p>Steam’s ’VR View <strong>did increase GPU time</strong> as you can see in the following gif:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*qQnZvLpzoJA4J6E0fzZxeg.gif" /><figcaption>GPU time when steam’s VR View is shown or hidden</figcaption></figure><p>When Steam’s VR view was visible, the GPU time graph exhibited some spikes. They increased the GPU time by 1,0 to 1,5 ms. This applies to other games as well.</p><h3>TLDR</h3><p>Here’s what you need to do to get a sharper image (higher fidelity level) in Alyx:</p><ul><li>Disable Steam VR’s “motion smoothing”</li><li>Set the headset’s refresh rate to 80Hz or 90Hz instead of 120Hz. The lower the refresh rate, the longer the GPU time window and thus the higher the fidelity level (resolution) the game will choose.</li><li>Set Steam VR’s render resolution to 100%. Higher values are not needed for Alyx.</li><li>Change the graphic options as follows: “characters” to “low”, “fog” to “low” or “medium”, “shadow” to “medium” or “high”</li><li>Minimize the spectator window if you’re using a laptop and close Steam’s VR View window (if open).</li></ul><p>To check out the frame times while in VR, or even from the desktop, check out <a href="https://store.steampowered.com/app/908520/fpsVR/">fpsVR</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d17fb8c19bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VSYNC with low input lag (50ms lower!!!)]]></title>
            <link>https://petrakeas.medium.com/vsync-with-low-input-lag-50ms-lower-2437118bfa5?source=rss-1516935fe5ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/2437118bfa5</guid>
            <category><![CDATA[videogames]]></category>
            <category><![CDATA[nvidia]]></category>
            <category><![CDATA[games]]></category>
            <dc:creator><![CDATA[Petros Douvantzis]]></dc:creator>
            <pubDate>Thu, 26 Apr 2018 20:41:49 GMT</pubDate>
            <atom:updated>2018-04-28T09:08:23.990Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*PAks7Otd5rQ0DEYZOGWkDQ.jpeg" /></figure><p>Too good to be true right? <strong>TLDR</strong>: limiting the game’s framerate and enabling vsync effectively disables buffer queueing and thus input lag. Read the guide <a href="https://www.blurbusters.com/howto-low-lag-vsync-on/">here</a>.</p><p><strong>The problem: No tearing VS lag</strong></p><p>When playing games on PC, two are the most common problems: <em>input lag</em>, which is the delay between hitting a button and seeing the result on screen and <a href="https://en.wikipedia.org/wiki/Screen_tearing"><em>tearing</em></a>, which is when the image is split vertically. Tearing is caused by the fact that the GPU renders frames in a different rate that the rate they are scanned and sent to the monitor.</p><p>The oldest solution that solves tearing is<strong> VSYNC</strong>, which in a very simple explanation makes sure the buffer from which the monitor reads is not swapped while it’s read. The game can continue to render frames as fast as possible and submit them to the buffer queue. When the queue is full, the game can’t submit another frame and hence it gets framerate limited. Note that due to the fact that more than 1 frame is queued, there will be a delay between the game rendering the frame and the GPU sending it to the monitor. Thus, input lag is increased. There’s a more in depth explanation of the problem and the solution, which will be presented below, in this <a href="https://forums.guru3d.com/threads/the-truth-about-pre-rendering-0.365860/page-12#post-5380262">post</a>.</p><p><strong>GSync</strong> and FreeSync (<a href="https://www.blurbusters.com/gsync/gsync101-input-lag-tests-and-settings/5/">combined with frame limiting</a> to 1 or 2 frames below the screen’s refresh rate) solve this problem by marginally increasing input lag. However, I don’t currently have such a monitor.</p><p><a href="https://www.blurbusters.com/gsync/gsync101-input-lag-tests-and-settings/8/"><strong>FastSync</strong></a> is another solution that makes sure that the GPU renders frames as fast as possible and the latest will be the one to send to the monitor. While sounds like the ultimate solution, in reality it onlyworks well when the GPU can achieve a framerate that is at least twice the screen’s refresh rate. Otherwise, judder is produced.</p><h3>The solution</h3><p>The idea is simple. We want to make sure that when the game renders a frame to a buffer, it will be the next buffer to be shown on screen and not queued behind another one. The way to do that: keeping the game’s framerate below the screen refresh rate.</p><p>For example, if a monitor has a refresh rate of 59,95 Hz (it’s shown as 59Hz in windows settings) and we limit the game framerate to 58 fps we can achieve “single buffer” VSYNC. However, we will render 1 frame less per second. The monitor will display one frame twice in one second and this will result in noticeable judder.</p><p>To avoid that, we want to lower the framerate marginally to something like: 59,94 fps. This way we get “single buffer” VSYNC and no judder (actually the monitor will repeat 1 frame in 100 seconds). To limit a game’s framerate, I propose the usage of <a href="http://www.guru3d.com/files-details/rtss-rivatuner-statistics-server-download.html">RTSS</a>. Even games that have limiters, don’t provide decimal precision, which is necessary in our case. Then, VSYNC can be enabled from within the game or the GPU’s options.</p><p>If you want to try the solution yourself, follow the detailed guide <a href="https://www.blurbusters.com/howto-low-lag-vsync-on/">here</a>.</p><h3>Testing</h3><p><strong>Overwatch</strong></p><p>Time for some testing. Input lag is really easy to “feel” in first person shooter games. So, I tried running Overwatch with VSYNC on. The lag was really noticable. I enabled framerate limiting via RTSS and I was amazed to feel the lag reduction instantly. However, after 1 minute I noticed the lag again. I guess that 1 more buffer got queued. So, I decreased my framerate limit to 59,930 fps and the problem was fixed.</p><p>I also tried FastSync and limited the framerate to 240 fps. I could feel that the input lag was even lower than the proposed solution. And of course, input lag was the lowest when no sync was used. Setting a framerate limit to 59 or 240 fps (with No Sync) was faster that the syncing methods.</p><p>I will continue to play Overwatch with No Sync because input lag is of outmost importance. The good think with first person shooters is that tearing is not very visible, especially when the framerate exceeds the refresh rate.</p><p><strong>Cuphead</strong></p><p>Cuphead is a 2D scrolling game where tearing is really easy to notice. On the other hand, input lag is important because of the fast nature of the game.</p><p>FastSync could not be used because the game frame limits itself and juddering was noticable.</p><p>The proposed solution worked perfectly. I can now enjoy the game without tearing or judder while it stays really responsive</p><p><strong>GSYNC VS FastSync VS VSYNC</strong></p><p>Even though I didn’t take measurements, I could feel that from lowest to highest the input lag goes as follows:</p><p>No Sync &lt; No Sync + framelimit &lt; FastSync &lt; VSync + framelimit &lt;&lt; VSYNC</p><p>I browsed through the measurements in <a href="https://www.blurbusters.com/gsync/gsync101-input-lag-tests-and-settings/">BlurBusters</a> and merged them in the following diagram. So, for 60Hz and Overwatch:</p><pre><br>No Sync + 58fps limit:    34 ms  |   0<br>GSync + 58fps limit:      37 ms  |  +3ms<br>Fast Sync:                39 ms  |  +5ms <br><strong>VSync + 58 fps limit:     48 ms  |  +14ms</strong><br>Vsync:                    98 ms  |  +64ms </pre><blockquote>The proposed method (VSYNC + limit) is 50ms faster than VSYNC.</blockquote><p>The added delay from No Sync is just 14ms. Note that there were no measurements from “No Sync” without frame limit, but judging from CSGO measurements (300fps limit), there’s 10ms lag involved between “No Sync 300fps VS No Sync 58fps”. So the added lag of “ No Sync 300 fps VS VSYNC 58fps” should be around: 10 + 14 = 24 ms.</p><h3>Remarks</h3><p>For the solution to work, your PC must be able to render frames at the specified framerate consistently. If it’s only able to render between 55–65 fps, this solution will not work for a 60Hz monitor.</p><p>The solution that is described here is not related to “<strong>maximum pre-rendered frames</strong>” setting in the nVidia control panel. This is a separate control that is not related to the buffer queue used by VSYNC. Setting this to “1” can additionally help in reducing the input lag.</p><h3><strong>Some tricks</strong></h3><p>In order to test whether RTSS is actually working and that you have chosen the correct framerate limit, don’t enable VSYNC just yet. Notice at which point of the screen you see the tearing. If it’s working correctly, the tearing should stay at the same vertical position and move downwards really slowly. If it stays in the same position for ever or moves upwards, then your framerate is higher that the screen’s refresh rate and when you enable VSYNC 2 buffers will be queued. If it’s changing position rapidly, framerate limiting doesn’t work as expected.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2437118bfa5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building my new PC]]></title>
            <link>https://petrakeas.medium.com/building-my-new-pc-b35d001df5e7?source=rss-1516935fe5ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/b35d001df5e7</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[pc]]></category>
            <dc:creator><![CDATA[Petros Douvantzis]]></dc:creator>
            <pubDate>Fri, 02 Feb 2018 14:44:41 GMT</pubDate>
            <atom:updated>2018-02-03T09:46:19.089Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G7z8tqjSLRGVvy-Ivhtljg.jpeg" /><figcaption>That’s Silent Beast :)</figcaption></figure><p>My PC and my Macbook are the center of my digital-life (besides the mobile phone I use as my daily driver). I use my PC mainly for Android development, a bit of Unity development, gaming, photo-video editing and a lot of other smaller tasks. My previous PC managed to last 10 years after several minor upgrades to memory, adding SSD and GPU upgrades. However, it was time to move forward. From all the tasks mentioned, it may surprise you that building on Android Studio is one of the heaviest! It requires a lot of memory and a really fast CPU.</p><p>So, my goal was to create a powerful and future-proof computer to handle all these tasks. I also wanted the system to be deadly silent at idle and as silent as possible under heavy load. Also, since we live in 2018 I couldn’t avoid a bit of RGB lighting in the build, but I think it’s subtle the way I have set it up. So, without further ado, and after a lot of research, reading benchmarks, reviews, reading long forum threads, here are the components I chose.</p><h3>The components</h3><h4>CPU</h4><p>Even though I wanted to “tap” AMD in the back for their amazing return, I chose team blue, because of the higher single-core performance. You can’t go wrong with i7 8700K anyway.</p><h4>CPU Cooler</h4><p>I didn’t choose an AIO liquid cooler because of the pump noise at idle. After doing my research, Thermalright’s TRUE Spirit 140 Power appeared as one of the most silent solutions out there. In case you don’t know, <a href="http://www.silentpcreview.com/">silent pc review</a> is perhaps the best place for this stuff. Unfortunately, it’s been a long time since they made a review, but their forums as still helpful.</p><p>The PWM 140 fan, <a href="http://www.thermalright.de/en/fans/46/ty-147-a?c=10">TY 147 A</a>, at 350 RPM is inaudible. Above 700 RPM a slight drone noise starts to appear, but it can’t be easily heard when the case is closed.</p><p>I used Thermal Grizzly’s Kryonaut between that and the CPU, because according to multiple benchmarks it results to 2 degrees colder CPU when compared to the best thermal pastes out there.</p><h4>Memory</h4><p>32 GB 3200 MHz CAS 14 with RGB lighting. After studying some benchmarks, it seems that the performance of Intel CPUs does not depend too much on memory speed and timings as it does on Ryzen ones. Even so, I wanted to pick one of the best memory modules out there.</p><h4>Storage</h4><p>1 Tb NVMe is one of the best options available right now. I chose Samsung 960 Pro, instead of 960 Evo, because of the longer warranty.</p><p>I also used the storage from my old computer, a Western Digital Blue 2 TB and a Samsung 850 EVO 500 GB.</p><h4>GPU</h4><p>Palit GTX 1080 GameRock Premium <a href="http://hexus.net/tech/reviews/graphics/94100-palit-geforce-gtx-1080-gamerock-premium-edition/">has probably</a> the best and most silent cooling solution out there.</p><p>As most cards these days, the fans don’t spin at idle.</p><h4>PSU</h4><p>be quiet! Dark Power Pro 11 650W is indeed truly inaudible both in idle and under load.</p><h4>Case</h4><p>I wanted a case that is high quality and beautiful. Phanteks Enthoo Evolv ATG Tempered Glass is easily one of the best options out there. I read some reviews that mentioned its restrictive airflow, so I was a bit worried. Turns out that the case, especially the top part, may not be the best case for attaching radiatrors. However, on an air-cooled system like this, the airflow was more than enough.</p><p>The case uses true aluminum on top and the front and tempered glass sides (not plastic). Every part of the case is really high quality and is gorgeous to look at. The right side panel is dimmed glass, so the cables are not easily seen. That said, the case is very easy to work with and results to a very clean, cable-wise, look. The left side panel is less dimmed and makes the internal of the case, as well as any internal LEDs, appear less bright and more impressive.</p><p><strong>Fan controller</strong></p><p>The case also has a fan controller that accepts a PWM signal from the motherboard and converts it to DC signal to drive up to 5 fans. A problem that I faced with this controller and my motherboard’s PWM signal is that the RPM do not increase linearly. For example, a 8% PWM value results to 50% of the maximum RPM. I didn’t face that issue with Thermalright’s PWM fan, so I guess that the problem lies in Phantek’s controller.</p><p>One downside of the case is that it’s not targeting silence. The 3 case fans, PH-F140SP, are considered silent but not one of the best options out there. The fans are silent at lowest RPM but not inaudible. Even worse, their noise was enhanced when I attached the side glass panels. I’ll probably change them with be Quiet’s Silent Wings 3 140.</p><p><strong>Acoustics</strong></p><p>Another issue that I faced with a Wester Digital Blue 2 TB is how noisy it sounded in this case. The case has 2 options to mount a 3.5 inch drive and both have some sort of dumpening material, but it didn’t help with the vibration or the spinning noise. What I ended up doing is remove the drive cage at the front of the shroud, and sound-proof that part of the shroud using acoustic foam. The front 140 fan was still able to cool the hard disk and the noise was considerably reduced.</p><p><strong>RGB LED controller</strong></p><p>Last but not least, the case has RBB LEDs at the power button and at the front. You can also attach led strips to light up the interior if you want. The case has an embedded LED controller that cycles between different colors, or dims or uses static color. You can adjust that using something that looks like a reset button.</p><h4>Motherboard</h4><p>I left the motherboard at the end since it’s the component that brings all the previous components together and I wanted to go deeper on that part.</p><p>I chose Asus Z370-E because it’s one of the best high-end motherboards without breaking the bank.</p><p>UEFI was very easy to use and it’s really easy to overclock with it.</p><p><strong>Fan control</strong></p><p>You can also define fan curves for all the fans and choose between PWM and DC operation. Asus provides a thermistor cable which I attached between the graphic card cooler’s fins. I then set its temperature to drive my case fans according to a user defined curve I made. Essentially, when the GPU’s temperature approaches 65 ℃, I increase the case fans speed in order to exhaust the heat generated by the GPU’s cooler.</p><p>You can also adjust the fan speed using Asus fan expert, which come bundled in AI Suite III, but I prefer a UEFI solution to a Windows one.</p><p><strong>Asus Aura</strong></p><p>The motherboard supports Asus Aura. This means that using Asus software I can control the motherboard’s lighting and anything that is compatible. In this build, I can control the memory sticks and the case lighting (but this requires an extra cable). The software is limited in options and I preferred the memory’s default color cycling. So, I just set the motherboard colors to some fixed gradient values and let the memory and case do their own thing. I disabled Asus’s lighting service from starting when Windows starts.</p><h3>Temperature and Noise</h3><p>I sat the multiplier to 47x for all cores under load. Speed-step is enabled, and Windows use the “Balanced” power plan. So, when the CPU is not performing heavy work, it can get as low as 8x.</p><p>My room had around 21 ℃ when the measurement were made. At idle, the CPU stays around 33 ℃ and the GPU at 41 ℃. CPU fan is around 350 RPM and is inaudible.</p><p>When stressing the CPU with Cinebench, it reaches 78 ℃, with the CPU fan at 900 RPM which is relatively quiet. Running Prime95 results to 94 ℃, but I consider this as a non realistic workload.</p><p>When playing Overwatch and hitting around 260 fps, the CPU temperature was 67 ℃, while the CPU fan was inaudible at 370 RPM. The GPU was around 70 ℃ with the GPU fans audible but tolerable at 1200 RPM.</p><h3>Conclusion</h3><p>I am quite happy with the result. You can find all the parts of the PC in my PC Part Picker<a href="https://pcpartpicker.com/b/MvD2FT"> completed build entry</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b35d001df5e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Alias free resize with RenderScript]]></title>
            <link>https://petrakeas.medium.com/alias-free-resize-with-renderscript-5bf15a86ce3?source=rss-1516935fe5ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bf15a86ce3</guid>
            <category><![CDATA[renderscript]]></category>
            <category><![CDATA[resize]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Petros Douvantzis]]></dc:creator>
            <pubDate>Wed, 08 Nov 2017 11:26:49 GMT</pubDate>
            <atom:updated>2017-11-12T19:22:38.749Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jf4EUb_-L9iHpyHdQB-7jg.jpeg" /></figure><p>Resizing a bitmap is a quite common task. Let’s say you want to create a thumbnail from a source image; you will have to resize it to quite a smaller size. However, if you try to do that using the provided tools, you’ll end up with aliasing artifacts.</p><p>Android’s <a href="https://developer.android.com/reference/android/graphics/Bitmap.html">Bitmap</a> class provides many methods that can downscale an image. Under the hood, it uses a <a href="https://developer.android.com/reference/android/graphics/Canvas.html">Canvas</a> and a <a href="https://developer.android.com/reference/android/graphics/Paint.html">Paint</a> object that has bilinear filtering <a href="https://developer.android.com/reference/android/graphics/Paint.html#setFilterBitmap(boolean)">enabled</a><a href="https://developer.android.com/reference/android/graphics/Paint.html#setFilterBitmap(boolean)).">.</a> However, when scaling down an image, bilinear filtering is not enough to prevent aliasing.</p><p>In the images below, an image with `2880 x 2160` resolution was resized to `360 x 270`. In the top one, you can see the result of using Bitmap’s <a href="https://developer.android.com/reference/android/graphics/Bitmap.html#createScaledBitmap(android.graphics.Bitmap,int,int,boolean)">CreateScaledBitmap()</a> method and on the bottom one you can see a proper resizing result. The aliasing artifacts due to subsampling are quite intense on the top one and the result is unacceptable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*sbxAhvABNX_0NF29mZKZtA.png" /><figcaption>Resizing with aliasing artifacts</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*3IVAYK-yVqX4nl_d_xBlCw.png" /><figcaption>Proper resizing</figcaption></figure><p><strong>Warning</strong>: Due to Medium resizing the images, the comparison above may not be represented faithfully. Please see the top image <a href="https://i.imgur.com/aCY5GM8.png">here</a> and the bottom one <a href="https://i.imgur.com/DdJClkW.png">here</a>. Original image <a href="https://i.imgur.com/RfHTT3B.jpg">here</a>.</p><h3>Partial solution</h3><p>The only out-of-the-box solution to downscaling without aliasing, is <a href="https://developer.android.com/reference/android/graphics/BitmapFactory.html">BitmapFactory</a><a href="https://developer.android.com/reference/android/graphics/BitmapFactory.html)&#39;s">&#39;s</a> decode methods where you need to provide a proper value to <a href="https://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize">sample size</a>.</p><p>For example the following code creates an image having 1/8th size to the original:</p><pre><br>BitmapFactory.Options options = new BitmapFactory.Options();<br>options.inSampleSize = 8;<br>Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), options);</pre><p>One major problem with this approach is that if your bitmap is already decoded, you can’t use this method. Also, sample size can only use values that are powers of 2. This means that you can’t downscale to an arbitrary resolution, but only to halves of the original resolution. Last but not least, this method works great with JPEG files, but if the decoded image is of PNG type you end up with aliasing.</p><p>A workaround to manage downscaling to an arbitrary size would be to first decode the image to the next power of 2 resolution and then use the Bitmap methods to downscale it exactly to the size you want. However, the result will be slightly blurry. <strong>Update</strong>: Instead of using the Bitmap methods to downscale the image to arbitrary size after the decode method, you can achieve the same visual result from within the decode method by also specifying the <a href="https://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inDensity">inDensity</a> and <a href="https://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inTargetDensity">inTargetDensit</a>y as explained in <a href="https://www.youtube.com/watch?v=HY9aaXHx8yA&amp;index=28&amp;list=PLWz5rJ2EKKc9CBxr3BVjPTPoDPLdPIFCE">this video</a>.</p><p>A workaround to getting high quality downscaling to powers of 2 dimensions when the bitmap is already decoded (and we can’t use the BitmapFactory’s decode methods), is by successively resizing the bitmap to half dimensions. You can see two implementations in this <a href="https://gist.github.com/Petrakeas/c47a406538cc9bd25fd4a2d19647539a">gist</a>. Note that if you need to downscale to arbitrary size, one more resize pass is needed to get from the next higher power-of-2 dimensions to the desired dimensions. As mentioned previously, this produces a bit blurry result.</p><h3>Prefiltering with RenderScript to the rescue</h3><p>As explained in all signal processing books, in order to subsample a signal and avoid aliasing, you first have to prefilter the signal to exclude high frequencies. Then, you can subsample it.</p><p>In other words, we first have to “blur” the image and then subsample it. The amount of blur we need to apply depends on the prefilering method and how much we need to subsample the image (see: <a href="https://en.wikipedia.org/wiki/Nyquist_frequency">Nyquist frequency</a>).</p><p>One of the quickest, implementation-wise, and fastest, performace-wise, ways to blur an image in Android, is using <a href="https://developer.android.com/guide/topics/renderscript/compute.html">RenderScript</a>. Fortunately, RenderScript comes bundled with a Gaussian filter implementation, the <a href="https://developer.android.com/reference/android/renderscript/ScriptIntrinsicBlur.html">ScriptIntrinsicBlur</a>, that can apply the prefiltering for us. It also provides an intrinsic for resizing, the <a href="https://developer.android.com/reference/android/renderscript/ScriptIntrinsicResize.html">ScriptIntrinsicResize</a>, which uses bicubic interpolation.</p><p>So, the idea is that we’ll first apply Gaussian blur to the image and then subsample it using bicubic interpolation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9de70588298ed5d978eec02a36c0830/href">https://medium.com/media/f9de70588298ed5d978eec02a36c0830/href</a></iframe><p>Perhaps the most difficult part of the code is calculating the Gaussian’s radius. At first, I calculate the Gaussian’s sigma relative to the subsampling ratio as: resizeRatio/p. This is derived by the fact that a Gaussian’s frequency response is another Gaussian and a bit of math. ScriptIntrinsicBlur has a radius parameter though, not a sigma. But Google’s sourcecode shows the relationship between the two: sigma = radius * 0.4 + 0.6. Solving for radius gives us: float radius = 2.5f * sigma -1.5f;.</p><p>The rest of the code is self-explanatory. We create allocations for the source image, blurred image and output image. We first apply Gaussian blur and then resize it. We also do a bit of memory management.</p><h4>Performance and comparison</h4><p>I tried the proposed method to resize a <em>2880x2160</em> image to <em>640x480. </em>I also tried the <a href="https://developer.android.com/reference/android/graphics/Bitmap.html#createScaledBitmap(android.graphics.Bitmap,%20int,%20int,%20boolean)">Bitmap.createScaledBitmap()</a> method, the successive resize method (using multiple <a href="https://developer.android.com/reference/android/graphics/Bitmap.html#createScaledBitmap(android.graphics.Bitmap,%20int,%20int,%20boolean)">Bitmap.createScaledBitmap()</a> calls) and the successive resize method using RenderScript’s bicubic interpolation. Here are the results:</p><p>createScaledBitmap: <strong>14ms</strong> [<a href="https://i.imgur.com/J1Oqk34.png">image</a>]<br>successive resizes: <strong>63ms</strong> [<a href="https://i.imgur.com/s1WMhU7.png">image</a>]<br>successive resizes (RenderScript): <strong>45ms</strong> [<a href="https://i.imgur.com/UsRa2Ro.png">image</a>]<br>proposed method: <strong>177 ms</strong> [<a href="https://i.imgur.com/M1oFqTX.png">image</a>]</p><p>The “<em>createScaledBitmap” </em>method, even though the fastest, has extreme aliasing. The “<em>successive resizes” </em>is a bit blurry and the “<em>successive resizes (RenderScript)</em>” is a bit sharper. The “proposed method” has by far the best quality.</p><p>If we downscale the image to the power-of-2 size of <strong><em>360x270</em></strong><em> </em>we have the following results:</p><p>createScaledBitmap: <strong>4ms</strong> [<a href="https://i.imgur.com/vkMKHgp.png">image</a>]<br>successive resizes: <strong>46ms</strong> [<a href="https://i.imgur.com/O7Hfcqj.png">image</a>]<br>successive resizes (RenderScript): <strong>34ms</strong> [<a href="https://i.imgur.com/Pk5PJ0M.png">image</a>]<br>proposed method: <strong>121 ms</strong> [<a href="https://i.imgur.com/4gMnd81.png">image</a>]</p><p>Because we are scaling down by a power-of-2, the results are a bit different quality-wise. The “<em>successive resizes”</em> method gives identical result to the proposed method due to the fact that no extra-resize is needed. The <em>successive resizes (RenderScript)</em>” is a bit sharper as usual.</p><p>The proposed method takes <strong>380ms</strong> to scale a <em>5760x4320</em> image to <em>640x480</em>.</p><p>All experiments ran on a Nexus 5.</p><h4>Some remarks</h4><p>Note that if resizeRatio is larger than <em>1</em>, then we are actually upscaling and prefiltering with Gaussian filter isn’t needed.</p><p>Gaussian filter is not the best prefiltering method, but the reason it was chosen here is due to the fact that RenderScript contains a ready-to-use intrinsic. Ideally, we could use an averaging filter, but this would require to write our own RenderScript kernel.</p><p>Applying a Gaussian blur to a large image is demanding. Also, the bigger the resizeRatio is, the larger the Gaussian radius gets and thus the processing gets more computationally expensive. What we could do to improve performance, is use BitmapFactory’s decode method to subsample the image and then apply this algorithm to the resulting image. For example, if the source image has a width of <em>5760</em> and the target width is <em>640</em>, the ratio is <em>9</em>. We could decode the image using options.inSampleSize = 2 and then apply the algorithm to the decoded (half size) image using resizeRation = resizeRatio/options.inSampleSize, which in our case is: <em>9 / 2 = 4.5</em>.</p><p>If you are interested in supporting older devices, you can use RenderScript via <a href="https://developer.android.com/topic/libraries/support-library/packages.html#v8">V8 Support Library</a>. In my tests, the support library had better performance than the native RenderScript runtime!</p><h4>This post was originally posted in <a href="https://blog.horizon.camera/post/167263897165/renderscript-resize">Horizon’s blog</a>.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bf15a86ce3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>