Videocaching, kann mit dem video_player-Paket verwendet werden. Unterstützt Formate wie m3u8 und mp4, spielt und cache Videos gleichzeitig und präcache das Video vor der Wiedergabe.
Aus öffentlichen Paketdaten erstellte Orientierung.
Flutter_video_caching ist ein Paket, das effizientes Video-Caching in Flutter-Anwendungen ermöglicht und mit dem video_player-Paket kompatibel ist. Es unterstützt gängige Formate wie m3u8 und mp4 und erlaubt gleichzeitiges Abspielen und Cachen von Videos. Das Paket ermöglicht auch das Vor-Cachen von Videos vor der Wiedergabe, wodurch die Benutzererfahrung durch kürzere Ladezeiten verbessert wird. Ideal für Offline-Wiedergabe und reibungsloses Streaming, funktioniert es auf den Plattformen Android, iOS, macOS, Windows und Linux.
Anwendungsfälle
Offline-Videowiedergabe
Streaming mit reduzierter Latenz
Vorladen von Videos für schnellere Zugriffe
Leistungsoptimierung für medienintensive Apps
Unterstützung für HLS (m3u8) und MP4-Formate
Hauptmerkmale
Gleichzeitige Wiedergabe und Caching
Vor-Cache-Unterstützung
HLS (m3u8) und MP4 Formatkompatibilität
Plattformübergreifende Unterstützung
Nahtlose Integration mit video_player
Geeignet für
Apps, die Offline-Videos benötigen
Streaming- oder Bildungs-Apps
Anwendungen mit hohem Volumen an Videoinhalten
Entwickler, die video_player verwenden
Projekte, die mehrere Betriebssysteme zielen
Hinweise
Erfordert zusätzliche Speicherverwaltung
Kann die App-Größe aufgrund zwischengespeicherter Dateien erhöhen
Cache-Cleanup-Strategie erforderlich
Abhängig vom video_player-Paket
Plattformspezifisches Caching-Verhalten kann variieren
Original-README
Originaler README-Schnappschuss aus dem verknüpften Quell-Repository. Aktuelle Inhalte finden Sie im Repository.
flutter_video_caching
flutter_video_caching is a powerful Flutter plugin for efficient video caching.
It supports integration with the video_player package and works with popular formats like m3u8 (HLS) and MP4.
The plugin enables simultaneous playback and caching, as well as pre-caching for smoother user experiences.
Version 1.x.x released, to migrate from v0.4.x, please refer to MIGRATION.MD.
🎊 Features
Multi-format support: Works with m3u8 (HLS), MP4, and other common video formats.
Memory & file cache: LRU-based memory cache combined with local file cache to minimize network requests.
Pre-caching: Download video segments in advance to ensure seamless playback.
Background downloading: Multi-task parallel downloads without blocking the UI.
If your video URL contains token parameters that change frequently, you can override matchCacheKey in UrlMatcher to define a custom cache key that ignores the token parameters, so that the video can be cached and reused even when the token changes.
// Remove cache for a single file or the entire directoryLruCacheSingleton().removeCacheByUrl(String url, {bool singleFile = false});
4. Custom request headers & cache file names
// Custom header for playback
_controller = VideoPlayerController.networkUrl(uri, httpHeaders: {'Token': 'xxxxxxx'});
// Custom header for pre-cachingVideoCaching.precache(url, headers: {'Token': 'xxxxxxx'});
// Custom cache file name using CUSTOM-CACHE-ID
_controller = VideoPlayerController.networkUrl(uri, httpHeaders: {'CUSTOM-CACHE-ID': 'xxxxxxx'});
VideoCaching.precache(url, headers: {'CUSTOM-CACHE-ID': 'xxxxxxx'});
5. Check cache
// Check whether the video was cachedVideoCaching.isCached(url, headers: {'Token': 'xxxxxxx'}, cacheSegments = 2);
6. Custom URL matching
Implement the UrlMatcher abstract class (lib/match/url_matcher.dart) to define custom logic for matching .m3u8, .ts, .mp4, m3u8 encryption keys, and cache keys.
The default cache key is the same as the original URL, but with query parameters removed, only startRange and endRange are kept.
mp4/others: The file is split into 2MB segments for caching.
To use your custom UrlMatcher, pass it to VideoProxy.init().
7. Custom HttpClient
You can customize the HTTP client used for video downloading and caching by implementing the HttpClientBuilder interface.
This allows you to configure certificate verification, custom headers, or other HTTP behaviors.
Example: Allow Self-Signed Certificates
classHttpClientCustomextendsHttpClientBuilder{
@overrideDiocreate() {
Dio dio = Dio();
dio.httpClientAdapter = IOHttpClientAdapter(createHttpClient: () {
final client =
HttpClient(context: SecurityContext(withTrustedRoots: false));
// You can test the intermediate / root cert here. We just ignore it.
client.badCertificateCallback =
(X509Certificate cert, String host, int port) {
// Print certificate info for debuggingdebugPrint('Certificate subject: ${cert.subject}');
debugPrint('Issuer: ${cert.issuer}');
debugPrint('Valid until: ${cert.endValidity}');
debugPrint('SHA-1 fingerprint: ${cert.sha1}');
// Custom verification logic: here simply allow all certificates, should be stricter in real applications// For example, verify if the certificate fingerprint matches the expected valuereturntrue;
};
return client;
});
return dio;
}
}
To use your custom client, pass it to VideoProxy.init().
Note: Allowing all certificates is insecure and should only be used for testing. In production, implement strict certificate validation.
If you want to cancel all download tasks related to a specific URL, you can use the following method.
For example, if the user navigates away from a video page and you want to stop downloading the remaining segments.
This will cancel all tasks that have the specified URL as their main m3u8 playlist URL or MP4 file URL.
After the app goes to the background, the video proxy server may be killed by the system.
You can check if the server is running when the app resumes, and restart it if necessary.
// In app lifecycle listener (e.g., AppLifecycleListener.onResume)voidonResume() async {
if (!awaitVideoProxy.isRunning()) {
awaitVideoProxy.restart();
}
// Then re-open media in your video players
}
🪧 Core Api
1. VideoProxy.init:
/// Initializes the video proxy server and related components.////// [ip]: Optional IP address for the proxy server to bind.<br>/// [port]: Optional port number for the proxy server to listen on.<br>/// [maxMemoryCacheSize]: Maximum memory cache size in MB (default: 100).<br>/// [maxStorageCacheSize]: Maximum storage cache size in MB (default: 1024).<br>/// [cacheDir]: Custom cache directory path (default: '').<br>/// [logPrint]: Enables or disables logging output (default: false).<br>/// [segmentSize]: Size of each video segment in MB (default: 2).<br>/// [maxConcurrentDownloads]: Maximum number of concurrent downloads (default: 8).<br>/// [urlMatcher]: Optional custom URL matcher for video URL filtering.<br>/// [httpClientBuilder]: Optional custom HTTP client builder for creating HTTP clients.<br>staticFuture<void> init({
String? ip,
int? port,
int maxMemoryCacheSize = 100,
int maxStorageCacheSize = 1024,
String cacheDir = '',
bool logPrint = false,
int segmentSize = 2,
int maxConcurrentDownloads = 8,
UrlMatcher? urlMatcher,
HttpClientBuilder? httpClientBuilder,
})
2. VideoCaching.precache:
/// Pre-caches the video at the specified [url].////// [url]: The video URL to be pre-cached./// [headers]: Optional HTTP headers for the request./// [cacheSegments]: Number of segments to cache (default: 2)./// [downloadNow]: If true, downloads segments immediately; if false, pushes to the queue (default: true)./// [progressListen]: If true, returns a [StreamController] with progress updates (default: false).////// Returns a [StreamController] emitting progress/status updates, or `null` if not listening.staticFuture<StreamController<Map>?> precache(
String url, {
Map<String, Object>? headers,
int cacheSegments = 2,
bool downloadNow = true,
bool progressListen = false,
})
🎛 Local Video Server
1. To start video server
run main.dart in server directory.
2. Config local domain name
Macos
run scutil --get LocalHostName in terminal to get your computer name. Then you can use http://computer-name.local:8080 to access services.
Windows
Modify the hosts in C:\Windows\System32\drivers\etc\hosts, add 127.0.0.1 computer-name.local to the end of the file. Then you can use http://computer-name.local:8080 to access services.
Linux
Modify the hosts in /etc/hosts, add 127.0.0.1 computer-name.local to the end of the file. Then you can use http://computer-name.local:8080 to access services.
❓ FAQ
1. How to set the maximum cache limit?
Set maxMemoryCacheSize and maxStorageCacheSize in VideoProxy.init.
{
'progress': 0.0, // Download progress (0.0 ~ 1.0)'segment_url': url, // Current segment URL being downloaded'parent_url': url, // Main m3u8 playlist URL'file_name': '', // Name of the segment file'hls_key': '', // The HLS key (generated from the URI) for the download, used to generate the cache directory,// so that the segments of the same video can be cached in the same directory.'total_segments': 0, // Total number of segments'current_segment_index': 0, // Index of the current segment being downloaded
}
For .mp4:
{
'progress': 0, // Download progress (0 ~ 100)'url': url, // MP4 file URL'startRange': 0, // Start byte of the current download range'endRange': 0, // End byte of the current download range
}
3. Does the library support download resume?
Yes. Downloaded segments are loaded from local cache, and unfinished segments will resume downloading when playback restarts.
4. After the cache reaches the maximum value set by the memory cache or storage cache, how does the plugin handle the cache?
LRU (Least Recently Used) cache, which evicts the least recently accessed item when the cache is full, making space for new data, based on the principle that recently used data is more likely to be used again soon.
🔧 Contributing
Contributions are welcome! Please submit issues and pull requests.