Skip to content

armgit / ente

Public Imported from GitHub
0

💚 End-to-end encrypted cloud for everything.

prefetch videos for memories under capped conditions

laurenspriem92cbfc8fc0d4
diff --git a/mobile/apps/photos/lib/services/video_preview_service.dart b/mobile/apps/photos/lib/services/video_preview_service.dart
index 0e20d7995d..666a470539 100644
--- a/mobile/apps/photos/lib/services/video_preview_service.dart
+++ b/mobile/apps/photos/lib/services/video_preview_service.dart
@@ -26,6 +26,7 @@ import "package:photos/gateways/files/file_data_gateway.dart";
import "package:photos/generated/intl/app_localizations.dart";
import "package:photos/models/base/id.dart";
import "package:photos/models/ffmpeg/ffprobe_props.dart";
+import "package:photos/models/file/extensions/file_props.dart";
import "package:photos/models/file/file.dart";
import "package:photos/models/file/file_type.dart";
import "package:photos/models/metadata/file_magic.dart";
@@ -892,7 +893,64 @@ class VideoPreviewService {
return await _getPlaylist(file);
}
- Future<PlaylistData?> _getPlaylist(EnteFile file) async {
+ Future<bool> prefetchExistingPreview(
+ EnteFile file, {
+ required int maxPreviewSizeBytes,
+ bool Function(int bytes)? tryReserveBytes,
+ }) async {
+ if (file.fileType != FileType.video || file.uploadedFileID == null) {
+ return false;
+ }
+ try {
+ await _ensurePreviewIdsInitialized();
+ Future<bool> isPreviewCached(PreviewInfo previewInfo) async {
+ final cachedPreview = await videoCacheManager.getFileFromCache(
+ _getVideoPreviewKey(previewInfo.objectId),
+ );
+ return cachedPreview != null;
+ }
+
+ final previewInfo = fileDataService.previewIds[file.uploadedFileID!];
+ if (previewInfo != null) {
+ if (await isPreviewCached(previewInfo)) {
+ return true;
+ }
+ if (previewInfo.objectSize > maxPreviewSizeBytes) {
+ return false;
+ }
+ }
+ if (previewInfo == null && file.isOwner) {
+ return false;
+ }
+ final playlist = await _getPlaylist(
+ file,
+ awaitPreviewCache: true,
+ maxPreviewSizeBytes: maxPreviewSizeBytes,
+ tryReserveBytes: tryReserveBytes,
+ );
+ if (playlist == null) {
+ return false;
+ }
+ final warmedPreviewInfo =
+ fileDataService.previewIds[file.uploadedFileID!];
+ return warmedPreviewInfo != null &&
+ await isPreviewCached(warmedPreviewInfo);
+ } catch (e, s) {
+ _logger.fine(
+ "Failed to prefetch preview video for ${file.uploadedFileID}",
+ e,
+ s,
+ );
+ return false;
+ }
+ }
+
+ Future<PlaylistData?> _getPlaylist(
+ EnteFile file, {
+ bool awaitPreviewCache = false,
+ int? maxPreviewSizeBytes,
+ bool Function(int bytes)? tryReserveBytes,
+ }) async {
_logger.fine("Getting playlist for $file");
int? width, height, size;
@@ -955,20 +1013,42 @@ class VideoPreviewService {
_getVideoPreviewKey(objectID),
))
?.file;
+ final effectiveSize = size ?? previewInfo?.objectSize;
+ final maxPreviewCacheSize =
+ maxPreviewSizeBytes ?? _maxPreviewSizeLimitForCache;
if (videoFile == null) {
previewURLResult = previewURLResult ?? await _getPreviewUrl(file);
- if (size != null && size < _maxPreviewSizeLimitForCache) {
- unawaited(
- videoCacheManager.downloadFile(
+ final canCachePreview = effectiveSize != null &&
+ effectiveSize <= maxPreviewCacheSize &&
+ (tryReserveBytes == null || tryReserveBytes(effectiveSize));
+ if (canCachePreview) {
+ if (awaitPreviewCache) {
+ final previewFile = await videoCacheManager.downloadFile(
previewURLResult.$1,
key: _getVideoPreviewKey(objectID),
- ),
+ );
+ finalPlaylist = finalPlaylist.replaceAll(
+ '\noutput.ts',
+ '\n${previewFile.file.path}',
+ );
+ } else {
+ unawaited(
+ videoCacheManager.downloadFile(
+ previewURLResult.$1,
+ key: _getVideoPreviewKey(objectID),
+ ),
+ );
+ finalPlaylist = finalPlaylist.replaceAll(
+ '\noutput.ts',
+ '\n${previewURLResult.$1}',
+ );
+ }
+ } else {
+ finalPlaylist = finalPlaylist.replaceAll(
+ '\noutput.ts',
+ '\n${previewURLResult.$1}',
);
}
- finalPlaylist = finalPlaylist.replaceAll(
- '\noutput.ts',
- '\n${previewURLResult.$1}',
- );
} else {
finalPlaylist = finalPlaylist.replaceAll(
'\noutput.ts',
@@ -990,7 +1070,7 @@ class VideoPreviewService {
preview: playlistFile,
width: width,
height: height,
- size: size,
+ size: effectiveSize,
durationInSeconds: parseDurationFromHLS(finalPlaylist),
);
if (shouldAppendPreview) {
diff --git a/mobile/apps/photos/lib/ui/home/memories/full_screen_memory.dart b/mobile/apps/photos/lib/ui/home/memories/full_screen_memory.dart
index eac08ff54d..6f21301034 100644
--- a/mobile/apps/photos/lib/ui/home/memories/full_screen_memory.dart
+++ b/mobile/apps/photos/lib/ui/home/memories/full_screen_memory.dart
@@ -32,6 +32,7 @@ import "package:photos/ui/actions/file/file_actions.dart";
import "package:photos/ui/components/base_bottom_sheet.dart";
import "package:photos/ui/home/memories/custom_listener.dart";
import "package:photos/ui/home/memories/memory_progress_indicator.dart";
+import "package:photos/ui/home/memories/memory_video_prefetcher.dart";
import "package:photos/ui/viewer/file/file_widget.dart";
import "package:photos/ui/viewer/file/thumbnail_widget.dart";
import "package:photos/ui/viewer/file_details/favorite_widget.dart";
@@ -81,6 +82,7 @@ class _FullScreenMemoryDataUpdaterState
StreamSubscription<List<ConnectivityResult>>? _connectivitySubscription;
final _ownedThumbnailRefs = <int, ({EnteFile file, Object token})>{};
final _pendingThumbnailRefIDs = <int>{};
+ final _videoPrefetcher = MemoryVideoPrefetcher();
// Seeded from checkConnectivity() before the listener attaches, so a real
// offline→online recovery (fire retry) is distinguishable from a WiFi↔
// cellular handoff where the old requests are still healthy.
@@ -95,6 +97,7 @@ class _FullScreenMemoryDataUpdaterState
widget.memories.length == widget.initialIndex + 1,
);
_warmThumbnailWindow(widget.initialIndex);
+ _warmVideoWindow(widget.initialIndex + 1);
unawaited(_setupConnectivityListener());
}
@@ -125,7 +128,9 @@ class _FullScreenMemoryDataUpdaterState
// the stale map entries; a synchronous call would re-bump the
// refcounts before the cancellation.
scheduleMicrotask(() {
- if (mounted) _warmThumbnailWindow(currentIndex);
+ if (!mounted) return;
+ _warmThumbnailWindow(currentIndex);
+ _warmVideoWindow(currentIndex + 1);
});
}
});
@@ -145,6 +150,20 @@ class _FullScreenMemoryDataUpdaterState
}
}
+ void _warmVideoWindow(int fromIndex) {
+ final start = fromIndex.clamp(0, widget.memories.length).toInt();
+ final end = (start + kMemoryVideoLookaheadCap)
+ .clamp(
+ 0,
+ widget.memories.length,
+ )
+ .toInt();
+ _videoPrefetcher.prefetchFiles(
+ widget.memories.sublist(start, end).map((memory) => memory.file),
+ replacePending: true,
+ );
+ }
+
void _preloadThumbnailOwned(EnteFile file) {
if (!file.isRemoteFile) {
preloadThumbnail(file);
@@ -204,6 +223,7 @@ class _FullScreenMemoryDataUpdaterState
void dispose() {
_connectivitySubscription?.cancel();
_releaseOwnedThumbnailRefs();
+ _videoPrefetcher.dispose();
indexNotifier.dispose();
super.dispose();
}
@@ -226,6 +246,7 @@ class _FullScreenMemoryDataUpdaterState
indexNotifier: indexNotifier,
removeCurrentMemory: removeCurrentMemory,
preloadThumbnail: _preloadThumbnailOwned,
+ preloadVideos: _warmVideoWindow,
child: widget.child,
);
}
@@ -236,12 +257,14 @@ class FullScreenMemoryData extends InheritedWidget {
final ValueNotifier<int> indexNotifier;
final VoidCallback removeCurrentMemory;
final void Function(EnteFile file) preloadThumbnail;
+ final void Function(int fromIndex) preloadVideos;
const FullScreenMemoryData({
required this.memories,
required this.indexNotifier,
required this.removeCurrentMemory,
required this.preloadThumbnail,
+ required this.preloadVideos,
required super.child,
super.key,
});
@@ -639,6 +662,7 @@ class _FullScreenMemoryState extends State<FullScreenMemory> {
if (j >= inheritedData.memories.length) break;
preloadFile(inheritedData.memories[j].file);
}
+ inheritedData.preloadVideos(index + 1);
final currentMemory = inheritedData.memories[index];
final isVideo =
currentMemory.file.fileType == FileType.video;
diff --git a/mobile/apps/photos/lib/ui/home/memories/memories_widget.dart b/mobile/apps/photos/lib/ui/home/memories/memories_widget.dart
index e880fdd534..7f757a6232 100644
--- a/mobile/apps/photos/lib/ui/home/memories/memories_widget.dart
+++ b/mobile/apps/photos/lib/ui/home/memories/memories_widget.dart
@@ -11,6 +11,7 @@ import "package:photos/models/memories/smart_memory.dart";
import "package:photos/service_locator.dart";
import "package:photos/ui/home/memories/memory_cover_util.dart";
import 'package:photos/ui/home/memories/memory_cover_widget.dart';
+import "package:photos/ui/home/memories/memory_video_prefetcher.dart";
class MemoriesWidget extends StatefulWidget {
const MemoriesWidget({super.key});
@@ -32,6 +33,7 @@ class _MemoriesWidgetState extends State<MemoriesWidget> {
Timer? _warmTimer;
int _warmGeneration = 0;
String? _lastWarmSignature;
+ final _videoPrefetcher = MemoryVideoPrefetcher();
@override
void initState() {
@@ -72,6 +74,7 @@ class _MemoriesWidgetState extends State<MemoriesWidget> {
_memoriesChangedSubscription.cancel();
_memorySeenSubscription.cancel();
_warmTimer?.cancel();
+ _videoPrefetcher.dispose();
super.dispose();
}
@@ -144,9 +147,18 @@ class _MemoriesWidgetState extends State<MemoriesWidget> {
_warmTimer?.cancel();
_warmTimer = Timer(const Duration(seconds: 5), () {
if (!mounted || gen != _warmGeneration) return;
+ final memoryLists = collated.map((e) => e.$1).toList(growable: false);
+ _videoPrefetcher.prefetchFiles(
+ memoryLists
+ .take(kMemoryCoverWarmCap)
+ .where((memories) => memories.isNotEmpty)
+ .map((memories) => memories[getNextMemoryIndex(memories)].file),
+ stillActive: () => mounted && gen == _warmGeneration,
+ replacePending: true,
+ );
unawaited(
warmMemoryCovers(
- collated.map((e) => e.$1).toList(growable: false),
+ memoryLists,
stillActive: () => mounted && gen == _warmGeneration,
),
);
@@ -169,13 +181,15 @@ class _MemoriesWidgetState extends State<MemoriesWidget> {
// Kill any pending or in-flight warm pass: cancels the delay timer, bumps
// the generation so a running warmMemoryCovers loop exits at its next
- // stillActive check, and clears the last-warmed marker so a subsequent
- // dataset re-schedules even if it's the same reference as before.
+ // stillActive check, clears pending video work, and clears the last-warmed
+ // marker so a subsequent dataset re-schedules even if it's the same
+ // reference as before.
void _cancelPendingWarm() {
_warmTimer?.cancel();
_warmTimer = null;
_warmGeneration++;
_lastWarmSignature = null;
+ _videoPrefetcher.clearPending();
}
Widget _buildMemories(List<(List<Memory>, String)> collated) {
diff --git a/mobile/apps/photos/lib/ui/home/memories/memory_video_prefetcher.dart b/mobile/apps/photos/lib/ui/home/memories/memory_video_prefetcher.dart
new file mode 100644
index 0000000000..7dd4f15344
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/home/memories/memory_video_prefetcher.dart
@@ -0,0 +1,159 @@
+import "dart:async";
+import "dart:collection";
+
+import "package:photos/models/file/file.dart";
+import "package:photos/models/file/file_type.dart";
+import "package:photos/service_locator.dart" show isOfflineMode;
+import "package:photos/services/video_preview_service.dart";
+import "package:photos/utils/file_util.dart";
+import "package:photos/utils/network_util.dart";
+
+const int kMemoryVideoLookaheadCap = 20;
+const int kMemoryVideoMaxConcurrentPrefetches = 1;
+
+const int kMemoryVideoPreviewMaxBytes = 25 * 1024 * 1024;
+const int kMemoryVideoOriginalMaxBytes = 25 * 1024 * 1024;
+const int kMemoryVideoOriginalMaxDurationSeconds = 30;
+const int kMemoryVideoSessionBudgetBytes = 100 * 1024 * 1024;
+
+class MemoryVideoPrefetcher {
+ final Queue<({EnteFile file, bool Function()? stillActive})> _queue =
+ Queue<({EnteFile file, bool Function()? stillActive})>();
+ final Set<int> _queuedIDs = <int>{};
+ final Set<int> _attemptedIDs = <int>{};
+
+ int _activeCount = 0;
+ int _reservedDownloadBytes = 0;
+ bool _disposed = false;
+
+ void prefetchFiles(
+ Iterable<EnteFile> files, {
+ bool Function()? stillActive,
+ bool replacePending = false,
+ }) {
+ if (_disposed || isOfflineMode) return;
+ if (replacePending) {
+ clearPending();
+ }
+ for (final file in files) {
+ if (stillActive != null && !stillActive()) return;
+ _enqueue(file, stillActive);
+ }
+ _pump();
+ }
+
+ void clearPending() {
+ _queue.clear();
+ _queuedIDs.clear();
+ }
+
+ void dispose() {
+ _disposed = true;
+ clearPending();
+ }
+
+ void _enqueue(EnteFile file, bool Function()? stillActive) {
+ if (file.fileType != FileType.video || !file.isRemoteFile) return;
+ final uploadedFileID = file.uploadedFileID;
+ if (uploadedFileID == null) return;
+ if (_attemptedIDs.contains(uploadedFileID) ||
+ _queuedIDs.contains(uploadedFileID)) {
+ return;
+ }
+ _queue.add((file: file, stillActive: stillActive));
+ _queuedIDs.add(uploadedFileID);
+ }
+
+ void _pump() {
+ if (_disposed || isOfflineMode) return;
+ while (_activeCount < kMemoryVideoMaxConcurrentPrefetches &&
+ _queue.isNotEmpty) {
+ final entry = _queue.removeFirst();
+ final file = entry.file;
+ final uploadedFileID = file.uploadedFileID;
+ if (uploadedFileID == null) continue;
+ _queuedIDs.remove(uploadedFileID);
+ if (_attemptedIDs.contains(uploadedFileID)) continue;
+ if (!_isActive(entry.stillActive)) continue;
+
+ _activeCount++;
+ unawaited(
+ _prefetch(file, uploadedFileID, entry.stillActive).whenComplete(() {
+ _activeCount--;
+ _pump();
+ }),
+ );
+ }
+ }
+
+ bool _isActive(bool Function()? stillActive) {
+ return !_disposed &&
+ !isOfflineMode &&
+ (stillActive == null || stillActive());
+ }
+
+ bool _tryReserveDownloadBytes(int bytes) {
+ if (_reservedDownloadBytes + bytes > kMemoryVideoSessionBudgetBytes) {
+ return false;
+ }
+ _reservedDownloadBytes += bytes;
+ return true;
+ }
+
+ Future<void> _prefetch(
+ EnteFile file,
+ int uploadedFileID,
+ bool Function()? stillActive,
+ ) async {
+ try {
+ if (!_isActive(stillActive)) return;
+ if (!await canUseHighBandwidth()) return;
+ if (!_isActive(stillActive)) return;
+
+ final didWarmPreview =
+ await VideoPreviewService.instance.prefetchExistingPreview(
+ file,
+ maxPreviewSizeBytes: kMemoryVideoPreviewMaxBytes,
+ tryReserveBytes: (bytes) {
+ return _isActive(stillActive) && _tryReserveDownloadBytes(bytes);
+ },
+ );
+ if (!_isActive(stillActive)) return;
+ if (!didWarmPreview) {
+ await _prefetchSmallOriginal(file, stillActive: stillActive);
+ }
+ if (!_isActive(stillActive)) return;
+ _attemptedIDs.add(uploadedFileID);
+ } catch (_) {
+ if (!_isActive(stillActive)) return;
+ _attemptedIDs.add(uploadedFileID);
+ }
+ }
+
+ Future<bool> _prefetchSmallOriginal(
+ EnteFile file, {
+ bool Function()? stillActive,
+ }) async {
+ final fileSize = file.fileSize;
+ final duration = file.duration;
+ if (fileSize == null ||
+ fileSize <= 0 ||
+ fileSize > kMemoryVideoOriginalMaxBytes ||
+ duration == null ||
+ duration <= 0 ||
+ duration > kMemoryVideoOriginalMaxDurationSeconds) {
+ return false;
+ }
+ if (await isFileCached(file)) {
+ return true;
+ }
+ if (!_isActive(stillActive)) {
+ return false;
+ }
+ if (!_tryReserveDownloadBytes(fileSize)) {
+ return false;
+ }
+ final prefetchedFile = await getFileFromServer(file);
+ return prefetchedFile != null;
+ }
+}