Skip to content

Preload media period not prepared when onContinueLoadingRequested is called #2315

Open

Description

@Apengsun

Version

Media3 1.5.1

More version details

无

Devices that reproduce the issue

Android14 Redmi Note 13 Pro 5G

Devices that do not reproduce the issue

都复现

Reproducible in the demo app?

No

Reproduction steps

无

Expected result

无奔溃

Actual result

Fatal Exception: java.lang.IllegalStateException:
       at androidx.media3.common.util.Assertions.checkState(Assertions.java:85)
       at androidx.media3.exoplayer.source.ProgressiveMediaPeriod.assertPrepared(ProgressiveMediaPeriod.java:999)
       at androidx.media3.exoplayer.source.ProgressiveMediaPeriod.getBufferedPositionUs(ProgressiveMediaPeriod.java)
       at androidx.media3.exoplayer.source.preload.PreloadMediaPeriod.getBufferedPositionUs(PreloadMediaPeriod.java:264)
       at androidx.media3.exoplayer.source.preload.PreloadMediaSource$PreloadMediaPeriodCallback.lambda$onContinueLoadingRequested$1(PreloadMediaSource.java:508)
       at android.os.Handler.handleCallback(Handler.java:883)
       at android.os.Handler.dispatchMessage(Handler.java:100)
       at android.os.Looper.loop(Looper.java:224)
       at android.app.ActivityThread.main(ActivityThread.java:7562)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

[com.android.thememanager_issue_2947d0273e7f29d94ddff2a6db7b788f_crash_session_67EE316A008700017C745A594FC6525D_DNE_0_v2_stacktrace.txt](https://github.com/user-attachments/files/19643871/com.android.thememanager_issue_2947d0273e7f29d94ddff2a6db7b788f_crash_session_67EE316A008700017C745A594FC6525D_DNE_0_v2_stacktrace.txt)

Media

无

Bug Report

Activity

  1. Apengsun commented on Apr 8, 2025

    @Apengsun
    Author
    public class VideoPreloadManager {
        private static final String TAG = "VideoPreloadManager";
        public static final Integer MAX_TIME = -1;
        public static final Integer PLAY_TIME = -2;
        private final DefaultPreloadManager preloadManager;
        private final Map<String, VideoMessage> mVideoMessageMap;
        private Set<String>  mVideoUrlReporteds = ConcurrentHashMap.newKeySet();
        private PreloadCallback preloadCallback;
        private static volatile VideoPreloadManager instance;
        private final Context mContext;
    
        private TargetPreloadStatusControl<Integer> mPreloadControl = new  TargetPreloadStatusControl<Integer>() {
            @Nullable
            @Override
            public PreloadStatus getTargetPreloadStatus(Integer duration) {
                if (duration == MAX_TIME || duration == PLAY_TIME) {
                    MLog.d(TAG, "getTargetPreloadStatus: duration == -1 || duration == -2");
                    return new DefaultPreloadManager.Status(DefaultPreloadManager.Status.STAGE_LOADED_FOR_DURATION_MS, 1000000);
                } else if (duration == null || duration <= 0) {
                    MLog.d(TAG, "getTargetPreloadStatus: duration is null or <= 0");
                    return new DefaultPreloadManager.Status(DefaultPreloadManager.Status.STAGE_LOADED_FOR_DURATION_MS, 0);
                } else {
                    MLog.d(TAG, "getTargetPreloadStatus: duration = " + duration);
                    return new DefaultPreloadManager.Status(DefaultPreloadManager.Status.STAGE_LOADED_FOR_DURATION_MS, duration);
                }
            }
        };
    
        public static VideoPreloadManager getInstance(Context context) {
            if (instance == null) {
                synchronized (VideoPreloadManager.class) {
                    if (instance == null) {
                        instance = new VideoPreloadManager(context);
                    }
                }
            }
            return instance;
        }
    
        public interface PreloadCallback {
            void onPreloadSuccess(VideoMessage message);
    
            void onPreloadFailed(VideoMessage message);
        }
    
        private VideoPreloadManager(Context context) {
            if (context == null) {
                throw new IllegalArgumentException("Context cannot be null");
            }
            this.mContext = context.getApplicationContext();
    
            CacheDataSource.Factory cacheDataSourceFactory = CacheManager.getCacheDataSourceFactory(mContext);
            DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter.Builder(mContext).build();
    
            preloadManager = new DefaultPreloadManager.Builder(mContext, mPreloadControl)
                    .setMediaSourceFactory(new CustomMediaSourceFactory(cacheDataSourceFactory))
                    .setBandwidthMeter(bandwidthMeter)
                    .setPreloadLooper(Looper.getMainLooper())
                    .build();
    
    
            preloadManager.addListener(new BasePreloadManager.Listener() {
                @Override
                public void onCompleted(MediaItem mediaItem) {
                    Uri uri = mediaItem.localConfiguration != null ? mediaItem.localConfiguration.uri : null;
                    if (uri != null) {
                        String url = uri.toString();
                        String key = getKey(url);
                        MLog.d(TAG, "key: " + key);
                        VideoMessage message = mVideoMessageMap.get(key);
                        if (message != null) {
                            if (message.duration == MAX_TIME) {
                                MLog.d(TAG, "End URL: " + url);
                                return;
                            }
                            message.notifyCallbacksPreloadSuccess();
                            MLog.d(TAG, "onCompleted: " + message);
                            preloadManager.remove(mediaItem);
                            goPreloadToEnd(url);
                        }
                    }
                    MLog.d(TAG, "onCompleted: " + mediaItem + " url: "+ uri);
                }
    
                @Override
                public void onError(PreloadException exception) {
                    MediaItem mediaItem = exception.mediaItem;
                    Uri uri = mediaItem.localConfiguration != null ? mediaItem.localConfiguration.uri : null;
                    if (uri != null) {
                        String url = uri.toString();
                        String key = getKey(url);
                        MLog.d(TAG, "key: " + key);
                        VideoMessage message = mVideoMessageMap.get(key);
                        if (message != null) {
                            message.notifyCallbacksPreloadFailed(exception);
                        }
                    }
                    MLog.e(TAG, "onError: " + exception.toString());
                }
            });
    
            mVideoMessageMap =  new ConcurrentHashMap<>();
        }
    
        public void addPreload(@NonNull String url, int duration ,PreloadCallback preloadCallback) {
            MediaItem mediaItem = getMediaItem(url);
            String key = getKey(url);
            MediaSource mediaSource = preloadManager.getMediaSource(mediaItem);
            VideoMessage message = mVideoMessageMap.get(key);
            MLog.d(TAG, "addPreload: mediaSource = " + mediaSource + " message = " + message);
            if (null != mediaSource && message != null) {
                message.addCallback(preloadCallback);
                MLog.d(TAG, "addPreload: " + url + " already preloaded ");
                if (message.isPreloadSuccess) {
                    message.notifyCallbacksPreloadSuccess();
                }
                return;
            }
            message = new VideoMessage(url, duration, preloadCallback);
            mVideoMessageMap.put(key, message);
            addMediaItemToPreloadManager(mediaItem, duration);
            MLog.d(TAG, "addPreload: " + url + " duration = " + duration);
        }
    
        public void removePreload(@NonNull String url) {
            MediaItem mediaItem = getMediaItem(url);
            preloadManager.remove(mediaItem);
            preloadManager.invalidate();
            MLog.d(TAG, "removePreload: " + url);
        }
    
        private void goPreloadToEnd(@NonNull String url) {
            MediaItem mediaItem = getMediaItem(url);
            VideoMessage message = new VideoMessage(url, MAX_TIME, null);
            mVideoMessageMap.put(getKey(url), message);
            addMediaItemToPreloadManager(mediaItem, MAX_TIME);
            MLog.d(TAG, "goPreloadToEnd: " + url);
        }
    
        public void goPlayToEnd(@NonNull String url) {
            MediaItem mediaItem = getMediaItem(url);
            VideoMessage message = new VideoMessage(url, PLAY_TIME, null);
            mVideoMessageMap.put(getKey(url), message);
            addMediaItemToPreloadManager(mediaItem, MAX_TIME);
            MLog.d(TAG, "goPlayToEnd: " + url);
        }
    
        private void addMediaItemToPreloadManager(MediaItem mediaItem, int duration) {
            preloadManager.add(mediaItem, duration);
            preloadManager.invalidate();
            MLog.d(TAG, "addMediaItemToPreloadManager: " + mediaItem + " duration = " + duration);
        }
    
        private MediaSource getPlayingMediaSource(String url) {
            MediaItem mediaItem = getMediaItem(url);
            MediaSource mediaSource = preloadManager.getMediaSource(mediaItem);
            MLog.d(TAG, "setPlaying: url = " + url + " ; mediaSource = " + mediaSource);
            return mediaSource;
        }
    
        public MediaSource getMediaSource(String url) {
            MediaSource mediaSource = getPlayingMediaSource(url);
            MLog.d(TAG, "getMediaSource : " + mediaSource);
            if (mediaSource == null) {
                goPlayToEnd(url);
                mediaSource = getPlayingMediaSource(url);
                MLog.d(TAG, "getMediaSource : " + mediaSource);
            }
            if (mediaSource == null) {
                ProgressiveMediaSource.Factory mediaSourceFactory = new ProgressiveMediaSource.Factory(
                        CacheManager.getCacheDataSourceFactory(mContext));
                MediaItem mediaItem = MediaItem.fromUri(Uri.parse(url));
                mediaSource = mediaSourceFactory.createMediaSource(mediaItem);
            }
            return mediaSource;
        }
    
        private MediaItem getMediaItem(String url) {
            return new MediaItem.Builder().setUri(url).build();
        }
    
        private String getKey(String url) {
            return url;
        }
    
        public void addVideoUrlReported(String url) {
            if (mVideoUrlReporteds != null || !TextUtils.isEmpty(url)){
                mVideoUrlReporteds.add(url);
            }
        }
    
        public boolean isVideoUrlReported(String url) {
            if (mVideoUrlReporteds != null){
                return mVideoUrlReporteds.contains(url);
            }
            return false;
        }
    
        public void release() {
            if (mVideoMessageMap != null) {
                mVideoMessageMap.clear();
            }
            if (preloadManager != null) {
                preloadManager.release();
            }
        }
    
        private class CustomMediaSourceFactory implements MediaSource.Factory {
            private final DataSource.Factory dataSourceFactory;
    
            public CustomMediaSourceFactory(DataSource.Factory dataSourceFactory) {
                this.dataSourceFactory = dataSourceFactory;
            }
    
            @Override
            public MediaSource createMediaSource(MediaItem mediaItem) {
                MediaSource mediaSource = new ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(mediaItem);
                MLog.d(TAG, "createMediaSource: " + mediaItem);
                return mediaSource;
            }
    
            @Override
            public MediaSource.Factory setDrmSessionManagerProvider(DrmSessionManagerProvider drmSessionManagerProvider) {
                return this;
            }
    
            @Override
            public MediaSource.Factory setLoadErrorHandlingPolicy(LoadErrorHandlingPolicy loadErrorHandlingPolicy) {
                return this;
            }
    
            @Override
            public int[] getSupportedTypes() {
                return new int[]{C.CONTENT_TYPE_OTHER}; 
            }
        }
    
    }
    
  2. marcbaechinger commented on Apr 8, 2025

    @marcbaechinger
    Contributor

    @Apengsun If you file a bug and then a question is asked to provide more information, please do not open a new bug but continue instead with the existing bug. I close the other bug. If you want to increase your chance to get help on an issue tracker, then you can add some concrete questions instead pasting code without any comments.

  3. marcbaechinger commented on Apr 9, 2025

    @marcbaechinger
    Contributor

    The stack trace originates from ActivityThread.main (I'm not sure if this is a red hearing though)

    at android.os.Handler.handleCallback(Handler.java:883)
           at android.os.Handler.dispatchMessage(Handler.java:100)
           at android.os.Looper.loop(Looper.java:224)
           at android.app.ActivityThread.main(ActivityThread.java:7562)
    

    and when the DefaultPreloadManager is built the main looper is passed to the builder:

    .setPreloadLooper(Looper.getMainLooper())
    

    Can you delete this line and try when the manager creates a loader thread internally? I'm unsure what the reason for the exception is but lets try with the default setting when it creates a thread internally.

    From the library side I think we can add an assertion there to assert that the looper passed in is not the main Looper.

  4. changed the title [-]使用 Media3 1.5.1版本[/-] [+]Preload media period not prepared when continueLoading is called[/+] on Apr 9, 2025
  5. changed the title [-]Preload media period not prepared when continueLoading is called[/-] [+]Preload media period not prepared when onContinueLoadingRequested is called[/+] on Apr 9, 2025
  6. tianyif commented on Apr 10, 2025

    @tianyif
    Contributor

    I'm able to reproduce this on demo-shortform app if I manually setContinueLoadingIntervalBytes() to a smaller value, with which the media period hasn't prepared and still needs more rounds of MediaPeriod.continueLoading to get it fully prepared.

    I'm going to send a fix for this. Also +1 on @marcbaechinger's suggestion to assert the preload looper passed not the main looper.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions