Search in sources :

Example 41 with PlayerView

use of com.google.android.exoplayer2.ui.PlayerView in project Player by moneytoo.

the class PlayerActivity method onCreate.

@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onCreate(Bundle savedInstanceState) {
    // Rotate ASAP, before super/inflating to avoid glitches with activity launch animation
    mPrefs = new Prefs(this);
    Utils.setOrientation(this, mPrefs.orientation);
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT == 28 && Build.MANUFACTURER.equalsIgnoreCase("xiaomi") && (Build.DEVICE.equalsIgnoreCase("oneday") || Build.DEVICE.equalsIgnoreCase("once"))) {
        setContentView(R.layout.activity_player_textureview);
    } else {
        setContentView(R.layout.activity_player);
    }
    if (Build.VERSION.SDK_INT >= 31) {
        Window window = getWindow();
        if (window != null) {
            window.setDecorFitsSystemWindows(false);
            WindowInsetsController windowInsetsController = window.getInsetsController();
            if (windowInsetsController != null) {
                // On Android 12 BEHAVIOR_DEFAULT allows system gestures without visible system bars
                windowInsetsController.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_DEFAULT);
            }
        }
    }
    isTvBox = Utils.isTvBox(this);
    if (isTvBox) {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    }
    final Intent launchIntent = getIntent();
    final String action = launchIntent.getAction();
    final String type = launchIntent.getType();
    if ("com.brouken.player.action.SHORTCUT_VIDEOS".equals(action)) {
        openFile(Utils.getMoviesFolderUri());
    } else if (Intent.ACTION_SEND.equals(action) && "text/plain".equals(type)) {
        String text = launchIntent.getStringExtra(Intent.EXTRA_TEXT);
        if (text != null) {
            final Uri parsedUri = Uri.parse(text);
            if (parsedUri.isAbsolute()) {
                mPrefs.updateMedia(this, parsedUri, null);
                focusPlay = true;
            }
        }
    } else if (launchIntent.getData() != null) {
        resetApiAccess();
        final Uri uri = launchIntent.getData();
        if (SubtitleUtils.isSubtitle(uri, type)) {
            handleSubtitles(uri);
        } else {
            Bundle bundle = launchIntent.getExtras();
            if (bundle != null) {
                apiAccess = bundle.containsKey(API_POSITION) || bundle.containsKey(API_RETURN_RESULT) || bundle.containsKey(API_TITLE) || bundle.containsKey(API_SUBS) || bundle.containsKey(API_SUBS_ENABLE);
                if (apiAccess) {
                    mPrefs.setPersistent(false);
                }
                apiTitle = bundle.getString(API_TITLE);
            }
            mPrefs.updateMedia(this, uri, type);
            if (bundle != null) {
                Uri defaultSub = null;
                Parcelable[] subsEnable = bundle.getParcelableArray(API_SUBS_ENABLE);
                if (subsEnable != null && subsEnable.length > 0) {
                    defaultSub = (Uri) subsEnable[0];
                }
                Parcelable[] subs = bundle.getParcelableArray(API_SUBS);
                String[] subsName = bundle.getStringArray(API_SUBS_NAME);
                if (subs != null && subs.length > 0) {
                    for (int i = 0; i < subs.length; i++) {
                        Uri sub = (Uri) subs[i];
                        String name = null;
                        if (subsName != null && subsName.length > i) {
                            name = subsName[i];
                        }
                        apiSubs.add(SubtitleUtils.buildSubtitle(this, sub, name, sub.equals(defaultSub)));
                    }
                }
            }
            if (apiSubs.isEmpty()) {
                searchSubtitles();
            }
            if (bundle != null) {
                intentReturnResult = bundle.getBoolean(API_RETURN_RESULT);
                if (bundle.containsKey(API_POSITION)) {
                    mPrefs.updatePosition((long) bundle.getInt(API_POSITION));
                }
            }
        }
        focusPlay = true;
    }
    coordinatorLayout = findViewById(R.id.coordinatorLayout);
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    playerView = findViewById(R.id.video_view);
    exoPlayPause = findViewById(R.id.exo_play_pause);
    loadingProgressBar = findViewById(R.id.loading);
    playerView.setShowNextButton(false);
    playerView.setShowPreviousButton(false);
    playerView.setShowFastForwardButton(false);
    playerView.setShowRewindButton(false);
    playerView.setRepeatToggleModes(Player.REPEAT_MODE_ONE);
    playerView.setControllerHideOnTouch(false);
    playerView.setControllerAutoShow(true);
    ((DoubleTapPlayerView) playerView).setDoubleTapEnabled(false);
    timeBar = playerView.findViewById(R.id.exo_progress);
    timeBar.addListener(new TimeBar.OnScrubListener() {

        @Override
        public void onScrubStart(TimeBar timeBar, long position) {
            if (player == null) {
                return;
            }
            restorePlayState = player.isPlaying();
            if (restorePlayState) {
                player.pause();
            }
            lastScrubbingPosition = position;
            scrubbingNoticeable = false;
            isScrubbing = true;
            frameRendered = true;
            playerView.setControllerShowTimeoutMs(-1);
            scrubbingStart = player.getCurrentPosition();
            player.setSeekParameters(SeekParameters.CLOSEST_SYNC);
            reportScrubbing(position);
        }

        @Override
        public void onScrubMove(TimeBar timeBar, long position) {
            reportScrubbing(position);
            for (long start : chapterStarts) {
                if ((lastScrubbingPosition < start && position >= start) || (lastScrubbingPosition > start && position <= start)) {
                    playerView.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK);
                }
            }
            lastScrubbingPosition = position;
        }

        @Override
        public void onScrubStop(TimeBar timeBar, long position, boolean canceled) {
            playerView.setCustomErrorMessage(null);
            isScrubbing = false;
            if (restorePlayState) {
                restorePlayState = false;
                playerView.setControllerShowTimeoutMs(PlayerActivity.CONTROLLER_TIMEOUT);
                player.setPlayWhenReady(true);
            }
        }
    });
    buttonOpen = new ImageButton(this, null, 0, R.style.ExoStyledControls_Button_Bottom);
    buttonOpen.setImageResource(R.drawable.ic_folder_open_24dp);
    buttonOpen.setId(View.generateViewId());
    buttonOpen.setContentDescription(getString(R.string.button_open));
    buttonOpen.setOnClickListener(view -> openFile(mPrefs.mediaUri));
    buttonOpen.setOnLongClickListener(view -> {
        if (!isTvBox && mPrefs.askScope) {
            askForScope(true, false);
        } else {
            loadSubtitleFile(mPrefs.mediaUri);
        }
        return true;
    });
    if (Utils.isPiPSupported(this)) {
        // TODO: Android 12 improvements:
        // https://developer.android.com/about/versions/12/features/pip-improvements
        mPictureInPictureParamsBuilder = new PictureInPictureParams.Builder();
        boolean success = updatePictureInPictureActions(R.drawable.ic_play_arrow_24dp, R.string.exo_controls_play_description, CONTROL_TYPE_PLAY, REQUEST_PLAY);
        if (success) {
            buttonPiP = new ImageButton(this, null, 0, R.style.ExoStyledControls_Button_Bottom);
            buttonPiP.setContentDescription(getString(R.string.button_pip));
            buttonPiP.setImageResource(R.drawable.ic_picture_in_picture_alt_24dp);
            buttonPiP.setOnClickListener(view -> enterPiP());
        }
    }
    buttonAspectRatio = new ImageButton(this, null, 0, R.style.ExoStyledControls_Button_Bottom);
    buttonAspectRatio.setId(Integer.MAX_VALUE - 100);
    buttonAspectRatio.setContentDescription(getString(R.string.button_crop));
    updatebuttonAspectRatioIcon();
    buttonAspectRatio.setOnClickListener(view -> {
        playerView.setScale(1.f);
        if (playerView.getResizeMode() == AspectRatioFrameLayout.RESIZE_MODE_FIT) {
            playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_ZOOM);
            Utils.showText(playerView, getString(R.string.video_resize_crop));
        } else {
            // Default mode
            playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT);
            Utils.showText(playerView, getString(R.string.video_resize_fit));
        }
        updatebuttonAspectRatioIcon();
        resetHideCallbacks();
    });
    if (isTvBox && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        buttonAspectRatio.setOnLongClickListener(v -> {
            scaleStart();
            updatebuttonAspectRatioIcon();
            return true;
        });
    }
    buttonRotation = new ImageButton(this, null, 0, R.style.ExoStyledControls_Button_Bottom);
    buttonRotation.setContentDescription(getString(R.string.button_rotate));
    updateButtonRotation();
    buttonRotation.setOnClickListener(view -> {
        mPrefs.orientation = Utils.getNextOrientation(mPrefs.orientation);
        Utils.setOrientation(PlayerActivity.this, mPrefs.orientation);
        updateButtonRotation();
        Utils.showText(playerView, getString(mPrefs.orientation.description), 2500);
        resetHideCallbacks();
    });
    final int titleViewPaddingHorizontal = Utils.dpToPx(14);
    final int titleViewPaddingVertical = getResources().getDimensionPixelOffset(R.dimen.exo_styled_bottom_bar_time_padding);
    FrameLayout centerView = playerView.findViewById(R.id.exo_controls_background);
    titleView = new TextView(this);
    titleView.setBackgroundResource(R.color.ui_controls_background);
    titleView.setTextColor(Color.WHITE);
    titleView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    titleView.setPadding(titleViewPaddingHorizontal, titleViewPaddingVertical, titleViewPaddingHorizontal, titleViewPaddingVertical);
    titleView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
    titleView.setVisibility(View.GONE);
    titleView.setMaxLines(1);
    titleView.setEllipsize(TextUtils.TruncateAt.END);
    titleView.setTextDirection(View.TEXT_DIRECTION_LOCALE);
    centerView.addView(titleView);
    titleView.setOnLongClickListener(view -> {
        // Prevent FileUriExposedException
        if (mPrefs.mediaUri != null && ContentResolver.SCHEME_FILE.equals(mPrefs.mediaUri.getScheme())) {
            return false;
        }
        final Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, mPrefs.mediaUri);
        if (mPrefs.mediaType == null)
            shareIntent.setType("video/*");
        else
            shareIntent.setType(mPrefs.mediaType);
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        // Start without intent chooser to allow any target to be set as default
        startActivity(shareIntent);
        return true;
    });
    controlView = playerView.findViewById(R.id.exo_controller);
    controlView.setOnApplyWindowInsetsListener((view, windowInsets) -> {
        if (windowInsets != null) {
            if (Build.VERSION.SDK_INT >= 31) {
                boolean visibleBars = windowInsets.isVisible(WindowInsets.Type.statusBars());
                if (visibleBars && !controllerVisible) {
                    playerView.postDelayed(barsHider, 2500);
                } else {
                    playerView.removeCallbacks(barsHider);
                }
            }
            view.setPadding(0, windowInsets.getSystemWindowInsetTop(), 0, windowInsets.getSystemWindowInsetBottom());
            int insetLeft = windowInsets.getSystemWindowInsetLeft();
            int insetRight = windowInsets.getSystemWindowInsetRight();
            int paddingLeft = 0;
            int marginLeft = insetLeft;
            int paddingRight = 0;
            int marginRight = insetRight;
            if (Build.VERSION.SDK_INT >= 28 && windowInsets.getDisplayCutout() != null) {
                if (windowInsets.getDisplayCutout().getSafeInsetLeft() == insetLeft) {
                    paddingLeft = insetLeft;
                    marginLeft = 0;
                }
                if (windowInsets.getDisplayCutout().getSafeInsetRight() == insetRight) {
                    paddingRight = insetRight;
                    marginRight = 0;
                }
            }
            Utils.setViewParams(titleView, paddingLeft + titleViewPaddingHorizontal, titleViewPaddingVertical, paddingRight + titleViewPaddingHorizontal, titleViewPaddingVertical, marginLeft, windowInsets.getSystemWindowInsetTop(), marginRight, 0);
            Utils.setViewParams(findViewById(R.id.exo_bottom_bar), paddingLeft, 0, paddingRight, 0, marginLeft, 0, marginRight, 0);
            findViewById(R.id.exo_progress).setPadding(windowInsets.getSystemWindowInsetLeft(), 0, windowInsets.getSystemWindowInsetRight(), 0);
            Utils.setViewMargins(findViewById(R.id.exo_error_message), 0, windowInsets.getSystemWindowInsetTop() / 2, 0, getResources().getDimensionPixelSize(R.dimen.exo_error_message_margin_bottom) + windowInsets.getSystemWindowInsetBottom() / 2);
            windowInsets.consumeSystemWindowInsets();
        }
        return windowInsets;
    });
    timeBar.setAdMarkerColor(Color.argb(0x00, 0xFF, 0xFF, 0xFF));
    timeBar.setPlayedAdMarkerColor(Color.argb(0x98, 0xFF, 0xFF, 0xFF));
    try {
        CustomDefaultTrackNameProvider customDefaultTrackNameProvider = new CustomDefaultTrackNameProvider(getResources());
        final Field field = StyledPlayerControlView.class.getDeclaredField("trackNameProvider");
        field.setAccessible(true);
        field.set(controlView, customDefaultTrackNameProvider);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        e.printStackTrace();
    }
    findViewById(R.id.delete).setOnClickListener(view -> askDeleteMedia());
    findViewById(R.id.next).setOnClickListener(view -> {
        if (!isTvBox && mPrefs.askScope) {
            askForScope(false, true);
        } else {
            skipToNext();
        }
    });
    exoPlayPause.setOnClickListener(view -> dispatchPlayPause());
    // Prevent double tap actions in controller
    findViewById(R.id.exo_bottom_bar).setOnTouchListener((v, event) -> true);
    // titleView.setOnTouchListener((v, event) -> true);
    playerListener = new PlayerListener();
    mBrightnessControl = new BrightnessControl(this);
    if (mPrefs.brightness >= 0) {
        mBrightnessControl.currentBrightnessLevel = mPrefs.brightness;
        mBrightnessControl.setScreenBrightness(mBrightnessControl.levelToBrightness(mBrightnessControl.currentBrightnessLevel));
    }
    playerView.setBrightnessControl(mBrightnessControl);
    final LinearLayout exoBasicControls = playerView.findViewById(R.id.exo_basic_controls);
    final ImageButton exoSubtitle = exoBasicControls.findViewById(R.id.exo_subtitle);
    exoBasicControls.removeView(exoSubtitle);
    exoSettings = exoBasicControls.findViewById(R.id.exo_settings);
    exoBasicControls.removeView(exoSettings);
    final ImageButton exoRepeat = exoBasicControls.findViewById(R.id.exo_repeat_toggle);
    exoBasicControls.removeView(exoRepeat);
    // exoBasicControls.setVisibility(View.GONE);
    exoSettings.setOnLongClickListener(view -> {
        // askForScope(false, false);
        Intent intent = new Intent(this, SettingsActivity.class);
        startActivityForResult(intent, REQUEST_SETTINGS);
        return true;
    });
    exoSubtitle.setOnLongClickListener(v -> {
        enableRotation();
        safelyStartActivityForResult(new Intent(Settings.ACTION_CAPTIONING_SETTINGS), REQUEST_SYSTEM_CAPTIONS);
        return true;
    });
    updateButtons(false);
    final HorizontalScrollView horizontalScrollView = (HorizontalScrollView) getLayoutInflater().inflate(R.layout.controls, null);
    final LinearLayout controls = horizontalScrollView.findViewById(R.id.controls);
    controls.addView(buttonOpen);
    controls.addView(exoSubtitle);
    controls.addView(buttonAspectRatio);
    if (Utils.isPiPSupported(this) && buttonPiP != null) {
        controls.addView(buttonPiP);
    }
    if (mPrefs.repeatToggle) {
        controls.addView(exoRepeat);
    }
    if (!isTvBox) {
        controls.addView(buttonRotation);
    }
    controls.addView(exoSettings);
    exoBasicControls.addView(horizontalScrollView);
    if (Build.VERSION.SDK_INT > 23) {
        horizontalScrollView.setOnScrollChangeListener((view, i, i1, i2, i3) -> resetHideCallbacks());
    }
    playerView.setControllerVisibilityListener(new StyledPlayerControlView.VisibilityListener() {

        @Override
        public void onVisibilityChange(int visibility) {
            controllerVisible = visibility == View.VISIBLE;
            controllerVisibleFully = playerView.isControllerFullyVisible();
            if (PlayerActivity.restoreControllerTimeout) {
                restoreControllerTimeout = false;
                if (player == null || !player.isPlaying()) {
                    playerView.setControllerShowTimeoutMs(-1);
                } else {
                    playerView.setControllerShowTimeoutMs(PlayerActivity.CONTROLLER_TIMEOUT);
                }
            }
            // https://developer.android.com/training/system-ui/immersive
            Utils.toggleSystemUi(PlayerActivity.this, playerView, visibility == View.VISIBLE);
            if (visibility == View.VISIBLE) {
                // Because when using dpad controls, focus resets to first item in bottom controls bar
                findViewById(R.id.exo_play_pause).requestFocus();
            }
            if (controllerVisible && playerView.isControllerFullyVisible()) {
                if (mPrefs.firstRun) {
                    TapTargetView.showFor(PlayerActivity.this, TapTarget.forView(buttonOpen, getString(R.string.onboarding_open_title), getString(R.string.onboarding_open_description)).outerCircleColor(R.color.green).targetCircleColor(R.color.white).titleTextSize(22).titleTextColor(R.color.white).descriptionTextSize(14).cancelable(true), new TapTargetView.Listener() {

                        @Override
                        public void onTargetClick(TapTargetView view) {
                            super.onTargetClick(view);
                            buttonOpen.performClick();
                        }
                    });
                    // TODO: Explain gestures?
                    // "Use vertical and horizontal gestures to change brightness, volume and seek in video"
                    mPrefs.markFirstRun();
                }
                if (errorToShow != null) {
                    showError(errorToShow);
                    errorToShow = null;
                }
            }
        }
    });
    youTubeOverlay = findViewById(R.id.youtube_overlay);
    youTubeOverlay.performListener(new YouTubeOverlay.PerformListener() {

        @Override
        public void onAnimationStart() {
            youTubeOverlay.setAlpha(1.0f);
            youTubeOverlay.setVisibility(View.VISIBLE);
        }

        @Override
        public void onAnimationEnd() {
            youTubeOverlay.animate().alpha(0.0f).setDuration(300).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    youTubeOverlay.setVisibility(View.GONE);
                    youTubeOverlay.setAlpha(1.0f);
                }
            });
        }
    });
}
Also used : TimeBar(com.google.android.exoplayer2.ui.TimeBar) DefaultTimeBar(com.google.android.exoplayer2.ui.DefaultTimeBar) YouTubeOverlay(com.brouken.player.dtpv.youtube.YouTubeOverlay) PictureInPictureParams(android.app.PictureInPictureParams) StyledPlayerControlView(com.google.android.exoplayer2.ui.StyledPlayerControlView) Uri(android.net.Uri) DoubleTapPlayerView(com.brouken.player.dtpv.DoubleTapPlayerView) Field(java.lang.reflect.Field) ImageButton(android.widget.ImageButton) TapTargetView(com.getkeepsafe.taptargetview.TapTargetView) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) TextView(android.widget.TextView) HorizontalScrollView(android.widget.HorizontalScrollView) WindowInsetsController(android.view.WindowInsetsController) Window(android.view.Window) Bundle(android.os.Bundle) ViewGroup(android.view.ViewGroup) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) Parcelable(android.os.Parcelable) SuppressLint(android.annotation.SuppressLint) Animator(android.animation.Animator) FrameLayout(android.widget.FrameLayout) AspectRatioFrameLayout(com.google.android.exoplayer2.ui.AspectRatioFrameLayout) LinearLayout(android.widget.LinearLayout) RequiresApi(androidx.annotation.RequiresApi)

Example 42 with PlayerView

use of com.google.android.exoplayer2.ui.PlayerView in project Player by moneytoo.

the class PlayerActivity method initializePlayer.

public void initializePlayer() {
    boolean isNetworkUri = mPrefs.mediaUri != null && Utils.isSupportedNetworkUri(mPrefs.mediaUri);
    haveMedia = mPrefs.mediaUri != null && (Utils.fileExists(this, mPrefs.mediaUri) || isNetworkUri);
    if (player != null) {
        player.removeListener(playerListener);
        player.clearMediaItems();
        player.release();
        player = null;
    }
    trackSelector = new DefaultTrackSelector(this);
    if (mPrefs.tunneling) {
        trackSelector.setParameters(trackSelector.buildUponParameters().setTunnelingEnabled(true));
    }
    trackSelector.setParameters(trackSelector.buildUponParameters().setPreferredAudioLanguages(Utils.getDeviceLanguages()));
    // https://github.com/google/ExoPlayer/issues/8571
    DefaultExtractorsFactory extractorsFactory = new DefaultExtractorsFactory().setTsExtractorFlags(DefaultTsPayloadReaderFactory.FLAG_ENABLE_HDMV_DTS_AUDIO_STREAMS).setTsExtractorTimestampSearchBytes(1500 * TsExtractor.TS_PACKET_SIZE);
    @SuppressLint("WrongConstant") RenderersFactory renderersFactory = new DefaultRenderersFactory(this).setExtensionRendererMode(mPrefs.decoderPriority);
    ExoPlayer.Builder playerBuilder = new ExoPlayer.Builder(this, renderersFactory).setTrackSelector(trackSelector).setMediaSourceFactory(new DefaultMediaSourceFactory(this, extractorsFactory));
    if (haveMedia && isNetworkUri) {
        if (mPrefs.mediaUri.getScheme().toLowerCase().startsWith("http")) {
            HashMap<String, String> headers = new HashMap<>();
            String userInfo = mPrefs.mediaUri.getUserInfo();
            if (userInfo != null && userInfo.length() > 0 && userInfo.contains(":")) {
                headers.put("Authorization", "Basic " + Base64.encodeToString(userInfo.getBytes(), Base64.NO_WRAP));
                DefaultHttpDataSource.Factory defaultHttpDataSourceFactory = new DefaultHttpDataSource.Factory();
                defaultHttpDataSourceFactory.setDefaultRequestProperties(headers);
                playerBuilder.setMediaSourceFactory(new DefaultMediaSourceFactory(defaultHttpDataSourceFactory, extractorsFactory));
            }
        }
    }
    player = playerBuilder.build();
    AudioAttributes audioAttributes = new AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.CONTENT_TYPE_MOVIE).build();
    player.setAudioAttributes(audioAttributes, true);
    if (mPrefs.skipSilence) {
        player.setSkipSilenceEnabled(true);
    }
    youTubeOverlay.player(player);
    playerView.setPlayer(player);
    mediaSession = new MediaSessionCompat(this, getString(R.string.app_name));
    MediaSessionConnector mediaSessionConnector = new MediaSessionConnector(mediaSession);
    mediaSessionConnector.setPlayer(player);
    mediaSessionConnector.setMediaMetadataProvider(player -> {
        if (mPrefs.mediaUri == null)
            return null;
        final String title = Utils.getFileName(PlayerActivity.this, mPrefs.mediaUri);
        if (title == null)
            return null;
        else
            return new MediaMetadataCompat.Builder().putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, title).putString(MediaMetadataCompat.METADATA_KEY_TITLE, title).build();
    });
    playerView.setControllerShowTimeoutMs(-1);
    locked = false;
    chapterStarts = new long[0];
    if (haveMedia) {
        if (isNetworkUri) {
            timeBar.setBufferedColor(DefaultTimeBar.DEFAULT_BUFFERED_COLOR);
        } else {
            // https://github.com/google/ExoPlayer/issues/5765
            timeBar.setBufferedColor(0x33FFFFFF);
        }
        playerView.setResizeMode(mPrefs.resizeMode);
        if (mPrefs.resizeMode == AspectRatioFrameLayout.RESIZE_MODE_ZOOM) {
            playerView.setScale(mPrefs.scale);
        } else {
            playerView.setScale(1.f);
        }
        updatebuttonAspectRatioIcon();
        MediaItem.Builder mediaItemBuilder = new MediaItem.Builder().setUri(mPrefs.mediaUri).setMimeType(mPrefs.mediaType);
        if (apiAccess && apiSubs.size() > 0) {
            mediaItemBuilder.setSubtitleConfigurations(apiSubs);
        } else if (mPrefs.subtitleUri != null && Utils.fileExists(this, mPrefs.subtitleUri)) {
            MediaItem.SubtitleConfiguration subtitle = SubtitleUtils.buildSubtitle(this, mPrefs.subtitleUri, null, true);
            mediaItemBuilder.setSubtitleConfigurations(Collections.singletonList(subtitle));
        }
        player.setMediaItem(mediaItemBuilder.build(), mPrefs.getPosition());
        if (loudnessEnhancer != null) {
            loudnessEnhancer.release();
        }
        try {
            loudnessEnhancer = new LoudnessEnhancer(player.getAudioSessionId());
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
        notifyAudioSessionUpdate(true);
        videoLoading = true;
        updateLoading(true);
        if (mPrefs.getPosition() == 0L || apiAccess) {
            play = true;
        }
        if (apiTitle != null) {
            titleView.setText(apiTitle);
        } else {
            titleView.setText(Utils.getFileName(this, mPrefs.mediaUri));
        }
        titleView.setVisibility(View.VISIBLE);
        updateButtons(true);
        ((DoubleTapPlayerView) playerView).setDoubleTapEnabled(true);
        if (!apiAccess) {
            if (nextUriThread != null) {
                nextUriThread.interrupt();
            }
            nextUri = null;
            nextUriThread = new Thread(() -> {
                Uri uri = findNext();
                if (!Thread.currentThread().isInterrupted()) {
                    nextUri = uri;
                }
            });
            nextUriThread.start();
        }
        Utils.markChapters(this, mPrefs.mediaUri, controlView);
        player.setHandleAudioBecomingNoisy(!isTvBox);
        mediaSession.setActive(true);
    } else {
        playerView.showController();
    }
    player.addListener(playerListener);
    player.prepare();
    if (restorePlayState) {
        restorePlayState = false;
        playerView.showController();
        playerView.setControllerShowTimeoutMs(PlayerActivity.CONTROLLER_TIMEOUT);
        player.setPlayWhenReady(true);
    }
}
Also used : DefaultExtractorsFactory(com.google.android.exoplayer2.extractor.DefaultExtractorsFactory) HashMap(java.util.HashMap) LoudnessEnhancer(android.media.audiofx.LoudnessEnhancer) DefaultExtractorsFactory(com.google.android.exoplayer2.extractor.DefaultExtractorsFactory) DefaultRenderersFactory(com.google.android.exoplayer2.DefaultRenderersFactory) DefaultTsPayloadReaderFactory(com.google.android.exoplayer2.extractor.ts.DefaultTsPayloadReaderFactory) DefaultMediaSourceFactory(com.google.android.exoplayer2.source.DefaultMediaSourceFactory) RenderersFactory(com.google.android.exoplayer2.RenderersFactory) DefaultRenderersFactory(com.google.android.exoplayer2.DefaultRenderersFactory) RenderersFactory(com.google.android.exoplayer2.RenderersFactory) ExoPlayer(com.google.android.exoplayer2.ExoPlayer) MediaSessionConnector(com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector) Uri(android.net.Uri) DoubleTapPlayerView(com.brouken.player.dtpv.DoubleTapPlayerView) DefaultRenderersFactory(com.google.android.exoplayer2.DefaultRenderersFactory) AudioAttributes(com.google.android.exoplayer2.audio.AudioAttributes) MediaSessionCompat(android.support.v4.media.session.MediaSessionCompat) DefaultMediaSourceFactory(com.google.android.exoplayer2.source.DefaultMediaSourceFactory) MediaItem(com.google.android.exoplayer2.MediaItem) DefaultTrackSelector(com.google.android.exoplayer2.trackselection.DefaultTrackSelector) SuppressLint(android.annotation.SuppressLint) DefaultHttpDataSource(com.google.android.exoplayer2.upstream.DefaultHttpDataSource)

Aggregations

PlayerView (com.google.android.exoplayer2.ui.PlayerView)25 TextView (android.widget.TextView)20 View (android.view.View)15 ImageView (android.widget.ImageView)14 RecyclerView (androidx.recyclerview.widget.RecyclerView)13 WebView (android.webkit.WebView)12 Uri (android.net.Uri)10 AdapterView (android.widget.AdapterView)10 NestedScrollView (androidx.core.widget.NestedScrollView)10 PhotoView (com.github.chrisbanes.photoview.PhotoView)10 SolidIconView (com.odysee.app.ui.controls.SolidIconView)10 MediaItem (com.google.android.exoplayer2.MediaItem)8 Context (android.content.Context)7 Nullable (androidx.annotation.Nullable)7 Player (com.google.android.exoplayer2.Player)7 MediaSource (com.google.android.exoplayer2.source.MediaSource)7 ProgressiveMediaSource (com.google.android.exoplayer2.source.ProgressiveMediaSource)7 SuppressLint (android.annotation.SuppressLint)6 Intent (android.content.Intent)6 SimpleExoPlayer (com.google.android.exoplayer2.SimpleExoPlayer)6