Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Single DB call and batch frame building to make fetching frames a lot faster

laurenspriemc84b530b842f
diff --git a/mobile/apps/photos/lib/ui/viewer/people/memory_lane_page.dart b/mobile/apps/photos/lib/ui/viewer/people/memory_lane_page.dart
index 2c1ddf87d7..85cc876ca3 100644
--- a/mobile/apps/photos/lib/ui/viewer/people/memory_lane_page.dart
+++ b/mobile/apps/photos/lib/ui/viewer/people/memory_lane_page.dart
@@ -11,6 +11,7 @@ import "package:photos/db/files_db.dart";
import "package:photos/db/ml/db.dart";
import "package:photos/ente_theme_data.dart";
import "package:photos/l10n/l10n.dart";
+import "package:photos/models/file/file.dart";
import "package:photos/models/memory_lane/memory_lane_models.dart";
import "package:photos/models/ml/face/face.dart";
import "package:photos/models/ml/face/person.dart";
@@ -55,6 +56,7 @@ class _MemoryLanePageState extends State<MemoryLanePage>
static const double _controlsHeightFallback = 140;
// Wait for this many frames (or the available total) before auto-starting playback.
static const int _initialFrameTarget = 120;
+ static const int _frameBuildConcurrency = 6;
static const double _appBarSideWidth = kToolbarHeight;
final Logger _logger = Logger("MemoryLanePage");
@@ -125,7 +127,10 @@ class _MemoryLanePageState extends State<MemoryLanePage>
_stackProgressNotifier.value = value;
}
+ String _ms(Duration duration) => "${duration.inMilliseconds}ms";
+
Future<void> _loadFrames() async {
+ final loadStopwatch = Stopwatch()..start();
_hasMarkedTimelineSeen =
localSettings.hasSeenMemoryLane(widget.person.remoteID);
_playTimer?.cancel();
@@ -135,9 +140,17 @@ class _MemoryLanePageState extends State<MemoryLanePage>
});
}
try {
+ final timelineStopwatch = Stopwatch()..start();
final timeline = await MemoryLaneService.instance.getTimeline(
widget.person.remoteID,
);
+ final timelineFetchTime = timelineStopwatch.elapsed;
+ _logger.info(
+ "memory_lane timeline_fetch person=${widget.person.remoteID} "
+ "elapsed=${_ms(timelineFetchTime)} "
+ "status=${timeline?.status.name ?? "null"} "
+ "entries=${timeline?.entries.length ?? 0}",
+ );
if (!mounted) {
return;
}
@@ -187,14 +200,28 @@ class _MemoryLanePageState extends State<MemoryLanePage>
..value = 0;
int loadedCount = 0;
- for (final entry in entries) {
- final frame = await _buildFrame(entry);
- if (!mounted) {
- return;
- }
- loadedCount += 1;
- _handleFrameLoaded(frame, loadedCount);
- }
+ final uniqueFileIds =
+ entries.map((entry) => entry.fileId).toSet().toList();
+ final filesById =
+ await FilesDB.instance.getFileIDToFileFromIDs(uniqueFileIds);
+ final Map<int, Future<List<Face>?>> facesFutures = {};
+
+ final frameStats = await _buildFramesInParallel(
+ entries: entries,
+ filesById: filesById,
+ facesFutures: facesFutures,
+ onFrameReady: (builtFrame) {
+ if (!mounted) {
+ return;
+ }
+ loadedCount += 1;
+ _handleFrameLoaded(
+ builtFrame.frame,
+ loadedCount,
+ buildDuration: builtFrame.buildDuration,
+ );
+ },
+ );
if (!mounted) {
return;
@@ -202,6 +229,15 @@ class _MemoryLanePageState extends State<MemoryLanePage>
setState(() {
_allFramesLoaded = true;
});
+ final double averageFrameMs =
+ loadedCount > 0 ? frameStats.totalFrameMs / loadedCount : 0;
+ _logger.info(
+ "memory_lane load_complete person=${widget.person.remoteID} "
+ "frames=$loadedCount total=${_ms(loadStopwatch.elapsed)} "
+ "avgFrameMs=${averageFrameMs.toStringAsFixed(1)} "
+ "firstFrame=${frameStats.firstFrameDuration != null ? _ms(frameStats.firstFrameDuration!) : "n/a"} "
+ "expected=$_expectedFrameCount",
+ );
_maybeMarkTimelineSeen();
} catch (error, stackTrace) {
_logger.severe(
@@ -242,7 +278,11 @@ class _MemoryLanePageState extends State<MemoryLanePage>
);
}
- void _handleFrameLoaded(_TimelineFrame frame, int loadedCount) {
+ void _handleFrameLoaded(
+ _TimelineFrame frame,
+ int loadedCount, {
+ Duration? buildDuration,
+ }) {
final bool isFirstFrame = _frames.isEmpty;
final int digitCount = _captionDigitCount(frame.captionValue);
setState(() {
@@ -261,10 +301,20 @@ class _MemoryLanePageState extends State<MemoryLanePage>
}
});
if (isFirstFrame) {
+ if (buildDuration != null) {
+ _logger.info(
+ "memory_lane first_frame_ready person=${widget.person.remoteID} "
+ "duration=${_ms(buildDuration)}",
+ );
+ }
_updateStackProgress(0);
}
if (!_hasStartedPlayback && loadedCount >= _initialFrameThreshold) {
_hasStartedPlayback = true;
+ _logger.info(
+ "memory_lane auto_start person=${widget.person.remoteID} "
+ "loaded=$loadedCount threshold=$_initialFrameThreshold",
+ );
_startPlayback();
_logPlaybackStart(_expectedFrameCount);
}
@@ -275,37 +325,164 @@ class _MemoryLanePageState extends State<MemoryLanePage>
return math.max(1, rounded.toString().length);
}
- Future<_TimelineFrame> _buildFrame(MemoryLaneEntry entry) async {
- final file = await FilesDB.instance.getAnyUploadedFile(entry.fileId);
+ Future<_FrameBuildStats> _buildFramesInParallel({
+ required List<MemoryLaneEntry> entries,
+ required Map<int, EnteFile> filesById,
+ required Map<int, Future<List<Face>?>> facesFutures,
+ required void Function(_BuiltFrame builtFrame) onFrameReady,
+ }) async {
+ final readyFrames = <int, _BuiltFrame?>{};
+ final completer = Completer<_FrameBuildStats>();
+ int nextEmitIndex = 0;
+ int inFlight = 0;
+ int started = 0;
+ int totalFrameMs = 0;
+ Duration? firstFrameDuration;
+
+ void maybeComplete() {
+ if (!completer.isCompleted &&
+ nextEmitIndex >= entries.length &&
+ inFlight == 0 &&
+ started >= entries.length) {
+ completer.complete(
+ _FrameBuildStats(
+ totalFrameMs: totalFrameMs,
+ firstFrameDuration: firstFrameDuration,
+ ),
+ );
+ }
+ }
+
+ void emitReady() {
+ while (readyFrames.containsKey(nextEmitIndex)) {
+ final _BuiltFrame? built = readyFrames.remove(nextEmitIndex);
+ if (built != null) {
+ totalFrameMs += built.buildDuration.inMilliseconds;
+ firstFrameDuration ??= built.buildDuration;
+ onFrameReady(built);
+ }
+ nextEmitIndex += 1;
+ }
+ maybeComplete();
+ }
+
+ void startNext() {
+ while (inFlight < _frameBuildConcurrency && started < entries.length) {
+ final int index = started;
+ started += 1;
+ inFlight += 1;
+ final entry = entries[index];
+ final facesFuture = facesFutures.putIfAbsent(
+ entry.fileId,
+ () => MLDataDB.instance.getFacesForGivenFileID(entry.fileId),
+ );
+ _buildFrame(
+ entry,
+ file: filesById[entry.fileId],
+ facesFuture: facesFuture,
+ ).then((built) {
+ readyFrames[index] = built;
+ }).catchError((error, stackTrace) {
+ _logger.warning(
+ "memory_lane frame_build_failed person=${widget.person.remoteID} "
+ "fileId=${entry.fileId} faceId=${entry.faceId}",
+ error,
+ stackTrace,
+ );
+ readyFrames[index] = null;
+ }).whenComplete(() {
+ inFlight -= 1;
+ emitReady();
+ startNext();
+ });
+ }
+ maybeComplete();
+ }
+
+ startNext();
+ return completer.future;
+ }
+
+ Future<_BuiltFrame> _buildFrame(
+ MemoryLaneEntry entry, {
+ EnteFile? file,
+ Future<List<Face>?>? facesFuture,
+ }) async {
+ final totalStopwatch = Stopwatch()..start();
+ final Stopwatch stepStopwatch = Stopwatch()..start();
+ Duration fileFetchDuration = Duration.zero;
+ Duration facesFetchDuration = Duration.zero;
+ Duration cropFetchDuration = Duration.zero;
+ bool fileFound = false;
+ int facesCount = 0;
+ String cropStatus = "skipped";
+ EnteFile? effectiveFile = file;
+ effectiveFile ??= await FilesDB.instance.getAnyUploadedFile(entry.fileId);
+ fileFetchDuration = stepStopwatch.elapsed;
+ stepStopwatch
+ ..reset()
+ ..start();
MemoryImage? image;
- if (file != null) {
- final faces = await MLDataDB.instance.getFacesForGivenFileID(
- entry.fileId,
- );
+ Uint8List? bytes;
+ if (effectiveFile != null) {
+ fileFound = true;
+ final List<Face>? faces;
+ if (facesFuture != null) {
+ faces = await facesFuture;
+ } else {
+ faces = await MLDataDB.instance.getFacesForGivenFileID(entry.fileId);
+ }
+ facesFetchDuration = stepStopwatch.elapsed;
+ stepStopwatch
+ ..reset()
+ ..start();
+ facesCount = faces?.length ?? 0;
final Face? face = faces?.firstWhereOrNull(
(element) => element.faceID == entry.faceId,
);
if (face != null) {
try {
+ final cropStopwatch = Stopwatch()..start();
final cropMap = await getCachedFaceCrops(
- file,
+ effectiveFile,
[face],
useFullFile: true,
useTempCache: false,
);
- final Uint8List? bytes = cropMap?[face.faceID];
+ bytes = cropMap?[face.faceID];
+ cropFetchDuration = cropStopwatch.elapsed;
if (bytes != null && bytes.isNotEmpty) {
image = MemoryImage(bytes);
+ cropStatus = "hit";
+ } else {
+ cropStatus = "empty";
}
} catch (error, stackTrace) {
+ cropStatus = "error";
_logger.warning(
"Failed to fetch face crop for ${entry.faceId}",
error,
stackTrace,
);
}
+ } else {
+ cropStatus = "face_missing";
}
+ } else {
+ cropStatus = "file_missing";
}
+ final totalDuration = totalStopwatch.elapsed;
+ _logger.fine(
+ "memory_lane frame_build person=${widget.person.remoteID} "
+ "fileId=${entry.fileId} faceId=${entry.faceId} "
+ "fileMs=${_ms(fileFetchDuration)} "
+ "facesMs=${_ms(facesFetchDuration)} "
+ "cropMs=${_ms(cropFetchDuration)} "
+ "totalMs=${_ms(totalDuration)} "
+ "fileFound=$fileFound faces=$facesCount "
+ "cropStatus=$cropStatus imageReady=${image != null} "
+ "bytes=${bytes?.length ?? 0}",
+ );
final creationDate = DateTime.fromMicrosecondsSinceEpoch(
entry.creationTimeMicros,
);
@@ -325,13 +502,14 @@ class _MemoryLanePageState extends State<MemoryLanePage>
captionValue = _yearsBetween(creationDate, DateTime.now());
}
captionValue = captionValue.clamp(0, double.infinity);
- return _TimelineFrame(
+ final timelineFrame = _TimelineFrame(
entry: entry,
image: image,
creationDate: creationDate,
captionType: captionType,
captionValue: captionValue,
);
+ return _BuiltFrame(frame: timelineFrame, buildDuration: totalDuration);
}
void _scheduleCardGapUpdate(double candidateGap) {
@@ -1399,3 +1577,23 @@ int _maxValueForDigits(int digits) {
}
return value;
}
+
+class _BuiltFrame {
+ final _TimelineFrame frame;
+ final Duration buildDuration;
+
+ const _BuiltFrame({
+ required this.frame,
+ required this.buildDuration,
+ });
+}
+
+class _FrameBuildStats {
+ final int totalFrameMs;
+ final Duration? firstFrameDuration;
+
+ const _FrameBuildStats({
+ required this.totalFrameMs,
+ required this.firstFrameDuration,
+ });
+}