GSYVideoPlayer

repository·master·Indexed 12 days ago

https://github.com/carguo/gsyvideoplayer

A highly customizable, multi-kernel video player library for Android. It abstracts playback engines including IJKPlayer, Media3 (ExoPlayer), MediaPlayer, and AliPlayer to provide a unified API for caching, casting, subtitle overlays, and custom UI layouts. Features include support for various protocols (rtsp, hls, rtmp), Jetpack Compose integration via gsyvideoplayer-compose v13.1.0, and advanced rendering modes with GL effects and filters.

Tokens
63.9K
Snippets
185
Records
256
Agent score
96%

What's inside GSYVideoPlayer

  1. Overview of the GSY Cast Receiver Design

    master

    The gsy-cast-receiver is a desktop-based DLNA/UPnP receiver designed for local testing and development of casting features. It acts as a 'virtual smart TV' on a desktop environment, allowing developers to test real Android mobile app casting logic without needing physical hardware.

    Key Characteristics:

    • Environment: A pure JVM application (Java 17+) running on a desktop.
    • Purpose: Provides a minimal closed-loop testing environment (Real Mobile App $\leftrightarrow$ Desktop Receiver).
    • Connectivity: Uses SSDP multicast for discovery and HTTP for media streaming.
    • Observability: Exposes HTTP endpoints (e.g., /log/tail) to allow automated test scripts to assert against logs and device state.
    • Constraint: This receiver is intended only for local testing and is not part of the official Maven Central/production release chain.
  2. Overview of GSYVideoPlayer features

    master

    GSYVideoPlayer is a multi-functional video player that supports multiple kernels including IJKPlayer, Media3 (ExoPlayer2), MediaPlayer, and AliPlayer. It provides a wide range of advanced features for Android video playback.

    Key Capabilities

    • Kernels: Switch between IJKPlayer, Media3(ExoPlayer), MediaPlayer, and AliPlayer, or implement a custom kernel.
    • Protocols: Supports h263, h264, h265, Https, concat, rtsp, hls, rtmp, mpeg, etc. (Note: protocol support varies by kernel; see DECODERS.md for IJK mode details).
    • Caching: Supports playing while caching via AndroidVideoCache (for IJK/MediaPlayer) or SimpleCache (for Media3/ExoPlayer).
    • Playback Control: List playback, continuous playback, fast/slow playback, and adaptive quality switching for HLS/DASH (Media3 mode).
    • Display & Layout: Adjust display ratios (default, 16:9, 4:3, fill), screen rotation (0, 90, 180, 270), and mirror rotation. Supports both full-screen and non-full-screen layouts.
    • Advanced UI: Supports small window (PIP) playback, multiple simultaneous windows, barrage (danmaku) functions, and custom layouts.
    • Subtitles: Unified external subtitle overlay for SRT/WebVTT across IJK, Media3, and MediaPlayer.
    • Casting: Built-in DLNA/UPnP casting using jUPnP 3.0.3 with CastCapability, CastProvider, and CastSession SPI.
    • Filters & Effects: Over 20 simple filters (mosaic, black and white, Gaussian, blur, etc.), animations, and watermarks.
    • Customization: Highly extensible with customizable rendering, management, playback (control), and cache layers.
  3. Implement multi-URL seamless quality switching

    master

    For scenarios where you have multiple independent URLs for different qualities (rather than a single HLS/DASH stream), use the SmartPickVideo approach. This uses a temporary manager to pre-load the new URL and then synchronizes the playback position to ensure a seamless transition.

    Key features of this optimization:

    • Records the latest playback position to avoid resetting to 0.
    • Includes seek error thresholds, retries, and timeout protection.
    • Automatically falls back to the original playback if the switch fails to prevent resource leaks.
  4. Handle fullscreen and non-fullscreen synchronization

    master

    If you have custom logic that needs to persist or synchronize when switching between fullscreen and normal modes, override startWindowFullscreen and resolveNormalVideoShow in your player class.

    /**
     * Handle logic when entering fullscreen
     */
    @Override
    public GSYBaseVideoPlayer startWindowFullscreen(Context context, boolean actionBar, boolean statusBar) {
        SmartPickVideo sampleVideo = (SmartPickVideo) super.startWindowFullscreen(context, actionBar, statusBar);
        // Transfer custom state to the fullscreen instance
        sampleVideo.mSourcePosition = mSourcePosition;
        sampleVideo.mType = mType;
        return sampleVideo;
    }
    
    /**
     * Handle logic when exiting fullscreen
     */
    @Override
    protected void resolveNormalVideoShow(View oldF, ViewGroup vp, GSYVideoPlayer gsyVideoPlayer) {
        super.resolveNormalVideoShow(oldF, vp, gsyVideoPlayer);
        if (gsyVideoPlayer != null) {
            SmartPickVideo sampleVideo = (SmartPickVideo) gsyVideoPlayer;
            // Restore state to the normal player
            mSourcePosition = sampleVideo.mSourcePosition;
            mType = sampleVideo.mType;
            setUp(mUrlList, mCache, mCachePath, mTitle);
        }
    }
  5. Compare Maven Central vs GitHub Packages dependency methods

    master

    Choose the dependency method based on your project requirements:

    FeatureMaven Central (Recommended)GitHub Packages
    GROUP IDio.github.carguocom.shuyu
    AccessPublicRequires GitHub token
    ComplexitySimpleMedium
    Best ForNew projects, public projectsPrivate projects, existing configurations

    Migration to Maven Central: If you are currently using com.shuyu and want to switch to Maven Central:

    1. Remove the GitHub Packages repository configuration.
    2. Replace the group ID com.shuyu with io.github.carguo.
    3. No token configuration is required.
  6. Use the On-device Loopback Receiver

    master

    GSYVideoPlayer supports an on-device Loopback Receiver, allowing the device to act as both the sender and the receiver.

    • DevReceiverService: Runs in a dedicated :dlna process and registers a LocalDevice (urn:schemas-upnp-org:device:MediaRenderer:1).
    • CastReceiverFloatingWindow: Renders the incoming stream in a SYSTEM_ALERT_WINDOW floating window using CastReceiverPlayer (which embeds an IJK kernel).
    • State Synchronization: The service and activity communicate via private broadcasts (ACTION_STATE_READY, ACTION_STATE_STOPPED, ACTION_STATE_ERROR). On Android 13+, RECEIVER_NOT_EXPORTED is used for security.
  7. Implement seamless video transitions (SwitchSeamless)

    master

    To achieve a seamless transition between a list view (thumbnail/small player) and a detail view (large player) without restarting the video or losing progress, use the same GSYPlayerController instance across both views.

    By attaching and detaching the GSYPlayerSurface to different parts of the UI while keeping the controller alive, the video continues playing uninterrupted. This avoids the need for setUp re-initialization.

  8. Supported Video Protocols and Kernels

    master

    GSYVideoPlayer's protocol support depends on the underlying kernel used. For the most comprehensive protocol support (including h263, h264, h265, rtsp, rtmp, etc.), IJKPlayer is recommended.

    TypeFunction
    CachePlay while caching, using AndroidVideoCache; Media3(ExoPlayer) uses SimpleCache.
    Protocolsh263, h264, h265, Https, concat, rtsp, hls, rtmp, crypto, mpeg, etc. [ (ijk mode format support) ]
    KernelIJKPlayer, Media3(EXOPlayer), MediaPlayer, AliPlayer switching, custom kernel
  9. Handle player initialization failures gracefully

    master
    The library is designed to prevent app crashes during player creation or initialization. When an IPlayerManager (IJK, System, Exo, or AliPlayer) fails to initialize (e.g., due to an invalid URL or missing codec), the error is routed through standard onError callbacks and resource cleanup routines rather than throwing an unhandled exception.
  10. Inject faults for testing DLNA robustness

    master

    Use the following fault injection modes to test how Android clients handle various error scenarios. These can be triggered via CLI flags or the /fault HTTP endpoint.

    | 模式 | CLI / API | 发送端预期 |
    | --- | --- | --- |
    | `--reject-uri` | `SetAVTransportURI` 返回 501 | Android `onCastError`,回退本地 |
    | `--slow-response=3000` | 所有 action 延迟 3s | Android loading UI 出现,不 ANR |
    | `--drop-after-play=10000` | 起播 10s 后关 SSDP 通告 | Android 检测断连,触发退投 |
    | `--wrong-position=+30000` | `getPositionInfo` 上报位置偏移 30s | Android UI 进度不错乱 |
  11. Monitor player state and events

    master

    You can observe the player's state and real-time events through the controller's snapshot and events streams.

    Snapshot (State)

    The snapshot provides current playback information, including:

    • currentPosition: Current playback position.
    • duration: Total duration.
    • isBuffering: Whether the player is buffering.
    • isPaused: Whether playback is paused.
    • isCacheReady: Whether the cache is ready.
    • netSpeedText: Human-readable network speed.
    • videoSarNum: Video SAR information.

    Events (Real-time)

    Use the events stream to react to specific playback occurrences, such as:

    • BufferingProgress(percent): Real-time buffering percentage.
    • SeekComplete: Triggered when a seek operation finishes.
    • GSYPlayerEvent: A wide range of events (24+ types) including fullscreen transitions and playback state changes.
  12. Understand the GSYVideoPlayer architecture

    master

    GSYVideoPlayer is organized into several layers that allow for modular replacement of the playback engine, management logic, and rendering. This architecture enables developers to swap out core components without affecting the UI or vice versa.

    Core Layers

    • Player Layer: The playback engines (e.g., IjkMediaPlayer, ExoPlayer2, MediaPlayer) managed by IPlayerManager.
    • Cache Layer: Handles caching logic via ICacheManager (e.g., ProxyCacheManager, ExoPlayerCacheManager).
    • Manager Layer: Orchestrates the playback via GSYVideoManager (which inherits GSYVideoBaseManager and implements GSYVideoViewBridge).
    • Video/UI Layer: The controller layer where most custom implementations occur. It spans from GSYTextureRenderView up to GSYVideoPlayer.
    • Render Layer: Handles the actual rendering using IGSYRenderView implementations like TextureView, SurfaceView, or GLSurfaceView.
    • Extension Layer: Features like subtitles, previews, screenshots, and GL effects are attached to the UI/Manager/Render layers to avoid polluting the core engine layer.