Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- package tech.iotait.tsetexoplayer;
- import android.app.Activity;
- import android.content.Intent;
- import android.content.pm.ActivityInfo;
- import android.content.res.Configuration;
- import android.net.Uri;
- import android.net.wifi.WifiManager;
- import android.os.Bundle;
- import android.os.Handler;
- import android.support.annotation.Nullable;
- import android.text.TextUtils;
- import android.text.format.Formatter;
- import android.util.Log;
- import android.view.KeyEvent;
- import android.view.Surface;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.view.ViewGroup;
- import android.view.Window;
- import android.view.WindowManager;
- import android.widget.FrameLayout;
- import android.widget.ImageButton;
- import android.widget.LinearLayout;
- import android.widget.SeekBar;
- import android.widget.Toast;
- import com.google.android.exoplayer2.C;
- import com.google.android.exoplayer2.C.ContentType;
- import com.google.android.exoplayer2.DefaultRenderersFactory;
- import com.google.android.exoplayer2.ExoPlaybackException;
- import com.google.android.exoplayer2.ExoPlayerFactory;
- import com.google.android.exoplayer2.PlaybackPreparer;
- import com.google.android.exoplayer2.Player;
- import com.google.android.exoplayer2.SimpleExoPlayer;
- import com.google.android.exoplayer2.drm.DefaultDrmSessionManager;
- import com.google.android.exoplayer2.drm.DrmSessionManager;
- import com.google.android.exoplayer2.drm.FrameworkMediaCrypto;
- import com.google.android.exoplayer2.drm.FrameworkMediaDrm;
- import com.google.android.exoplayer2.drm.HttpMediaDrmCallback;
- import com.google.android.exoplayer2.drm.UnsupportedDrmException;
- import com.google.android.exoplayer2.ext.okhttp.OkHttpDataSourceFactory;
- import com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.DecoderInitializationException;
- import com.google.android.exoplayer2.mediacodec.MediaCodecUtil.DecoderQueryException;
- import com.google.android.exoplayer2.source.BehindLiveWindowException;
- import com.google.android.exoplayer2.source.MediaSource;
- import com.google.android.exoplayer2.source.MediaSourceEventListener;
- import com.google.android.exoplayer2.source.TrackGroupArray;
- import com.google.android.exoplayer2.source.ads.AdsLoader;
- import com.google.android.exoplayer2.source.ads.AdsMediaSource;
- 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.MappingTrackSelector.MappedTrackInfo;
- import com.google.android.exoplayer2.trackselection.TrackSelection;
- import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
- import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
- import com.google.android.exoplayer2.ui.DebugTextViewHelper;
- import com.google.android.exoplayer2.ui.PlayerControlView;
- import com.google.android.exoplayer2.ui.PlayerView;
- import com.google.android.exoplayer2.upstream.DataSource;
- import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
- import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
- import com.google.android.exoplayer2.upstream.HttpDataSource;
- import com.google.android.exoplayer2.util.EventLogger;
- import com.google.android.exoplayer2.util.Util;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.lang.reflect.Constructor;
- import java.net.CookieHandler;
- import java.net.CookieManager;
- import java.net.CookiePolicy;
- import java.net.InetAddress;
- import java.net.NetworkInterface;
- import java.net.SocketException;
- import java.net.URL;
- import java.security.MessageDigest;
- import java.security.NoSuchAlgorithmException;
- import java.util.Enumeration;
- import java.util.UUID;
- import okhttp3.CacheControl;
- import okhttp3.OkHttpClient;
- import org.apache.commons.codec.binary.Base64;
- import org.apache.commons.codec.digest.DigestUtils;
- import org.joda.time.DateTime;
- import org.joda.time.DateTimeZone;
- import org.joda.time.format.DateTimeFormat;
- import org.joda.time.format.DateTimeFormatter;
- import java.io.UnsupportedEncodingException;
- import java.util.Locale;
- import static android.content.ContentValues.TAG;
- /** An activity that plays media using {@link SimpleExoPlayer}. */
- public class PlayerActivity extends Activity implements PlaybackPreparer, PlayerControlView.VisibilityListener {
- public static final String DRM_SCHEME_EXTRA = "drm_scheme";
- public static final String DRM_LICENSE_URL = "drm_license_url";
- public static final String DRM_KEY_REQUEST_PROPERTIES = "drm_key_request_properties";
- public static final String DRM_MULTI_SESSION = "drm_multi_session";
- public static final String PREFER_EXTENSION_DECODERS = "prefer_extension_decoders";
- public static final String AD_TAG_URI_EXTRA = "ad_tag_uri";
- // For backwards compatibility.
- private static final String DRM_SCHEME_UUID_EXTRA = "drm_scheme_uuid";
- private static final DefaultBandwidthMeter BANDWIDTH_METER = new DefaultBandwidthMeter();
- private static final CookieManager DEFAULT_COOKIE_MANAGER;
- static {
- DEFAULT_COOKIE_MANAGER = new CookieManager();
- DEFAULT_COOKIE_MANAGER.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
- }
- private Handler mainHandler;
- private EventLogger eventLogger;
- private PlayerView playerView;
- private LinearLayout debugRootView;
- private DataSource.Factory mediaDataSourceFactory;
- private SimpleExoPlayer player;
- private DefaultTrackSelector trackSelector;
- private DebugTextViewHelper debugViewHelper;
- private boolean inErrorState;
- private TrackGroupArray lastSeenTrackGroupArray;
- private boolean shouldAutoPlay;
- private int resumeWindow;
- private long resumePosition;
- // Fields used only for ad playback. The ads loader is loaded via reflection.
- private AdsLoader adsLoader;
- private Uri loadedAdTagUri;
- private ViewGroup adUiViewGroup;
- SeekBar seekBar;
- String clientIP = ""; // generate User IP;
- String password = "123z123z"; // further improvement planned on this
- // Activity lifecycle
- @Override
- public void onCreate(Bundle savedInstanceState) {
- requestWindowFeature(Window.FEATURE_NO_TITLE);
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
- super.onCreate(savedInstanceState);
- getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
- shouldAutoPlay = true;
- clearResumePosition();
- String userAgent1 = "";
- String urltest1 = "http://142.93.218.69:8081/test/anik/playlist.m3u8";
- WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
- String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
- clientIP = "103.113.152.106";
- if (urltest1.contains("okaystreamz.tk")) {
- userAgent1 = "tvingoplus@livetv.tvingo1Z!2018";
- }else if (urltest1.contains("hoichoi")) {
- userAgent1 = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"; }
- else{
- userAgent1 = "IOTAIT";
- }
- mediaDataSourceFactory = new DefaultDataSourceFactory(this, BANDWIDTH_METER,
- new OkHttpDataSourceFactory(new OkHttpClient.Builder().build(),
- userAgent1,
- BANDWIDTH_METER, CacheControl.FORCE_NETWORK));
- mainHandler = new Handler();
- final View decorView = getWindow().getDecorView();
- decorView.setOnSystemUiVisibilityChangeListener(
- new View.OnSystemUiVisibilityChangeListener() {
- @Override
- public void onSystemUiVisibilityChange(int visibility) {
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
- getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
- }
- }
- );
- if (CookieHandler.getDefault() != DEFAULT_COOKIE_MANAGER) {
- CookieHandler.setDefault(DEFAULT_COOKIE_MANAGER);
- }
- setContentView(R.layout.player_activity);
- final ImageButton buttonSetLandscape = (ImageButton)this.findViewById(R.id.setLandscape);
- final ImageButton buttonSetPortrait = (ImageButton)findViewById(R.id.setPortrait);
- buttonSetLandscape.setOnClickListener(new OnClickListener(){
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
- buttonSetLandscape.setVisibility(View.GONE);
- buttonSetPortrait.setVisibility(View.VISIBLE);
- playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FILL);
- }});
- buttonSetPortrait.setOnClickListener(new OnClickListener(){
- @Override
- public void onClick(View arg0) {
- // TODO Auto-generated method stub
- setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
- buttonSetPortrait.setVisibility(View.GONE);
- buttonSetLandscape.setVisibility(View.VISIBLE);
- playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT);
- }});
- seekBar = findViewById(R.id.volumeseekbar);
- seekBar.setMax(100);
- seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
- {
- @Override
- public void onProgressChanged(final SeekBar seekBar, final int progress, final boolean fromUser)
- {
- final float adjust = (float) progress / 100;
- Log.d(TAG, "Volume: " + adjust);
- player.setVolume(adjust);
- }
- @Override
- public void onStartTrackingTouch(final SeekBar seekBar)
- {
- }
- @Override
- public void onStopTrackingTouch(final SeekBar seekBar)
- {
- }
- });
- playerView = findViewById(R.id.player_view);
- playerView.setControllerVisibilityListener(this);
- playerView.requestFocus();
- int orientation = getResources().getConfiguration().orientation;
- int rotation = getWindowManager().getDefaultDisplay().getRotation();
- int actual_orientation = -1;
- if (orientation == Configuration.ORIENTATION_LANDSCAPE
- && (rotation == Surface.ROTATION_0
- || rotation == Surface.ROTATION_90)){
- orientation = 1;
- } else if (orientation == Configuration.ORIENTATION_PORTRAIT
- && (rotation == Surface.ROTATION_0
- || rotation == Surface.ROTATION_90)) {
- orientation = 2;
- } else if (orientation == Configuration.ORIENTATION_LANDSCAPE
- && (rotation == Surface.ROTATION_180
- || rotation == Surface.ROTATION_270)){
- orientation = 3;//any constant for reverse landscape orientation;
- } else {
- if (orientation == Configuration.ORIENTATION_PORTRAIT
- && (rotation == Surface.ROTATION_180
- || rotation == Surface.ROTATION_270)){
- orientation = 4;//any constant for reverse portrait orientation;
- }
- }
- if (orientation == 1 || orientation == 3) {
- playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FILL);
- }else if(orientation == 2 || orientation == 4) {
- playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT);
- }
- }
- public String getExternalIpAddress() throws Exception {
- URL whatismyip = new URL("http://checkip.amazonaws.com");
- BufferedReader in = null;
- try {
- in = new BufferedReader(new InputStreamReader(
- whatismyip.openStream()));
- String ip = in.readLine();
- return ip;
- } finally {
- if (in != null) {
- try {
- in.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- // This method requires no change.
- public static String getFinalURL(String urlofStream, String clientIP, String password) throws UnsupportedEncodingException
- {
- DateTimeFormatter timeFormatter = DateTimeFormat.forPattern("M/d/y h:m:s a").withZone(DateTimeZone.UTC).withLocale(Locale.US);
- DateTime currentServerTime = new DateTime(DateTimeZone.UTC); // lets get localtime in UTC timezone
- String today = timeFormatter.print(currentServerTime);
- String video_url = urlofStream;
- String ip = clientIP;
- String key = password;
- String validminutes = "20";
- String to_hash = ip + key + today + validminutes;
- byte[] ascii_to_hash = to_hash.getBytes("UTF-8");
- String base64hash = new String(Base64.encodeBase64(ascii_to_hash));
- String urlsignature = "server_time=" + today + "&hash_value=" + base64hash + "&validminutes=" + validminutes;
- String base64urlsignature = new String(Base64.encodeBase64(urlsignature.getBytes("UTF-8")));
- String signedurlwithvalidinterval = video_url + "?wmsAuthSign=" + base64urlsignature;
- return signedurlwithvalidinterval;
- }
- @Override
- public void onConfigurationChanged(Configuration newConfig) {
- super.onConfigurationChanged(newConfig);
- int rotation = getWindowManager().getDefaultDisplay().getRotation();
- // Checks the orientation of the screen
- if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE && (rotation == Surface.ROTATION_0
- || rotation == Surface.ROTATION_90)) {
- playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FILL);
- } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT && (rotation == Surface.ROTATION_0
- || rotation == Surface.ROTATION_90)){
- playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT);
- } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE && (rotation == Surface.ROTATION_180
- || rotation == Surface.ROTATION_270) ) {
- playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FILL);
- }else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT && (rotation == Surface.ROTATION_180
- || rotation == Surface.ROTATION_270)){
- playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT);
- }
- }
- @Override
- public void onWindowFocusChanged(boolean hasFocus) {
- super.onWindowFocusChanged(hasFocus);
- if (hasFocus) {
- //getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
- getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
- }
- }
- @Override
- public void onNewIntent(Intent intent) {
- releasePlayer();
- shouldAutoPlay = true;
- clearResumePosition();
- setIntent(intent);
- }
- @Override
- public void onStart() {
- super.onStart();
- if (Util.SDK_INT > 23) {
- initializePlayer();
- }
- }
- @Override
- public void onResume() {
- super.onResume();
- if (Util.SDK_INT <= 23 || player == null) {
- initializePlayer();
- }
- }
- @Override
- public void onPause() {
- super.onPause();
- if (Util.SDK_INT <= 23) {
- releasePlayer();
- }
- }
- @Override
- public void onStop() {
- super.onStop();
- if (Util.SDK_INT > 23) {
- releasePlayer();
- }
- }
- @Override
- public void onDestroy() {
- super.onDestroy();
- releaseAdsLoader();
- }
- // Activity input
- @Override
- public boolean dispatchKeyEvent(KeyEvent event) {
- // See whether the player view wants to handle media or DPAD keys events.
- return playerView.dispatchKeyEvent(event) || super.dispatchKeyEvent(event);
- }
- // OnClickListener methods
- // PlaybackControlView.PlaybackPreparer implementation
- @Override
- public void preparePlayback() {
- initializePlayer();
- }
- // PlaybackControlView.VisibilityListener implementation
- @Override
- public void onVisibilityChange(int visibility) {
- // debugRootView.setVisibility(visibility);
- }
- // Internal methods
- private void initializePlayer() {
- Intent intent = getIntent();
- boolean needNewPlayer = player == null;
- if (needNewPlayer) {
- TrackSelection.Factory adaptiveTrackSelectionFactory =
- new AdaptiveTrackSelection.Factory(BANDWIDTH_METER);
- trackSelector = new DefaultTrackSelector(adaptiveTrackSelectionFactory);
- lastSeenTrackGroupArray = null;
- eventLogger = new EventLogger(trackSelector);
- DrmSessionManager<FrameworkMediaCrypto> drmSessionManager = null;
- if (intent.hasExtra(DRM_SCHEME_EXTRA) || intent.hasExtra(DRM_SCHEME_UUID_EXTRA)) {
- String drmLicenseUrl = intent.getStringExtra(DRM_LICENSE_URL);
- String[] keyRequestPropertiesArray = intent.getStringArrayExtra(DRM_KEY_REQUEST_PROPERTIES);
- boolean multiSession = intent.getBooleanExtra(DRM_MULTI_SESSION, false);
- int errorStringId = R.string.error_drm_unknown;
- if (Util.SDK_INT < 18) {
- errorStringId = R.string.error_drm_not_supported;
- } else {
- try {
- String drmSchemeExtra = intent.hasExtra(DRM_SCHEME_EXTRA) ? DRM_SCHEME_EXTRA
- : DRM_SCHEME_UUID_EXTRA;
- UUID drmSchemeUuid = Util.getDrmUuid(intent.getStringExtra(drmSchemeExtra));
- if (drmSchemeUuid == null) {
- errorStringId = R.string.error_drm_unsupported_scheme;
- } else {
- drmSessionManager =
- buildDrmSessionManagerV18(
- drmSchemeUuid, drmLicenseUrl, keyRequestPropertiesArray, multiSession);
- }
- } catch (UnsupportedDrmException e) {
- errorStringId = e.reason == UnsupportedDrmException.REASON_UNSUPPORTED_SCHEME
- ? R.string.error_drm_unsupported_scheme : R.string.error_drm_unknown;
- }
- }
- if (drmSessionManager == null) {
- showToast(errorStringId);
- return;
- }
- }
- boolean preferExtensionDecoders = intent.getBooleanExtra(PREFER_EXTENSION_DECODERS, false);
- @DefaultRenderersFactory.ExtensionRendererMode int extensionRendererMode =
- ((AppController) getApplication()).useExtensionRenderers()
- ? (preferExtensionDecoders ? DefaultRenderersFactory.EXTENSION_RENDERER_MODE_PREFER
- : DefaultRenderersFactory.EXTENSION_RENDERER_MODE_ON)
- : DefaultRenderersFactory.EXTENSION_RENDERER_MODE_OFF;
- DefaultRenderersFactory renderersFactory = new DefaultRenderersFactory(this,
- drmSessionManager, extensionRendererMode);
- player = ExoPlayerFactory.newSimpleInstance(renderersFactory, trackSelector);
- player.addListener(new PlayerEventListener());
- player.addListener(eventLogger);
- player.addMetadataOutput(eventLogger);
- player.addAudioDebugListener(eventLogger);
- player.addVideoDebugListener(eventLogger);
- player.setPlayWhenReady(shouldAutoPlay);
- playerView.setPlayer(player);
- playerView.setPlaybackPreparer(this);
- }
- // Uri url = this.getIntent().getData();
- // String VIDEO_URI = url.toString();
- try {
- String VIDEO_URI = "http://142.93.218.69:8081/test/anik/playlist.m3u8";
- String finalURL = null;
- finalURL = getFinalURL(VIDEO_URI, clientIP, password);
- Uri uri = Uri.parse(finalURL);
- Log.d("FINAL_URL",finalURL);
- if (Util.maybeRequestReadExternalStoragePermission(this, uri)) {
- // The player will be reinitialized if the permission is granted.
- return;
- }
- //
- MediaSource mediaSource= new HlsMediaSource(uri,mediaDataSourceFactory,mainHandler,eventLogger);
- //MediaSource mediaSource = buildMediaSource(uri,null, mainHandler, eventLogger);
- String adTagUriString = intent.getStringExtra(AD_TAG_URI_EXTRA);
- if (adTagUriString != null) {
- Uri adTagUri = Uri.parse(adTagUriString);
- if (!adTagUri.equals(loadedAdTagUri)) {
- releaseAdsLoader();
- loadedAdTagUri = adTagUri;
- }
- MediaSource adsMediaSource = createAdsMediaSource(mediaSource, Uri.parse(adTagUriString));
- if (adsMediaSource != null) {
- mediaSource = adsMediaSource;
- } else {
- showToast(R.string.ima_not_loaded);
- }
- } else {
- releaseAdsLoader();
- }
- boolean haveResumePosition = resumeWindow != C.INDEX_UNSET;
- if (haveResumePosition) {
- player.seekTo(resumeWindow, resumePosition);
- }
- player.prepare(mediaSource, !haveResumePosition, false);
- inErrorState = false;
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- Toast.makeText(this, "Error" + e.getMessage(), Toast.LENGTH_SHORT).show();
- }
- //Toast.makeText(this, ""+VIDEO_URI, Toast.LENGTH_SHORT).show();
- //
- }
- private MediaSource buildMediaSource(
- Uri uri,
- String overrideExtension,
- @Nullable Handler handler,
- @Nullable MediaSourceEventListener listener) {
- @ContentType int type = TextUtils.isEmpty(overrideExtension) ? Util.inferContentType(uri)
- : Util.inferContentType("." + overrideExtension);
- switch (type) {
- default: {
- return new HlsMediaSource.Factory(mediaDataSourceFactory)
- .createMediaSource(uri, handler, listener);
- }
- }
- }
- private DrmSessionManager<FrameworkMediaCrypto> buildDrmSessionManagerV18(UUID uuid,
- String licenseUrl, String[] keyRequestPropertiesArray, boolean multiSession)
- throws UnsupportedDrmException {
- HttpMediaDrmCallback drmCallback = new HttpMediaDrmCallback(licenseUrl,
- buildHttpDataSourceFactory(false));
- if (keyRequestPropertiesArray != null) {
- for (int i = 0; i < keyRequestPropertiesArray.length - 1; i += 2) {
- drmCallback.setKeyRequestProperty(keyRequestPropertiesArray[i],
- keyRequestPropertiesArray[i + 1]);
- }
- }
- return new DefaultDrmSessionManager<>(uuid, FrameworkMediaDrm.newInstance(uuid), drmCallback,
- null, mainHandler, eventLogger, multiSession);
- }
- private void releasePlayer() {
- if (player != null) {
- //debugViewHelper.stop();
- debugViewHelper = null;
- shouldAutoPlay = player.getPlayWhenReady();
- updateResumePosition();
- player.release();
- player = null;
- eventLogger = null;
- }
- }
- private void updateResumePosition() {
- resumeWindow = player.getCurrentWindowIndex();
- resumePosition = Math.max(0, player.getContentPosition());
- }
- private void clearResumePosition() {
- resumeWindow = C.INDEX_UNSET;
- resumePosition = C.TIME_UNSET;
- }
- /**
- * Returns a new DataSource factory.
- *
- * @param useBandwidthMeter Whether to set {@link #BANDWIDTH_METER} as a listener to the new
- * DataSource factory.
- * @return A new DataSource factory.
- */
- private DataSource.Factory buildDataSourceFactory(boolean useBandwidthMeter) {
- return ((AppController) getApplication())
- .buildDataSourceFactory(useBandwidthMeter ? BANDWIDTH_METER : null);
- }
- /**
- * Returns a new HttpDataSource factory.
- *
- * @param useBandwidthMeter Whether to set {@link #BANDWIDTH_METER} as a listener to the new
- * DataSource factory.
- * @return A new HttpDataSource factory.
- */
- private HttpDataSource.Factory buildHttpDataSourceFactory(boolean useBandwidthMeter) {
- return ((AppController) getApplication())
- .buildHttpDataSourceFactory(useBandwidthMeter ? BANDWIDTH_METER : null);
- }
- /** Returns an ads media source, reusing the ads loader if one exists. */
- private @Nullable
- MediaSource createAdsMediaSource(MediaSource mediaSource, Uri adTagUri) {
- // Load the extension source using reflection so the demo app doesn't have to depend on it.
- // The ads loader is reused for multiple playbacks, so that ad playback can resume.
- try {
- Class<?> loaderClass = Class.forName("com.google.android.exoplayer2.ext.ima.ImaAdsLoader");
- if (adsLoader == null) {
- // Full class names used so the LINT.IfChange rule triggers should any of the classes move.
- // LINT.IfChange
- Constructor<? extends AdsLoader> loaderConstructor =
- loaderClass
- .asSubclass(AdsLoader.class)
- .getConstructor(android.content.Context.class, Uri.class);
- // LINT.ThenChange(../../../../../../../../proguard-rules.txt)
- adsLoader = loaderConstructor.newInstance(this, adTagUri);
- adUiViewGroup = new FrameLayout(this);
- // The demo app has a non-null overlay frame layout.
- playerView.getOverlayFrameLayout().addView(adUiViewGroup);
- }
- AdsMediaSource.MediaSourceFactory adMediaSourceFactory =
- new AdsMediaSource.MediaSourceFactory() {
- @Override
- public MediaSource createMediaSource(
- Uri uri, @Nullable Handler handler, @Nullable MediaSourceEventListener listener) {
- return PlayerActivity.this.buildMediaSource(
- uri, /* overrideExtension= */ null, handler, listener);
- }
- @Override
- public int[] getSupportedTypes() {
- return new int[] {C.TYPE_DASH, C.TYPE_SS, C.TYPE_HLS, C.TYPE_OTHER};
- }
- };
- return new AdsMediaSource(
- mediaSource, adMediaSourceFactory, adsLoader, adUiViewGroup, mainHandler, eventLogger);
- } catch (ClassNotFoundException e) {
- // IMA extension not loaded.
- return null;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- private void releaseAdsLoader() {
- if (adsLoader != null) {
- adsLoader.release();
- adsLoader = null;
- loadedAdTagUri = null;
- playerView.getOverlayFrameLayout().removeAllViews();
- }
- }
- // User controls
- private void showControls() {
- //debugRootView.setVisibility(View.VISIBLE);
- }
- private void showToast(int messageId) {
- showToast(getString(messageId));
- }
- private void showToast(String message) {
- Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
- }
- private static boolean isBehindLiveWindow(ExoPlaybackException e) {
- if (e.type != ExoPlaybackException.TYPE_SOURCE) {
- return false;
- }
- Throwable cause = e.getSourceException();
- while (cause != null) {
- if (cause instanceof BehindLiveWindowException) {
- return true;
- }
- cause = cause.getCause();
- }
- return false;
- }
- private class PlayerEventListener extends Player.DefaultEventListener {
- @Override
- public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
- if (playbackState == Player.STATE_ENDED) {
- showControls();
- }
- }
- @Override
- public void onPositionDiscontinuity(@Player.DiscontinuityReason int reason) {
- if (inErrorState) {
- // This will only occur if the user has performed a seek whilst in the error state. Update
- // the resume position so that if the user then retries, playback will resume from the
- // position to which they seeked.
- updateResumePosition();
- }
- }
- @Override
- public void onPlayerError(ExoPlaybackException e) {
- String errorString = null;
- if (e.type == ExoPlaybackException.TYPE_RENDERER) {
- Exception cause = e.getRendererException();
- if (cause instanceof DecoderInitializationException) {
- // Special case for decoder initialization failures.
- DecoderInitializationException decoderInitializationException =
- (DecoderInitializationException) cause;
- if (decoderInitializationException.decoderName == null) {
- if (decoderInitializationException.getCause() instanceof DecoderQueryException) {
- errorString = getString(R.string.error_querying_decoders);
- } else if (decoderInitializationException.secureDecoderRequired) {
- errorString = getString(R.string.error_no_secure_decoder,
- decoderInitializationException.mimeType);
- } else {
- errorString = getString(R.string.error_no_decoder,
- decoderInitializationException.mimeType);
- }
- } else {
- errorString = getString(R.string.error_instantiating_decoder,
- decoderInitializationException.decoderName);
- }
- }
- }
- if (errorString != null) {
- showToast(errorString);
- }
- inErrorState = true;
- if (isBehindLiveWindow(e)) {
- clearResumePosition();
- initializePlayer();
- } else {
- showControls();
- }
- }
- @Override
- @SuppressWarnings("ReferenceEquality")
- public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
- if (trackGroups != lastSeenTrackGroupArray) {
- MappedTrackInfo mappedTrackInfo = trackSelector.getCurrentMappedTrackInfo();
- if (mappedTrackInfo != null) {
- if (mappedTrackInfo.getTrackTypeRendererSupport(C.TRACK_TYPE_VIDEO)
- == MappedTrackInfo.RENDERER_SUPPORT_UNSUPPORTED_TRACKS) {
- showToast(R.string.error_unsupported_video);
- }
- if (mappedTrackInfo.getTrackTypeRendererSupport(C.TRACK_TYPE_AUDIO)
- == MappedTrackInfo.RENDERER_SUPPORT_UNSUPPORTED_TRACKS) {
- showToast(R.string.error_unsupported_audio);
- }
- }
- lastSeenTrackGroupArray = trackGroups;
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment