<?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 Oğuzhan Ekşi on Medium]]></title>
        <description><![CDATA[Stories by Oğuzhan Ekşi on Medium]]></description>
        <link>https://medium.com/@ouzhaneki?source=rss-aedc8b3df276------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oJNGrP1_ZZ7WfqZI3HP4sg.jpeg</url>
            <title>Stories by Oğuzhan Ekşi on Medium</title>
            <link>https://medium.com/@ouzhaneki?source=rss-aedc8b3df276------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 15:13:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ouzhaneki/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[“The video is low quality.” That one sentence may cost teams days.]]></title>
            <link>https://medium.com/@ouzhaneki/the-video-is-low-quality-that-one-sentence-may-cost-teams-days-c449ba1b95fc?source=rss-aedc8b3df276------2</link>
            <guid isPermaLink="false">https://medium.com/p/c449ba1b95fc</guid>
            <category><![CDATA[quality-assurance]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[media3]]></category>
            <dc:creator><![CDATA[Oğuzhan Ekşi]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 11:01:28 GMT</pubDate>
            <atom:updated>2026-06-30T11:16:38.573Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Media3/ExoPlayer case study on turning vague OTT playback complaints into evidence-rich triage signals.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dIIFWaTnRF8TRxqZQU-JUg.png" /></figure><p>Imagine this bug report landing in your queue: <em>“the video is playing at low quality.”</em></p><p>One sentence. And it’s almost useless, because at least five completely different root causes produce exactly that symptom. The manifest was trimmed and the high rungs were never offered. The network link genuinely can’t sustain the top rung. The CDN is missing cache on every segment. The player is hard-capped to a low resolution by its own config. Or the player’s ABR is mistuned and refuses to climb even though it could.</p><p>Same blurry picture. Five different fixes, owned by four different teams: encoding, networking, CDN, client. Pick the wrong one and you don’t lose minutes. You lose days.</p><p>So basically, before this is a technical problem, it’s an evidence-routing problem.</p><h3>Why this is your problem, not just an engineer’s</h3><p>Here’s why this matters if you’re an EM or a tech lead. When a ticket lands as “the video is blurry,” nobody knows which of those four teams owns it. So it bounces.</p><p>It lands in the encoding queue. They check the ladder: “looks fine.” Bounce to networking. Networking checks the link: “healthy.” Bounce to CDN. CDN checks cache: “hot.” Bounce back to client. Client checks the player: “rendering correctly.” Or it just sits in QA limbo waiting for someone to claim it.</p><p>One misrouted ticket doesn’t cost five minutes of handoff. It costs <strong>days</strong>: days of limbo, no owner, no forward motion. Multiply that across a month of “it’s blurry” reports and you’re looking at lost velocity that never shows up in a single sprint metric. The interesting part: the actual diagnosis, once it reaches the right person, often takes <strong>minutes</strong>. The cost isn’t the fix. It’s the routing.</p><h3>The setup (so you don’t have to trust me)</h3><p>I want to be upfront about how I proved this, because the whole thing falls apart if the numbers are massaged.</p><p>I built a controlled rig: one real HLS ladder (240p / 480p / 720p in AVC, 1080p in HEVC), an nginx server that serves the same ladder under several profiles (full manifest, a manifest trimmed to 480p, a byte-rate-throttled path, and a path that stamps fake cache-MISS headers), and a demo Android app that can mistune its own ExoPlayer on command.</p><p>Each fault is a known, injected condition. I know the right answer going in. The only question is how fast each approach <em>gets</em> to it. Every screenshot and every metric below is a real, unedited capture. The faults are staged. The measurements are not. You can run the rig yourself, the repo is linked at the end.</p><h3>Same symptom, opposite causes</h3><p>Let me show you two cases that look identical on screen and have nothing in common underneath.</p><p><strong>Case A, the manifest caps out.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Abt0jVg3sALERuYG0el9Wg.png" /><figcaption>The ladder is capped at 480p, but the network is fast: encoding is the bottleneck.</figcaption></figure><p>The Tracks tab lists the runtime ladder, every rung the player actually knows about: <strong>426×240 and 854×480, and nothing above</strong>. Now look at the throughput in the header: <strong>39 MB/s</strong>. The link is plainly fast. The bandwidth is right there. The player <em>can’t</em> pick a higher rung because the ladder doesn’t offer one. The cap is in the manifest, not the network. This routes to the encoding/packaging team.</p><p><strong>Case B, the network chokes.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OaNShtLlCO8RR-5Br74PHA.png" /><figcaption>The ladder is full, but every segment crawls in: the network is the bottleneck.</figcaption></figure><p>Same blurry video. But now the ladder is <em>full</em>: 240p, 480p, 720p all present and selectable. Yet look at the latest segment: <strong>2031 ms</strong> to download a single chunk, at <strong>927.5 KB/s</strong>. The link is saturated. The player is correctly sitting low because the network can’t feed the top rung. (A curl on the same segment confirms it: <strong>2.03 s</strong> on the throttled path versus <strong>20 ms</strong> unthrottled, roughly 100x slower.) The rungs exist. The link can&#39;t reach them. This routes to networking.</p><p>Two screenshots, opposite root causes, identical picture on the device.</p><p><em>Now you might be wondering: couldn’t an engineer just read this from logs?</em></p><p>Yes, mostly. ExoPlayer ships EventLogger, an AnalyticsListener that dumps the runtime ladder and the player&#39;s track-selection state. A competent engineer attaches it and reads the same ladder I just showed you. So I want to be honest: raw tools <em>can</em> reconstruct most of this. But two things. First, EventLogger gives you the ladder, not the per-segment timing or the throughput, so you still need a second tool (curl or a proxy) for the &quot;is the link fast&quot; half of every diagnosis. Second, and this is the real point: <strong>In most QA and support workflows, that stack is not self-service.</strong> EventLogger needs source access, a debug build, a wired device, adb, and the fluency to read a logcat firehose. A QA tester has none of those. For them the raw arm isn&#39;t slower, it&#39;s <strong>absent</strong>.</p><p>The remaining three cases, one sentence each:</p><ul><li><strong>cdn_miss:</strong> quality is actually fine, but every segment is a cache MISS that pays full origin latency. The overlay flags <strong>every segment with a red MISS dot</strong> and reads the cache header outright (CDN STATUS: [CLOUDFLARE] ○ MISS). Routes to CDN.</li><li><strong>constrained:</strong> the full ladder is present and the link is fast, but a setMaxVideoSize(854, 480) removed 720p from the pool entirely, so the <strong>720p rung is greyed out</strong>. Routes to client.</li><li><strong>bw_misconfig:</strong> full ladder, fast link, and here the <strong>720p rung is green</strong> (it&#39;s in the pool, fully selectable), but a mistuned bandwidthFraction means ABR just won&#39;t climb to it. Also client, different cause.</li></ul><p>That last pair is worth pausing on. constrained and bw_misconfig look identical to the naked eye (blurry video, full ladder, fast link). The overlay separates them with one visual cue: it colors each rung by whether it&#39;s in the player&#39;s current selection pool. Greyed 720p means &quot;capped out of the pool.&quot; Green 720p means &quot;in the pool, the algorithm just won&#39;t climb.&quot; Capped versus mistuned, at a glance.</p><h3>The scorecard: what it actually costs</h3><p>All five cases point to the same gap: <strong>QA has no on-device visibility into the streaming state.</strong> They can describe what they see (“it’s blurry”). They can’t see <em>why</em>.</p><ul><li><strong>manifest_cap</strong> → Encoding. QA can&#39;t self-route: for an engineer with adb, minutes; for QA, escalate and wait days.</li><li><strong>network_throttle</strong> → Networking. QA can&#39;t self-route: same.</li><li><strong>cdn_miss</strong> → CDN. QA can&#39;t self-route: worse, nobody even thinks to suspect the CDN.</li><li><strong>constrained</strong> → Client. QA can&#39;t self-route: same.</li><li><strong>bw_misconfig</strong> → Client. QA can&#39;t self-route: same.</li></ul><p>Five faults. Five teams. Every single one: QA can’t self-route. Not because testers lack skill, but because the data isn’t exposed on-device. For an engineer, the raw tools exist and the diagnosis is genuinely fast, often a couple of minutes. For QA and triage, the tools are <em>absent</em>, not just slow. So the bug routes on intuition and bounce patterns instead of evidence.</p><p>And cdn_miss is the one that hurts most. Even an engineer with every tool has to first <em>suspect</em> the CDN before they set up a proxy. Nothing prompts that hypothesis. If it never occurs to anyone, the ticket just stays open.</p><p>This is QA’s real job, by the way: not to <em>solve</em> the bug, but to <em>route</em> it correctly on day one. A two-minute “the ladder caps at 480p” on day one saves three days of bouncing. But they can’t route what they can’t see.</p><h3>The honest part: where my own tool falls short</h3><p>Here’s where I need to be straight with you, because a diagnostics tool you can’t trust to admit what it <em>can’t</em> see isn’t a diagnostics tool.</p><p>When I put constrained and bw_misconfig side by side, I expected the overlay to be uniquely able to tell them apart. That overstates it. EventLogger&#39;s track dump exposes the same per-rung detail the overlay colors, the [X] versus [ ] split is right there in the Media3 data. The overlay&#39;s contribution is making it visual and on-device, not making it visible at all. I&#39;d rather say that plainly than oversell.</p><p>And there’s a real gap one level deeper, where the overlay and EventLogger are <em>not</em> equal. The 1080p rung is greyed in both constrained and bw_misconfig, but for a different reason than 720p: on this device, 1080p is HEVC the hardware can&#39;t decode. Same grey dot, two meanings (deselected by config vs. undecodable by hardware). EventLogger already prints a supported= flag per rung, so it can name that. The overlay can&#39;t yet, because its VariantInfo doesn&#39;t carry the flag.</p><p>That admission points at two directions I’m exploring, not promises:</p><ol><li><strong>Surface </strong><strong>isSupported on </strong><strong>VariantInfo.</strong> Media3 already exposes Tracks.Group.isTrackSupported(i). Plumbing it through would let the overlay mark a rung &quot;present but undecodable&quot; and kill the 1080p ambiguity directly. The data exists; the overlay just isn&#39;t reading it.</li><li><strong>Expose the active </strong><strong>TrackSelectionParameters.</strong> Today the overlay shows <em>that</em> the pool was narrowed, not <em>why</em>. A max-size cap, a max-bitrate cap, and a low bandwidth-fraction all look alike from outside. Surfacing the live constraints would turn &quot;the player chose 480p&quot; into &quot;the player chose 480p <em>because</em> of constraint Y,&quot; and would separate constrained from bw_misconfig by cause, not just by symptom.</li></ol><p>Neither is shipped. Naming them is the point.</p><h3>What I want to leave you with</h3><p>“The video is blurry” isn’t a technical problem. It’s a triage problem. It’s an observability gap. And it’s solvable.</p><p>The payoff lands at two altitudes. For engineers, the win is real but modest: the state is already reachable with EventLogger and a proxy, so the overlay mostly saves you the setup tax (no logger to attach, no logcat to filter, no proxy to stand up) and puts the ladder, the throughput, and the cache status side by side, on-device, next to the playback they describe. For QA and triage, the swing is much larger, from &quot;none&quot; to &quot;enough to route the ticket correctly on the first try.&quot; That&#39;s the difference between a bug that&#39;s owned in seconds and one that ricochets between encoding, networking, CDN, and client for days.</p><p>This is the kind of player-visible state I think every OTT team should be able to see on-device. Not for fun. Because it’s the cheapest way to stop “it’s blurry” tickets from costing you days each.</p><p>So if your team ships an OTT player and you’ve watched these tickets bounce between teams, I’d genuinely like to hear how you triage them today. Drop it in the replies, or check out the repo. There’s a lot more in there, including the <a href="https://github.com/oguzhaneksi/StreamProbe/blob/master/tools/fault-deck/case-study/symptom-lies-full-report.md">raw </a><a href="https://github.com/oguzhaneksi/StreamProbe/blob/master/tools/fault-deck/case-study/symptom-lies-full-report.md">EventLogger and mitmproxy captures behind every number above</a>. :)</p><p><em>StreamProbe is a debug-only diagnostics SDK for Media3/ExoPlayer (Android) and AVFoundation (iOS). It is never enabled in release builds. Repo: </em><a href="https://github.com/oguzhaneksi/StreamProbe"><em>https://github.com/oguzhaneksi/StreamProbe</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c449ba1b95fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Android MediaSession and how to use it?]]></title>
            <link>https://medium.com/@ouzhaneki/what-is-android-mediasession-and-how-to-use-it-3cf911c74b77?source=rss-aedc8b3df276------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cf911c74b77</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[exoplayer]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[android-mediasession]]></category>
            <category><![CDATA[media3]]></category>
            <dc:creator><![CDATA[Oğuzhan Ekşi]]></dc:creator>
            <pubDate>Mon, 27 Apr 2026 10:06:21 GMT</pubDate>
            <atom:updated>2026-04-27T10:06:21.675Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oD8e1VlxUMt14rAg" /></figure><h3>Do you really need MediaSession?</h3><p>Before talking about MediaSession in detail, you can understand whether you really need to use MediaSession in your application by looking at the flowchart below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IyZsZwDNG9ZR8cLDKNkBwg.png" /><figcaption>MediaSession necessity flowchart</figcaption></figure><h3>How is MediaSession used in real life?</h3><h4>Music applications (e.g. YouTube Music, Spotify)</h4><ul><li>Users can control the player externally through headphones or a connected smartwatch.</li><li>Information about the currently playing track appears on the lock or notification screen.</li><li>Thanks to integration with Android Auto, users can control the player using buttons in the car (like steering wheel buttons) without touching the phone. This provides a safe driving experience.</li></ul><h4>Podcast applications (e.g. Overcast, Spotify)</h4><ul><li>Users can switch between content remotely or move forward or backward within the same content.</li><li>In addition, the features available in music applications can also be used.</li></ul><h4>Audiobook applications (e.g. Audible)</h4><ul><li>With MediaSession, users can stop and resume audiobooks remotely, or switch between chapters.</li><li>Similarly, audiobook information also appears on the phone’s notification or lock screen.</li></ul><h4>Video watching applications (e.g. Netflix, YouTube)</h4><ul><li>Although these applications provide video playback, they still frequently use MediaSession to play in the background or in picture-in-picture mode.</li><li>Similarly, video content information also appears on the phone’s notification or lock screen.</li></ul><h3>What is MediaSession?</h3><p>We can briefly define MediaSession as a Jetpack Media3 component that allows ExoPlayer to be controlled externally on Android. So in what ways can we control the Player externally? For example, we can stop and resume the player with headphone buttons or Google Assistant commands (e.g. by saying “pause the video”), we can skip forward/backward, and we can play the next/previous content. At the same time, it notifies the outside about changes in the player (e.g. when starting to play the next track in a playlist, the current position information of the content). Thus, it allows us to control the player remotely without direct interaction with the device.</p><p>These external sources we mentioned also implement <a href="https://developer.android.com/reference/androidx/media3/session/MediaController">MediaController</a>, which makes it easier to connect to MediaSession and notify player command requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*41_l5MO8qP2ezaWp.png" /><figcaption>MediaController notifies player command requests from external sources to MediaSession</figcaption></figure><h4>Innovations coming with Media3</h4><p>Unlike older libraries, Jetpack Media3 automatically updates MediaSession according to changes in the Player. Thus, there is no need for manual mapping from Player to session as in old approaches, or more specifically, creating and managing <a href="https://developer.android.com/reference/android/support/v4/media/session/PlaybackStateCompat">PlaybackStateCompat</a> for each state (e.g. reporting player error).</p><p>Secondly, with Media3, components like MediaSession and MediaController are based on a common Player interface. Thus, there is no need for “connector” objects that attempt to convert commands and notifications between Player and MediaSession in a compatible way, which could cause compatibility problems like in older libraries.</p><h3>How to Use It?</h3><p>After talking about what MediaSession is and what purposes it’s used for, it’s time to move on to the practical side. In this article, I’ll explain step by step how MediaSession is used in a simple way. More advanced scenarios will be the subject of another article.</p><p>Here, let’s continue from the demo application we created in the previous article. You can access the version without MediaSession added from <a href="https://github.com/oguzhaneksi/Media3Demo">here</a>.</p><p>We’ll only make a few small additions for MediaSession, that’s all.</p><pre>var mediaSession: MediaSession? by remember {  <br>  mutableStateOf(null)  <br>}</pre><p>First, we declare the MediaSession variable like this.</p><pre>fun initMediaSession(context: Context, player: Player): MediaSession {  <br>    return MediaSession.Builder(context, player)  <br>        .build()  <br>}</pre><p>And we define the function that builds MediaSession in MainActivity like this.</p><p><strong>Note:</strong> By creating MediaSession this way, we’re allowing it to support all commands by default (e.g. play/pause, skip forward/backward, or more advanced searches between content, etc.) and giving all <a href="https://developer.android.com/reference/androidx/media3/session/MediaController">MediaController</a>s access to it. To customize these, you can check the section below called “Managing player commands”.</p><pre>mediaSession = initMediaSession(context, player!!)</pre><p>Just like Player, we create and release MediaSession according to lifecycle. We can create it in onStart() or onResume() methods.</p><pre>mediaSession?.release()  <br>mediaSession = null</pre><p>Similarly, we release mediaSession like this in onPause() or onStop() methods.</p><p>Complete code:</p><pre>@Composable  <br>fun Player() {  <br>    val context = LocalContext.current  <br>  <br>    var player: Player? by remember {  <br>        mutableStateOf(null)  <br>    }  <br>    var mediaSession: MediaSession? by remember {  <br>        mutableStateOf(null)  <br>    }  <br>    val playerView = createPlayerView(player)  <br>  <br>    ComposableLifecycle { _, event -&gt;  <br>        when (event) {  <br>            Lifecycle.Event.ON_START -&gt; {  <br>                if (Build.VERSION.SDK_INT &gt; 23) {  <br>                    player = initPlayer(context)  <br>                    mediaSession = initMediaSession(context, player!!)  <br>                    playerView.onResume()  <br>                }  <br>            }  <br>            Lifecycle.Event.ON_RESUME -&gt; {  <br>                if (Build.VERSION.SDK_INT &lt;= 23) {  <br>                    player = initPlayer(context)  <br>                    mediaSession = initMediaSession(context, player!!)  <br>                    playerView.onResume()  <br>                }  <br>            }  <br>            Lifecycle.Event.ON_PAUSE -&gt; {  <br>                if (Build.VERSION.SDK_INT &lt;= 23) {  <br>                    playerView.apply {  <br>                        player?.release()  <br>                        onPause()  <br>                        player = null  <br>                    }  <br>                    mediaSession?.release()  <br>                    mediaSession = null  <br>                }  <br>            }  <br>            Lifecycle.Event.ON_STOP -&gt; {  <br>                if (Build.VERSION.SDK_INT &gt; 23) {  <br>                    playerView.apply {  <br>                        player?.release()  <br>                        onPause()  <br>                        player = null  <br>                    }  <br>                    mediaSession?.release()  <br>                    mediaSession = null  <br>                }  <br>            }  <br>            else -&gt; {}  <br>        }  <br>    }  <br>  <br>    AndroidView(  <br>        factory = { playerView }  <br>    )  <br>}</pre><h3>Managing Player Commands</h3><p>In this section, I’ll talk about determining which commands will be supported and customizing how the player behaves in response to commands. Let’s start by determining which commands will be supported.</p><h4>Determining Supported Commands</h4><p>With Media3, we can determine which commands external control components can use or which MediaControllers can access.</p><pre>class MediaSessionCallback: MediaSession.Callback {  <br>    override fun  onConnect(  <br>        session: MediaSession,  <br>        controller: MediaSession.ControllerInfo  <br>    ): MediaSession.ConnectionResult {  <br>        val connectionResult = super.onConnect(session, controller)  <br>        val sessionCommands = connectionResult.availableSessionCommands  <br>        val playerCommands = Player.Commands.Builder()  <br>            .add(Player.COMMAND_PLAY_PAUSE)  <br>            .add(Player.COMMAND_SEEK_BACK)  <br>            .add(Player.COMMAND_SEEK_FORWARD)  <br>            .build()  <br>        return MediaSession.ConnectionResult.accept(  <br>            sessionCommands, playerCommands  <br>        )  <br>    }  <br>}</pre><p>Here, we created a separate class that implements MediaSession.Callback and overrode the <a href="https://developer.android.com/reference/androidx/media3/session/MediaSession.Callback#onConnect(androidx.media3.session.MediaSession,androidx.media3.session.MediaSession.ControllerInfo)">onConnect()</a> method. <strong>If we hadn’t overridden it, we would have allowed all MediaControllers to connect to MediaSession and use all session and player commands.</strong></p><p>The onConnect() method is called whenever any controller is about to connect to the session. What do I mean? When any command comes from an external source, the MediaController implemented by that external source sends a connection request before relaying the command to MediaSession, and we can accept or reject the incoming request in this onConnect() method.</p><p>As you may have noticed, there are two types of commands: player commands and session commands. That is, <a href="https://developer.android.com/reference/androidx/media3/common/Player.Command">Player.Command</a> and <a href="https://developer.android.com/reference/androidx/media3/session/SessionCommand">SessionCommand</a>. The first is as its name suggests a Player-related command type, while the other is generally related to media library management (e.g. searching between content).</p><p>In the code block above, for the player, we only accept stop/resume, and skip forward/backward commands. On the other hand, we can accept all session commands. Besides this, for example, when we tell the Assistant “play the video at 1.25x speed”, MediaSession won’t execute this command.</p><p>To use this callback we created, we set it when creating MediaSession like below:</p><pre>MediaSession.Builder(context, player)  <br>    .setCallback(MediaSessionCallback())  <br>    .build()</pre><h4>Customizing Player Command Behaviors</h4><p>To customize command behaviors defined in the Player interface (e.g. play(), pause(), seekBack()), we create a ForwardingPlayer like the following using our previously created <em>player</em> instance:</p><pre>val forwardingPlayer = object : ForwardingPlayer(player) {  <br>        override fun play() {  <br>            // We can add our own code here  <br>            super.play()  <br>        }  <br>  <br>        override fun pause() {  <br>            // We can add our own code here  <br>            super.pause()  <br>        }  <br>  <br>        override fun seekBack() {  <br>            // We can add our own code here  <br>            super.seekBack()  <br>        }  <br>  <br>        override fun seekForward() {  <br>            // We can add our own code here  <br>            super.seekForward()  <br>        }  <br>    }</pre><p>Since we previously only allowed play, pause, seekBack, and seekForward commands, it would be more appropriate to override these four command behaviors.</p><p>What can be done for a real-life scenario? For example, when we receive a play() command from outside, we can report this through a third-party analytics SDK.</p><p>In our demo application, to see how this works, we’ll just show a toast:</p><pre>@androidx.annotation.OptIn(UnstableApi::class)  <br>fun initForwardingPlayer(context: Context, player: Player): ForwardingPlayer {  <br>    return object : ForwardingPlayer(player) {  <br>        override fun play() {  <br>            Toast.makeText(context, &quot;Video played&quot;, Toast.LENGTH_LONG).show()  <br>            super.play()  <br>        }  <br>  <br>        override fun pause() {  <br>            Toast.makeText(context, &quot;Video paused&quot;, Toast.LENGTH_LONG).show()  <br>            super.pause()  <br>        }  <br>  <br>        override fun seekBack() {  <br>            Toast.makeText(context, &quot;Video rewound&quot;, Toast.LENGTH_LONG).show()  <br>            super.seekBack()  <br>        }  <br>  <br>        override fun seekForward() {  <br>            Toast.makeText(context, &quot;Video forwarded&quot;, Toast.LENGTH_LONG).show()  <br>            super.seekForward()  <br>        }  <br>    }  <br>}</pre><p>After writing the function that creates ForwardingPlayer like above, in the same way after player is initialized, we create the variable below and make sure to use that variable when creating MediaSession:</p><pre>player = initPlayer(context)  <br>val forwardingPlayer = initForwardingPlayer(context, player!!)  <br>mediaSession = initMediaSession(context, forwardingPlayer)</pre><p>And the result looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*tf72D8BKLVgzUMEk.gif" /><figcaption><em>MediaSession works as expected when we pause the video :)</em></figcaption></figure><p>You can access the complete project from here:</p><p><a href="https://github.com/oguzhaneksi/Media3Demo/tree/mediasession-basic">GitHub - oguzhaneksi/Media3Demo at mediasession-basic</a></p><p>To summarize, we can say that MediaSession is an excellent component that allows the player in the application to be controlled from external sources.</p><p>In this article, I talked about MediaSession mainly at a fundamental level comprehensively and created a simple demo application without background content playback. I hope it was helpful :)</p><p>Happy coding everyone :)</p><p><strong>Resources:</strong></p><ul><li><a href="https://developer.android.com/media/media3/session/control-playback">Control and advertise playback using a MediaSession | Android media | Android Developers</a></li><li><a href="https://medium.com/androiddevelopers/understanding-mediasession-part-1-3-e4d2725f18e4">Understanding MediaSession (Part 1/4)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cf911c74b77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Alpha to Almost-Production: Building Media3Watch Part 2]]></title>
            <link>https://medium.com/@ouzhaneki/from-alpha-to-almost-production-building-media3watch-part-2-5c60cebebfcc?source=rss-aedc8b3df276------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c60cebebfcc</guid>
            <category><![CDATA[media]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[media3]]></category>
            <category><![CDATA[video-analytics]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Oğuzhan Ekşi]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 07:38:57 GMT</pubDate>
            <atom:updated>2026-03-04T07:38:57.566Z</atom:updated>
            <content:encoded><![CDATA[<h4>Clearing the roadmap with Offline Resilience, ABR Telemetry, a Debug Overlay, and Maven Central Publishing.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wKMtKrtxxOMYUApUAciNnQ.png" /></figure><p><strong><em>Note: This is Part 2 of the Media3Watch series. If you missed it, check out </em></strong><a href="https://medium.com/@ouzhaneki/building-a-local-first-native-video-analytics-sdk-for-android-media3-117c3cf77baa"><strong><em>[Part 1: Building a Local-First Native Video Analytics SDK for Android Media3]</em></strong></a></p><h3>Introduction: The “Part 2” Promise</h3><p>In Part 1, I introduced <strong>Media3Watch</strong>, an open-source, local-first video analytics SDK for Android Jetpack Media3. I outlined the core pain point — flying blind when videos buffer in production — and presented a lightweight SDK + Ktor backend solution.</p><p>At the end of that article, I laid out a transparent roadmap with four major milestones to move the SDK from a “nifty local utility” into a robust tool:</p><ol><li>Solidifying ABR (HLS/DASH) Telemetry</li><li>Offline Resilience (Store-and-Forward Caching)</li><li>A Standalone Debug Overlay</li><li>Frictionless Publishing to Maven Central</li></ol><p>Over the past week, I shipped every single one of them.</p><p>In this article, I want to walk you through exactly how I implemented these features, the engineering trade-offs I had to make (because building an SDK is very different from building an app), and the lessons I learned building this in public.</p><h3>Feature 1: Solidifying ABR (HLS/DASH) Telemetry</h3><p><strong>The Problem:</strong> Part 1 fully supported progressive media (like standard .mp4 URLs). However, modern video streaming heavily relies on Adaptive Bitrate (ABR) protocols like HLS and DASH, where the player constantly switches qualities based on network conditions.</p><p><strong>The Approach:</strong> To track bitrate changes without bogging down the main thread, I tapped into Media3’s AnalyticsListener.onVideoInputFormatChanged. Whenever the player shifts up or down in quality, the SDK captures the new bitrate. This currentBitrate is now added to the SessionSnapshot emitted to the observers.</p><p><strong>The Struggle: Fighting with PlaybackStatsListener:</strong> To test this properly, I added a stream selector to the demo app, allowing on-the-fly switching between MP4, HLS, and DASH streams. Immediately, I hit a bizarre bug: during transitions between streams, my playbackStats were suddenly being sent to the backend as null. Diving into the source code, I realized Media3&#39;s PlaybackStatsListenermanages its own internal session state. I was reusing a single listener instance across multiple media items. After some deep digging into best practices, I learned that in this architecture, it&#39;s actually much safer to aggressively create and attach a <em>new</em> instance of PlaybackStatsListener for every single session rather than trying to reuse a global one. Making that architectural switch instantly fixed the null drops.</p><p><strong>The Trade-off:</strong> “Perfect ABR tracking” would mean recording the exact timeline of every micro-shift in quality, tracking segment fetch times, and parsing master playlist errors. Instead of going down that endless rabbit hole right away, I embraced a “V1 mentality”. I opted for a reliable baseline: capturing the meanVideoFormatBitrate overall, and exposing an experimental currentBitrate for real-time overlays. It doesn&#39;t solve every HLS edge case yet, but it immediately gives developers visibility into whether their stream is actually adapting properly.</p><h3>Feature 2: Offline Resilience — Store-and-Forward Caching</h3><p><strong>The Problem:</strong> Mobile networks are flaky. You might watch a video perfectly, but if your phone loses cellular connection the exact second you background the app, the final session_end upload fails. Without caching, that telemetry data is gone forever.</p><p><strong>The Architecture:</strong> The immediate temptation in Android is to reach for Room or WorkManager. But remember the golden rule of SDK development: <strong>Do no harm (and keep it light).</strong></p><p>I completely rejected heavy dependencies. Instead, I built a lightweight FileQueue paired with AndroidX&#39;s AtomicFile.</p><ul><li><strong>State Management:</strong> When a network request fails, the JSON payload is safely written to disk using AtomicFile (providing crash-safe file I/O) protected by a Coroutine Mutex.</li><li><strong>Eviction Policy:</strong> I implemented a strict FIFO (First-In-First-Out) eviction strategy with a maxQueuedPayloadslimit (default 100). This guarantees the SDK will never silently eat a user&#39;s storage space.</li><li><strong>Upsert Magic:</strong> Because our backend uses Idempotent UPSERTs (ON CONFLICT (session_id) DO UPDATE), if the SDK retries the same session multiple times upon network restoration, the database handles it gracefully. No duplicate rows. We just flush the disk queue on the next attach() call when the UI is active.</li></ul><h3>Feature 3: Standalone Debug Overlay</h3><p><strong>The Problem:</strong> Logcat summaries are fantastic for Android engineers, but QA engineers testing out in the field rarely have their phones tethered to Android Studio.</p><p><strong>The Architecture:</strong> I built a dedicated :overlay module. The core design decision was to keep it strictly <strong>UI-agnostic</strong>. I avoided forcing Jetpack Compose or XML onto consumers. It uses pure Android View APIs to draw a floating widget over the player.</p><p>To ensure it doesn’t break player controls, it uses onInterceptTouchEvent = false for touch-through capabilities.</p><p><strong>The Observer Pattern:</strong> How does the overlay get data without coupling the core SDK to Android UI components? Through a strict MetricsObserver contract. The UI registers callbacks like onSnapshotUpdated, onSessionStarted, and onSessionEnded. The core SDK simply broadcasts its state.</p><p>The result? A slick, color-coded floating pill that shows you ▶ PLAYING | Start 450ms | Reb 1 | Err 0 and expands into a full stats card when tapped.</p><h3>Feature 4: Frictionless Publishing (Maven Central)</h3><p><strong>The Problem:</strong> In Part 1, using Media3Watch meant cloning the repo and pulling the module into your project manually. That’s a huge barrier to entry.</p><p><strong>The Implementation:</strong> I set up GitHub Actions with the vanniktech/gradle-maven-publish-plugin. The CI pipeline triggers on GitHub releases and is split into two robust, sequential jobs:</p><ol><li><strong>Validate:</strong> A dry-run (publishToMavenLocal) to ensure POM generation and GPG signing will succeed.</li><li><strong>Publish:</strong> Once validation passes, this job executes publishAndReleaseToMavenCentral.</li></ol><p><strong>The Struggle: The GPG Signing Nightmare:</strong> Getting GPG signing to work with in-memory keys and GitHub Secrets absolutely broke me. I spent hours tweaking my publish-sdk.yml workflow and generating new keys, yet every single pipeline run failed with could not read gpg key. I was so incredibly frustrated that I genuinely considered giving up on Maven Central publishing altogether. Then, I realized my fatal mistake: I was repetitively hitting &quot;Re-run all jobs&quot; on the <em>same</em> GitHub release tag after pushing configuration changes. GitHub Actions wasn&#39;t pulling my fresh workflow state for the old tag! Instead of re-running the job, I deleted the existing release and created a brand-new release tag. Suddenly, the changes reflected, the errors advanced, and one or two commits later, the artifact was successfully signed and published. A brutal lesson in CI caching.</p><p>Media3Watch is now a one-line integration:implementation(&quot;io.github.oguzhaneksi:media3watch-sdk:&lt;version&gt;&quot;)</p><h3>Backend Hardening: Community-Driven Security</h3><p>While the client was getting smarter, the Ktor backend also needed to graduate from a “local dev dummy server” to something capable of handling actual traffic. After sharing Part 1 of this series on the r/androiddev subreddit, a fellow developer gave me some incredibly valuable (and humbling) feedback regarding the vulnerabilities of my simple Ktor endpoint.</p><p>Taking that community feedback to heart, I implemented several crucial hardening measures:</p><ul><li><strong>Rate Limiting &amp; Security:</strong> Added per-API-key rate limiting and constant-time API key comparisons to prevent timing attacks.</li><li><strong>Input Validation:</strong> Strict UUID validation, numeric range checks, and a hard 64KB request body limit.</li><li><strong>Prometheus Metrics:</strong> Added JVM and custom business metrics (sessions_ingested_total, sessions_failed_total) for true observability.</li><li><strong>Retention Cleanup:</strong> Implemented a scheduled, batched delete worker to automatically clear out sessions older than the retention period.</li></ul><h3>Engineering Lessons Learned — Part 2</h3><h4>1. Every Byte Counts in an SDK</h4><p>Deciding to build FileQueue by hand using basic File I/O rather than importing Room was difficult but correct. When developers evaluate third-party SDKs, the dependency graph is heavily scrutinized. Bringing in massive libraries for simple features is a quick way to get your SDK rejected by a tech lead.</p><h4>2. The Observer Pattern is Your Best Friend</h4><p>The decoupling of the :overlay UI module from the :sdk core via the MetricsObserver interface is what keeps the architecture clean. The core SDK does not know, nor care, if it&#39;s logging to a text console, sending HTTP requests, or drawing a UI.</p><h4>3. The Real Value of CI: Green Checks Equal Sleep</h4><p>Automating Maven Central publishing forced me to respect my own unit tests. A green checkmark on the Validate workflow means I can tag a release and go to sleep knowing the artifact isn&#39;t broken.</p><h4>4. Perfect is the Enemy of Good (Again)</h4><p>This was especially true for the ABR tracking. I wanted to build a complex state machine for HLS segments. Instead, I shipped a “V1” that tracks mean bitrate and exposes the current bitrate as an experimental field. It delivers 80% of the value with 20% of the effort, allowing me to ship without getting bogged down.</p><h4>5. Open Source Means Free Code Reviews (The Reddit Effect)</h4><p>Posting daily updates on X (Twitter) kept the momentum alive, but sharing the project on r/androiddev gave me something even better: raw, unfiltered feedback. The community quickly pointed out the security flaws in my backend MVP. Building in public isn&#39;t just about accountability; it&#39;s about crowdsourcing architectural wisdom and letting the community stress-test your code.</p><h3>Current State &amp; What’s Still Missing (Transparency)</h3><p>To keep with the theme of honesty, Media3Watch still has architecture and infrastructure gaps before it can be labeled perfectly “Enterprise-Ready”. Based on a recent production-readiness audit, here is what I am actively looking to fix:</p><p><strong>Critical Android Edge Cases:</strong></p><ul><li><strong>ProGuard Rules:</strong> The SDK currently lacks shipped consumer ProGuard rules (e.g., for kotlinx.serialization models). This is a P0 issue; minified apps will crash at runtime when attempting to serialize telemetry payloads.</li><li><strong>Coroutine Lifecycle Management:</strong> The SDK’s internal CoroutineScope is deliberately detached from the UI lifecycle (which is correct—we need final telemetry uploads to complete even if the user leaves the app or destroys the Activity), but it currently lacks a graceful application-level &quot;shutdown&quot; mechanism, risking memory leaks if instances are recreated.</li><li><strong>Missing Contextual Metadata:</strong> We still aren’t gathering OS version, device model, SDK version, or connection type in the telemetry payload. Debugging “slow start times” without knowing the user’s device capabilities is extremely difficult.</li><li><strong>Thread Safety &amp; Shared Clients:</strong> Minor race conditions exist around session ID resets, and the HttpSendercurrently instantiates a new OkHttpClient per analytics instance instead of using a shared pool.</li></ul><p><strong>Backend Hardening Needs:</strong></p><ul><li><strong>Shallow Health Checks:</strong> The Ktor /health endpoint only verifies that the server is responding; it doesn&#39;t currently ping the PostgreSQL database. If the DB connection pool depletes, the server will still report &quot;healthy&quot; to the load balancer while dropping every analytics request.</li><li><strong>Multi-Tenant Support:</strong> The system relies on a single global API key. Supporting different environments (Staging vs. Prod) or multiple apps requires proper tenant isolation (e.g., app_id).</li><li><strong>Connection Pooling:</strong> The background worker that clears out expired sessions currently requests a new DB connection for every single batch operation instead of executing the entire cleanup transaction under one connection.</li></ul><p><strong>Roadmap V2:</strong> Looking forward, the next big focus areas are:</p><ol><li><strong>Cross-Platform:</strong> KMP (Kotlin Multiplatform) adapters for iOS (AVPlayer) and Web.</li><li><strong>Observability:</strong> Trace ID injection so playback failures can be mapped directly from the Android client through the backend logs.</li><li><strong>Advanced Playback:</strong> Managing complex player lifecycle edge cases like Picture-in-Picture (PiP) and background audio transitions.</li></ol><h3>Conclusion &amp; Call to Action</h3><p>The initial roadmap is clear. Media3Watch now supports offline resilience, handles basic ABR telemetry, provides a gorgeous debug overlay, and is officially available on Maven Central.</p><p>If you are tired of guessing why ExoPlayer is dropping frames and want instant local observability, integration is officially one line of code away.</p><p><strong>Here is how you can help:</strong></p><ul><li>⭐ <strong>Star the repo</strong> on <a href="https://github.com/oguzhaneksi/Media3Watch">GitHub</a>.</li><li>🐛 <strong>Submit a Pull Request</strong> (Tackling the ProGuard rules would be an amazing first contribution!)</li><li>🐦 <strong>Let’s connect on X (Twitter):</strong> <a href="https://x.com/oguzhaneksi97">@oguzhaneksi97</a> to follow my “build in public” journey.</li></ul><p>Happy coding, and may your rebuffer ratios stay safely under 2%. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c60cebebfcc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Local-First Native Video Analytics SDK for Android Media3]]></title>
            <link>https://medium.com/@ouzhaneki/building-a-local-first-native-video-analytics-sdk-for-android-media3-117c3cf77baa?source=rss-aedc8b3df276------2</link>
            <guid isPermaLink="false">https://medium.com/p/117c3cf77baa</guid>
            <dc:creator><![CDATA[Oğuzhan Ekşi]]></dc:creator>
            <pubDate>Fri, 20 Feb 2026 18:03:14 GMT</pubDate>
            <atom:updated>2026-02-20T21:16:51.949Z</atom:updated>
            <content:encoded><![CDATA[<h4>A lightweight, drop-in observability tool to track video buffering and startup times without the enterprise vendor lock-in.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*4HEn46T9tdpfNGIWVPLGoA@2x.jpeg" /></figure><h3>TL;DR</h3><ul><li><strong>The Pain:</strong> Flying blind while users drop 1-star reviews because your app’s video player keeps freezing is absolutely brutal. We’ve all been there, and relying on crash reporters for video performance is a lost cause.</li><li><strong>The Fix:</strong> Enter <strong>Media3Watch</strong> — a drop-in, open-source video analytics SDK for Android Jetpack Media3. Because honestly, paying ridiculous enterprise SaaS fees and getting locked into third-party servers just to track startup times is a massive L.</li><li><strong>The Tech:</strong> It spits clean, formatted session summaries straight into Logcat for instant local debugging. Need more? It ships with a dummy-proof, Dockerized backend (Ktor + Postgres + Grafana) so you can self-host and actually own your telemetry.</li><li><strong>The Reality Check:</strong> It’s an absolute W for progressive media right now, but we’re still cooking up bulletproof support for the chaotic edge cases of adaptive bitrate (HLS/DASH).</li></ul><h3>Introduction: The Blind Spot in Android Video Playback</h3><p>Playing video on Android is easier today than it has ever been. Thanks to Jetpack Media3 (and its core, ExoPlayer), building a decent video player takes just a few lines of code. It works perfectly on your office Wi-Fi, the emulator is smooth, and QA approves the ticket.</p><p>But then production hits.</p><p>Users start leaving 1-star reviews: <em>“The video keeps freezing”</em> or <em>“It takes forever to load.”</em> Your Product Manager asks for the average startup time of your new video feed, and you realize something terrifying: <strong>you have absolutely no idea what’s happening on your users’ screens.</strong></p><p>We have Crashlytics for crashes and APMs for network requests, but what about Video Quality of Experience (QoE)? If a user waits 4 seconds for a video to start playing, or if it buffers three times in a single minute, your crash reporter stays silent. There is no stack trace for a poor viewing experience. Most developers are flying completely blind when it comes to video performance.</p><h3>The Inspiration: Why I Built Media3Watch</h3><p>Faced with this blind spot, Android teams usually encounter the classic “Build vs. Buy” dilemma:</p><ol><li><strong>Buy an Enterprise Solution:</strong> You integrate industry-standard tools like Mux, Bitmovin, or Conviva. They are incredibly powerful, but they come with significant drawbacks for smaller teams, startups, or MVPs: steep pricing, vendor lock-in, and the requirement to send all your playback data to a third-party server.</li><li><strong>Build It In-House:</strong> You decide to build your own analytics. You attach a listener to ExoPlayer, but quickly realize that tracking dropped frames, differentiating between seek buffering and network rebuffering, and handling lifecycle edge cases (like backgrounding the app or switching media items) is a massive headache. A weekend task suddenly turns into a 3-month engineering marathon.</li></ol><p>I needed a middle ground. I wanted a drop-in, open-source SDK that respects user privacy, gives me immediate insights locally during development, and allows me to own my data if I decide to centralize it.</p><p>That was the birth of <strong>Media3Watch</strong> — a lightweight, local-first video analytics SDK for Android. Its goal was simple: provide instant session summaries in Logcat for fast debugging, and offer a ready-to-use Dockerized backend (Ktor + Postgres + Grafana) for those who want to self-host their telemetry. No vendor lock-in, no hidden costs, just raw engineering.</p><h3>Architecture &amp; Tech Stack: A Full-Stack Approach</h3><p>To build a truly end-to-end telemetry system, Media3Watch consists of three distinct components: the client SDK, the backend API, and a visualization layer. Instead of relying on external SaaS platforms, the entire stack is designed to run locally or be easily self-hosted for internal testing.</p><p>Here is how the architecture is layered:</p><p><strong>1. The Android SDK (Kotlin &amp; Media3)</strong> At the heart of the client side is the Media3WatchAnalytics class, which registers Media3’s AnalyticsListener (along with PlaybackStatsListener) to hook directly into the active ExoPlayer instance.</p><ul><li><strong>Event Aggregation:</strong> Instead of reinventing the wheel, the SDK leverages Media3’s built-in PlaybackStatsListener to seamlessly calculate complex metrics like rebuffer ratios and play times. It also passively listens to playback state changes, video format adjustments, and performance events (e.g., dropped frames, seek operations) via AnalyticsListener.</li><li><strong>Lifecycle-Aware Sessions:</strong> Metrics are aggregated into a SessionSummary data model. A tracking session is strictly scoped to the player attachment—starting when the user requests playback and gracefully terminating when playback ends or the analytics instance is detached.</li><li><strong>Zero-Friction Debugging (Logcat):</strong> Upon session completion, it dumps a highly readable, formatted summary directly into Logcat. For day-to-day local debugging, this feature alone saves countless hours.</li><li><strong>Non-Blocking I/O:</strong> To ensure zero impact on video rendering and the main thread, optional HTTP uploads (both periodic real-time updates and the final summary) are dispatched safely on a background Kotlin Coroutine dispatcher (Dispatchers.Default for JSON serialization, then moving to IO) using OkHttp.</li></ul><p><strong>2. The Backend Service (Kotlin Ktor &amp; PostgreSQL)</strong> When you need to aggregate metrics across multiple test devices or an internal beta group, the SDK can forward data to the backend component. I chose Ktor over heavier frameworks like Spring Boot to keep the service lightweight and to maintain an idiomatic Kotlin ecosystem from client to server.</p><ul><li><strong>Data Ingestion:</strong> A REST API receives JSON payloads containing the playback metrics. It intelligently handles both periodic live-session updates and final comprehensive summaries, utilizing PostgreSQL UPSERT (ON CONFLICT (session_id) DO UPDATE ...) operations to maintain strict idempotency.</li><li><strong>Persistence:</strong> PostgreSQL serves as the robust, structured storage layer for all session data.</li><li><strong>Containerized Setup (Dev-Optimized):</strong> The backend is fully Dockerized. A single docker-compose up command spins up the Ktor app, the database, and the visualization tools, ensuring an Android developer doesn&#39;t need to spend hours wrestling with local server configurations. Note: The current backend is optimized for out-of-the-box local development and internal beta testing. Scaling it for production SaaS usage would require adding your own auth layers and rate limits.</li></ul><p><strong>3. Visualization (Grafana)</strong> Raw data in a SQL table isn’t very useful until you can spot the trends. To complete the observability loop, I integrated Grafana into the stack.</p><ul><li><strong>Auto-Provisioned Dashboards:</strong> The Docker Compose setup automatically provisions a Grafana instance and pre-connects it to the Postgres database.</li><li><strong>Actionable Insights:</strong> An out-of-the-box dashboard allows you to immediately visualize critical QoE (Quality of Experience) trends — observing everything from mean startup times to rebuffer ratios across all captured sessions without writing a single SQL query.</li></ul><h3>Key Engineering Decisions &amp; Trade-Offs</h3><p>When building an SDK that lives inside other developers’ applications, you have a strict “do no harm” mandate. A video analytics tool cannot be the reason a video stutters or the app crashes. Here are some of the critical decisions I made:</p><p><strong>1. Idempotent Backend Operations (UPSERTs)</strong> Mobile networks are inherently flaky. A user might drive through a tunnel, causing the session_end HTTP POST request to fail and trigger a retry. To prevent our backend metrics from turning into duplicate chaos, every session is assigned a unique UUID by the client upon initialization. The backend utilizes PostgreSQL&#39;s ON CONFLICT (session_id) DO UPDATE mechanism. This guarantees that whether the backend receives one packet or five retried packets for the same session, the database state remains consistent and accurate.</p><p><strong>2. Lightweight Authentication (API Keys)</strong> Security is crucial, but implementing OAuth or JWT for a simple telemetry ingestion endpoint would have been severe over-engineering, unnecessarily complicating the SDK footprint. For an internal tool designed to be self-hosted, I opted for a simple, configurable API Key validation via HTTP Headers. It’s just enough friction to reject untrusted spam requests while keeping the client integration strictly to one line of configuration code.</p><p><strong>3. Flat Data Structures for Easy Visualization</strong> When designing the SessionSummary JSON payload, I could have nested everything beautifully into hierarchical objects (e.g., separating network, playback, and device nodes). Instead, I made a conscious trade-off to keep the data model relatively flat. A flat JSON structure maps cleanly to a flat PostgreSQL table. This decision drastically reduces the complexity of writing Grafana queries. You don&#39;t need to write expensive JSONB extract operators; you can simply SELECT avg(startup_time_ms) directly from the table.</p><p><strong>4. Decoupling the Listeners</strong> By leveraging Jetpack Media3’s PlaybackStatsListener, the SDK offloads the complex math (like calculating exactly how much time was spent in the Rebuffering state versus Seeking) to the core library itself. I combined this with a standard AnalyticsListener for real-time events. This trade-off means Media3Watch is tightly coupled to Media3 (and won&#39;t work on older ExoPlayer v2 implementations), but the benefit is near-zero maintenance overhead for the complex state machine tracking.</p><p><strong>5. Non-Intrusive Telemetry Tracking (The “Do No Harm” Rule)</strong> To prevent the analytics SDK from interfering with video rendering — which runs heavily on the main thread — all intensive operations (like JSON serialization and HTTP uploading) are explicitly offloaded to background Coroutine dispatchers (Dispatchers.Default and Dispatchers.IO). If network calls hang or JSON parsing takes extra cycles, the ExoPlayer instance remains completely oblivious and lag-free.</p><h3>Current State &amp; Known Limitations (The Honest Truth)</h3><p>A core principle of open-source engineering is <strong>transparency</strong>. As it stands today, MediaWatch is highly effective for basic debugging and internal beta tracking, but it is not yet a mature, drop-in replacement for enterprise-grade analytics platforms.</p><p>Here is what you need to know about the current constraints:</p><h4>1. Progressive Media vs. Adaptive Bitrate (ABR) Streaming</h4><p>Currently, the SDK has been thoroughly tested and confirmed to work flawlessly with progressive media formats (like standard .mp4 URLs). The calculations for startup times, rebuffering, and dropped frames map perfectly to the actual user experience.</p><ul><li><strong>The Catch:</strong> ABR protocols like <strong>HLS</strong> and <strong>DASH</strong> introduce complex edge cases. In ABR, the player constantly switches video qualities (bitrates) on the fly based on fluctuating network bandwidth. While Media3Watch captures the meanVideoFormatBitrate, tracking the exact timeline of quality shifts or parsing specific master playlist errors requires deeper, stream-specific heuristics that haven&#39;t been fully stress-tested yet.</li></ul><h4>2. Backgrounding &amp; Edge Case Lifecycles</h4><p>The SDK binds a “session” strictly to the lifecycle of the player attachment.</p><ul><li><strong>The Limitation:</strong> If a user backgrounds the app, playback usually pauses, but depending on your app’s architecture, the session logic might not gracefully suspend. This can potentially lead to skewed session durations. Handling complex OS-level interruptions (like phone calls) or transitions to <strong>Picture-in-Picture (PiP)</strong> mode requires further refinement to ensure duration metrics stay 100% accurate.</li></ul><h4>3. Device-Level Isolation</h4><p>Right now, the SDK captures exactly what the device experiences. It knows the video took 5 seconds to start, but it doesn’t intuitively know <strong>why</strong>.</p><ul><li><strong>The Gap:</strong> Was the delay caused by a slow CDN edge node, a congested local Wi-Fi, or a slow DRM license fetch? Connecting client-side QoE telemetry to backend <strong>trace IDs</strong> for full end-to-end observability is not yet supported out-of-the-box.</li></ul><h4>4. Ecosystem Lock-in (Android &amp; Jetpack Media3)</h4><p>While the Media3Watch backend is scalable and platform-agnostic, the client SDK is <strong>explicitly and tightly coupled</strong> to the Android ecosystem and Jetpack Media3.</p><ul><li><strong>The Reality:</strong> If your product ecosystem includes an iOS app (using AVPlayer), a web client, or an older app still running ExoPlayer v2, you cannot use Media3Watch to track those sessions without significant custom work. Decoupling the tracking logic from Media3’s specific listeners remains a major roadmap item.</li></ul><h3>What’s Next Roadmap (A Reality Check)</h3><p>Building Media3Watch has been an incredibly rewarding process of scratching my own itch as a mobile developer. The immediate satisfaction of seeing the Logcat summary after a buffering-heavy session proved to me that this tool has tangible value. But an open-source project is never truly “finished.”</p><p>Looking ahead, here are the key milestones on the roadmap, viewed through an engineering reality-check lens:</p><h4>1. Solidifying ABR (HLS/DASH) Telemetry</h4><p>Progressive media is great, but modern streams rely on Adaptive Bitrate (ABR). Capturing accurate metrics during dynamic bitrate shifts or sudden HLS playlist errors is notoriously tricky.</p><p>The immediate goal isn’t necessarily <em>perfect</em> tracking out of the gate, but rather a solid “V1” that robustly captures stream format changes without overloading the player. This requires creating a robust local testing environment simulating network throttling and playlist manipulations — because guessing what ExoPlayer is doing under the hood never ends well.</p><h4>2. Offline-Resilience (Store-and-Forward Caching)</h4><p>Network requests inherently fail on mobile. Currently, a failed session_end upload simply means lost data. A caching mechanism is necessary to flush telemetry when connectivity is finally restored.</p><p>However, a crucial design principle here is to <strong>avoid dependency bloat</strong>. Instead of pulling in massive databases like Room or complex WorkManager setups, the solution needs a lightweight, file-backed I/O queue. This maintains the SDK’s small footprint while mitigating multi-threading risks and data corruption.</p><h4>3. Standalone Debug Overlay</h4><p>While Logcat is excellent for developers, QA engineers aren’t always tethered to Android Studio. An offline-friendly, visual debug overlay rendered directly on top of the player view would be invaluable for field testing.</p><p>The main constraint here is remaining completely <strong>UI-agnostic</strong>. The plan is to ship this as a separate artifact (e.g., :sdk-ui). This avoids forcing Jetpack Compose or XML layout dependencies into the core SDK and ensures we don&#39;t accidentally intercept touch events meant for the player&#39;s native controls.</p><h4>4. Frictionless Publishing (Maven Central)</h4><p>Right now, incorporating Media3Watch requires importing the source module directly. To lower the barrier to entry, automatic artifact publishing to Maven Central is an <strong>urgent priority</strong>, not just a distant milestone.</p><p>Integrating tools like the gradle-maven-publish-plugin via GitHub Actions will transform adoption from a manual &quot;fork-and-link&quot; chore to a simple one-line addition: implementation(&quot;com.media3watch:sdk:1.0.0&quot;)</p><h3>The Long-Term Vision</h3><p>Beyond the immediate feature set, migrating Media3Watch from a “nifty local utility” to a comprehensive, ecosystem-wide observability tool requires a broader horizon:</p><h4>5. Cross-Platform Observability (iOS &amp; Web)</h4><p>Currently, Media3Watch is tightly coupled to the Android Jetpack Media3 ecosystem. However, video playback issues rarely exist in a silo. The long-term architectural goal is to decouple the core metrics aggregation logic (potentially leveraging <strong>Kotlin Multiplatform</strong>) and build lightweight, native adapters for iOS (AVPlayer) and Web (video.js / hls.js).</p><p>The vision is a single Grafana dashboard where you can filter QoE metrics not just by video, but across your entire product ecosystem.</p><h4>6. Scaling the Backend for Enterprise Traffic</h4><p>The existing Ktor + Postgres + Docker Compose stack is intentionally designed for zero-friction local development, QA environments, and small beta groups.</p><p>To make the self-hosted backend truly “Production-Ready” to handle tens of thousands of concurrent video sessions, the architecture will need to evolve. This means moving beyond simple API keys toward robust authentication (OAuth/JWT), introducing a message broker (like <strong>Kafka</strong> or <strong>Redis</strong>) to gracefully absorb ingestion spikes, and implementing aggressive PostgreSQL table partitioning to manage massive historical data volumes.</p><h3>Lessons Learned as a Product Engineer</h3><p>Building an end-to-end tool from scratch shifts your perspective from being just an “Android Developer” to acting as a Product Engineer. Here are the most valuable lessons I took away:</p><h4>1. Building an SDK is Not Building an App</h4><p>When you write an app, you own the environment. If your background thread takes a bit too long, maybe a loading spinner stutters. But when you write an SDK, you are a guest in someone else’s house. You have zero control over their architecture. If your analytics listener blocks the main thread and causes their video to drop frames, your SDK will be ripped out immediately. The “Do No Harm” mandate forces you to write defensive, highly optimized code.</p><h4>2. Developer Experience (DX) is an MVP Feature</h4><p>In the beginning, I was obsessed with getting the data into Postgres and showing it on Grafana. But halfway through, I realized that printing a clean, formatted text block into Logcat when the session ends was actually the most immediate “Aha!” moment. For many developers, just seeing rebufferRatio: 0.02 locally without opening a dashboard solves 80% of their daily debugging pain. Don&#39;t underestimate the power of simple, visible console outputs.</p><h4>3. Full-Stack Context Makes You a Better Client Developer</h4><p>Knowing exactly how the Ktor backend handles ingestion (using PostgreSQL UPSERTs) completely changed how I wrote the Android chunk-upload logic. Because I knew the backend was naturally idempotent and explicitly handled sessionId collisions, I didn&#39;t have to write overly complex, stateful retry mechanisms on the client. I simply let OkHttp retry safely. Understanding the entire data pipeline—from the ExoPlayer listener down to the SQL row—eliminates the guessing game between Frontend and Backend teams.</p><h4>4. Stand on the Shoulders of Giants</h4><p>Initially, I thought I had to manually calculate every millisecond of rebuffering by listening to Player.STATE_BUFFERING. Then I discovered Media3&#39;s PlaybackStatsListener. Yes, it tightly coupled the SDK to specific Media3 versions, but it saved me weeks of writing and maintaining complex, bug-prone state machines. Recognizing when to use a platform&#39;s native tools instead of reinventing the wheel is critical for shipping MVPs.</p><h4>5. Ship the Imperfect MVP, Then Iterate (The Perfectionism Trap)</h4><p>I initially spent an entire week designing what I thought was the “perfect” architecture to anticipate every edge case. The result? Zero working code. I made a brutal decision: scrap the sophisticated design and build the simplest version that prints metrics to Logcat. Within 48 hours, I had a working prototype. I learned the hard way that in SDK development, “working and improvable” beats “planned and perfect” every time — your first version just needs to solve one painful problem really well.</p><h4>6. Build in Public Creates Momentum (Accountability Over Perfection)</h4><p>Committing to “build in public” on X (Twitter) unexpectedly transformed this project. Every day, I posted small updates — even if it was just “fixed a bug for 3 hours.” While live-debugging in public felt uncomfortable at first, knowing people were watching gave me the accountability to make daily progress. It also attracted external validation and helpful suggestions during the messy middle phase, keeping me from abandoning the project when nothing was working.</p><h3>Conclusion &amp; How to Get Involved</h3><p>Media3Watch started as an attempt to solve a specific, painful problem I faced as a mobile developer: the lack of visibility into Android video playback performance without buying an expensive enterprise subscription. What it evolved into is a completely open-source, local-first SDK and self-hosted backend that puts the power of Quality of Experience (QoE) telemetry back into the hands of independent developers and small teams.</p><p>Is it perfect? Not entirely — we still have mountains to climb regarding robust ABR (HLS/DASH) tracking and cross-platform support. Is it useful? Absolutely. Dropping it into your project today will give you immediate, actionable insights into exactly why your users’ videos are buffering.</p><p>If you’re an Android engineer tired of guessing why ExoPlayer is dropping frames, I’d love for you to give Media3Watch a spin.</p><p><strong>Here is how you can get involved:</strong></p><ul><li>⭐ <strong>Star the repo</strong> on GitHub to follow the journey.</li><li>🐛 <strong>Open an issue</strong> if you encounter unexpected edge cases (especially if you’re working heavily with HLS streams).</li><li>🛠️ <strong>Submit a Pull Request!</strong> I’m actively looking for contributions on the Offline Store-and-Forward caching strategy and Maven Central publishing automation.</li></ul><p>Check out the full source code and the complete setup guide here: <a href="https://github.com/oguzhaneksi/Media3Watch"><strong>Media3Watch GitHub Repository</strong></a></p><p>Happy coding, and may your startup times always be sub-second! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=117c3cf77baa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic background playback implementation with Media3 MediaSessionService]]></title>
            <link>https://medium.com/@ouzhaneki/basic-background-playback-implementation-with-media3-mediasessionservice-4d571f15bdc2?source=rss-aedc8b3df276------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d571f15bdc2</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[exoplayer]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[media3]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Oğuzhan Ekşi]]></dc:creator>
            <pubDate>Mon, 18 Dec 2023 07:50:18 GMT</pubDate>
            <atom:updated>2023-12-18T07:50:18.339Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N_BupX7P7VDUyLW6" /></figure><p>While creating a media playback application, being able to play the media in the background is almost essential for a better user experience. For example, a music app can allow users to listen to their favorite song while engaging in other activities, such as gaming, chatting with friends or the device is locked. The Media3 library offers developers the tools needed to easily implement support for background playback.</p><p>How is Media3 different from other playback libraries?</p><blockquote>One of the primary characteristics that distinguishes Media3 from previous media APIs is that there is no longer a need for connectors between components. The new <strong>MediaSession</strong> class takes any class that implements the<strong>Player</strong> interface, as can the UI. Both <strong>ExoPlayer</strong> and <strong>MediaController</strong> are classes which implement that interface. This facilitates much simpler interaction between the components.</blockquote><p>That sounds promising! But what exactly is MediaSession? To briefly describe, MediaSession exposes media playback externally and receives playback commands from external sources. For example, it provides managing the playback by using headset buttons, or by talking to Google Assitant. For more detailed information about MediaSession, you can follow this link:</p><p><a href="https://developer.android.com/guide/topics/media/session/mediasession">Control and advertise playback using a MediaSession | Android Developers</a></p><p>Without further delay, let’s delve into the details of MediaSessionService.</p><h3>What is MediaSessionService?</h3><p>To continue playback in the background, you should create a service contains Player and MediaSession. So basically, this lets the device keep playing media even if your app isn’t actively open.</p><p>The service you create should extend MediaSessionService. This MediaSessionService lets external clients like Google Assistant manage the playback even if the app is not in the foreground.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iUArfGiaTNHUVc3k.png" /><figcaption>The MediaSessionService lets the media session run independently from the app’s activity.</figcaption></figure><p>MediaSessionService is a bound service that runs as long as MediaController binds to the service. MediaController is a key component that interacts with the MediaSession hosted by MediaSessionService. <strong>It is used in the UI to send commands to the player.</strong></p><h4>MediaSessionService Lifecycle</h4><p>Before delving into the MediaSessionService lifecycle, let‘s define the main methods.</p><p><strong>onCreate()</strong> is invoked when the first controller is about to connect and the service is created and started. This is the best place to build the Player and MediaSession. The creation of the MediaSessionService allows it to run separately from the app&#39;s activity, enabling external clients like Google Assistant, system media controls, or companion devices to discover your service, connect to it, and control playback.</p><p><strong>onTaskRemoved(Intent)</strong> is called when the app is removed from the recent tasks. If playback is ongoing, the app can choose to keep the service running in the foreground. However, if the player is paused and the service is not in the foreground, it should be stopped.</p><p><strong>onDestroy()</strong> is invoked when the service is being stopped. It’s important to release all resources, including the player and the session in this method.</p><p><strong>onGetSession()</strong> is called when a MediaController is created and it returns a MediaSession that the controller will connect to, or null to reject the connection request.</p><p>When a MediaController is created first, it binds to MediaSessionService. Bound services have onBind() method which is fired when a client binds to a service. Similarly, when a MediaController binds to MediaSessionService, onBind() method is executed and onGetSession() is subsequently called within onBind().</p><p>The service will be destroyed when MediaSession is released, or no controller is bound to the service when the service is in the background.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*DpT5AuCyaisWqi2T516wdw.png" /><figcaption>A flowchart of a typical MediaSessionService lifecycle</figcaption></figure><h3>Basic Implementation</h3><h4>1-) Dependency Setup</h4><p>Before we start implementing the background playback, we must implement the Media3 dependencies below:</p><pre>// For media playback using ExoPlayer<br>implementation(&quot;androidx.media3:media3-exoplayer:$media3Version&quot;)<br>// For exposing and controlling media sessions<br>implementation(&quot;androidx.media3:media3-session:$media3Version&quot;)</pre><h4>2-) Create a MediaSessionService</h4><p>As previously discussed in the lifecycle section, we need to implement four methods in our service. Initially, we create a service that extends MediaSessionService. After that, we override these four methods.</p><pre>class PlaybackService : MediaSessionService() {<br><br>    /**<br>     * This method is called when the service is being created.<br>     * It initializes the ExoPlayer and MediaSession instances.<br>     */<br>    override fun onCreate() {<br>        super.onCreate() // Call the superclass method<br>    <br>        // Create an ExoPlayer instance<br>        val player = ExoPlayer.Builder(this).build()<br>    <br>        // Create a MediaSession instance<br>        _mediaSession = MediaSession.Builder(this, player)<br>            .build()<br>    }<br><br>    /**<br>     * This method is called when the system determines that the service is no longer used and is being removed.<br>     * It checks the player&#39;s state and if the player is not ready to play or there are no items in the media queue, it stops the service.<br>     *<br>     * @param rootIntent The original root Intent that was used to launch the task that is being removed.<br>     */<br>    override fun onTaskRemoved(rootIntent: Intent?) {<br>        // Get the player from the media session<br>        val player = mediaSession.player<br>    <br>        // Check if the player is not ready to play or there are no items in the media queue<br>        if (!player.playWhenReady || player.mediaItemCount == 0) {<br>            // Stop the service<br>            stopSelf()<br>        }<br>    }<br><br>    /**<br>     * This method is called when a MediaSession.ControllerInfo requests the MediaSession.<br>     * It returns the current MediaSession instance.<br>     *<br>     * @param controllerInfo The MediaSession.ControllerInfo that is requesting the MediaSession.<br>     * @return The current MediaSession instance.<br>     */<br>    override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? {<br>        return _mediaSession<br>    }<br><br>    /**<br>     * This method is called when the service is being destroyed.<br>     * It releases the player and the MediaSession instances.<br>     */<br>    override fun onDestroy() {<br>        // If _mediaSession is not null, run the following block<br>        _mediaSession?.run {<br>            // Release the player<br>            player.release()<br>            // Release the MediaSession instance<br>            release()<br>            // Set _mediaSession to null<br>            _mediaSession = null<br>        }<br>        // Call the superclass method<br>        super.onDestroy()<br>    }<br><br>}</pre><p>Next, we need to declare this service in the AndroidManifest.xml.</p><pre>&lt;service<br>    android:name=&quot;.PlaybackService&quot;<br>    android:foregroundServiceType=&quot;mediaPlayback&quot;<br>    android:exported=&quot;true&quot;&gt;<br>    &lt;intent-filter&gt;<br>        &lt;action android:name=&quot;androidx.media3.session.MediaSessionService&quot;/&gt;<br>    &lt;/intent-filter&gt;<br>&lt;/service&gt;</pre><p>If your app targets API level 29 (Android 10) and higher, you need to define a foregroundServiceType which is mediaPlayback to indicate that the service plays a media.</p><p>Additionally, it’s necessary to include the FOREGROUND_SERVICE permission in the manifest. For apps targeting API 34 (Android 14) or higher, the FOREGROUND_SERVICE_MEDIA_PLAYBACK permission is also required.</p><pre>&lt;uses-permission android:name=&quot;android.permission.FOREGROUND_SERVICE&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK&quot; /&gt;</pre><h4>3-) Implement MediaController in your UI</h4><p>After creating the service, we need to create a connection between the UI and media session using MediaController. Since MediaController also implements the Player interface, all player commands can be utilized through the controller. In this example, we’ll implement the UI using Compose, but I think it’s easily applicable to Activity, or Fragment, too.</p><p><strong>Create a MediaController</strong></p><p>To create a MediaController, we need a SessionToken to connect to our MediaSessionService.</p><pre>SessionToken(context, ComponentName(context, PlaybackService::class.java))</pre><p>Then we create a ListenableFuture&lt;MediaController&gt; to build the controller asynchronously using the SessionToken we created.</p><pre>val factory = MediaController.Builder(<br>  context,<br>  SessionToken(context, ComponentName(context, PlaybackService::class.java))<br>).buildAsync()</pre><p>Subsequently, we add a listener to listen when the ListenableFuture completes its execution.</p><pre>factory?.addListener(<br>   {<br>     // MediaController is available here with controllerFuture.get()<br>     mediaController = factory?.let {<br>       if (it.isDone)<br>         it.get()<br>       else<br>         null <br>     }<br>   },<br>   MoreExecutors.directExecutor()<br>)</pre><p><strong>All of these operations are implemented in </strong><strong>onStart() method of the Activity lifecycle.</strong></p><p><strong>In line with Media3’s best practices, the </strong><strong>MediaController is released in the </strong><strong>onStop() method of the Activity lifecycle when it‘s no longer needed.</strong></p><pre>factory?.let {<br>  MediaController.releaseFuture(it)<br>  mediaController = null<br>}<br>factory = null</pre><p>Now, you might be wondering, <strong>“Okay, you explained it like this, but how do we implement this in a real scenario?”.</strong> Don’t worry, I will cover all these details and share the complete repository at the end of this article.</p><p>In our sample Jetpack Compose application, I created a Composable function that returns state of MediaController and the lifecycle of MediaController is managed within this function.</p><pre>/**<br> * A Composable function that provides a managed MediaController instance.<br> *<br> * @param lifecycle The lifecycle of the owner of this MediaController. Defaults to the lifecycle of the LocalLifecycleOwner.<br> * @return A State object containing the MediaController instance. The Composable will automatically re-compose whenever the state changes.<br> */<br>@Composable<br>fun rememberManagedMediaController(<br>    lifecycle: Lifecycle = LocalLifecycleOwner.current.lifecycle<br>): State&lt;MediaController?&gt; {<br>    // Application context is used to prevent memory leaks<br>    val appContext = LocalContext.current.applicationContext<br>    val controllerManager = remember { MediaControllerManager.getInstance(appContext) }<br><br>    // Observe the lifecycle to initialize and release the MediaController at the appropriate times.<br>    DisposableEffect(lifecycle) {<br>        val observer = LifecycleEventObserver { _, event -&gt;<br>            when (event) {<br>                Lifecycle.Event.ON_START -&gt; controllerManager.initialize()<br>                Lifecycle.Event.ON_STOP -&gt; controllerManager.release()<br>                else -&gt; {}<br>            }<br>        }<br>        lifecycle.addObserver(observer)<br>        onDispose { lifecycle.removeObserver(observer) }<br>    }<br><br>    return controllerManager.controller<br>}</pre><pre>/**<br> * A Singleton class that manages a MediaController instance.<br> *<br> * This class observes the Remember lifecycle to release the MediaController when it&#39;s no longer needed.<br> */<br>@Stable<br>internal class MediaControllerManager private constructor(context: Context) : RememberObserver {<br>    private val appContext = context.applicationContext<br>    private var factory: ListenableFuture&lt;MediaController&gt;? = null<br>    var controller = mutableStateOf&lt;MediaController?&gt;(null)<br>        private set<br><br>    init { initialize() }<br><br>    /**<br>     * Initializes the MediaController.<br>     *<br>     * If the MediaController has not been built or has been released, this method will build a new one.<br>     */<br>    @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)<br>    internal fun initialize() {<br>        if (factory == null || factory?.isDone == true) {<br>            factory = MediaController.Builder(<br>                appContext,<br>                SessionToken(appContext, ComponentName(appContext, PlaybackService::class.java))<br>            ).buildAsync()<br>        }<br>        factory?.addListener(<br>            {<br>                // MediaController is available here with controllerFuture.get()<br>                controller.value = factory?.let {<br>                    if (it.isDone)<br>                        it.get()<br>                    else<br>                        null<br>                }<br>            },<br>            MoreExecutors.directExecutor()<br>        )<br>    }<br><br>    /**<br>     * Releases the MediaController.<br>     *<br>     * This method will release the MediaController and set the controller state to null.<br>     */<br>    internal fun release() {<br>        factory?.let {<br>            MediaController.releaseFuture(it)<br>            controller.value = null<br>        }<br>        factory = null<br>    }<br><br>    // Lifecycle methods for the RememberObserver interface.<br>    override fun onAbandoned() { release() }<br>    override fun onForgotten() { release() }<br>    override fun onRemembered() {}<br><br>    companion object {<br>        @Volatile<br>        private var instance: MediaControllerManager? = null<br><br>        /**<br>         * Returns the Singleton instance of the MediaControllerManager.<br>         *<br>         * @param context The context to use when creating the MediaControllerManager.<br>         * @return The Singleton instance of the MediaControllerManager.<br>         */<br>        fun getInstance(context: Context): MediaControllerManager {<br>            return instance ?: synchronized(this) {<br>                instance ?: MediaControllerManager(context).also { instance = it }<br>            }<br>        }<br>    }<br>}</pre><p>Thus, the MediaController instance can be seamlessly utilized via the rememberManagedMediaController() function, eliminating the need to manually handle its lifecycle.</p><pre>// Get the managed MediaController<br>val mediaController by rememberManagedMediaController()</pre><p><strong>Use the MediaController in your UI</strong></p><p>Since MediaController implements the Player interface, it allows you to use the commands and methods defined in the interface to control playback of the connected MediaSession. Below is a simple use-case example:</p><pre>// Create a MediaItem<br>val mediaItem =<br>    MediaItem.Builder()<br>      // Set a unique media ID for the media item<br>      .setMediaId(&quot;media-1&quot;)<br>      // Set the URI (Uniform Resource Identifier) for the media content<br>      .setUri(mediaUri)<br>      // Set the media metadata, which includes details about the media content<br>      .setMediaMetadata(<br>        MediaMetadata.Builder()<br>          // Set the artist&#39;s name for the media content<br>          .setArtist(&quot;David Bowie&quot;)<br>          // Set the title of the media content<br>          .setTitle(&quot;Heroes&quot;)<br>          // Set the URI for the artwork or album cover associated with the media content<br>          .setArtworkUri(artworkUri)<br>          .build()<br>      )<br>      .build()<br><br>// Set the created MediaItem on a MediaController<br>mediaController.setMediaItem(mediaItem)<br><br>// Prepare the MediaController for playback (loading media resources, etc.)<br>mediaController.prepare()<br><br>// Start playback using the MediaController<br>mediaController.play()</pre><p>If your app contains single playable content, it’s so straightforward as above. But what if you have more than one playable contents? Actually, there’s not much difference. addMediaItems(mediaItems) method is used for this case instead of setMediaItem(mediaItem). <strong>It’s important to avoid duplicating </strong><strong>MediaItems unintentionally, as the MediaStyle notification generated by our </strong><strong>MediaSessionService remains synchronized with the provided content information. Duplicated contents in the notification could lead to a confusing user experience.</strong></p><p><strong>How to handle </strong><strong>MediaController in Compose?</strong></p><p>In our sample app, where contents are loaded in a paginated manner, as each new page is fetched, we can add the subsequent MediaItems to the existing MediaController.</p><p>The following extensions are useful for managing this situation:</p><pre>// Extension property for Player class to get the current media items.<br>// It returns a list of MediaItem objects.<br>internal val Player.currentMediaItems: List&lt;MediaItem&gt; get() {<br>    return List(mediaItemCount, ::getMediaItemAt)<br>}<br><br>// Extension function for Player class to update the playlist.<br>// It takes a list of incoming MediaItem objects, filters out the ones that are already in the playlist,<br>// and then adds them to the player.<br>fun Player.updatePlaylist(incoming: List&lt;MediaItem&gt;) {<br>    val oldMediaIds = currentMediaItems.map { it.mediaId }.toSet()<br>    val itemsToAdd = incoming.filterNot { item -&gt; item.mediaId in oldMediaIds }<br>    addMediaItems(itemsToAdd)<br>}</pre><p>When a user selects a playable content from the list, this function is triggered:</p><pre>// Extension function for Player class to play a media item at a specific index.<br>// If the current media item index is the same as the provided index, it does nothing.<br>// Otherwise, it seeks to the default position of the media item at the provided index,<br>// sets the player to play when ready, and prepares the player to recover from any errors<br>// that may have happened at previous media positions.<br>fun Player.playMediaAt(index: Int) {<br>    if (currentMediaItemIndex == index)<br>        return<br>    seekToDefaultPosition(index)<br>    playWhenReady = true<br>    // Recover from any errors that may have happened at previous media positions<br>    prepare()<br>}</pre><p><strong>If you don’t bind the </strong><strong>MediaController to any </strong><strong>PlayerView, you can use </strong><a href="https://github.com/oguzhaneksi/RadioRoam/blob/master/app/src/main/java/com/radioroam/android/ui/state/PlayerState.kt"><strong>PlayerState</strong></a><strong> to handle </strong><strong>MediaController state in your Composable UI in the declarative way.</strong></p><p>In conclusion, the implementation of MediaSessionService plays an important role for enhancing the user experience. Throughout this article, I tried to explain the structure of MediaSessionService, and the implementation of it in Jetpack Compose. In my humble opinion, the MediaSessionService not only simplifies the media control in background but also opens doors for more intuitive and interactive app designs.</p><p>Thank you for reading! Happy coding :)</p><p><strong>Source code on GitHub:</strong></p><p><a href="https://github.com/oguzhaneksi/RadioRoam">GitHub - oguzhaneksi/RadioRoam: This app demonstrates use of media sessions with Jetpack Compose.</a></p><p><strong>Further reading:</strong></p><ul><li><a href="https://developer.android.com/guide/topics/media/session/mediasessionservice">Background playback with a MediaSessionService | Android Developers</a></li><li><a href="https://developer.android.com/guide/topics/media/session/mediacontroller">Connect to a media app | Android Developers</a></li><li><a href="https://developer.android.com/reference/androidx/media3/session/MediaSessionService">MediaSessionService | Android Developers</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d571f15bdc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android MediaSession nedir? Nasıl kullanılır?]]></title>
            <link>https://medium.com/@ouzhaneki/android-mediasession-nedir-nas%C4%B1l-kullan%C4%B1l%C4%B1r-704e3878f56a?source=rss-aedc8b3df276------2</link>
            <guid isPermaLink="false">https://medium.com/p/704e3878f56a</guid>
            <category><![CDATA[media3]]></category>
            <category><![CDATA[android-mediasession]]></category>
            <category><![CDATA[mediasession]]></category>
            <category><![CDATA[exoplayer]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Oğuzhan Ekşi]]></dc:creator>
            <pubDate>Thu, 26 Oct 2023 06:26:56 GMT</pubDate>
            <atom:updated>2023-10-26T06:26:56.944Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CVOl_c6CuQkeVSeo" /></figure><p>Selam arkadaşlar, önceki Jetpack Media3 ile ilgili yazımda MediaSession’a kısaca değinmiştik. Burada MediaSession’dan biraz daha detaylı bahsedip bunu bir de demo bir uygulama üzerinden nasıl kullanacağımızı anlatacağım.</p><p>Önceki yazım için:</p><p><a href="https://medium.com/@ouzhaneki/jetpack-media3-nedir-0c5dde3fb061">Jetpack Media3 Nedir?</a></p><h3>MediaSession’a gerçekten gerek var mı?</h3><p>MediaSession’dan detaylıca bahsetmeden önce aşağıdaki akış grafiğine bakarak uygulamanızda gerçekten MediaSession kullanmanıza gerek olup olmadığını anlayabilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PjFFgj7MDSoVLbRXEYPiUg.png" /><figcaption>MediaSession gereklilik akış grafiği</figcaption></figure><h3>Gerçek hayatta MediaSession nasıl kullanılıyor?</h3><h4>Müzik uygulamaları (örn. YouTube Music, Spotify)</h4><ul><li>Kullanıcılar oynatıcıyı dışarıdan kulaklıkla veya bağlı olduğu akıllı saati ile kontrol edebilir.</li><li>Anlık oynatılan parçanın bilgileri kilit veya bildirim ekranında görünür.</li><li>Android Auto ile entegrasyon sayesinde kullanıcılar oynatıcıyı telefona dokunmadan arabadaki tuşlarla (direksiyon tuşları gibi) kontrol edebilir. Bu da güvenli bir sürüş deneyimini sağlar.</li></ul><h4>Podcast uygulamaları (örn. Overcast, Spotify)</h4><ul><li>Kullanıcılar uzaktan içerikler arasında geçiş yapabilir veya aynı içerik içerisinde ileri veya geriye doğru gidebilir.</li><li>Bunun dışında müzik uygulamalarındaki özellikler de kullanılabilir.</li></ul><h4>Sesli kitap uygulamaları (örn. Audible)</h4><ul><li>MediaSession sayesinde kullanıcılar sesli kitabı uzaktan durdurup devam ettirebilirler, veya bölümler arası geçiş yapabilirler.</li><li>Aynı şekilde sesli kitabın bilgileri de telefonun bildirim veya kilit ekranında görünür.</li></ul><h4>Video izleme uygulamaları (örn. Netflix, YouTube)</h4><ul><li>Her ne kadar bu uygulamalar video izlemeyi sağlasa da, yine de bu uygulamalar sıklıkla arkaplanda veya picture-in-picture modunda oynatmak için MediaSession kullanırlar.</li><li>MediaSession sayesinde aynı şekilde video içeriğin bilgileri telefonun bildirim veya kilit ekranında görünür.</li></ul><h3>MediaSession Nedir?</h3><p>MediaSession’ı, kısaca Android’de ExoPlayer’ın dışarıdan kontrol edilebilmesine olanak sağlayan bir Jetpack Media3 bileşeni olarak tanımlayabiliriz. Peki hangi yollarla Player’ı dışarıdan kontrol edebiliriz? Mesela kulaklık tuşlarıyla veya Google Assistant komutlarıyla (örn. “videoyu durdur” diyerek) oynatıcıyı durdurup devam ettirebiliriz, ileri/geri sarabiliriz ve önceki/sonraki içeriği oynatmasını sağlayabiliriz. Aynı zamanda player’daki değişiklikleri (örn. bir oynatma listesinde sonraki parçayı oynatmaya başladığı an, içeriğin anlık pozisyon bilgisi) dışarıya bildirir. Böylece cihaz ile direkt etkileşime geçmeden player’ı uzaktan kontrol edebilmemizi sağlıyor.</p><p>Bu bahsettiğimiz dış kaynaklar, bir de MediaSession’a bağlanmayı ve oynatıcı komut isteklerini bildirmeyi kolaylaştıran <a href="https://developer.android.com/reference/androidx/media3/session/MediaController">MediaController</a> implement eder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6dsA--b09hbQ1Q1z.png" /><figcaption>MediaController, dış kaynaklardan gelen komut isteklerini MediaSession’a bildirir</figcaption></figure><h4>Media3 ile gelen yenilikler</h4><p>Eski kütüphanelerden farklı olarak Jetpack Media3, MediaSession’ı Player’daki değişikliklere göre otomatik olarak günceller. Böylece eski yaklaşımlardaki gibi Player’dan session’a elle haritalama yapmaya, daha doğrusu her bir durum için <a href="https://developer.android.com/reference/android/support/v4/media/session/PlaybackStateCompat">PlaybackStateCompat</a> oluşturup onları yönetmeye (örn. player hatası bildirmek) gerek kalmadı.</p><p>İkinci olarak Media3 ile birlikte MediaSession ve MediaController gibi bileşenler ortak Player interface’ini baz alır. Böylece eski kütüphanelerdeki gibi uyum problemlerine neden olabilen Player ve MediaSession arasındaki komutları ve bildirimleri birbirine uyumlu olarak çevirmeye çalışan “connector” objelerine ihtiyaç kalmadı.</p><h3>Nasıl Kullanılır?</h3><p>MediaSession’ın ne olduğundan ve hangi amaçlarla kullanıldığından bahsettikten sonra artık işin pratik tarafına geçmenin vakti geldi. Bu makalede basit bir şekilde MediaSession nasıl kullanılır, adım adım bundan bahsedeceğim. Daha gelişmiş senaryo da başka bir makalenin konusu olsun.</p><p>Burada daha önceki makalede oluşturduğumuz demo uygulamasından ilerleyelim. <a href="https://github.com/oguzhaneksi/Media3Demo">Buradan</a> MediaSession eklenmemiş haline erişebilirsiniz. MediaSession için sadece ufak birkaç ekleme yapacağız hepsi bu aslında.</p><pre>var mediaSession: MediaSession? by remember {<br>  mutableStateOf(null)<br>}</pre><p>İlk olarak bu şekilde MediaSession değişkenini deklare ediyoruz.</p><pre>fun initMediaSession(context: Context, player: Player): MediaSession {<br>    return MediaSession.Builder(context, player)<br>        .build()<br>}</pre><p>Ve MediaSession build eden fonksiyonunu da MainActivity içerisinde bu şekilde tanımlıyoruz.</p><p><strong>Not:</strong> MediaSession’ı bu şekilde oluşturarak standart olarak tüm komutları (örn. oynatma/durdurma, ileri/geri sarma, ya da daha gelişmiş halinde içerikler arasında arama yapma vs.) desteklemesine ve tüm <a href="https://developer.android.com/reference/androidx/media3/session/MediaController">MediaController</a>’ların erişimine izin veriyoruz. Bunları özelleştirmek için aşağıdaki “Oynatıcı komutlarını yönetmek” kısmını inceleyebilirsiniz.</p><pre>mediaSession = initMediaSession(context, player!!)</pre><p>Aynı Player gibi MediaSession’ı da lifecycle’a göre oluşturup bırakıyoruz. onStart() veya onResume() methodlarında oluşturabiliriz.</p><pre>mediaSession?.release()<br>mediaSession = null</pre><p>Aynı şekilde onPause() veya onStop() methodlarında mediaSession’ı bu şekilde bırakıyoruz.</p><p>Kodun tam hali:</p><pre>@Composable<br>fun Player() {<br>    val context = LocalContext.current<br><br>    var player: Player? by remember {<br>        mutableStateOf(null)<br>    }<br>    var mediaSession: MediaSession? by remember {<br>        mutableStateOf(null)<br>    }<br>    val playerView = createPlayerView(player)<br><br>    ComposableLifecycle { _, event -&gt;<br>        when (event) {<br>            Lifecycle.Event.ON_START -&gt; {<br>                if (Build.VERSION.SDK_INT &gt; 23) {<br>                    player = initPlayer(context)<br>                    mediaSession = initMediaSession(context, player!!)<br>                    playerView.onResume()<br>                }<br>            }<br>            Lifecycle.Event.ON_RESUME -&gt; {<br>                if (Build.VERSION.SDK_INT &lt;= 23) {<br>                    player = initPlayer(context)<br>                    mediaSession = initMediaSession(context, player!!)<br>                    playerView.onResume()<br>                }<br>            }<br>            Lifecycle.Event.ON_PAUSE -&gt; {<br>                if (Build.VERSION.SDK_INT &lt;= 23) {<br>                    playerView.apply {<br>                        player?.release()<br>                        onPause()<br>                        player = null<br>                    }<br>                    mediaSession?.release()<br>                    mediaSession = null<br>                }<br>            }<br>            Lifecycle.Event.ON_STOP -&gt; {<br>                if (Build.VERSION.SDK_INT &gt; 23) {<br>                    playerView.apply {<br>                        player?.release()<br>                        onPause()<br>                        player = null<br>                    }<br>                    mediaSession?.release()<br>                    mediaSession = null<br>                }<br>            }<br>            else -&gt; {}<br>        }<br>    }<br><br>    AndroidView(<br>        factory = { playerView }<br>    )<br>}</pre><h3>Oynatıcı komutlarını yönetmek</h3><p>Bu kısımda hangi komutların destekleneceğini belirlemekten ve komutlar karşısında oynatıcının nasıl davranacağını özelleştirmekten bahsedeceğim. İlk olarak desteklenecek komutları belirlemekle başlayalım</p><h4>Desteklenecek komutları belirlemek</h4><p>Media3 ile birlikte dışarıdan kontrol eden bileşenlerin hangi komutları kullanabileceğini ya da hangi MediaController’ların erişebileceğini de belirleyebiliyoruz.</p><pre>class MediaSessionCallback: MediaSession.Callback {<br>    override fun  onConnect(<br>        session: MediaSession,<br>        controller: MediaSession.ControllerInfo<br>    ): MediaSession.ConnectionResult {<br>        val connectionResult = super.onConnect(session, controller)<br>        val sessionCommands = connectionResult.availableSessionCommands<br>        val playerCommands = Player.Commands.Builder()<br>            .add(Player.COMMAND_PLAY_PAUSE)<br>            .add(Player.COMMAND_SEEK_BACK)<br>            .add(Player.COMMAND_SEEK_FORWARD)<br>            .build()<br>        return MediaSession.ConnectionResult.accept(<br>            sessionCommands, playerCommands<br>        )<br>    }<br>}</pre><p>Burada ayrı bir MediaSession.Callback’i implement eden bir class oluşturduk ve <a href="https://developer.android.com/reference/androidx/media3/session/MediaSession.Callback#onConnect(androidx.media3.session.MediaSession,androidx.media3.session.MediaSession.ControllerInfo)">onConnect()</a> methodunu override ettik. <strong>Eğer override etmeseydik tüm MediaController’ların MediaSession’a bağlanmasına ve tüm session ve player komutlarının kullanılabilmesine izin vermiş olurduk.</strong></p><p>onConnect() methodu; herhangi bir controller, session’a bağlanmak üzere olduğu zaman çağrılır. Ne demek istiyorum? Dış kaynaktan herhangi bir komut geldiğinde o dış kaynak tarafından implement edilen MediaController, o komutu MediaSession’a iletirken öncesinde bir bağlantı isteği gönderiyor ve biz de bu onConnect() methodu içinde gelen isteği kabul etmesini veya etmemesini sağlayabiliyoruz.</p><p>Burada farkettiyseniz iki tip komut tipi var: player komutları ve session komutları. Yani <a href="https://developer.android.com/reference/androidx/media3/common/Player.Command">Player.Command</a> ve <a href="https://developer.android.com/reference/androidx/media3/session/SessionCommand">SessionCommand</a>. İlki adı üstünde Player ile ilgili komut türüyken diğeri de genelde medya kütüphanelerinin yönetimi (örn. içerikler arası arama yapma) ile ilgili komut türüdür.</p><p>Bu yukarıdaki kod bloğunda, player için yalnızca durdurup devam ettirme, ileri/geri sarma komutlarını kabul ediyoruz. Diğer yandan tüm session komutlarını kabul edebiliyoruz. Bunun dışında örn. Assistant ile “videonun hızını 1.25x yap” dediğimiz zaman MediaSession bu komutu yerine getirmeyecektir.</p><p>Bu oluşturduğumuz callback’i kullanabilmek için de aşağıdaki gibi MediaSession oluştururken set ediyoruz.</p><pre>MediaSession.Builder(context, player)<br>    .setCallback(MediaSessionCallback())<br>    .build()</pre><h4>Oynatıcı komut davranışlarını özelleştirmek</h4><p>Player interface’inde tanımlanan komut davranışlarını (örn. play(), pause(), seekBack()) özelleştirmek için, daha önce oluşturduğumuz <em>player</em> instance’ını kullanarak aşağıdaki gibi ForwardingPlayer oluşturuyoruz.</p><pre>val forwardingPlayer = object : ForwardingPlayer(player) {<br>        override fun play() {<br>            // Buraya kendi kodumuzu ekleyebiliriz<br>            super.play()<br>        }<br><br>        override fun pause() {<br>            // Buraya kendi kodumuzu ekleyebiliriz<br>            super.pause()<br>        }<br><br>        override fun seekBack() {<br>            // Buraya kendi kodumuzu ekleyebiliriz<br>            super.seekBack()<br>        }<br><br>        override fun seekForward() {<br>            // Buraya kendi kodumuzu ekleyebiliriz<br>            super.seekForward()<br>        }<br>    }</pre><p>Biz de burada önceden sadece play, pause, seekBack ve seekForward komutlarına izin verdiğimiz için bu dört komut davranışını override etmemiz daha uygun olur.</p><p>Gerçek yaşam senaryosu için burada ne yapılabilir? Örneğin, dışarıdan play() komutu aldığı zaman 3. parti analytics sdk aracılığıyla bunu raporlayabiliriz.</p><p>Biz demo uygulamamızda bunun nasıl çalıştığını görebilmek adına sadece bir toast gösterilmesini sağlayacağız.</p><pre>@androidx.annotation.OptIn(UnstableApi::class)<br>fun initForwardingPlayer(context: Context, player: Player): ForwardingPlayer {<br>    return object : ForwardingPlayer(player) {<br>        override fun play() {<br>            Toast.makeText(context, &quot;Video oynatıldı&quot;, Toast.LENGTH_LONG).show()<br>            super.play()<br>        }<br><br>        override fun pause() {<br>            Toast.makeText(context, &quot;Video durduruldu&quot;, Toast.LENGTH_LONG).show()<br>            super.pause()<br>        }<br><br>        override fun seekBack() {<br>            Toast.makeText(context, &quot;Video geri sarıldı&quot;, Toast.LENGTH_LONG).show()<br>            super.seekBack()<br>        }<br><br>        override fun seekForward() {<br>            Toast.makeText(context, &quot;Video ileri sarıldı&quot;, Toast.LENGTH_LONG).show()<br>            super.seekForward()<br>        }<br>    }<br>}</pre><p>Yukarıdaki gibi ForwardingPlayer oluşturan fonksiyonu yazdıktan sonra yine aynı şekilde player başlatıldıktan sonra aşağıdaki gibi değişken oluşturup MediaSession oluştururken o değişkeni kullanmasını sağlıyoruz:</p><pre>player = initPlayer(context)<br>val forwardingPlayer = initForwardingPlayer(context, player!!)<br>mediaSession = initMediaSession(context, forwardingPlayer)</pre><p>Ve sonuç bu şekilde:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*nZRAM5AU810dH4udmwmEZQ.gif" /><figcaption>MediaSession ile videoyu durdurunca beklediğimiz oluyor :)</figcaption></figure><p>Projenin tam haline buradan ulaşabilirsiniz:</p><p><a href="https://github.com/oguzhaneksi/Media3Demo/tree/mediasession-basic">GitHub - oguzhaneksi/Media3Demo at mediasession-basic</a></p><p>Özetlemek gerekirse MediaSession, uygulamada oynatıcının dış kaynaklardan kontrol edilebilmesini sağlayan harika bir bileşendir diyebiliriz.</p><p>Bu yazımda daha çok temel düzeyde kapsamlı bir şekilde MediaSession’dan bahsettim ve arkaplan’da içerik oynatmadan basit bir demo uygulaması oluşturduk. Umarım faydalı olmuştur :)</p><p>Herkese iyi kodlamalar :)</p><p>Kaynaklar:</p><ul><li><a href="https://developer.android.com/guide/topics/media/session/mediasession">Control and advertise playback using a MediaSession | Android Developers</a></li><li><a href="https://medium.com/androiddevelopers/understanding-mediasession-part-1-3-e4d2725f18e4">Understanding MediaSession (Part 1/4)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=704e3878f56a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Media3 Nedir?]]></title>
            <link>https://medium.com/@ouzhaneki/jetpack-media3-nedir-0c5dde3fb061?source=rss-aedc8b3df276------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c5dde3fb061</guid>
            <category><![CDATA[android-media]]></category>
            <category><![CDATA[media3]]></category>
            <category><![CDATA[exoplayer2]]></category>
            <category><![CDATA[exoplayer]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Oğuzhan Ekşi]]></dc:creator>
            <pubDate>Thu, 12 Oct 2023 08:02:15 GMT</pubDate>
            <atom:updated>2023-10-13T10:07:06.614Z</atom:updated>
            <content:encoded><![CDATA[<p>Herkese selamlar, bu yazımda Android’in bize sunduğu Media3 kütüphanesi, entegrasyonu ve ExoPlayer’dan Media3&#39;e geçişten kısaca bahsedeceğim.</p><h3><strong>Media3 Nedir?</strong></h3><p>Jetpack Media3, Google tarafından ilk olarak Ekim 2021&#39;de alpha sürümüyle tanıtılmış olup, Mart 2023&#39;te ilk kararlı hali release edilmiş kolaylıkla kullanılabilir, karmaşıklıktan uzak ve güvenilir bir AndroidX medya oynatma kütüphanesidir. Bu kütüphane aynı zamanda <a href="https://exoplayer.dev/">ExoPlayer</a>, <a href="https://developer.android.com/jetpack/androidx/releases/media2">Media2</a> ve <a href="https://developer.android.com/reference/kotlin/android/support/v4/media/package-summary">MediaCompat</a> kütüphanelerinin halefi olarak görülür ve eğer bunlardan en az biri hakkında bilgi sahibiyseniz Media3&#39;ü öğrenmeniz oldukça kolay olacaktır :) Ve Media3&#39;ün en güzel yanı ise kullanım amacına göre farklı farklı kütüphaneleri kullanıp aralarındaki uyumsuzluklarla uğraşmaktan kurtarıp medya ile ilgili birçok özelliği (farklı video formatları, DRM, MediaSession vs.) birbirleriyle uyumlu çalışacak şekilde bünyesinde toplamasıdır.</p><h3>Temel Bileşenler</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1iOzlevyYFTH5EoR.png" /><figcaption>Medya uygulama bileşenleri</figcaption></figure><p><strong>Player:</strong> Media player için play, pause, ileri/geri sarma gibi geleneksel fonksiyonları barındıran bir interface.</p><p><strong>ExoPlayer:</strong> Media3&#39;te içeriklerin oynatılmasını sağlayan Player’ın default implementasyonu.</p><p><strong>MediaSession:</strong> Medya oynatıcının dışarıdan kontrol edilebilmesini sağlayan bir bileşen. Player ile farklı arayüzlerin (bildirim paneli, kilit ekranı hatta kulaklık ve araba teybi) arasında bir köprü olarak görev alır. Player’ı MediaSession ile bağladığınızda oynatıcının dışarıdan (örn. kulaklığın ses tuşları) yönetilmesine olanak tanır.</p><p><strong>MediaSessionService:</strong> İçeriği arkaplanda oynatmayı aktifleştiren ve içerisinde MediaSession barındıran bir Android servisidir. Favori müzik uygulamanızda arkaplanda ve hatta kilit ekranında bile şarkının oynatmaya devam etmesini sağlayan bu bileşendir diyebiliriz.</p><p><strong>MediaController:</strong> Medyanın uzaktan (bildirim paneli, kilit ekranı gibi) kontrol edilebilmesine olanak sağlayan bir arayüz. Player’ın durdurulup oynatılmasına veya ileri/geri sarılmasına imkan sağlar. Aynı zamanda Player’ın şu anki pozisyonu ve durumu gibi bilgileri de anlık olarak gösterir.</p><p><strong>MediaLibraryService:</strong> MediaSessionService’e benzer, ancak ekstra olarak dış istemcilerin oynatılabilir içeriklere erişimini sağlar. Dış istemcilere mobil ve tabletlerde bildirim paneli veya kilit ekranındaki kontroller, Android Auto, WearOS ve Google Assistant örnek olarak verilebilir.</p><p><strong>MediaBrowser:</strong> Dış istemciler için içerik aramaya veya seçmeye yardımcı olan bir katalog gibidir. Medya kütüphanesini araştırmak için MediaLibraryService ile etkileşime geçer ve oynatıcıyı kontrol etmek için MediaSession’a bağlanır.</p><h3>Peki Media3&#39;te neler yeni?</h3><p>Birkaç yenilik sayabilirim bununla ilgili. İlk olarak tüm medya kütüphanelerini tek bir çatı altında toplaması, MediaSession yönetimi ve MediaLibraryService. Biraz daha detaylı bahsedeceksek;</p><p><strong>Birleşik Media API:</strong> AndroidX Media, geliştiricilerin medya uygulamaları ile çalışmalarını kolaylaştırması için kullanım amaçlarına göre farklı medya kütüphaneleri birbirleriyle uyumlu hale getirip tek bir çatı altında topladı.</p><p><strong>Media session yönetimi: </strong>AndroidX Media, media session yönetimini otomatikleştirip oynatıcının dışarıdan kolaylıkla kontrol edilebilmesini sağlar.</p><ul><li><strong>Problem:</strong> Media3&#39;ü diğer kütüphanelerden ayıran bir özellik ise bileşenler arası herhangi bir bağlayıcıya ihtiyaç duyulmamasıdır. Örneğin, ExoPlayer veya Media2 kütüphanelerini kullanarak MediaSession veya MediaController kullanmak gerektiğinde ayrı bir bağlayıcı (örn. MediaSessionConnector) gerekiyordu. Çünkü MediaSession/Controller, o kütüphanelerle uyumlu değildi.</li><li><strong>Çözüm: </strong>Media3 ile MediaSession/Controller gibi tüm bileşenler, player baz alınarak yeniden düzenlendi ve eskiden olduğu gibi ayrı bir bağlayıcıya bir ihtiyaç kalmadı. Artık MediaSession veya MediaController, Player ile direkt etkileşime girebiliyor ve dolayısıyla uygulamanız daha modern ve stabil hale geliyor.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wHjkQmqqMLpmTXsW.png" /><figcaption>#AndroidDevSummit</figcaption></figure><p><strong>MediaLibraryService:</strong> Medya uygulamaları genelde hiyerarşik bir yapıda medya içerikleri içerir. Örneğin; albüm içerisinde şarkılar ya da bir oynatma listesinde herhangi bir dizinin bölümleri olabilir. Bu medya içeriklerinin olduğu hiyerarşiye de medya kütüphanesi diyebiliriz. MediaLibraryService de bu medya kütüphanesine diğer uygulamalardan veya dış istemcilerden ulaşılmasını oldukça kolaylaştırır. Örneğin, medya uygulamanıza Android Auto desteği eklediğinizde medya kütüphaneniz için sürücü dostu bir kullanıcı arayüzü sağlar.</p><h3>ExoPlayer’dan Media3&#39;e geçiş</h3><p>ExoPlayer2 kütüphanesi bugün itibariyle deprecate oldu ve artık desteklenmeyecek. Bu nedenden dolayı ExoPlayer2 kütüphanesi kullanan uygulamaların artık Media3&#39;e migrate edilmesi gerekiyor.</p><p>Media3&#39;e geçişin 2 yolu var:</p><ol><li><a href="https://developer.android.com/guide/topics/media/media3/getting-started/migration-guide">Resmi dökümandaki</a> talimatları adım adım takip ederek.</li><li>Veya bu <a href="https://developer.android.com/guide/topics/media/media3/getting-started/migration-guide#usingscript">migration script</a>’i kullanarak direkt ExoPlayer2&#39;dan Media3&#39;e çevirerek.</li></ol><p>İşin en güzel yanı eğer uygulamanızda zaten ExoPlayer kullanıyorsanız ekstra kod değişikliğine ve yeniden entegrasyona gerek olmaması :)</p><h3>Media3 nasıl kullanılır?</h3><p>Aslında Media3&#39;ün kullanımı şu an itibariyle deprecate olmuş ExoPlayer2 kullanımına oldukça benziyor. Adım adım beraber basit bir Jetpack Compose uygulaması oluşturup Media3 ile içerikleri nasıl oynatabileceğimizi öğreneceğiz.</p><p>İlk olarak yeni bir tane uygulama oluşturup uygulama seviyesindeki build.gradle dosyasına aşağıdaki kütüphaneleri eklememiz gerekiyor (Ekim 2023 itibariyle Media3&#39;ün güncel versiyonu 1.1.1&#39;dir. İleride bu sürüm kesinlikle güncellenecektir):</p><pre>val media3Version = &quot;1.1.1&quot;<br>implementation(&quot;androidx.media3:media3-exoplayer:$media3Version&quot;)<br>implementation(&quot;androidx.media3:media3-ui:$media3Version&quot;)</pre><p>Daha sonra internetten içerik oynatacağımız için AndroidManifest.xml dosyasına şu izni ekliyoruz:</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;</pre><p>Composable fonksiyonlarına geçtiğimizde ilk olarak Player() adında bir composable fonksiyon oluşturuyoruz. Bu fonksiyonun içerisinde ExoPlayer ve PlayerView instance’ı oluşturuyoruz.</p><pre>@Composable<br>fun Player() {<br>    val context = LocalContext.current<br>    val exoPlayer = remember {<br>        ExoPlayer.Builder(context).build().apply {<br>            setMediaItem(MediaItem.fromUri(&quot;https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4&quot;))<br>            playWhenReady = true<br>            prepare()<br>        }<br>    }<br><br>    AndroidView(<br>        factory = { ctx -&gt;<br>            PlayerView(ctx).also {<br>                it.player = exoPlayer<br>            }<br>        }<br>    )<br>}</pre><p>Daha sonra bunu MainActivity.kt’de bu şekilde çağırıyoruz:</p><pre>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            Media3DemoTheme {<br>                Surface(<br>                    modifier = Modifier.fillMaxSize(),<br>                    color = MaterialTheme.colorScheme.background<br>                ) {<br>                    <br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Şimdiye kadar ne yaptık? İlk olarak Media3&#39;ün default player implementasyonu olan ExoPlayer instance’ı oluşturduk.</p><ul><li><strong>setMediaItem() </strong>metoduyla örnek bir video url ile oluşturduğumuz MediaItem’ı set ettik.</li><li><strong>playWhenReady = true</strong> ile player’ın hazır olduğu anda oynatmaya başlatmasını sağladık.</li><li><strong>prepare() </strong>ile player’ı hazır ettik.</li></ul><p>Sonra da AndroidView() ile Jetpack Compose içinde PlayerView’ı kullanarak bu oluşturduğumuz player’ı ona set ettik. Artık uygulamamız video oynatmaya hazır diyebiliriz.</p><p>Ancak ufak bir problem var. <strong>Uygulamanın şu anki halinde kullanıcı uygulamayı arkaplana alsa dahi video oynatmaya devam edecektir ve bu da kesinlikle iyi bir kullanıcı deneyimi olmayacaktır ve performans sorunlarına neden olacaktır. </strong>Bunu nasıl çözebiliriz:</p><p>ExoPlayer’ı, activity’nin onStart() veya onResume() metodlarında başlatıp onPause() veya onStop() metodlarında durdurarak bunu çözebiliriz. Böylece uygulamayı arkaplana alınca veya kapatınca arkada player’ın aktif olmasını önleyip performans sorununu çözmüş oluruz. Jetpack Compose ile bunu nasıl yapabileceğimizi aşağıda görebilirsiniz:</p><pre>@Composable<br>fun ComposableLifecycle(<br>    lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,<br>    onEvent: (LifecycleOwner, Lifecycle.Event) -&gt; Unit<br>) {<br><br>    DisposableEffect(lifecycleOwner) {<br>        val observer = LifecycleEventObserver { source, event -&gt;<br>            onEvent(source, event)<br>        }<br>        lifecycleOwner.lifecycle.addObserver(observer)<br><br>        onDispose {<br>            lifecycleOwner.lifecycle.removeObserver(observer)<br>        }<br>    }<br>}</pre><p>Öncelikle bu fonksiyonu composable içinde lifecycle eventlerini algılayabilmemiz için oluşturuyoruz.</p><pre>@Composable<br>fun createPlayerView(player: Player?): PlayerView {<br>    val context = LocalContext.current<br>    val playerView = remember {<br>        PlayerView(context).apply {<br>            this.player = player<br>        }<br>    }<br>    DisposableEffect(key1 = player) {<br>        playerView.player = player<br>        onDispose {<br>            playerView.player = null<br>        }<br>    }<br>    return playerView<br>}</pre><p>Daha sonra yukarıdaki gibi PlayerView oluşturan bir fonksiyon yazıyoruz.</p><p>Bu oluşturduğumuz iki composable fonksiyonu aşağıdaki gibi kullanabiliriz:</p><pre>@Composable<br>fun Player() {<br>    val context = LocalContext.current<br><br>    var player: Player? by remember {<br>        mutableStateOf(null)<br>    }<br>    val playerView = createPlayerView(player)<br><br>    ComposableLifecycle { _, event -&gt;<br>        when (event) {<br>            Lifecycle.Event.ON_START -&gt; {<br>                if (Build.VERSION.SDK_INT &gt; 23) {<br>                    player = initPlayer(context)<br>                    playerView.onResume()<br>                }<br>            }<br>            Lifecycle.Event.ON_RESUME -&gt; {<br>                if (Build.VERSION.SDK_INT &lt;= 23) {<br>                    player = initPlayer(context)<br>                    playerView.onResume()<br>                }<br>            }<br>            Lifecycle.Event.ON_PAUSE -&gt; {<br>                if (Build.VERSION.SDK_INT &lt;= 23) {<br>                    playerView.apply {<br>                        player?.release()<br>                        onPause()<br>                        player = null<br>                    }<br>                }<br>            }<br>            Lifecycle.Event.ON_STOP -&gt; {<br>                if (Build.VERSION.SDK_INT &gt; 23) {<br>                    playerView.apply {<br>                        player?.release()<br>                        onPause()<br>                        player = null<br>                    }<br>                }<br>            }<br>            else -&gt; {}<br>        }<br>    }<br><br>    AndroidView(<br>        factory = { playerView }<br>    )<br>}</pre><p>Yukarıda da gördüğümüz gibi artık en temel biçimde activity lifecycle’larına göre player başlatıp bırakabiliyoruz.</p><p>Kodun tamamı için:</p><p><a href="https://github.com/oguzhaneksi/Media3Demo">GitHub - oguzhaneksi/Media3Demo: A basic Media3 ExoPlayer demo application in Jetpack Compose</a></p><p>Toparlamak gerekirse Media3, Android medya uygulamalarının gelişimi için oldukça büyük bir adım ve geliştiriciler için birçok özellik ve kolaylık sağlıyor.</p><p>Bu yazımda Media3 nedir, ExoPlayer’dan Media3&#39;e geçiş ve en basit haliyle Media3 ExoPlayer’ı bir uygulamada nasıl kullanabiliriz bundan bahsettim. Umarım bir faydam dokunmuştur :)</p><p>Sonraki yazımda Media3 kütüphanesi içerisinde MediaSession’dan daha detaylı bahsedip onunla neler yapabiliriz onu anlatacağım.</p><p>Herkese iyi kodlamalar :)</p><p>Kaynaklar:</p><ul><li><a href="https://developer.android.com/guide/topics/media/media3">Introduction to Jetpack Media3 | Android media | Android Developers</a></li><li><a href="https://developer.android.com/guide/topics/media/media3/getting-started/migration-guide">AndroidX Media3 migration guide | Android Developers</a></li><li><a href="https://github.com/androidx/media">GitHub - androidx/media: Jetpack Media3 support libraries for media use cases, including ExoPlayer, an extensible media player for Android</a></li><li><a href="https://medium.com/@mahdizareeii/handling-app-lifecycle-events-in-jetpack-compose-d3b7f526514b">Handling app lifecycle events in Jetpack Compose</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FsTIBDcyCmCg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DsTIBDcyCmCg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FsTIBDcyCmCg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b23c7a692ef1e0f8c52c5c260c03919d/href">https://medium.com/media/b23c7a692ef1e0f8c52c5c260c03919d/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c5dde3fb061" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>