Guest User

Untitled

a guest
Jan 19th, 2019
326
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 33.33 KB | None | 0 0
  1. /*
  2. * Copyright (C) 2016 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package tech.iotait.tsetexoplayer;
  17.  
  18. import android.app.Activity;
  19. import android.content.Intent;
  20. import android.content.pm.ActivityInfo;
  21. import android.content.res.Configuration;
  22. import android.net.Uri;
  23. import android.net.wifi.WifiManager;
  24. import android.os.Bundle;
  25. import android.os.Handler;
  26. import android.support.annotation.Nullable;
  27. import android.text.TextUtils;
  28. import android.text.format.Formatter;
  29. import android.util.Log;
  30. import android.view.KeyEvent;
  31. import android.view.Surface;
  32. import android.view.View;
  33. import android.view.View.OnClickListener;
  34. import android.view.ViewGroup;
  35. import android.view.Window;
  36. import android.view.WindowManager;
  37. import android.widget.FrameLayout;
  38. import android.widget.ImageButton;
  39. import android.widget.LinearLayout;
  40. import android.widget.SeekBar;
  41. import android.widget.Toast;
  42.  
  43. import com.google.android.exoplayer2.C;
  44. import com.google.android.exoplayer2.C.ContentType;
  45. import com.google.android.exoplayer2.DefaultRenderersFactory;
  46. import com.google.android.exoplayer2.ExoPlaybackException;
  47. import com.google.android.exoplayer2.ExoPlayerFactory;
  48. import com.google.android.exoplayer2.PlaybackPreparer;
  49. import com.google.android.exoplayer2.Player;
  50. import com.google.android.exoplayer2.SimpleExoPlayer;
  51. import com.google.android.exoplayer2.drm.DefaultDrmSessionManager;
  52. import com.google.android.exoplayer2.drm.DrmSessionManager;
  53. import com.google.android.exoplayer2.drm.FrameworkMediaCrypto;
  54. import com.google.android.exoplayer2.drm.FrameworkMediaDrm;
  55. import com.google.android.exoplayer2.drm.HttpMediaDrmCallback;
  56. import com.google.android.exoplayer2.drm.UnsupportedDrmException;
  57. import com.google.android.exoplayer2.ext.okhttp.OkHttpDataSourceFactory;
  58. import com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.DecoderInitializationException;
  59. import com.google.android.exoplayer2.mediacodec.MediaCodecUtil.DecoderQueryException;
  60. import com.google.android.exoplayer2.source.BehindLiveWindowException;
  61. import com.google.android.exoplayer2.source.MediaSource;
  62. import com.google.android.exoplayer2.source.MediaSourceEventListener;
  63. import com.google.android.exoplayer2.source.TrackGroupArray;
  64. import com.google.android.exoplayer2.source.ads.AdsLoader;
  65. import com.google.android.exoplayer2.source.ads.AdsMediaSource;
  66. import com.google.android.exoplayer2.source.hls.HlsMediaSource;
  67. import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
  68. import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
  69. import com.google.android.exoplayer2.trackselection.MappingTrackSelector.MappedTrackInfo;
  70. import com.google.android.exoplayer2.trackselection.TrackSelection;
  71. import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
  72. import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
  73. import com.google.android.exoplayer2.ui.DebugTextViewHelper;
  74. import com.google.android.exoplayer2.ui.PlayerControlView;
  75. import com.google.android.exoplayer2.ui.PlayerView;
  76. import com.google.android.exoplayer2.upstream.DataSource;
  77. import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
  78. import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
  79. import com.google.android.exoplayer2.upstream.HttpDataSource;
  80. import com.google.android.exoplayer2.util.EventLogger;
  81. import com.google.android.exoplayer2.util.Util;
  82.  
  83. import java.io.BufferedReader;
  84. import java.io.IOException;
  85. import java.io.InputStreamReader;
  86. import java.lang.reflect.Constructor;
  87. import java.net.CookieHandler;
  88. import java.net.CookieManager;
  89. import java.net.CookiePolicy;
  90. import java.net.InetAddress;
  91. import java.net.NetworkInterface;
  92. import java.net.SocketException;
  93. import java.net.URL;
  94. import java.security.MessageDigest;
  95. import java.security.NoSuchAlgorithmException;
  96. import java.util.Enumeration;
  97. import java.util.UUID;
  98.  
  99. import okhttp3.CacheControl;
  100. import okhttp3.OkHttpClient;
  101.  
  102.  
  103. import org.apache.commons.codec.binary.Base64;
  104. import org.apache.commons.codec.digest.DigestUtils;
  105. import org.joda.time.DateTime;
  106. import org.joda.time.DateTimeZone;
  107. import org.joda.time.format.DateTimeFormat;
  108. import org.joda.time.format.DateTimeFormatter;
  109.  
  110. import java.io.UnsupportedEncodingException;
  111. import java.util.Locale;
  112.  
  113. import static android.content.ContentValues.TAG;
  114.  
  115. /** An activity that plays media using {@link SimpleExoPlayer}. */
  116. public class PlayerActivity extends Activity implements PlaybackPreparer, PlayerControlView.VisibilityListener {
  117.  
  118. public static final String DRM_SCHEME_EXTRA = "drm_scheme";
  119. public static final String DRM_LICENSE_URL = "drm_license_url";
  120. public static final String DRM_KEY_REQUEST_PROPERTIES = "drm_key_request_properties";
  121. public static final String DRM_MULTI_SESSION = "drm_multi_session";
  122. public static final String PREFER_EXTENSION_DECODERS = "prefer_extension_decoders";
  123.  
  124. public static final String AD_TAG_URI_EXTRA = "ad_tag_uri";
  125.  
  126. // For backwards compatibility.
  127. private static final String DRM_SCHEME_UUID_EXTRA = "drm_scheme_uuid";
  128.  
  129. private static final DefaultBandwidthMeter BANDWIDTH_METER = new DefaultBandwidthMeter();
  130. private static final CookieManager DEFAULT_COOKIE_MANAGER;
  131.  
  132. static {
  133.  
  134. DEFAULT_COOKIE_MANAGER = new CookieManager();
  135. DEFAULT_COOKIE_MANAGER.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
  136.  
  137. }
  138.  
  139. private Handler mainHandler;
  140. private EventLogger eventLogger;
  141. private PlayerView playerView;
  142. private LinearLayout debugRootView;
  143.  
  144. private DataSource.Factory mediaDataSourceFactory;
  145. private SimpleExoPlayer player;
  146. private DefaultTrackSelector trackSelector;
  147. private DebugTextViewHelper debugViewHelper;
  148. private boolean inErrorState;
  149. private TrackGroupArray lastSeenTrackGroupArray;
  150.  
  151. private boolean shouldAutoPlay;
  152. private int resumeWindow;
  153. private long resumePosition;
  154.  
  155. // Fields used only for ad playback. The ads loader is loaded via reflection.
  156.  
  157. private AdsLoader adsLoader;
  158. private Uri loadedAdTagUri;
  159. private ViewGroup adUiViewGroup;
  160. SeekBar seekBar;
  161.  
  162.  
  163. String clientIP = ""; // generate User IP;
  164. String password = "123z123z"; // further improvement planned on this
  165.  
  166. // Activity lifecycle
  167.  
  168. @Override
  169. public void onCreate(Bundle savedInstanceState) {
  170.  
  171.  
  172. requestWindowFeature(Window.FEATURE_NO_TITLE);
  173. getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  174. super.onCreate(savedInstanceState);
  175.  
  176. getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
  177. shouldAutoPlay = true;
  178. clearResumePosition();
  179.  
  180. String userAgent1 = "";
  181. String urltest1 = "http://142.93.218.69:8081/test/anik/playlist.m3u8";
  182.  
  183. WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
  184. String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
  185.  
  186. clientIP = "103.113.152.106";
  187.  
  188.  
  189. if (urltest1.contains("okaystreamz.tk")) {
  190. userAgent1 = "tvingoplus@livetv.tvingo1Z!2018";
  191.  
  192. }else if (urltest1.contains("hoichoi")) {
  193. userAgent1 = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"; }
  194. else{
  195. userAgent1 = "IOTAIT";
  196. }
  197.  
  198. mediaDataSourceFactory = new DefaultDataSourceFactory(this, BANDWIDTH_METER,
  199. new OkHttpDataSourceFactory(new OkHttpClient.Builder().build(),
  200. userAgent1,
  201. BANDWIDTH_METER, CacheControl.FORCE_NETWORK));
  202.  
  203. mainHandler = new Handler();
  204. final View decorView = getWindow().getDecorView();
  205. decorView.setOnSystemUiVisibilityChangeListener(
  206. new View.OnSystemUiVisibilityChangeListener() {
  207. @Override
  208. public void onSystemUiVisibilityChange(int visibility) {
  209. getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
  210. getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
  211. getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
  212.  
  213. }
  214. }
  215. );
  216.  
  217. if (CookieHandler.getDefault() != DEFAULT_COOKIE_MANAGER) {
  218. CookieHandler.setDefault(DEFAULT_COOKIE_MANAGER);
  219. }
  220. setContentView(R.layout.player_activity);
  221.  
  222.  
  223.  
  224. final ImageButton buttonSetLandscape = (ImageButton)this.findViewById(R.id.setLandscape);
  225. final ImageButton buttonSetPortrait = (ImageButton)findViewById(R.id.setPortrait);
  226.  
  227. buttonSetLandscape.setOnClickListener(new OnClickListener(){
  228.  
  229. @Override
  230. public void onClick(View v) {
  231. // TODO Auto-generated method stub
  232. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
  233. buttonSetLandscape.setVisibility(View.GONE);
  234. buttonSetPortrait.setVisibility(View.VISIBLE);
  235. playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FILL);
  236.  
  237. }});
  238.  
  239. buttonSetPortrait.setOnClickListener(new OnClickListener(){
  240. @Override
  241. public void onClick(View arg0) {
  242. // TODO Auto-generated method stub
  243. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
  244. buttonSetPortrait.setVisibility(View.GONE);
  245. buttonSetLandscape.setVisibility(View.VISIBLE);
  246. playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT);
  247.  
  248. }});
  249.  
  250. seekBar = findViewById(R.id.volumeseekbar);
  251.  
  252. seekBar.setMax(100);
  253. seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
  254. {
  255. @Override
  256. public void onProgressChanged(final SeekBar seekBar, final int progress, final boolean fromUser)
  257. {
  258. final float adjust = (float) progress / 100;
  259. Log.d(TAG, "Volume: " + adjust);
  260. player.setVolume(adjust);
  261. }
  262.  
  263. @Override
  264. public void onStartTrackingTouch(final SeekBar seekBar)
  265. {
  266. }
  267.  
  268. @Override
  269. public void onStopTrackingTouch(final SeekBar seekBar)
  270. {
  271. }
  272. });
  273.  
  274. playerView = findViewById(R.id.player_view);
  275. playerView.setControllerVisibilityListener(this);
  276. playerView.requestFocus();
  277.  
  278.  
  279. int orientation = getResources().getConfiguration().orientation;
  280. int rotation = getWindowManager().getDefaultDisplay().getRotation();
  281. int actual_orientation = -1;
  282. if (orientation == Configuration.ORIENTATION_LANDSCAPE
  283. && (rotation == Surface.ROTATION_0
  284. || rotation == Surface.ROTATION_90)){
  285. orientation = 1;
  286. } else if (orientation == Configuration.ORIENTATION_PORTRAIT
  287. && (rotation == Surface.ROTATION_0
  288. || rotation == Surface.ROTATION_90)) {
  289. orientation = 2;
  290. } else if (orientation == Configuration.ORIENTATION_LANDSCAPE
  291. && (rotation == Surface.ROTATION_180
  292. || rotation == Surface.ROTATION_270)){
  293. orientation = 3;//any constant for reverse landscape orientation;
  294. } else {
  295. if (orientation == Configuration.ORIENTATION_PORTRAIT
  296. && (rotation == Surface.ROTATION_180
  297. || rotation == Surface.ROTATION_270)){
  298. orientation = 4;//any constant for reverse portrait orientation;
  299. }
  300. }
  301. if (orientation == 1 || orientation == 3) {
  302. playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FILL);
  303. }else if(orientation == 2 || orientation == 4) {
  304. playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT);
  305. }
  306.  
  307. }
  308.  
  309. public String getExternalIpAddress() throws Exception {
  310. URL whatismyip = new URL("http://checkip.amazonaws.com");
  311. BufferedReader in = null;
  312. try {
  313. in = new BufferedReader(new InputStreamReader(
  314. whatismyip.openStream()));
  315. String ip = in.readLine();
  316. return ip;
  317. } finally {
  318. if (in != null) {
  319. try {
  320. in.close();
  321. } catch (IOException e) {
  322. e.printStackTrace();
  323. }
  324. }
  325. }
  326. }
  327.  
  328.  
  329.  
  330. // This method requires no change.
  331. public static String getFinalURL(String urlofStream, String clientIP, String password) throws UnsupportedEncodingException
  332. {
  333.  
  334. DateTimeFormatter timeFormatter = DateTimeFormat.forPattern("M/d/y h:m:s a").withZone(DateTimeZone.UTC).withLocale(Locale.US);
  335. DateTime currentServerTime = new DateTime(DateTimeZone.UTC); // lets get localtime in UTC timezone
  336. String today = timeFormatter.print(currentServerTime);
  337. String video_url = urlofStream;
  338. String ip = clientIP;
  339. String key = password;
  340. String validminutes = "20";
  341. String to_hash = ip + key + today + validminutes;
  342. byte[] ascii_to_hash = to_hash.getBytes("UTF-8");
  343. String base64hash = new String(Base64.encodeBase64(ascii_to_hash));
  344. String urlsignature = "server_time=" + today + "&hash_value=" + base64hash + "&validminutes=" + validminutes;
  345. String base64urlsignature = new String(Base64.encodeBase64(urlsignature.getBytes("UTF-8")));
  346. String signedurlwithvalidinterval = video_url + "?wmsAuthSign=" + base64urlsignature;
  347.  
  348. return signedurlwithvalidinterval;
  349.  
  350. }
  351.  
  352. @Override
  353. public void onConfigurationChanged(Configuration newConfig) {
  354. super.onConfigurationChanged(newConfig);
  355. int rotation = getWindowManager().getDefaultDisplay().getRotation();
  356. // Checks the orientation of the screen
  357. if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE && (rotation == Surface.ROTATION_0
  358. || rotation == Surface.ROTATION_90)) {
  359. playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FILL);
  360. } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT && (rotation == Surface.ROTATION_0
  361. || rotation == Surface.ROTATION_90)){
  362. playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT);
  363. } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE && (rotation == Surface.ROTATION_180
  364. || rotation == Surface.ROTATION_270) ) {
  365. playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FILL);
  366. }else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT && (rotation == Surface.ROTATION_180
  367. || rotation == Surface.ROTATION_270)){
  368. playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT);
  369. }
  370. }
  371.  
  372. @Override
  373. public void onWindowFocusChanged(boolean hasFocus) {
  374. super.onWindowFocusChanged(hasFocus);
  375. if (hasFocus) {
  376. //getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
  377. getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
  378. getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
  379.  
  380. }
  381. }
  382.  
  383.  
  384. @Override
  385. public void onNewIntent(Intent intent) {
  386. releasePlayer();
  387. shouldAutoPlay = true;
  388. clearResumePosition();
  389. setIntent(intent);
  390. }
  391.  
  392. @Override
  393. public void onStart() {
  394. super.onStart();
  395. if (Util.SDK_INT > 23) {
  396. initializePlayer();
  397. }
  398. }
  399.  
  400. @Override
  401. public void onResume() {
  402. super.onResume();
  403. if (Util.SDK_INT <= 23 || player == null) {
  404. initializePlayer();
  405. }
  406. }
  407.  
  408. @Override
  409. public void onPause() {
  410. super.onPause();
  411. if (Util.SDK_INT <= 23) {
  412. releasePlayer();
  413. }
  414. }
  415.  
  416. @Override
  417. public void onStop() {
  418. super.onStop();
  419. if (Util.SDK_INT > 23) {
  420. releasePlayer();
  421. }
  422. }
  423.  
  424. @Override
  425. public void onDestroy() {
  426. super.onDestroy();
  427. releaseAdsLoader();
  428. }
  429.  
  430. // Activity input
  431.  
  432. @Override
  433. public boolean dispatchKeyEvent(KeyEvent event) {
  434. // See whether the player view wants to handle media or DPAD keys events.
  435. return playerView.dispatchKeyEvent(event) || super.dispatchKeyEvent(event);
  436. }
  437.  
  438. // OnClickListener methods
  439.  
  440. // PlaybackControlView.PlaybackPreparer implementation
  441.  
  442. @Override
  443. public void preparePlayback() {
  444. initializePlayer();
  445. }
  446.  
  447. // PlaybackControlView.VisibilityListener implementation
  448.  
  449. @Override
  450. public void onVisibilityChange(int visibility) {
  451. // debugRootView.setVisibility(visibility);
  452. }
  453.  
  454. // Internal methods
  455.  
  456. private void initializePlayer() {
  457. Intent intent = getIntent();
  458. boolean needNewPlayer = player == null;
  459. if (needNewPlayer) {
  460. TrackSelection.Factory adaptiveTrackSelectionFactory =
  461. new AdaptiveTrackSelection.Factory(BANDWIDTH_METER);
  462. trackSelector = new DefaultTrackSelector(adaptiveTrackSelectionFactory);
  463. lastSeenTrackGroupArray = null;
  464. eventLogger = new EventLogger(trackSelector);
  465.  
  466. DrmSessionManager<FrameworkMediaCrypto> drmSessionManager = null;
  467. if (intent.hasExtra(DRM_SCHEME_EXTRA) || intent.hasExtra(DRM_SCHEME_UUID_EXTRA)) {
  468. String drmLicenseUrl = intent.getStringExtra(DRM_LICENSE_URL);
  469. String[] keyRequestPropertiesArray = intent.getStringArrayExtra(DRM_KEY_REQUEST_PROPERTIES);
  470. boolean multiSession = intent.getBooleanExtra(DRM_MULTI_SESSION, false);
  471. int errorStringId = R.string.error_drm_unknown;
  472. if (Util.SDK_INT < 18) {
  473. errorStringId = R.string.error_drm_not_supported;
  474. } else {
  475. try {
  476. String drmSchemeExtra = intent.hasExtra(DRM_SCHEME_EXTRA) ? DRM_SCHEME_EXTRA
  477. : DRM_SCHEME_UUID_EXTRA;
  478. UUID drmSchemeUuid = Util.getDrmUuid(intent.getStringExtra(drmSchemeExtra));
  479. if (drmSchemeUuid == null) {
  480. errorStringId = R.string.error_drm_unsupported_scheme;
  481. } else {
  482. drmSessionManager =
  483. buildDrmSessionManagerV18(
  484. drmSchemeUuid, drmLicenseUrl, keyRequestPropertiesArray, multiSession);
  485. }
  486. } catch (UnsupportedDrmException e) {
  487. errorStringId = e.reason == UnsupportedDrmException.REASON_UNSUPPORTED_SCHEME
  488. ? R.string.error_drm_unsupported_scheme : R.string.error_drm_unknown;
  489. }
  490. }
  491. if (drmSessionManager == null) {
  492. showToast(errorStringId);
  493. return;
  494. }
  495. }
  496.  
  497. boolean preferExtensionDecoders = intent.getBooleanExtra(PREFER_EXTENSION_DECODERS, false);
  498. @DefaultRenderersFactory.ExtensionRendererMode int extensionRendererMode =
  499. ((AppController) getApplication()).useExtensionRenderers()
  500. ? (preferExtensionDecoders ? DefaultRenderersFactory.EXTENSION_RENDERER_MODE_PREFER
  501. : DefaultRenderersFactory.EXTENSION_RENDERER_MODE_ON)
  502. : DefaultRenderersFactory.EXTENSION_RENDERER_MODE_OFF;
  503. DefaultRenderersFactory renderersFactory = new DefaultRenderersFactory(this,
  504. drmSessionManager, extensionRendererMode);
  505.  
  506. player = ExoPlayerFactory.newSimpleInstance(renderersFactory, trackSelector);
  507. player.addListener(new PlayerEventListener());
  508. player.addListener(eventLogger);
  509. player.addMetadataOutput(eventLogger);
  510. player.addAudioDebugListener(eventLogger);
  511. player.addVideoDebugListener(eventLogger);
  512. player.setPlayWhenReady(shouldAutoPlay);
  513.  
  514.  
  515.  
  516. playerView.setPlayer(player);
  517. playerView.setPlaybackPreparer(this);
  518. }
  519.  
  520.  
  521.  
  522.  
  523.  
  524.  
  525.  
  526. // Uri url = this.getIntent().getData();
  527. // String VIDEO_URI = url.toString();
  528.  
  529. try {
  530. String VIDEO_URI = "http://142.93.218.69:8081/test/anik/playlist.m3u8";
  531. String finalURL = null;
  532. finalURL = getFinalURL(VIDEO_URI, clientIP, password);
  533. Uri uri = Uri.parse(finalURL);
  534. Log.d("FINAL_URL",finalURL);
  535. if (Util.maybeRequestReadExternalStoragePermission(this, uri)) {
  536. // The player will be reinitialized if the permission is granted.
  537. return;
  538. }
  539. //
  540.  
  541. MediaSource mediaSource= new HlsMediaSource(uri,mediaDataSourceFactory,mainHandler,eventLogger);
  542.  
  543. //MediaSource mediaSource = buildMediaSource(uri,null, mainHandler, eventLogger);
  544. String adTagUriString = intent.getStringExtra(AD_TAG_URI_EXTRA);
  545. if (adTagUriString != null) {
  546. Uri adTagUri = Uri.parse(adTagUriString);
  547. if (!adTagUri.equals(loadedAdTagUri)) {
  548. releaseAdsLoader();
  549. loadedAdTagUri = adTagUri;
  550. }
  551. MediaSource adsMediaSource = createAdsMediaSource(mediaSource, Uri.parse(adTagUriString));
  552. if (adsMediaSource != null) {
  553. mediaSource = adsMediaSource;
  554. } else {
  555. showToast(R.string.ima_not_loaded);
  556. }
  557. } else {
  558. releaseAdsLoader();
  559. }
  560. boolean haveResumePosition = resumeWindow != C.INDEX_UNSET;
  561. if (haveResumePosition) {
  562. player.seekTo(resumeWindow, resumePosition);
  563. }
  564. player.prepare(mediaSource, !haveResumePosition, false);
  565. inErrorState = false;
  566. } catch (UnsupportedEncodingException e) {
  567. e.printStackTrace();
  568. Toast.makeText(this, "Error" + e.getMessage(), Toast.LENGTH_SHORT).show();
  569. }
  570. //Toast.makeText(this, ""+VIDEO_URI, Toast.LENGTH_SHORT).show();
  571.  
  572.  
  573.  
  574.  
  575.  
  576.  
  577.  
  578.  
  579.  
  580. //
  581.  
  582. }
  583.  
  584. private MediaSource buildMediaSource(
  585. Uri uri,
  586.  
  587. String overrideExtension,
  588. @Nullable Handler handler,
  589. @Nullable MediaSourceEventListener listener) {
  590. @ContentType int type = TextUtils.isEmpty(overrideExtension) ? Util.inferContentType(uri)
  591. : Util.inferContentType("." + overrideExtension);
  592. switch (type) {
  593.  
  594. default: {
  595. return new HlsMediaSource.Factory(mediaDataSourceFactory)
  596. .createMediaSource(uri, handler, listener);
  597. }
  598. }
  599. }
  600.  
  601. private DrmSessionManager<FrameworkMediaCrypto> buildDrmSessionManagerV18(UUID uuid,
  602. String licenseUrl, String[] keyRequestPropertiesArray, boolean multiSession)
  603. throws UnsupportedDrmException {
  604. HttpMediaDrmCallback drmCallback = new HttpMediaDrmCallback(licenseUrl,
  605. buildHttpDataSourceFactory(false));
  606. if (keyRequestPropertiesArray != null) {
  607. for (int i = 0; i < keyRequestPropertiesArray.length - 1; i += 2) {
  608. drmCallback.setKeyRequestProperty(keyRequestPropertiesArray[i],
  609. keyRequestPropertiesArray[i + 1]);
  610. }
  611. }
  612. return new DefaultDrmSessionManager<>(uuid, FrameworkMediaDrm.newInstance(uuid), drmCallback,
  613. null, mainHandler, eventLogger, multiSession);
  614. }
  615.  
  616. private void releasePlayer() {
  617. if (player != null) {
  618. //debugViewHelper.stop();
  619. debugViewHelper = null;
  620. shouldAutoPlay = player.getPlayWhenReady();
  621. updateResumePosition();
  622. player.release();
  623. player = null;
  624. eventLogger = null;
  625. }
  626. }
  627.  
  628. private void updateResumePosition() {
  629. resumeWindow = player.getCurrentWindowIndex();
  630. resumePosition = Math.max(0, player.getContentPosition());
  631. }
  632.  
  633. private void clearResumePosition() {
  634. resumeWindow = C.INDEX_UNSET;
  635. resumePosition = C.TIME_UNSET;
  636. }
  637.  
  638. /**
  639. * Returns a new DataSource factory.
  640. *
  641. * @param useBandwidthMeter Whether to set {@link #BANDWIDTH_METER} as a listener to the new
  642. * DataSource factory.
  643. * @return A new DataSource factory.
  644. */
  645. private DataSource.Factory buildDataSourceFactory(boolean useBandwidthMeter) {
  646. return ((AppController) getApplication())
  647. .buildDataSourceFactory(useBandwidthMeter ? BANDWIDTH_METER : null);
  648. }
  649.  
  650. /**
  651. * Returns a new HttpDataSource factory.
  652. *
  653. * @param useBandwidthMeter Whether to set {@link #BANDWIDTH_METER} as a listener to the new
  654. * DataSource factory.
  655. * @return A new HttpDataSource factory.
  656. */
  657. private HttpDataSource.Factory buildHttpDataSourceFactory(boolean useBandwidthMeter) {
  658. return ((AppController) getApplication())
  659. .buildHttpDataSourceFactory(useBandwidthMeter ? BANDWIDTH_METER : null);
  660. }
  661.  
  662. /** Returns an ads media source, reusing the ads loader if one exists. */
  663. private @Nullable
  664. MediaSource createAdsMediaSource(MediaSource mediaSource, Uri adTagUri) {
  665. // Load the extension source using reflection so the demo app doesn't have to depend on it.
  666. // The ads loader is reused for multiple playbacks, so that ad playback can resume.
  667. try {
  668. Class<?> loaderClass = Class.forName("com.google.android.exoplayer2.ext.ima.ImaAdsLoader");
  669. if (adsLoader == null) {
  670. // Full class names used so the LINT.IfChange rule triggers should any of the classes move.
  671. // LINT.IfChange
  672. Constructor<? extends AdsLoader> loaderConstructor =
  673. loaderClass
  674. .asSubclass(AdsLoader.class)
  675. .getConstructor(android.content.Context.class, Uri.class);
  676. // LINT.ThenChange(../../../../../../../../proguard-rules.txt)
  677. adsLoader = loaderConstructor.newInstance(this, adTagUri);
  678. adUiViewGroup = new FrameLayout(this);
  679. // The demo app has a non-null overlay frame layout.
  680. playerView.getOverlayFrameLayout().addView(adUiViewGroup);
  681. }
  682. AdsMediaSource.MediaSourceFactory adMediaSourceFactory =
  683. new AdsMediaSource.MediaSourceFactory() {
  684. @Override
  685. public MediaSource createMediaSource(
  686. Uri uri, @Nullable Handler handler, @Nullable MediaSourceEventListener listener) {
  687. return PlayerActivity.this.buildMediaSource(
  688. uri, /* overrideExtension= */ null, handler, listener);
  689. }
  690.  
  691. @Override
  692. public int[] getSupportedTypes() {
  693. return new int[] {C.TYPE_DASH, C.TYPE_SS, C.TYPE_HLS, C.TYPE_OTHER};
  694. }
  695. };
  696. return new AdsMediaSource(
  697. mediaSource, adMediaSourceFactory, adsLoader, adUiViewGroup, mainHandler, eventLogger);
  698. } catch (ClassNotFoundException e) {
  699. // IMA extension not loaded.
  700. return null;
  701. } catch (Exception e) {
  702. throw new RuntimeException(e);
  703. }
  704. }
  705.  
  706. private void releaseAdsLoader() {
  707. if (adsLoader != null) {
  708. adsLoader.release();
  709. adsLoader = null;
  710. loadedAdTagUri = null;
  711. playerView.getOverlayFrameLayout().removeAllViews();
  712. }
  713. }
  714.  
  715. // User controls
  716.  
  717. private void showControls() {
  718. //debugRootView.setVisibility(View.VISIBLE);
  719. }
  720.  
  721. private void showToast(int messageId) {
  722. showToast(getString(messageId));
  723. }
  724.  
  725. private void showToast(String message) {
  726. Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
  727. }
  728.  
  729. private static boolean isBehindLiveWindow(ExoPlaybackException e) {
  730. if (e.type != ExoPlaybackException.TYPE_SOURCE) {
  731. return false;
  732. }
  733. Throwable cause = e.getSourceException();
  734. while (cause != null) {
  735. if (cause instanceof BehindLiveWindowException) {
  736. return true;
  737. }
  738. cause = cause.getCause();
  739. }
  740. return false;
  741. }
  742.  
  743. private class PlayerEventListener extends Player.DefaultEventListener {
  744.  
  745. @Override
  746. public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
  747.  
  748.  
  749. if (playbackState == Player.STATE_ENDED) {
  750. showControls();
  751. }
  752. }
  753.  
  754. @Override
  755. public void onPositionDiscontinuity(@Player.DiscontinuityReason int reason) {
  756. if (inErrorState) {
  757. // This will only occur if the user has performed a seek whilst in the error state. Update
  758. // the resume position so that if the user then retries, playback will resume from the
  759. // position to which they seeked.
  760. updateResumePosition();
  761. }
  762. }
  763.  
  764. @Override
  765. public void onPlayerError(ExoPlaybackException e) {
  766. String errorString = null;
  767. if (e.type == ExoPlaybackException.TYPE_RENDERER) {
  768. Exception cause = e.getRendererException();
  769. if (cause instanceof DecoderInitializationException) {
  770. // Special case for decoder initialization failures.
  771. DecoderInitializationException decoderInitializationException =
  772. (DecoderInitializationException) cause;
  773. if (decoderInitializationException.decoderName == null) {
  774. if (decoderInitializationException.getCause() instanceof DecoderQueryException) {
  775. errorString = getString(R.string.error_querying_decoders);
  776. } else if (decoderInitializationException.secureDecoderRequired) {
  777. errorString = getString(R.string.error_no_secure_decoder,
  778. decoderInitializationException.mimeType);
  779. } else {
  780. errorString = getString(R.string.error_no_decoder,
  781. decoderInitializationException.mimeType);
  782. }
  783. } else {
  784. errorString = getString(R.string.error_instantiating_decoder,
  785. decoderInitializationException.decoderName);
  786. }
  787. }
  788. }
  789. if (errorString != null) {
  790. showToast(errorString);
  791. }
  792. inErrorState = true;
  793. if (isBehindLiveWindow(e)) {
  794. clearResumePosition();
  795. initializePlayer();
  796. } else {
  797. showControls();
  798. }
  799. }
  800.  
  801. @Override
  802. @SuppressWarnings("ReferenceEquality")
  803. public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
  804. if (trackGroups != lastSeenTrackGroupArray) {
  805. MappedTrackInfo mappedTrackInfo = trackSelector.getCurrentMappedTrackInfo();
  806. if (mappedTrackInfo != null) {
  807. if (mappedTrackInfo.getTrackTypeRendererSupport(C.TRACK_TYPE_VIDEO)
  808. == MappedTrackInfo.RENDERER_SUPPORT_UNSUPPORTED_TRACKS) {
  809. showToast(R.string.error_unsupported_video);
  810. }
  811. if (mappedTrackInfo.getTrackTypeRendererSupport(C.TRACK_TYPE_AUDIO)
  812. == MappedTrackInfo.RENDERER_SUPPORT_UNSUPPORTED_TRACKS) {
  813. showToast(R.string.error_unsupported_audio);
  814. }
  815. }
  816. lastSeenTrackGroupArray = trackGroups;
  817. }
  818. }
  819.  
  820. }
  821.  
  822. }
Add Comment
Please, Sign In to add comment