<?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 Burak Oguz on Medium]]></title>
        <description><![CDATA[Stories by Burak Oguz on Medium]]></description>
        <link>https://medium.com/@burak.oguz?source=rss-aa627913228d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*nyTaQyF-4JpM9txe.</url>
            <title>Stories by Burak Oguz on Medium</title>
            <link>https://medium.com/@burak.oguz?source=rss-aa627913228d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:23:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@burak.oguz/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[Playing Widevine (DRM) enabled DASH Streams with Exoplayer on Android]]></title>
            <link>https://medium.com/@burak.oguz/playing-widevine-drm-enabled-dash-streams-with-exoplayer-on-android-5541d7199ef0?source=rss-aa627913228d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5541d7199ef0</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[widevine]]></category>
            <category><![CDATA[dash]]></category>
            <category><![CDATA[exoplayer]]></category>
            <dc:creator><![CDATA[Burak Oguz]]></dc:creator>
            <pubDate>Fri, 12 Mar 2021 18:06:21 GMT</pubDate>
            <atom:updated>2021-03-16T22:30:01.152Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://en.wikipedia.org/wiki/Digital_rights_management">Digital rights management</a> (DRM) is a set of tools and techniques to create access control generally around proprietary hardware or copyright materials online. <a href="https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP">Dynamic Adaptive Streaming over HTTP</a> is an adaptive bitrate streaming technique similar to Apple’s <a href="https://en.wikipedia.org/wiki/HTTP_Live_Streaming">HTTP Live Streaming (HLS)</a> solution that serves high quality streaming over HTTP by dividing the content into a sequence of smaller segments and making this content available at different bit rates. <a href="https://exoplayer.dev/">Exoplayer</a> is a popular application level video player alternative to Android’s MediaPlayer framework, and <a href="https://en.wikipedia.org/wiki/Widevine">Widevine</a> is the most popular digital rights management technology from Google. Widevine is currently being used by Google Chrome, Firefox, Android, and Android TV. In this article, we will focus on explaining how DRM works and how to integrate Exoplayer and Wideview content using <a href="https://developer.android.com/reference/android/media/MediaDrm">MediaDRM</a> with online and downloadable content use cases.</p><p>Please note that the code samples in this article rely on the knowledge of Exoplayer and dependency injection. They are not full examples, due to the complexities of setting up license and content servers.</p><h3>DRM Workflow and License Exchange</h3><p>There are four main components of Widevine streaming:</p><ol><li>The client attempting to play the content</li><li>The license server that generates the decryption keys based on the request parameters from the client</li><li>The provisioning server if it is required to distribute device unique credentials</li><li>The content server which serves the encrypted content</li></ol><p>When the client tries to play protected content from the content server via a <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/source/dash/DashMediaSource.html">DashMediaSource</a> with a provided <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/DrmSessionManager.html">DrmSessionManager</a>, the client will automatically initiate a DRM license request via <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/MediaDrmCallback.html">MediaDrmCallback</a>. In the meantime, if the device needs provisioning, a request to the provisioning server will be done via callback. After the MediaDRM client receives the license, it will pass it to Exoplayer via the media source and media playback will begin. For non-persistent licenses, this procedure will be repeated with any media playback request. For persistent license cases, applications may save the persistent license and can reuse the license until it expires. Also for persistent license requests, the license can be fetched before the video playback starts with <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/OfflineLicenseHelper.html">OfflineLicenseHelper</a> so that video initialization will not depend on callback’s successful license fetch operation. Now we will detail how these classes will be utilized.</p><h3>Playing DASH content in Exoplayer</h3><p>According to product and system requirements, it is possible to implement the business logic that manages the license exchange in very different ways. However, the most basic way of doing the license exchange is using <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/HttpMediaDrmCallback.html">HttpMediaDrmCallback</a>. This method can be utilized if your license servers don’t require any custom processing on the license exchange request. As you can see below, it is quite straightforward to build a <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/source/dash/DashMediaSource.html">DashMediaSource</a> with a <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/DefaultDrmSessionManager.html">DefaultDrmSessionManager</a> using a <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/HttpMediaDrmCallback.html">HttpMediaDrmCallback</a>. In the example, when the player loads the <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/source/dash/DashMediaSource.html">DashMediaSource</a>, if it encounters encrypted content that requires a license to play, it will ask <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/DefaultDrmSessionManager.html">DefaultDrmSessionManager</a> to provide a license and <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/DefaultDrmSessionManager.html">DefaultDrmSessionManager</a> will use <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/HttpMediaDrmCallback.html">HttpMediaDrmCallback</a> to fetch the license from the provided license URL. Calling <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/DefaultDrmSessionManager.html#setMode(int,byte%5B%5D)">setMode</a> with null license data will force <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/DefaultDrmSessionManager.html">DefaultDrmSessionManager</a> to utilize <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/HttpMediaDrmCallback.html">HttpMediaDrmCallback</a> when there is a license request. If a license is provided to <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/DefaultDrmSessionManager.html#setMode(int,byte%5B%5D)">setMode</a>, <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/DefaultDrmSessionManager.html">DefaultDrmSessionManager</a> will try to use it first, and if the license doesn’t successfully decrypt the content, it will again try to utilize the provided <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/MediaDrmCallback.html">MediaDrmCallback</a> to fetch a new license.</p><pre>@Singleton</pre><pre>internal class FooDownloader @Inject constructor(</pre><pre>private val customHttpDrmMediaCallback: CustomHttpDrmMediaCallback</pre><pre>) {</pre><pre>fun download(context: Context, downloadUrl: Uri) {</pre><pre>val sessionManager = DefaultDrmSessionManager.Builder().build(customHttpDrmMediaCallback)</pre><pre>sessionManager.setMode(DefaultDrmSessionManager.MODE_DOWNLOAD, null)</pre><pre>DownloadHelper.forMediaItem(</pre><pre>MediaItem.fromUri(downloadUrl),</pre><pre>DefaultTrackSelector.Parameters.getDefaults(context),</pre><pre>DefaultRenderersFactory(context),</pre><pre>DefaultHttpDataSourceFactory(&quot;userAgent&quot;),</pre><pre>sessionManager)</pre><pre>}</pre><pre>}</pre><h3>Custom MediaDrmCallback</h3><p>Of course, the example above is not functionally complete. In most cases, the license server will need an authentication token or other information based on the media subject to the license exchange request. In order to achieve this, it is possible to use built-in <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/HttpMediaDrmCallback.html">HttpMediaDrmCallback</a> or implement a custom <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/MediaDrmCallback.html">MediaDrmCallback</a>. It is also possible to build a custom <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/MediaDrmCallback.html">MediaDrmCallback</a> using <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/HttpMediaDrmCallback.html">HttpMediaDrmCallback</a>. In the callback below, <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/MediaDrmCallback.html#executeKeyRequest(java.util.UUID,com.google.android.exoplayer2.drm.ExoMediaDrm.KeyRequest)">executeKeyRequest</a> and <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/MediaDrmCallback.html#executeProvisionRequest(java.util.UUID,com.google.android.exoplayer2.drm.ExoMediaDrm.ProvisionRequest)">executeProvisioningRequest</a> methods will be executed in a background thread. This allows additional business logic around network calls or database/file IO access to be done without thread switching. As you can see below, when an <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/MediaDrmCallback.html#executeKeyRequest(java.util.UUID,com.google.android.exoplayer2.drm.ExoMediaDrm.KeyRequest)">executeKeyRequest</a> is done, the authentication token is fetched from a remote API and the key request is executed with an updated license URL. The same flow applies to <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/MediaDrmCallback.html#executeProvisionRequest(java.util.UUID,com.google.android.exoplayer2.drm.ExoMediaDrm.ProvisionRequest)">executeProvisioningRequest</a> as well.</p><pre>@Singleton</pre><pre>internal class CustomHttpDrmMediaCallback @Inject constructor(</pre><pre>@Named(“drm”) private val factory: OkHttpDataSourceFactory,</pre><pre>private val apiClient: VideoApiClient</pre><pre>) : MediaDrmCallback {</pre><pre>companion object {</pre><pre>private const val defaultLicenseUrl = “https://license.url/server/fetch-license&quot;</pre><pre>}</pre><pre>private val httpMediaDrmCallback = HttpMediaDrmCallback(defaultLicenseUrl, false, factory)</pre><pre>override fun executeKeyRequest(uuid: UUID, request: ExoMediaDrm.KeyRequest): ByteArray {</pre><pre>val authenticationToken = apiClient.getLicenseAuthenticationToken()</pre><pre>val licenseUrl = Uri.parse(defaultLicenseUrl)</pre><pre>.buildUpon()</pre><pre>.appendQueryParameter(“token”, authenticationToken)</pre><pre>.build()</pre><pre>.toString()</pre><pre>val updatedRequest = ExoMediaDrm.KeyRequest(request.data, licenseUrl)</pre><pre>return httpMediaDrmCallback.executeKeyRequest(uuid, updatedRequest)</pre><pre>}</pre><pre>override fun executeProvisionRequest(uuid: UUID, request: ExoMediaDrm.ProvisionRequest): ByteArray {</pre><pre>val authenticationToken = apiClient.getLicenseAuthenticationToken()</pre><pre>val licenseUrl = Uri.parse(defaultLicenseUrl)</pre><pre>.buildUpon()</pre><pre>.appendQueryParameter(“token”, authenticationToken)</pre><pre>.build()</pre><pre>.toString()</pre><pre>val updatedRequest = ExoMediaDrm.ProvisionRequest(request.data, drmLicenseUrl)</pre><pre>return httpMediaDrmCallback.executeProvisionRequest(uuid, updatedRequest)</pre><pre>}</pre><pre>}</pre><h3>Utilizing Offline Licenses</h3><p>In the cases covered so far, the application needed online access for license exchange operations at the time of playback. Depending on the product and system requirements, it is possible to fetch licenses prior to video playback and cache them for later use. This will also have a positive impact on video playback start-up times. In order to fetch licenses without <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/DrmSessionManager.html">DrmSessionManager</a> or <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/MediaDrmCallback.html">MediaDrmCallback</a>, it is possible to build a custom client to execute license exchange operations. However, there is already a class called <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/OfflineLicenseHelper.html">OfflineLicenseHelper</a> to expedite this process. As illustrated below, with a given DRM license fetch URL and URI to the video path, first it is needed to create a new instance that supports Wideview license download and then it is possible to download license with <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/OfflineLicenseHelper.html#downloadLicense(com.google.android.exoplayer2.Format)">downloadLicense</a> method and extract the expiration date with <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/OfflineLicenseHelper.html#getLicenseDurationRemainingSec(byte%5B%5D)">getLicenseDurationRemainingSec</a> method.</p><pre>@Singleton</pre><pre>internal class OfflineRemoteLicenseFetcher @Inject constructor(</pre><pre>@Named(“drm”) private val okHttpDataSourceFactory: OkHttpDataSourceFactory,</pre><pre>) {</pre><pre>fun downloadLicense(drmLicenseUrl: String, videoPath: Uri): Pair&lt;ByteArray?, Long&gt;? {</pre><pre>val offlineLicenseHelper = OfflineLicenseHelper.newWidevineInstance(drmLicenseUrl,</pre><pre>okHttpDataSourceFactory, DrmSessionEventListener.EventDispatcher())</pre><pre>val dataSource = okHttpDataSourceFactory.createDataSource()</pre><pre>val dashManifest = DashUtil.loadManifest(dataSource, videoPath)</pre><pre>val drmInitData = DashUtil.loadFormatWithDrmInitData(dataSource, dashManifest.getPeriod(0))</pre><pre>val licenseData = drmInitData?.let {</pre><pre><strong>offlineLicenseHelper.downloadLicense(it)</strong></pre><pre>}</pre><pre>val licenseExpiration = if (licenseData != null) {</pre><pre>System.currentTimeMillis() + (<strong>offlineLicenseHelper.getLicenseDurationRemainingSec(licenseData).first</strong> * 1000)</pre><pre>} else {</pre><pre>0</pre><pre>}</pre><pre>return Pair(licenseData, licenseExpiration)</pre><pre>}</pre><pre>}</pre><p>After fetching the license, it is possible to cache it.The next time applicable content is accessed, the cached license can be provided to the <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/DrmSessionManager.html">DrmSessionManager</a> via the <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/DefaultDrmSessionManager.html#setMode(int,byte%5B%5D)">setMode</a> method shown below. As mentioned above, if the cached license data becomes invalid, <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/DrmSessionManager.html">DrmSessionManager</a> will use <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/MediaDrmCallback.html">MediaDrmCallback</a> to fetch a new license.</p><pre>sessionManager.setMode(DefaultDrmSessionManager.MODE_PLAYBACK, licenseData)</pre><h3>Handling Errors</h3><p>It is important to keep in mind that the added layer of operations may cause an added number of error cases and these errors need to be handled properly. DRM license related playback errors will end up in Exoplayer’s <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/Player.EventListener.html">Player.EventListener</a>.<a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/Player.EventListener.html#onPlayerError(com.google.android.exoplayer2.ExoPlaybackException)">onPlayerError</a> method. <a href="https://developer.android.com/reference/android/media/MediaCodec.CryptoException">MediaCodec.CryptoException</a> and <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/DrmSession.DrmSessionException.html">DrmSession.DrmSessionException</a> are common exceptions that need to be handled in the player flow. Additionally, if it is preferred to implement a custom <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/DrmSessionManager.html">DrmSessionManager</a>, it will be necessary to register an event handler for <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/DrmSessionEventListener.html">DrmSessionEventListener</a> and handle errors in <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/DrmSessionEventListener.html#onDrmSessionManagerError(int,com.google.android.exoplayer2.source.MediaSource.MediaPeriodId,java.lang.Exception)">onDrmSessionManagerError</a>.</p><h3>Utilizing DrmSessionManager with Exoplayer DownloadHelper</h3><p>Another important feature that Exoplayer provides is being able to download adaptive streams to the client. Exoplayer supports downloading of both HLS and DASH streams. Even though <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/offline/DownloadHelper.html">DownloadHelper</a> has a basic interface, integrating it with product and system requirements can become complicated, especially while downloading DRM enabled DASH content. Keep in mind that a <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/drm/DrmSessionManager.html">DrmSessionManager</a> has to be provided to the <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/offline/DownloadHelper.html">DownloadHelper</a>.<a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/offline/DownloadHelper.html#forMediaItem(com.google.android.exoplayer2.MediaItem,com.google.android.exoplayer2.trackselection.DefaultTrackSelector.Parameters,com.google.android.exoplayer2.RenderersFactory,com.google.android.exoplayer2.upstream.DataSource.Factory,com.google.android.exoplayer2.drm.DrmSessionManager)">forMediaItem</a> method.</p><pre>@Singleton</pre><pre>internal class DashDownloader @Inject constructor(</pre><pre>private val customHttpDrmMediaCallback: CustomHttpDrmMediaCallback</pre><pre>) {</pre><pre>fun download(context: Context, downloadUrl: Uri) {</pre><pre>val sessionManager = DefaultDrmSessionManager.Builder().build(customHttpDrmMediaCallback)</pre><pre>sessionManager.setMode(DefaultDrmSessionManager.MODE_DOWNLOAD, null)</pre><pre>DownloadHelper.forMediaItem(</pre><pre>MediaItem.fromUri(downloadUrl),</pre><pre>DefaultTrackSelector.Parameters.getDefaults(context),</pre><pre>DefaultRenderersFactory(context),</pre><pre>DefaultHttpDataSourceFactory(“userAgent”),</pre><pre>sessionManager)</pre><pre>}</pre><pre>}</pre><p>Another important thing to remember related to downloaded DRM content, is to cache the license data to enable users to play the encrypted content when they don’t have a connection. Lastly, don’t forget to set up a periodic worker via <a href="https://developer.android.com/jetpack/androidx/releases/work">WorkManager</a> to refresh offline licenses whenever a user has a connection according to license expiration requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5541d7199ef0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Fairplay/DRM integration with different use cases]]></title>
            <link>https://medium.com/@burak.oguz/ios-fairplay-drm-integration-with-different-use-cases-8aff3d4248dd?source=rss-aa627913228d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8aff3d4248dd</guid>
            <category><![CDATA[avplayer]]></category>
            <category><![CDATA[apple-fairplay-drm]]></category>
            <category><![CDATA[avcontentkeysession]]></category>
            <category><![CDATA[udemy]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Burak Oguz]]></dc:creator>
            <pubDate>Thu, 18 Feb 2021 18:13:21 GMT</pubDate>
            <atom:updated>2021-02-18T18:26:49.807Z</atom:updated>
            <content:encoded><![CDATA[<h3>DRM and Fairplay</h3><p><a href="https://en.wikipedia.org/wiki/Digital_rights_management">Digital rights management</a> (DRM) is a set of tools and techniques to create access control generally around proprietary hardware or copyright materials online. <a href="https://developer.apple.com/streaming/fps/">Fairplay</a> framework is the DRM implementation that works over HTTP Live Streaming (HLS) protocol in iOS, iPadOS, watchOS 7, tvOS, and macOS. Fairplay framework consists of server side and client side components that help developers and content providers with content encryption, key generation, key exchange, and playback protection. In this post, we will focus on how to utilize Fairplay with online and offline use cases with <a href="https://developer.apple.com/documentation/avfoundation/avplayer">AVPlayer</a>, <a href="https://developer.apple.com/documentation/avfoundation/avassetdownloadtask">AVAssetDownloadTask</a> and <a href="https://developer.apple.com/documentation/avfoundation/avcontentkeysession">AVContentKeySession</a> on iOS.</p><h3>Key Exchange Process with Fairplay</h3><p>There are three main components of Fairplay streaming:</p><ol><li>The client that tries to play the content</li><li>The key server that generates the decryption keys based on the request parameters from the client</li><li>The content server</li></ol><p>When the client tries to playback content from the content server, the content server checks the playlist for the HLS manifest whether the content is protected or not. If the content is protected, then the client (iOS) will automatically initiate a Fairplay key request which generates a one-time anonymous encrypted server playback context (SPC) message and sends this to the key server to receive the content key context (CKC). SPC message can contain options like whether we want a persistent or non-persistent key from the key server. Then the client will use this CKC to request a play context. Next to the content key, CKC contains the expiration information for time-sensitive use cases like video rental and secure lease.</p><p>Take a look at the <a href="https://download.developer.apple.com/Developer_Tools/FairPlay_Streaming_Server_SDK_v3.0/FairPlayStreamingOverview.pdf">Fairplay Streaming Overview</a> (needs Apple Developer Account) document for technical details of these mentioned contexts. You can see the sequence of these transactions in the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*LawGt4j7XKWJO1XfUvlzbQ.png" /></figure><h3>Integrating AVAssetResourceLoaderDelegate with video streaming</h3><p>In order to allow applications to be able to play Fairplay protected content, we need to implement an <a href="https://developer.apple.com/documentation/avfoundation/avassetresourceloaderdelegate">AVAssetResourceLoaderDelegate</a> in our application and pass this implementation to AVPlayer with the AVPlayerItem. Please see <a href="https://github.com/udemy/ios-fairplay-blog-samples/blob/main/SampleResourceLoaderDelegate.swift">SampleResourceLoaderDelegate</a> implementation and how it is being used in AVPlayerItem set up in the sample code below. Please take note that a target dispatch queue needs to be provided to the delegate setup.</p><pre>let resourceLoader: AVAssetResourceLoaderDelegate = SampleResourceLoaderDelegate()</pre><pre>let resourceLoaderQueue = DispatchQueue(label: “fairplay.queue”)</pre><pre>let player: AVPlayer = .init()</pre><pre>let asset: AVURLAsset = .init(url: url, options: options)</pre><pre>// Set the resource loader delegate to this class. The `resourceLoader`’s delegate will be</pre><pre>// triggered when FairPlay handling is required.</pre><pre>// If this is not a DRM protected video path, delegate will not get triggered</pre><pre>asset.resourceLoader.setDelegate(resourceLoader, queue: resourceLoaderQueue)</pre><pre>let newItem: AVPlayerItem = .init(asset: asset)</pre><pre>observePlayerItemProperties(for: newItem)</pre><pre>// Load player item to AVPlayer</pre><pre>player.replaceCurrentItem(with: newItem)</pre><p>After setting up the player, AVPlayer connects to the content server and when it encounters a Fairplay protected content, it will trigger resource delegate’s “<a href="https://developer.apple.com/documentation/avfoundation/avassetresourceloaderdelegate/1388121-resourceloader">func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -&gt; Bool</a>” method. There are some important steps in execution that we need to highlight.</p><ol><li>Check whether we have a url for the loading request and extract content id from this url. This may change depending on the implementation of the key server.</li><li>Retrieve SPC message from loading request with <a href="https://developer.apple.com/documentation/avfoundation/avassetresourceloadingrequest">AVAssetResourceLoadingRequest</a>’s “<a href="https://developer.apple.com/documentation/avfoundation/avassetresourceloadingrequest/1386116-streamingcontentkeyrequestdata">func streamingContentKeyRequestData(forApp appIdentifier: Data, contentIdentifier: Data, options: [String : Any]? = nil) throws -&gt; Data</a>” method</li><li>With the SPC message make a URLRequest to the key server to fetch the CKC data.</li><li>After receiving the CKC data, if we requested for a non-persistent key, we can finish loading and respond to the data request. Otherwise, we need to generate a persistent key with CKC using “<a href="https://developer.apple.com/documentation/avfoundation/avassetresourceloadingrequest/1623676-persistentcontentkey">func persistentContentKey(fromKeyVendorResponse keyVendorResponse: Data, options: [String : Any]? = nil) throws -&gt; Data</a>” and finish loading with setting “<a href="https://developer.apple.com/documentation/avfoundation/avassetresourceloadingrequest/1390340-contentinformationrequest">contentInformationRequest</a>.contentType” to “AVStreamingKeyDeliveryPersistentContentKeyType”</li></ol><pre>/// Asks the delegate if it wants to load the requested resource.</pre><pre>/// — Parameters:</pre><pre>/// — resourceLoader: The resource loader object that is making the request.</pre><pre>/// — loadingRequest: The loading request object that contains information about the requested resource.</pre><pre>/// — Returns: true if your delegate can load the resource specified by the loadingRequest parameter or false if it cannot.</pre><pre>func resourceLoader(_ resourceLoader: AVAssetResourceLoader,</pre><pre>shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -&gt; Bool {</pre><pre>// We first check if a url is set in the manifest.</pre><pre>guard let url = loadingRequest.request.url else {</pre><pre>logger.info(“Unable to read the url/host data.”)</pre><pre>loadingRequest.finishLoading(with: DRMError.noURLFound)</pre><pre>return false</pre><pre>}</pre><pre>// Get the content id. Content id will be stored in the host of the request url</pre><pre>guard let contentId = url.host, let contentIdData = contentId.data(using: String.Encoding.utf8) else {</pre><pre>logger.error(“Unable to read the content id.”)</pre><pre>loadingRequest.finishLoading(with: DRMError.noContentIdFound)</pre><pre>return false</pre><pre>}</pre><pre>// Request SPC data from OS</pre><pre>var _spcData: Data?</pre><pre>var _spcError: Error?</pre><pre>do {</pre><pre>_spcData = try loadingRequest.streamingContentKeyRequestData(forApp: certificateData, contentIdentifier: contentIdData, options: [AVAssetResourceLoadingRequestStreamingContentKeyRequestRequiresPersistentKey: true as AnyObject])</pre><pre>} catch {</pre><pre>_spcError = error</pre><pre>logger.error(“Failed to get stream content key with error: \(error)”)</pre><pre>}</pre><pre>guard let spcData = _spcData, let dataRequest = loadingRequest.dataRequest else {</pre><pre>loadingRequest.finishLoading(with: DRMError.noSPCFound(underlyingError: _spcError))</pre><pre>logger.error(“Unable to read the SPC data.”)</pre><pre>return false</pre><pre>}</pre><pre>let stringBody: String = “spc=\(spcData.base64EncodedString())&amp;assetId=\(contentId)”</pre><pre>var ckcRequest = URLRequest(url: self.keyServerUrl)</pre><pre>ckcRequest.httpMethod = HTTPMethod.post.rawValue</pre><pre>ckcRequest.httpBody = stringBody.data(using: String.Encoding.utf8)</pre><pre>URLSession(configuration: URLSessionConfiguration.default).dataTask(with: ckcRequest) { data, _, error in</pre><pre>guard let data = data else {</pre><pre>logger.error(“Error in response data in CKC request: \(error)”)</pre><pre>loadingRequest.finishLoading(with: DRMError.unableToFetchKey(underlyingError: _spcError))</pre><pre>return</pre><pre>}</pre><pre>// The CKC is correctly returned and is now send to the `AVPlayer` instance so we</pre><pre>// can continue to play the stream.</pre><pre>guard let ckcData = Data(base64Encoded: data) else {</pre><pre>logger.error(“Can’t create base64 encoded data”)</pre><pre>loadingRequest.finishLoading(with: DRMError.cannotEncodeCKCData)</pre><pre>return</pre><pre>}</pre><pre>// If we need non-persistent token, then complete loading</pre><pre>// dataRequest.respond(with: data)</pre><pre>// loadingRequest.finishLoading()</pre><pre>// If we need persistent token, then it is time to add persistence option</pre><pre>var persistentKeyData: Data?</pre><pre>do {</pre><pre>persistentKeyData = try loadingRequest.persistentContentKey(fromKeyVendorResponse: ckcData, options: nil)</pre><pre>} catch {</pre><pre>logger.error(“Failed to get persistent key with error: \(error)”)</pre><pre>loadingRequest.finishLoading(with: DRMError.unableToGeneratePersistentKey))</pre><pre>return</pre><pre>}</pre><pre>// set type of the key</pre><pre>loadingRequest.contentInformationRequest?.contentType = AVStreamingKeyDeliveryPersistentContentKeyType</pre><pre>dataRequest.respond(with: persistentKeyData)</pre><pre>loadingRequest.finishLoading()</pre><pre>}.resume()</pre><pre>return true</pre><pre>}</pre><p>Regarding error handling, if the delegate finishes the resource loading request with an error, you can handle this error in the <a href="https://github.com/udemy/ios-fairplay-blog-samples/blob/main/PlayerItemStatus.swift">status observer</a> of AVPlayerItem.</p><pre>private func observePlayerItemProperties(for item: AVPlayerItem) {</pre><pre>item.observe(\.status, changeHandler: self.onStatusObserverChanged)</pre><pre>….</pre><pre>}</pre><pre>private func onStatusObserverChanged(playerItem: AVPlayerItem, change: NSKeyValueObservedChange&lt;AVPlayerItem.Status&gt;) {</pre><pre>guard playerItem.status != .failed else {</pre><pre>if let error = playerItem.error as? Error {</pre><pre>// DRM Errors handled here</pre><pre>}</pre><pre>return</pre><pre>}</pre><pre>….</pre><pre>}</pre><h3>Integrating AVAssetResourceLoaderDelegate with HLS downloading</h3><p>Another useful feature of AVFoundation is being able to download HLS content for offline playback. Extending from <a href="https://developer.apple.com/documentation/foundation/urlsession">URLSession</a>, <a href="https://developer.apple.com/documentation/avfoundation/avassetdownloadurlsession">AVAssetDownloadURLSession</a> class contains specific methods to enable developers to easily download HLS content via <a href="https://developer.apple.com/documentation/avfoundation/avassetdownloadtask">AVAssetDownloadTask</a> class. For detailed information on HLS downloading and offline playback, please refer to this <a href="https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/MediaPlaybackGuide/Contents/Resources/en.lproj/HTTPLiveStreaming/HTTPLiveStreaming.html">document</a> and this <a href="https://developer.apple.com/videos/play/wwdc2020/10655/">WWDC 2020</a> video.</p><p>For FairPlay enabled content, a resource loader delegate has to be provided to the <a href="https://developer.apple.com/documentation/avfoundation/avurlasset">AVURLAsset</a> while initiating the download task.</p><pre>let resourceLoader: AVAssetResourceLoaderDelegate = SampleResourceLoaderDelegate()</pre><pre>let resourceLoaderQueue = DispatchQueue(label: “fairplay.queue”)</pre><pre>let downloadSession = AVAssetDownloadURLSession(…)</pre><pre>let bitrate = 500000</pre><pre>let urlAsset = AVURLAsset(url: requestURL, options: options)</pre><pre>// If this is not a DRM protected video path, delegate will not get triggered</pre><pre>urlAsset.resourceLoader.setDelegate(resourceLoader, queue: resourceLoaderQueue)</pre><pre>urlAsset.resourceLoader.preloadsEligibleContentKeys = true</pre><pre>let downloadTask = downloadSession.makeAssetDownloadTask(asset: urlAsset, assetTitle: “hls stream”, assetArtworkData: nil, options: [AVAssetDownloadTaskMinimumRequiredMediaBitrateKey: bitrate])</pre><pre>downloadTask.resume()</pre><p>The important thing to keep in mind is that for offline available streams, it will be useful to have a persistent key with a valid expiration cached in the device so that users will be able to play the downloaded content even if they are not connected. One other important thing to note is that the errors from the resource loader delegate will get handled with “<a href="https://developer.apple.com/documentation/foundation/urlsessiontaskdelegate/1411610-urlsession">func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)</a>” method of the <a href="https://developer.apple.com/documentation/foundation/urlsessiontaskdelegate">URLSessionTaskDelegate</a></p><h3>Using AVContentKeySession for key management</h3><p><a href="https://developer.apple.com/documentation/avfoundation/avcontentkeysession">AVContentKeySession</a> is another tool that you can use to create and track decryption keys for media content. In spite of <a href="https://developer.apple.com/documentation/avfoundation/avassetresourceloaderdelegate">AVAssetResourceLoaderDelegate</a> being coupled with AVPlayer, <a href="https://developer.apple.com/documentation/avfoundation/avcontentkeysession">AVContentKeySession</a> provides an extensive feature set that you can utilize independently from AVPlayer. Please take a look at this <a href="https://developer.apple.com/videos/play/wwdc2018/507/">WWDC 2018</a> video for more information. In this example, we will be utilizing <a href="https://developer.apple.com/documentation/avfoundation/avcontentkeysession">AVContentKeySession</a> to refetch the expiring persistent keys that we initially fetched with <a href="https://developer.apple.com/documentation/avfoundation/avassetresourceloaderdelegate">AVAssetResourceLoaderDelegate</a>.</p><p><a href="https://developer.apple.com/documentation/avfoundation/avcontentkeysession">AVContentKeySession</a> supports a preset initializer FairPlay key system. After initializing the key session, we need to set the delegate and the dispatch queue that we want the delegate methods to be triggered. After session delegate is set, a new key request can be initiated with “<a href="https://developer.apple.com/documentation/avfoundation/avcontentkeysession/2799180-processcontentkeyrequest">func processContentKeyRequest(withIdentifier identifier: Any?, initializationData: Data?, options: [String : Any]? = nil)</a>” where the identifier is the “contentId” that we mentioned before that we extracted from the loading request’s url in <a href="https://developer.apple.com/documentation/avfoundation/avassetresourceloaderdelegate">AVAssetResourceLoaderDelegate</a>.</p><pre>let session: AVContentKeySession = AVContentKeySession(keySystem: .fairPlayStreaming)</pre><pre>let queue = DispatchQueue(label: “fairplay.refresher.queue”)</pre><pre>session.setDelegate(self, queue: self.queue)</pre><pre>session.processContentKeyRequest(withIdentifier: contentId, initializationData: nil, options: nil)</pre><p>There are different methods to manage persistent and non-persistent keys in the <a href="https://developer.apple.com/documentation/avfoundation/avcontentkeysessiondelegate">AVContentKeySessionDelegate</a>. In the the example implementation of <a href="https://github.com/udemy/ios-fairplay-blog-samples/blob/main/SampleKeyRefresher.swift">SampleKeyRefresher</a>, below, non-persistent key request delegate method is getting redirected to persistent key request delegate method “<a href="https://developer.apple.com/documentation/avfoundation/avcontentkeysessiondelegate/2799200-contentkeysession">func contentKeySession(_ session: AVContentKeySession, didProvide keyRequest: AVPersistableContentKeyRequest)</a>”. The structure of the key fetch operation is very similar to <a href="https://developer.apple.com/documentation/avfoundation/avassetresourceloaderdelegate">AVAssetResourceLoaderDelegate</a>.</p><ol><li>Extract content id from key request object.</li><li>Retrieve SPC message from key request with “<a href="https://developer.apple.com/documentation/avfoundation/avcontentkeyrequest/2799198-makestreamingcontentkeyrequestda">func makeStreamingContentKeyRequestData(forApp appIdentifier: Data, contentIdentifier: Data?, options: [String : Any]? = nil, completionHandler handler: @escaping (Data?, Error?) -&gt; Void)</a>” method</li><li>With the SPC message make a URL request to the key server to fetch the CKC data.</li><li>After receiving the CKC data, convert it to a persistent key and return the response in a <a href="https://developer.apple.com/documentation/avfoundation/avcontentkeyresponse">AVContentKeyResponse</a> object.</li></ol><pre>func contentKeySession(_ session: AVContentKeySession, didProvide keyRequest: AVPersistableContentKeyRequest) {</pre><pre>logger.debug(“Start persistable content key request”)</pre><pre>// We first check if a url is set in the manifest.</pre><pre>guard let contentId = keyRequest.identifier as? String, let contentIdData = contentId.data(using: String.Encoding.utf8) else {</pre><pre>logger.error(“Unable to read contentId.”)</pre><pre>keyRequest.processContentKeyResponseError(DelegateError.noContentId)</pre><pre>return</pre><pre>}</pre><pre>keyRequest.makeStreamingContentKeyRequestData(forApp: certificateData, contentIdentifier: contentIdData, options: [AVAssetResourceLoadingRequestStreamingContentKeyRequestRequiresPersistentKey: true as AnyObject]) { spcData, spcError in</pre><pre>guard let spcData = spcData else {</pre><pre>let error = spcError ?? DelegateError.noSPCData</pre><pre>logger.error(“Unable to fetch SPC data \(error).”)</pre><pre>keyRequest.processContentKeyResponseError(error)</pre><pre>return</pre><pre>}</pre><pre>logger.debug(“SPC data fetched, requesting CKC”)</pre><pre>let stringBody: String = “spc=\(spcData.base64EncodedString())&amp;assetId=\(contentId)”</pre><pre>var ckcRequest = URLRequest(url: self.keyServerUrl)</pre><pre>ckcRequest.httpMethod = HTTPMethod.post.rawValue</pre><pre>ckcRequest.httpBody = stringBody.data(using: String.Encoding.utf8)</pre><pre>URLSession(configuration: URLSessionConfiguration.default).dataTask(with: ckcRequest) { data, _, error in</pre><pre>guard let data = data else {</pre><pre>logger.error(“Error in response data in CKC request: \(error)”)</pre><pre>keyRequest.processContentKeyResponseError(error)</pre><pre>return</pre><pre>}</pre><pre>// The CKC is correctly returned and is now send to the `AVPlayer` instance so we</pre><pre>// can continue to play the stream.</pre><pre>guard let ckcData = Data(base64Encoded: data) else {</pre><pre>logger.error(“Can’t create base64 encoded data”)</pre><pre>keyRequest.processContentKeyResponseError(DelegateError.ckcFetch)</pre><pre>return</pre><pre>}</pre><pre>var persistentKeyData: Data?</pre><pre>do {</pre><pre>persistentKeyData = try keyRequest.persistableContentKey(fromKeyVendorResponse: data, options: nil)</pre><pre>} catch {</pre><pre>logger.error(“Unable to create persistable content key \(error).”)</pre><pre>keyRequest.processContentKeyResponseError(error)</pre><pre>return</pre><pre>}</pre><pre>let keyResponse = AVContentKeyResponse(fairPlayStreamingKeyResponseData: persistentKeyData)</pre><pre>keyRequest.processContentKeyResponse(keyResponse)</pre><pre>logger.debug(“CKC received, loading complete”)</pre><pre>}.resume()</pre><pre>}</pre><pre>}</pre><p>As mentioned above <a href="https://developer.apple.com/documentation/avfoundation/avcontentkeysession">AVContentKeySession</a> has many other functionalities that can be used to manage decryption keys for media content. The example above is just a small portion of the framework to refresh any expiring persistent license.</p><h3>Sample code</h3><p><a href="https://github.com/udemy/ios-fairplay-blog-samples">https://github.com/udemy/ios-fairplay-blog-samples</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8aff3d4248dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>