Skip to content

armgit / ente

Public Imported from GitHub
0

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

Implement kd tree for location clustering

laurenspriem4cfcb77c8b0f
diff --git a/mobile/apps/photos/lib/services/location_service.dart b/mobile/apps/photos/lib/services/location_service.dart
index b658e734d5..d9840a7eb0 100644
--- a/mobile/apps/photos/lib/services/location_service.dart
+++ b/mobile/apps/photos/lib/services/location_service.dart
@@ -30,9 +30,14 @@ class LocationService {
// need to refresh the discovery section after the cities are loaded.
bool reloadLocationDiscoverySection = false;
- static const kCitiesRemotePath = "https://static.ente.io/world_cities.json";
+ static const _kCitiesKdTreeRemotePath =
+ "https://assets.ente.io/world_cities.kdtree.bin";
List<City> _cities = [];
+ List<List<int>> _kdTreeNodes = [];
+ int _kdTreeRoot = -1;
+ double _kdTreeMaxLatDelta = 0;
+ double _kdTreeMaxLngDelta = 0;
// TODO: lau: consider actually using this in location section
List<BaseLocation> baseLocations = [];
@@ -74,13 +79,20 @@ class LocationService {
}
final EnteWatch w = EnteWatch("cities_search")..start();
w.log('start for files ${allFiles.length} and query $query');
+ final args = <String, dynamic>{
+ "query": query,
+ "cities": _cities,
+ "files": allFiles,
+ };
+ if (_kdTreeNodes.isNotEmpty && _kdTreeRoot >= 0) {
+ args["kdTreeNodes"] = _kdTreeNodes;
+ args["kdTreeRoot"] = _kdTreeRoot;
+ args["kdTreeMaxLatDelta"] = _kdTreeMaxLatDelta;
+ args["kdTreeMaxLngDelta"] = _kdTreeMaxLngDelta;
+ }
final result = await _computer.compute(
getCityResults,
- param: {
- "query": query,
- "cities": _cities,
- "files": allFiles,
- },
+ param: args,
);
w.log(
'end for query: $query on ${allFiles.length} files, found '
@@ -247,16 +259,27 @@ class LocationService {
}
}
+ void _applyKdTreeLoadResult(Map<String, dynamic> result) {
+ _cities = result["cities"] as List<City>;
+ _kdTreeNodes = (result["nodes"] as List).cast<List<int>>();
+ _kdTreeRoot = result["root"] as int;
+ _kdTreeMaxLatDelta = (result["maxLatDelta"] as num).toDouble();
+ _kdTreeMaxLngDelta = (result["maxLngDelta"] as num).toDouble();
+ }
+
Future<void> _loadCities() async {
+ final startTime = DateTime.now();
try {
- final file =
- await RemoteAssetsService.instance.getAsset(kCitiesRemotePath);
- final startTime = DateTime.now();
- _cities =
- await _computer.compute(parseCities, param: {"filePath": file.path});
- final endTime = DateTime.now();
+ final file = await RemoteAssetsService.instance.getAsset(
+ _kCitiesKdTreeRemotePath,
+ );
+ final kdTreeResult = await _computer.compute(
+ parseCitiesFromKdTreeBin,
+ param: {"filePath": file.path},
+ );
+ _applyKdTreeLoadResult(kdTreeResult);
_logger.info(
- "Loaded cities in ${(endTime.millisecondsSinceEpoch - startTime.millisecondsSinceEpoch)}ms, reloadingDiscovery: $reloadLocationDiscoverySection",
+ "Loaded KD-tree cities from CDN in ${(DateTime.now().millisecondsSinceEpoch - startTime.millisecondsSinceEpoch)}ms, reloadingDiscovery: $reloadLocationDiscoverySection",
);
if (reloadLocationDiscoverySection) {
reloadLocationDiscoverySection = false;
@@ -264,7 +287,7 @@ class LocationService {
.fire(LocationTagUpdatedEvent(LocTagEventType.dataSetLoaded));
}
} catch (e, s) {
- _logger.severe("Failed to load cities", e, s);
+ _logger.severe("Failed to load KD-tree cities", e, s);
}
}
}
@@ -304,45 +327,288 @@ Map<LocationTag, int> _getLocationTagsToOccurenceForIsolate(
return locationTagToOccurence;
}
-Future<List<City>> parseCities(Map args) async {
- final file = File(args["filePath"]);
- final citiesJson = json.decode(await file.readAsString());
+Future<Map<String, dynamic>> parseCitiesFromKdTreeBin(Map args) async {
+ final String filePath = args["filePath"] as String;
+ final payload = ByteData.sublistView(await File(filePath).readAsBytes());
+ final buffer = payload.buffer;
+ final baseOffset = payload.offsetInBytes;
+ const endian = Endian.little;
+
+ final magic = String.fromCharCodes(
+ [
+ payload.getUint8(0),
+ payload.getUint8(1),
+ payload.getUint8(2),
+ payload.getUint8(3),
+ ],
+ );
+ if (magic != "KDT1") {
+ throw FormatException("Unsupported KD-tree magic: $magic");
+ }
+ final headerSize = payload.getUint16(4, endian);
+ final version = payload.getUint16(6, endian);
+ if (headerSize < 64 || version != 1) {
+ throw FormatException(
+ "Unsupported KD-tree header: size=$headerSize version=$version",
+ );
+ }
+ final flags = payload.getUint32(8, endian);
+ if ((flags & 0x1) == 0) {
+ throw const FormatException("Unsupported KD-tree coordinate format");
+ }
+
+ final nodeCount = payload.getUint32(12, endian);
+ final pointCount = payload.getUint32(16, endian);
+ final cityCount = payload.getUint32(20, endian);
+ final countryCount = payload.getUint32(24, endian);
+ final rootIndex = payload.getInt32(28, endian);
+ final nodesOffset = payload.getUint32(32, endian);
+ final pointsOffset = payload.getUint32(36, endian);
+ final citiesOffsetsOffset = payload.getUint32(40, endian);
+ final citiesBlobOffset = payload.getUint32(44, endian);
+ final countriesOffsetsOffset = payload.getUint32(48, endian);
+ final countriesBlobOffset = payload.getUint32(52, endian);
+
+ final parsedNodes = <List<int>>[];
+ final nodesBaseOffset = nodesOffset;
+ for (var i = 0; i < nodeCount; i += 1) {
+ final nodeOffset = nodesBaseOffset + i * 16;
+ parsedNodes.add(
+ [
+ payload.getInt32(nodeOffset, endian),
+ payload.getInt32(nodeOffset + 4, endian),
+ payload.getInt32(nodeOffset + 8, endian),
+ payload.getInt32(nodeOffset + 12, endian),
+ ],
+ );
+ }
+
+ final cityOffsets = List<int>.generate(
+ cityCount + 1,
+ (index) => payload.getUint32(citiesOffsetsOffset + index * 4, endian),
+ growable: false,
+ );
+ final cityBlobLength = cityOffsets[cityCount];
+ final cityBlob = Uint8List.view(
+ buffer,
+ baseOffset + citiesBlobOffset,
+ cityBlobLength,
+ );
+ final cityNames = List<String>.generate(
+ cityCount,
+ (index) {
+ final start = cityOffsets[index];
+ final end = cityOffsets[index + 1];
+ return utf8.decode(cityBlob.sublist(start, end));
+ },
+ growable: false,
+ );
+
+ final countryOffsets = List<int>.generate(
+ countryCount + 1,
+ (index) => payload.getUint32(countriesOffsetsOffset + index * 4, endian),
+ growable: false,
+ );
+ final countryBlobLength = countryOffsets[countryCount];
+ final countryBlob = Uint8List.view(
+ buffer,
+ baseOffset + countriesBlobOffset,
+ countryBlobLength,
+ );
+ final countryNames = List<String>.generate(
+ countryCount,
+ (index) {
+ final start = countryOffsets[index];
+ final end = countryOffsets[index + 1];
+ return utf8.decode(countryBlob.sublist(start, end));
+ },
+ growable: false,
+ );
+
+ final cities = <City>[];
+ double maxA = 0;
+ double maxB = 0;
+ final pointsBaseOffset = pointsOffset;
+ for (var i = 0; i < pointCount; i += 1) {
+ final pointOffset = pointsBaseOffset + i * 16;
+ final lat = payload.getFloat32(pointOffset, endian);
+ final lng = payload.getFloat32(pointOffset + 4, endian);
+ final cityIndex = payload.getUint32(pointOffset + 8, endian);
+ final countryIndex = payload.getUint32(pointOffset + 12, endian);
+ final a = (defaultCityRadius * scaleFactor(lat)) / kilometersPerDegree;
+ const b = defaultCityRadius / kilometersPerDegree;
+ cities.add(
+ City(
+ city: cityNames[cityIndex],
+ country: countryNames[countryIndex],
+ lat: lat,
+ lng: lng,
+ a: a,
+ aSquare: a * a,
+ b: b,
+ bSquare: b * b,
+ ),
+ );
+ if (a > maxA) {
+ maxA = a;
+ }
+ if (b > maxB) {
+ maxB = b;
+ }
+ }
+
+ return {
+ "cities": cities,
+ "nodes": parsedNodes,
+ "root": rootIndex,
+ "maxLatDelta": maxA,
+ "maxLngDelta": maxB,
+ };
+}
- final List<dynamic> jsonData = citiesJson['data'];
- final cities =
- jsonData.map<City>((jsonItem) => City.fromMap(jsonItem)).toList();
- return cities;
+List<int> _kdTreeRangeSearch({
+ required List<List<int>> nodes,
+ required List<City> cities,
+ required int rootIndex,
+ required double minLat,
+ required double maxLat,
+ required double minLng,
+ required double maxLng,
+}) {
+ if (rootIndex < 0 || nodes.isEmpty) {
+ return const [];
+ }
+ final results = <int>[];
+ final stack = <int>[rootIndex];
+ while (stack.isNotEmpty) {
+ final nodeIndex = stack.removeLast();
+ if (nodeIndex < 0 || nodeIndex >= nodes.length) {
+ continue;
+ }
+ final node = nodes[nodeIndex];
+ final pointIndex = node[0];
+ if (pointIndex < 0 || pointIndex >= cities.length) {
+ continue;
+ }
+ final city = cities[pointIndex];
+ final lat = city.lat;
+ final lng = city.lng;
+ if (lat >= minLat && lat <= maxLat && lng >= minLng && lng <= maxLng) {
+ results.add(pointIndex);
+ }
+ final axis = node[3];
+ final leftIndex = node[1];
+ final rightIndex = node[2];
+ if (axis == 0) {
+ if (minLat <= lat && leftIndex >= 0 && leftIndex < nodes.length) {
+ stack.add(leftIndex);
+ }
+ if (maxLat >= lat && rightIndex >= 0 && rightIndex < nodes.length) {
+ stack.add(rightIndex);
+ }
+ } else if (axis == 1) {
+ if (minLng <= lng && leftIndex >= 0 && leftIndex < nodes.length) {
+ stack.add(leftIndex);
+ }
+ if (maxLng >= lng && rightIndex >= 0 && rightIndex < nodes.length) {
+ stack.add(rightIndex);
+ }
+ } else {
+ if (leftIndex >= 0 && leftIndex < nodes.length) {
+ stack.add(leftIndex);
+ }
+ if (rightIndex >= 0 && rightIndex < nodes.length) {
+ stack.add(rightIndex);
+ }
+ }
+ }
+ return results;
}
Map<City, List<EnteFile>> getCityResults(Map args) {
final query = (args["query"] as String).toLowerCase();
final List<City> cities = args["cities"] as List<City>;
final List<EnteFile> files = args["files"] as List<EnteFile>;
+ final kdTreeNodesRaw = args["kdTreeNodes"];
+ final List<List<int>> kdTreeNodes =
+ kdTreeNodesRaw is List ? kdTreeNodesRaw.cast<List<int>>() : const [];
+ final int kdTreeRoot = (args["kdTreeRoot"] as int?) ?? -1;
+ final double kdTreeMaxLatDelta =
+ (args["kdTreeMaxLatDelta"] as num?)?.toDouble() ?? 0;
+ final double kdTreeMaxLngDelta =
+ (args["kdTreeMaxLngDelta"] as num?)?.toDouble() ?? 0;
+ final bool useKdTree = kdTreeNodes.isNotEmpty &&
+ kdTreeRoot >= 0 &&
+ kdTreeMaxLatDelta > 0 &&
+ kdTreeMaxLngDelta > 0;
+
+ if (!useKdTree) {
+ final matchingCities = cities
+ .where(
+ (city) => city.city.toLowerCase().contains(query),
+ )
+ .toList();
+
+ final Map<City, List<EnteFile>> results = {};
+ for (final file in files) {
+ if (!file.hasLocation) continue; // Skip files without location
+ final fileLocation = file.location!;
+ for (final city in matchingCities) {
+ final x = city.lat - fileLocation.latitude!;
+ final y = city.lng - fileLocation.longitude!;
+
+ // Bounding box pre-filter: quick rejection for points clearly outside
+ if (x.abs() > city.a || y.abs() > city.b) continue;
+
+ // Ellipse containment check using pre-computed squared parameters
+ if ((x * x) / city.aSquare + (y * y) / city.bSquare <= 1) {
+ results.putIfAbsent(city, () => []).add(file);
+ break; // Stop searching once a file is matched with a city
+ }
+ }
+ }
+ return results;
+ }
- final matchingCities = cities
- .where(
- (city) => city.city.toLowerCase().contains(query),
- )
- .toList();
-
+ final bool hasQuery = query.isNotEmpty;
final Map<City, List<EnteFile>> results = {};
for (final file in files) {
if (!file.hasLocation) continue; // Skip files without location
final fileLocation = file.location!;
- for (final city in matchingCities) {
- final x = city.lat - fileLocation.latitude!;
- final y = city.lng - fileLocation.longitude!;
-
- // Bounding box pre-filter: quick rejection for points clearly outside
- if (x.abs() > city.a || y.abs() > city.b) continue;
-
- // Ellipse containment check using pre-computed squared parameters
+ final fileLat = fileLocation.latitude!;
+ final fileLng = fileLocation.longitude!;
+ final candidateIndices = _kdTreeRangeSearch(
+ nodes: kdTreeNodes,
+ cities: cities,
+ rootIndex: kdTreeRoot,
+ minLat: fileLat - kdTreeMaxLatDelta,
+ maxLat: fileLat + kdTreeMaxLatDelta,
+ minLng: fileLng - kdTreeMaxLngDelta,
+ maxLng: fileLng + kdTreeMaxLngDelta,
+ );
+ int bestIndex = -1;
+ for (final cityIndex in candidateIndices) {
+ final city = cities[cityIndex];
+ if (hasQuery && !city.city.toLowerCase().contains(query)) {
+ continue;
+ }
+ final x = city.lat - fileLat;
+ final y = city.lng - fileLng;
+ if (x.abs() > city.a || y.abs() > city.b) {
+ continue;
+ }
if ((x * x) / city.aSquare + (y * y) / city.bSquare <= 1) {
- results.putIfAbsent(city, () => []).add(file);
- break; // Stop searching once a file is matched with a city
+ if (bestIndex == -1 || cityIndex < bestIndex) {
+ bestIndex = cityIndex;
+ }
}
}
+ if (bestIndex != -1) {
+ final city = cities[bestIndex];
+ results.putIfAbsent(city, () => []).add(file);
+ }
}
+
return results;
}