Giter VIP home page Giter VIP logo

exoplayerdrm's Introduction

What is DRM? 🤔

Screenshot

Digital rights management (DRM) is a way to protect copyrights for digital media. This approach includes the use of technologies that limit the copying and use of copyrighted works and proprietary software.

In a way, digital rights management allows publishers or authors to control what paying users can do with their works. For companies, implementing digital rights management systems or processes can help to prevent users from accessing or using certain assets, allowing the organization to avoid legal issues that arise from unauthorized use. Today, DRM is playing a growing role in data security.

With the rise of peer-to-peer file exchange services such as torrent sites, online piracy has been the bane of copyrighted material. DRM technologies do not catch those who engage in piracy. Instead, they make it impossible to steal or share the content in the first place.

For more please read this article : https://streaminglearningcenter.com/articles/what-is-drm.html

Digital rights management - ExoPlayer 📺

ExoPlayer uses Android’s MediaDrm API to support DRM protected playbacks.

The minimum Android versions required for different supported DRM schemes, along with the streaming formats for which they’re supported, are:

DRM scheme Android version number Android API level Supported formats
Widevine “cenc” 4.4 19 DASH, HLS (FMP4 only)
Widevine “cbcs” 7.1 25 DASH, HLS (FMP4 only)
ClearKey 5.0 21 DASH
PlayReady SL2000 AndroidTV AndroidTV DASH, SmoothStreaming, HLS (FMP4 only)

In order to play DRM protected content with ExoPlayer, the UUID of the DRM system and the license server URI should be specified when building a media item. The player will then use these properties to build a default implementation of DrmSessionManager, called DefaultDrmSessionManager, that’s suitable for most use cases. For some use cases additional DRM properties may be necessary, as outlined in the sections below.

For more please read document : https://exoplayer.dev/drm.html

How to use DRM in ExoPlayer ⁉️

In order to play a Drm video in Exoplayer, we need to have a DASH(.mdp) type video url. We will decode the encrypted video and play it.

First of all, we can start our example by following the steps below.

Step - 1️⃣

We are creating an Android project in the Kotlin language.

Step - 2️⃣

We add the internet permission to the Android Manifest file.

<uses-permission android:name="android.permission.INTERNET"/>

Step - 3️⃣

Add the link of the ExoPlayer library to the .build gradle file.

implementation 'com.google.android.exoplayer:exoplayer:2.17.1'

Step - 4️⃣

If not enabled already, you need to turn on Java 8 support in all build.gradle files depending on ExoPlayer, by adding the following to the android section:

compileOptions {
        targetCompatibility JavaVersion.VERSION_1_8
}

Step - 5️⃣

Add playerView to the activity_main.xml file.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:argType="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.google.android.exoplayer2.ui.StyledPlayerView
        android:id="@+id/playerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        argType:resize_mode="fixed_width"
        argType:show_buffering="when_playing"
        argType:show_fastforward_button="true"
        argType:show_next_button="false"
        argType:show_previous_button="false"
        argType:show_rewind_button="true"
        argType:show_subtitle_button="true"
        argType:use_artwork="true"
        argType:use_controller="true">

    </com.google.android.exoplayer2.ui.StyledPlayerView>

</androidx.constraintlayout.widget.ConstraintLayout>

Step - 6️⃣

Player, binding variables have been defined.

private lateinit var playerView: ExoPlayer
private lateinit var binding: ActivityMainBinding

Step - 7️⃣

A function has been created for the Factory operation.

  val defaultHttpDataSourceFactory = DefaultHttpDataSource.Factory()
             .setUserAgent(userAgent)
             .setTransferListener(
                 DefaultBandwidthMeter.Builder(context)
                     .setResetOnNetworkTypeChange(false)
                     .build()
             )

         val dashChunkSourceFactory: DashChunkSource.Factory = DefaultDashChunkSource.Factory(
             defaultHttpDataSourceFactory
         )

Step - 8️⃣

We have created a method in which the necessary operations are performed to play a drm type video.

  val dashMediaSource =
             DashMediaSource.Factory(dashChunkSourceFactory, manifestDataSourceFactory)
                 .createMediaSource(
                     MediaItem.Builder()
                         .setUri(Uri.parse(url))
                          // DRM Configuration
                         .setDrmConfiguration(
                             MediaItem.DrmConfiguration.Builder(drmSchemeUuid)
                                 .setLicenseUri(drmLicenseUrl).build()
                         )
                         .setMimeType(MimeTypes.APPLICATION_MPD)
                         .setTag(null)
                         .build()
                 )

Step - 9️⃣

Added url, drm license to play. It is made ready to be played.

Drm License Url : https://proxy.uat.widevine.com/proxy?provider=widevine_test

Drm Url : https://bitmovin-a.akamaihd.net/content/art-of-motion_drm/mpds/11331.mpd

 // Prepare the player.
         playerView = ExoPlayer.Builder(this)
             .setSeekForwardIncrementMs(10000)
             .setSeekBackIncrementMs(10000)
             .build()
         playerView.playWhenReady = true
         binding.playerView.player = playerView
         playerView.setMediaSource(dashMediaSource, true)
         playerView.prepare()

Step - 🔟

Call the initializePlayer() function inside onCreate.

  override fun onCreate(savedInstanceState: Bundle?) {
          super.onCreate(savedInstanceState)
          binding = ActivityMainBinding.inflate(layoutInflater)
          val view = binding.root
          setContentView(view)
          initializePlayer()
      }
  }

Result 📌

Yes ✅ The url in DRM type played smoothly. All dash type contents are played on the player with the Drm setting.


But setDrmConfiguration If you make a comment line, you will not be able to view the content.

 .setDrmConfiguration(MediaItem.DrmConfiguration.Builder(drmSchemeUuid)
                      .setLicenseUri(drmLicenseUrl).build())


Donation 💸

If this project help 💁 you to develop, you can give me a cup of coffee. ☕

"Buy Me A Coffee"

Resources 📚

License 📋

MIT License

Copyright (c) 2023 Halil OZEL

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

exoplayerdrm's People

Contributors

halilozel1903 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

exoplayerdrm's Issues

This code is working in Emulator Only

This code is working in Emulator Only but not in real device. Why? Here is my PlayerActivity.class

`package com.example.myapplication;

import android.app.AlertDialog;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.DefaultRenderersFactory;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.PlaybackException;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.drm.DefaultDrmSessionManager;
import com.google.android.exoplayer2.drm.DrmSessionManager;
import com.google.android.exoplayer2.drm.FrameworkMediaDrm;
import com.google.android.exoplayer2.drm.HttpMediaDrmCallback;
import com.google.android.exoplayer2.drm.LocalMediaDrmCallback;
import com.google.android.exoplayer2.drm.MediaDrmCallback;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.dash.DashChunkSource;
import com.google.android.exoplayer2.source.dash.DashMediaSource;
import com.google.android.exoplayer2.source.dash.DefaultDashChunkSource;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.ExoTrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelectionParameters;
import com.google.android.exoplayer2.ui.StyledPlayerView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSource;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource;
import com.google.android.exoplayer2.upstream.HttpDataSource;
import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.Util;

import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.UUID;

public class PlayerActivity extends AppCompatActivity{
private StyledPlayerView exoPlayerView;

private static final CookieManager DEFAULT_COOKIE_MANAGER;
static
{
    DEFAULT_COOKIE_MANAGER = new CookieManager();
    DEFAULT_COOKIE_MANAGER.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
}

@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (CookieHandler.getDefault() != DEFAULT_COOKIE_MANAGER) {
        CookieHandler.setDefault(DEFAULT_COOKIE_MANAGER);
    }
    supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
    );
    setContentView(R.layout.activity_player);
    hideSystemUI();
    initVars();

    ////////////////////////////////////////////////////////////////////////////////////////////

    String video = "https://bitmovin-a.akamaihd.net/content/art-of-motion_drm/mpds/11331.mpd";

    String license = "https://proxy.uat.widevine.com/proxy?provider=widevine_test";

    String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36";

    play(Uri.parse(video), userAgent, license);



}

//--------------------------------------------------------------------------------------------------

private DefaultDrmSessionManager buildDrmSessionManager(UUID uuid, String licenseUrl, String userAgent) {

    HttpDataSource.Factory licenseDataSourceFactory = new DefaultHttpDataSource.Factory()
            .setAllowCrossProtocolRedirects(true)
            .setUserAgent(userAgent);

    HttpMediaDrmCallback drmCallback = new HttpMediaDrmCallback(licenseUrl, true,
            licenseDataSourceFactory);

    return new DefaultDrmSessionManager.Builder()
            .setUuidAndExoMediaDrmProvider(uuid, FrameworkMediaDrm.DEFAULT_PROVIDER)
            .build(drmCallback);
}

private HlsMediaSource buildHlsMediaSource(Uri uri, String drmLicense) {

    String userAgent = getString(R.string.user_agent);
    UUID drmSchemeUuid = Util.getDrmUuid(C.WIDEVINE_UUID.toString());

    DrmSessionManager drmSessionManager = buildDrmSessionManager(drmSchemeUuid, drmLicense, userAgent);

    DataSource.Factory dataSourceFactory = new DefaultDataSource.Factory(this, new DefaultHttpDataSource.Factory()
            .setUserAgent(userAgent));

    return new HlsMediaSource.Factory(dataSourceFactory)
            .setDrmSessionManagerProvider(mediaItem -> drmSessionManager)
            .createMediaSource(
                    new MediaItem.Builder()
                            .setUri(uri)
                            .setMimeType(MimeTypes.APPLICATION_M3U8)
                            .build()
            );
}


 private DashMediaSource buildDashMediaSource(Uri uri, String userAgent, String drmLicenseUrl) {

     DataSource.Factory defaultHttpDataSourceFactory = new DefaultHttpDataSource.Factory()
             .setUserAgent(userAgent)
             .setAllowCrossProtocolRedirects(true)
             .setTransferListener(
                     new DefaultBandwidthMeter.Builder(PlayerActivity.this)
                             .setResetOnNetworkTypeChange(false)
                             .build()
             );

     DashChunkSource.Factory dashChunkSourceFactory = new DefaultDashChunkSource.Factory(defaultHttpDataSourceFactory);

     DataSource.Factory manifestDataSourceFactory = new DefaultHttpDataSource.Factory()
             .setUserAgent(userAgent)
             .setAllowCrossProtocolRedirects(true);

     return new DashMediaSource.Factory(dashChunkSourceFactory, manifestDataSourceFactory)
             .createMediaSource(
                     new MediaItem.Builder()
                             .setUri(uri)
                             // DRM Configuration
                             .setDrmConfiguration(
                                     new MediaItem.DrmConfiguration.Builder(C.WIDEVINE_UUID)
                                             .setLicenseUri(drmLicenseUrl)
                                             .build()
                             )
                             .setMimeType(MimeTypes.APPLICATION_MPD)
                             .setTag(null)
                             .build()
             );
 }


@RequiresApi(api = Build.VERSION_CODES.O)
private void play(Uri vUri, String userAgent ,String drmLicense) {

    ExoTrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory();

    DefaultTrackSelector trackSelector = new DefaultTrackSelector(this, videoTrackSelectionFactory);

    TrackSelectionParameters parameters = trackSelector
            .getParameters()
            .buildUpon()
            .setRendererDisabled(C.TRACK_TYPE_TEXT,true)
            .clearOverrides()
            .build();

    trackSelector.setParameters(parameters);


    DefaultRenderersFactory renderersFactory = new DefaultRenderersFactory(this)
            .forceEnableMediaCodecAsynchronousQueueing()
            .setExtensionRendererMode(DefaultRenderersFactory.EXTENSION_RENDERER_MODE_OFF);

    int maxBufferMs = DefaultLoadControl.DEFAULT_MAX_BUFFER_MS;

    DefaultLoadControl loadControl = new DefaultLoadControl.Builder()
            .setBufferDurationsMs(DefaultLoadControl.DEFAULT_MIN_BUFFER_MS,
                    maxBufferMs,
                    DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_MS,
                    DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS)
            .build();


    ExoPlayer exoPlayer = new ExoPlayer.Builder(this)
            .setTrackSelector(trackSelector)
            .setLoadControl(loadControl)
            .setRenderersFactory(renderersFactory)
            .build();


    if (vUri.toString().toLowerCase().contains(".m3u8")){
        MediaSource mediaSource = buildHlsMediaSource(vUri, drmLicense);
        exoPlayer.setMediaSource(mediaSource);
    }
    else if (vUri.toString().toLowerCase().contains(".mpd")){
        MediaSource mediaSource = buildDashMediaSource(vUri, userAgent, drmLicense);
        exoPlayer.setMediaSource(mediaSource);
    }
    else{
        exoPlayer.setMediaItem(MediaItem.fromUri(vUri));
    }

    exoPlayer.prepare();

    exoPlayerView.setPlayer(exoPlayer);

    exoPlayer.addListener(new Player.Listener() {

        @Override
        public void onPlaybackStateChanged(int playbackState) {

        }

        @Override
        public void onPlayerError(@NonNull PlaybackException error) {

            if (error.errorCode == PlaybackException.ERROR_CODE_PARSING_CONTAINER_MALFORMED) {

                TrackSelectionParameters selectionParameters = exoPlayer.getTrackSelectionParameters()
                        .buildUpon()
                        .setTrackTypeDisabled(C.TRACK_TYPE_TEXT, true)
                        .clearOverridesOfType(C.TRACK_TYPE_TEXT)
                        .build();

                exoPlayer.setTrackSelectionParameters(selectionParameters);

                exoPlayer.prepare();
            }

// trackSelector
// .buildUponParameters()
// .setRendererDisabled(exoPlayer.getRendererType(C.TRACK_TYPE_TEXT), true);

            AlertDialog.Builder builder = new AlertDialog.Builder(PlayerActivity.this);
            builder.setTitle("Error " + exoPlayer.getRendererCount());
            builder.setCancelable(false);
            builder.setMessage(error.getMessage() + "\n" + error.getErrorCodeName());
            builder.setPositiveButton("Ok", (dialogInterface, i) -> dialogInterface.dismiss());
            builder.create().show();
        }
    });

    exoPlayer.prepare();
    exoPlayer.setPlayWhenReady(true);

    exoPlayerView.setPlayer(exoPlayer);
    exoPlayerView.setShowNextButton(false);
    exoPlayerView.setShowPreviousButton(false);
    exoPlayerView.setControllerShowTimeoutMs(2500);
}

//--------------------------------------------------------------------------------------------------

private void hideSystemUI() {
    // Set the IMMERSIVE flag.
    // Set the content to appear under the system bars so that the content
    // doesn't resize when the system bars hide and show.
    getWindow().getDecorView().setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE);
}

//--------------------------------------------------------------------------------------------------

private void initVars() {
    exoPlayerView = findViewById(R.id.exoPlayerView);
}

//--------------------------------------------------------------------------------------------------

@Override
public void onBackPressed() {
    finish();
}

}`

Get DRM License URL

Hi @halilozel1903

The code sample for playing DRM content was very helpful, thank you for sharing it with us.
I need help to understand from where did you get the DRM license URL?
In my application, I am using Azure Media Service & Widevine DRM.

exoplayer

merhaba exoplayerde ac3 ve eac3 ses formatlarını oynatmıyor. video var ama ses yok nasıl aşabilirim. media3

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.