From 21c84cf530ecd50a0a9fcb13405d81509179560f Mon Sep 17 00:00:00 2001 From: Caglar Pir Date: Tue, 1 Dec 2026 12:50:10 +0100 Subject: [PATCH] Keep the gaps between GPX track segments inside a video in its description GPS loggers, such as the Mapillary apps, start a new GPX track segment where they lost the GPS. process merged the segments into one track, whose interpolation across the gap places the video there on a straight line, as if the GPS had been there. The GPX video extractor now keeps the boundaries between the segments of the track file, and process writes those inside the video to its description as MAPGPSTrackGaps: the times, in milliseconds of video, of the points on either side of each gap. A boundary counts where the next segment starts more than MAPILLARY_TOOLS_MAX_GPX_SEGMENT_GAP_SECONDS (5) after the previous one ends, so a logger that splits its track every few fixes leaves none, and where no point of another segment is in between: segments that overlap, as two loggers' tracks merged into one file do, leave none there, and segments that touch leave none. The track of a video without a GPS clock that lasts twice as long as the video or more keeps no gap, as it may be that of a timelapse. Where the start or the end of the video falls in such a gap, process interpolated a point there across the gap. The fixes on the far side of the gap are now left out instead, as for a gap of more than MAPILLARY_TOOLS_MAX_GPX_GAP_SECONDS: the video has no position until the first fix after the gap, or after the last one before it. The warning about a GPX file of several segments counted them as tracks, and said they were merged into one: it now counts segments, and process says that gaps of more than the limit between them inside a video are kept as gaps. Sampling is not changed here: it still places frames across these gaps. Uploads are unchanged too: uploading each part of the video between the gaps as its own sequence comes in a follow-up. --- docs/command_reference.md | 8 + mapillary_tools/constants.py | 8 + .../geotag/geotag_images_from_gpx_file.py | 2 +- .../geotag/video_extractors/gpx.py | 203 ++++++++++++- mapillary_tools/serializer/description.py | 21 ++ mapillary_tools/types.py | 5 + schema/image_description_schema.json | 18 ++ tests/integration/test_video_process.py | 4 +- tests/unit/test_gpx_video_segment_gaps.py | 273 ++++++++++++++++++ tests/unit/test_read_track_files_once.py | 4 +- 10 files changed, 526 insertions(+), 20 deletions(-) create mode 100644 tests/unit/test_gpx_video_segment_gaps.py diff --git a/docs/command_reference.md b/docs/command_reference.md index 5ffe6a66c..ea7fcb577 100644 --- a/docs/command_reference.md +++ b/docs/command_reference.md @@ -298,6 +298,13 @@ Images are placed on the track by their capture time; videos by the times of the - Files outside the track fail with `MapillaryOutsideGPXTrackError`: images captured before the track starts, after it ends, or in a gap of more than an hour between two points (such as between two trips in one file). Set `MAPILLARY_TOOLS_MAX_GPX_GAP_SECONDS` to allow longer gaps. +- GPS loggers, such as the Mapillary apps, start a new GPX track segment (``) where they lost the GPS. + `process` keeps such a gap inside a video in its description (`MAPGPSTrackGaps`), where the next segment starts + more than 5 seconds (`MAPILLARY_TOOLS_MAX_GPX_SEGMENT_GAP_SECONDS`) after the previous one ends, with no point + of another segment in between. Where the start or the end of the video falls in such a gap, the fixes on its far + side are left out, and the video has no position until the first fix after the gap (or after the last one before + it). The track of a video without a GPS clock that lasts twice as long as the video or more may be that of a + timelapse, and keeps no gap. Sampling (`video_process`) still places frames across these gaps. - If the camera and GPS clocks differ, `--interpolation_offset_time N` adds N seconds to the capture times before placing them. It moves videos geotagged from a track too: in a folder with images and videos, an offset that fixes the image camera clock can push the videos off their tracks. Process the images alone with @@ -602,6 +609,7 @@ in the user data folder (or `MAPILLARY_TOOLS_EXIFTOOL_INSTALL_DIR`) and prints t | `MAPILLARY_TOOLS_EXIFTOOL_INSTALL_DIR` | in the user data folder | Where `install_exiftool` installs ExifTool. | | `MAPILLARY_TOOLS_FFMPEG_PATH`, `MAPILLARY_TOOLS_FFPROBE_PATH` | `ffmpeg`, `ffprobe` | The FFmpeg executables. | | `MAPILLARY_TOOLS_MAX_GPX_GAP_SECONDS` | 3600 | The longest gap in a GPX or NMEA track that files can be placed in, and how far from the rest of a track ExifTool points can be. | +| `MAPILLARY_TOOLS_MAX_GPX_SEGMENT_GAP_SECONDS` | 5 | The longest time between two segments of a GPX track inside a video that `process` keeps no gap for. | | `MAPILLARY_UPLOAD_HISTORY_PATH` | in the user data folder | Where the upload history is kept. | | `MAPILLARY_TOOLS_MAX_SEQUENCE_LENGTH` | 1000 | The most images in a sequence. | | `MAPILLARY_TOOLS_MAX_CAPTURE_SPEED_KMH` | 400 | The fastest average speed that passes the speed check. | diff --git a/mapillary_tools/constants.py b/mapillary_tools/constants.py index 3ad7bfeaa..72bac96b3 100644 --- a/mapillary_tools/constants.py +++ b/mapillary_tools/constants.py @@ -87,6 +87,14 @@ def _parse_scaled_integers( # logger switched off between trips: the time inside it is outside the track, # like the time before its start or after its end MAX_GPX_GAP_SECONDS = float(os.getenv(_ENV_PREFIX + "MAX_GPX_GAP_SECONDS", 3600)) +# In seconds. Where a GPX file starts a new track segment more than this after +# the previous one ends, inside a video that process geotags from it, the GPS +# was lost, and the gap is kept in the description of the video +# (MAPGPSTrackGaps). Segments that follow each other a few fixes apart, as one +# logged once a second does, leave no gap +MAX_GPX_SEGMENT_GAP_SECONDS = float( + os.getenv(_ENV_PREFIX + "MAX_GPX_SEGMENT_GAP_SECONDS", 5) +) ############################ diff --git a/mapillary_tools/geotag/geotag_images_from_gpx_file.py b/mapillary_tools/geotag/geotag_images_from_gpx_file.py index 1855808ba..d63c7ed3e 100644 --- a/mapillary_tools/geotag/geotag_images_from_gpx_file.py +++ b/mapillary_tools/geotag/geotag_images_from_gpx_file.py @@ -66,7 +66,7 @@ def _read_gpx_points(source_path: Path) -> list[geo.Point]: utils.warn_once( source_path, ("tracks", len(tracks)), - "Found %s tracks in the GPX file %s. Will merge points in all the tracks as a single track for interpolation", + "Found %s track segments in the GPX file %s. Will merge their points into one track by time for interpolation", len(tracks), source_path, ) diff --git a/mapillary_tools/geotag/video_extractors/gpx.py b/mapillary_tools/geotag/video_extractors/gpx.py index c7ec48d41..550a8375a 100644 --- a/mapillary_tools/geotag/video_extractors/gpx.py +++ b/mapillary_tools/geotag/video_extractors/gpx.py @@ -224,6 +224,11 @@ def __init__( # What extract() warned of about the placement of the track, which it # returns with the metadata of the video self.warnings: list[exceptions.MapillaryProcessWarning] = [] + # The last point of a segment of the track file and the first of the + # next, as _read_gpx_points() reads them (see _segment_boundaries). + # They are those of the track it returns, which placing the track on + # the video moves in place + self._segment_boundaries: list[tuple[geo.Point, geo.Point]] = [] @override def extract(self) -> types.VideoMetadata: @@ -245,8 +250,11 @@ def extract(self) -> types.VideoMetadata: rate = self._duration_ratio() self._apply_offset_time(gpx_points, rate=rate) self._check_coverage(gpx_points, gpx_unix_times, [], start_clock, rate) + segment_gaps: list[tuple[float, float]] = [] if self.clip_to_video: - gpx_points = self._clip_to_video(gpx_points, start_clock, rate) + gpx_points, segment_gaps = self._clip_to_video( + gpx_points, start_clock, rate + ) # The camera that the video names is no less known without its GPS make, model = extract_make_and_model(self.video_path) return types.VideoMetadata( @@ -257,6 +265,7 @@ def extract(self) -> types.VideoMetadata: make=make, model=model, warnings=list(self.warnings), + track_gaps=segment_gaps, ) video_clock = self._read_video_clock(native_video_metadata.points) @@ -306,11 +315,15 @@ def extract(self) -> types.VideoMetadata: None if self.sync_mode is SyncMode.REBASE else clock, rate, ) + segment_gaps = [] if self.clip_to_video: - gpx_points = self._clip_to_video(gpx_points, clock, rate) + gpx_points, segment_gaps = self._clip_to_video(gpx_points, clock, rate) return dataclasses.replace( - native_video_metadata, points=gpx_points, warnings=list(self.warnings) + native_video_metadata, + points=gpx_points, + warnings=list(self.warnings), + track_gaps=segment_gaps, ) def read_tracks(self) -> None: @@ -332,7 +345,8 @@ def read_tracks(self) -> None: def _read_gpx_points(self) -> list[geo.Point]: """ - Read the points of the GPX file, merged into one track in time order + Read the points of the GPX file, merged into one track in time order, + and the boundaries between its segments (see _segment_boundaries) """ warned = self._tracks is not None gpx_tracks = self._parse_tracks() @@ -343,16 +357,16 @@ def _read_gpx_points(self) -> list[geo.Point]: # other readers of the file. With the garbage collector paused, as # there are as many as the file has points (see utils.gc_paused()) with utils.gc_paused(): - gpx_points = [ - dataclasses.replace(p) + segments = [ + [dataclasses.replace(p) for p in track if _GPS_EPOCH <= p.time] for track in gpx_tracks - for p in track - if _GPS_EPOCH <= p.time ] + gpx_points = [p for segment in segments for p in segment] # The tracks need not be in time order, and interpolation needs the # merged points to be gpx_points.sort(key=lambda p: p.time) + self._segment_boundaries = _segment_boundaries(segments, gpx_points) return gpx_points def _warn_of_tracks(self, gpx_tracks: list[list[geo.Point]]) -> None: @@ -361,14 +375,19 @@ def _warn_of_tracks(self, gpx_tracks: list[list[geo.Point]]) -> None: once for each file """ if 1 < len(gpx_tracks): - geotag_utils.warn_once( - self.gpx_path, - ("tracks", len(gpx_tracks)), - "Found %d tracks in the %s file %s. Will merge points in all the tracks as a single track for interpolation", + # Each of each is read as a track + message = "Found %d track segments in the %s file %s. Will merge their points into one track by time for interpolation" + args: tuple[object, ...] = ( len(gpx_tracks), self.file_format, self.gpx_path, ) + if self.clip_to_video: + message += ", keeping a gap of more than %g seconds between two segments inside a video as a gap" + args += (constants.MAX_GPX_SEGMENT_GAP_SECONDS,) + geotag_utils.warn_once( + self.gpx_path, ("tracks", len(gpx_tracks)), message, *args + ) num_points = sum(len(track) for track in gpx_tracks) num_kept = sum(1 for track in gpx_tracks for p in track if _GPS_EPOCH <= p.time) @@ -409,7 +428,7 @@ def _read_tracks(self) -> list[list[geo.Point]]: def _clip_to_video( self, gpx_points: list[geo.Point], clock: VideoClock | None, rate: float - ) -> list[geo.Point]: + ) -> tuple[list[geo.Point], list[tuple[float, float]]]: """ Clip a GPX track to the video, from video time 0 to where the video ends along it, which is known when a **clock** gives its pace along @@ -431,14 +450,98 @@ def _clip_to_video( nothing of where the video was: the fixes on its far side are left out, with no point interpolated across it, as if the track started (or ended) there. One inside the video fails it (see _check_coverage). + So is a gap between two segments of the track (see _segment_gaps) + that video time 0 or the end of the video falls in. + + Return the clipped track, and the video times of the points on either + side of each gap between two of its segments inside the video. """ video_duration = _video_duration(self.video_path) gpx_points = _leave_out_far_side_of_gaps( gpx_points, constants.MAX_GPX_GAP_SECONDS, video_duration, rate ) + segment_gaps = self._segment_gaps(gpx_points, clock, rate, video_duration) + if segment_gaps: + gpx_points = _leave_out_far_side_of_gaps( + gpx_points, + constants.MAX_GPX_SEGMENT_GAP_SECONDS, + video_duration, + rate, + between=segment_gaps, + ) if clock is None: - return _clip_track(gpx_points, None) - return _clip_track(gpx_points, video_duration) + gpx_points = _clip_track(gpx_points, None) + else: + gpx_points = _clip_track(gpx_points, video_duration) + return gpx_points, [ + (before.time, after.time) + for before, after in segment_gaps + if video_duration is not None + and 0 <= before.time + and after.time <= video_duration + ] + + def _segment_gaps( + self, + gpx_points: T.Sequence[geo.Point], + clock: VideoClock | None, + rate: float, + video_duration: float | None, + ) -> list[tuple[geo.Point, geo.Point]]: + """ + The gaps of a GPX track, placed on the video, where the GPS was lost + in the video: the boundaries between two of its segments (see + _segment_boundaries) that leave more than + constants.MAX_GPX_SEGMENT_GAP_SECONDS (at **rate** GPS seconds per + second of video) between them, inside the video or across its start + or end. A GPS logger, such as that of the Mapillary apps, starts a new + segment where it lost the GPS, so the track says nothing of where the + video was in the gap. Each gap is given by the points on either side + of it. + + A gap before the start or after the end of the video is none of them. + Nor is any gap of the track of a video without a **clock** that lasts + twice as long as the video or more: it may be that of a timelapse (see + _check_length), whose frames are paced along the whole track. + """ + if ( + video_duration is None + or len(gpx_points) < 2 + or ( + clock is None + and 2 * video_duration + <= gpx_points[-1].time - max(gpx_points[0].time, 0.0) + ) + ): + return [] + + gaps: list[tuple[geo.Point, geo.Point]] = [] + for before, after in self._segment_boundaries: + if not (before.time < video_duration and 0 < after.time): + continue + # Not "<=", so that no gap is kept for a limit that is no number + if not ( + constants.MAX_GPX_SEGMENT_GAP_SECONDS + < gps_seconds_apart(before, after, rate) + ): + continue + gaps.append((before, after)) + before_time, after_time = before.get_unix_time(), after.get_unix_time() + LOG.warning( + "The %s track in %s has %s between two of its segments, in the video %s (%s to %s seconds into it): no position of the video is known in it", + self.file_format, + self.gpx_path, + describe_gap( + before, + after, + before.time if before_time is None else before_time, + after.time if after_time is None else after_time, + ), + self.video_path, + round(max(before.time, 0.0), 3), + round(min(after.time, video_duration), 3), + ) + return gaps def _place_without_video_gps( self, gpx_points: T.Sequence[geo.Point] @@ -1305,16 +1408,81 @@ def describe_long_track( ) +def _segment_boundaries( + segments: T.Sequence[T.Sequence[geo.Point]], track: T.Sequence[geo.Point] +) -> list[tuple[geo.Point, geo.Point]]: + """ + The boundaries between the segments of a track, in time order: the last + point of a segment, and the point that follows it in **track**, the + points of all the segments in time order, where that is the first point + of another segment, and later. Where segments overlap, as the tracks of + two loggers merged into one file do, the points of one fall between the + ends of the other, which leave no boundary there. Segments that touch, + one starting when the other ends, leave none either + + >>> p = lambda t: geo.Point(time=t, lat=0, lon=0, alt=None, angle=None) + >>> def boundaries(*segments): + ... track = sorted((q for s in segments for q in s), key=lambda q: q.time) + ... return [(a.time, b.time) for a, b in _segment_boundaries(segments, track)] + >>> boundaries([p(30), p(31)], [p(0), p(1)], [p(10), p(11)]) + [(1, 10), (11, 30)] + >>> boundaries([p(0), p(10)], [p(5), p(15)]) + [] + >>> boundaries([p(0), p(1)], [p(1), p(2)], [p(9), p(10)], [p(15), p(20)], [p(18)]) + [(2, 9), (10, 15)] + >>> boundaries([p(0), p(1)], []) + [] + """ + if len(segments) < 2: + return [] + + # The first point of each segment, and the last, the earliest and the + # latest in the track where several points have their time + firsts: dict[int, int] = {} + lasts: list[tuple[int, geo.Point]] = [] + for idx, segment in enumerate(segments): + if segment: + firsts[id(min(segment, key=lambda p: p.time))] = idx + lasts.append((idx, max(reversed(segment), key=lambda p: p.time))) + + boundaries: list[tuple[geo.Point, geo.Point]] = [] + for idx, last in lasts: + pos = _index_in_track(track, last) + 1 + if pos < len(track): + after = track[pos] + other = firsts.get(id(after)) + if other is not None and other != idx and last.time < after.time: + boundaries.append((last, after)) + boundaries.sort(key=lambda boundary: boundary[0].time) + return boundaries + + +def _index_in_track(track: T.Sequence[geo.Point], point: geo.Point) -> int: + """The index of a point in a track in time order""" + lo, hi = 0, len(track) + while lo < hi: + mid = (lo + hi) // 2 + if track[mid].time < point.time: + lo = mid + 1 + else: + hi = mid + while track[lo] is not point: + lo += 1 + return lo + + def _leave_out_far_side_of_gaps( points: T.Sequence[geo.Point], max_gap: float, end: float | None, rate: float = 1.0, + between: T.Collection[tuple[geo.Point, geo.Point]] | None = None, ) -> list[geo.Point]: """ Leave out of a track, sorted by time, the points on the far side of a gap of more than **max_gap** GPS seconds (see gps_seconds_apart()) that time 0, - or **end** (None if unknown), falls in + or **end** (None if unknown), falls in; only of a gap **between** one of + these pairs of points, if given >>> track = [geo.Point(time=t, lat=t, lon=0, alt=None, angle=None) for t in (-9000, 99, 200, 9000)] >>> [p.time for p in _leave_out_far_side_of_gaps(track, 3600, 300)] @@ -1324,8 +1492,11 @@ def _leave_out_far_side_of_gaps( >>> [p.time for p in _leave_out_far_side_of_gaps(track, 10000, 300)] [-9000, 99, 200, 9000] """ + pairs = None if between is None else {(id(b), id(a)) for b, a in between} start, stop = 0, len(points) for idx, (before, after) in enumerate(geo.pairwise(points)): + if pairs is not None and (id(before), id(after)) not in pairs: + continue if gps_seconds_apart(before, after, rate) <= max_gap: continue if before.time < 0 < after.time: diff --git a/mapillary_tools/serializer/description.py b/mapillary_tools/serializer/description.py index 78a9df587..573e3e5fe 100644 --- a/mapillary_tools/serializer/description.py +++ b/mapillary_tools/serializer/description.py @@ -87,6 +87,7 @@ class ImageDescription(_SharedDescription, total=False): class VideoDescription(_SharedDescription, total=False): MAPGPSTrack: Required[list[T.Sequence[float | int | None]]] + MAPGPSTrackGaps: list[T.Sequence[float | int]] MAPDeviceMake: str MAPDeviceModel: str MAPCameraUUID: str @@ -201,6 +202,17 @@ class ErrorDescription(TypedDict, total=False): ], }, }, + "MAPGPSTrackGaps": { + "type": "array", + "description": "Gaps of the track inside the video, where the GPS was lost: the track says nothing of where the video was in them", + "items": { + "type": "array", + "description": "Time offsets of the track points on either side of the gap, in milliseconds, relative to the beginning of the video", + "prefixItems": [{"type": "number"}, {"type": "number"}], + "minItems": 2, + "maxItems": 2, + }, + }, "MAPDeviceMake": { "type": "string", "description": "Device make, e.g. GoPro, BlackVue, Insta360", @@ -405,6 +417,11 @@ def _as_video_desc(cls, metadata: VideoMetadata) -> VideoDescription: "filesize": metadata.filesize, "MAPGPSTrack": [PointEncoder.encode(p) for p in metadata.points], } + if metadata.track_gaps: + desc["MAPGPSTrackGaps"] = [ + [int(start * 1000), int(end * 1000)] + for start, end in metadata.track_gaps + ] if metadata.make: desc["MAPDeviceMake"] = metadata.make if metadata.model: @@ -505,6 +522,10 @@ def _from_video_desc(cls, desc: VideoDescription) -> VideoMetadata: make=desc.get("MAPDeviceMake"), model=desc.get("MAPDeviceModel"), camera_uuid=desc.get("MAPCameraUUID"), + track_gaps=[ + (start / 1000, end / 1000) + for start, end in desc.get("MAPGPSTrackGaps", []) + ], ) diff --git a/mapillary_tools/types.py b/mapillary_tools/types.py index 98c26036f..2988a0a88 100644 --- a/mapillary_tools/types.py +++ b/mapillary_tools/types.py @@ -81,6 +81,11 @@ class VideoMetadata: warnings: list[exceptions.MapillaryProcessWarning] = dataclasses.field( default_factory=list, compare=False, repr=False ) + # The gaps of the track inside the video, where the GPS was lost: the + # video times (seconds) of the points on either side of each, in time + # order. Set by geotagging from a GPX track, which says where the GPS was + # lost by starting a new segment + track_gaps: list[tuple[float, float]] = dataclasses.field(default_factory=list) def update_md5sum(self) -> None: if self.md5sum is None: diff --git a/schema/image_description_schema.json b/schema/image_description_schema.json index 5a4c7e33a..07c86ac2e 100644 --- a/schema/image_description_schema.json +++ b/schema/image_description_schema.json @@ -45,6 +45,24 @@ ] } }, + "MAPGPSTrackGaps": { + "type": "array", + "description": "Gaps of the track inside the video, where the GPS was lost: the track says nothing of where the video was in them", + "items": { + "type": "array", + "description": "Time offsets of the track points on either side of the gap, in milliseconds, relative to the beginning of the video", + "prefixItems": [ + { + "type": "number" + }, + { + "type": "number" + } + ], + "minItems": 2, + "maxItems": 2 + } + }, "MAPDeviceMake": { "type": "string", "description": "Device make, e.g. GoPro, BlackVue, Insta360" diff --git a/tests/integration/test_video_process.py b/tests/integration/test_video_process.py index 07e52c6c6..0e944b26f 100644 --- a/tests/integration/test_video_process.py +++ b/tests/integration/test_video_process.py @@ -311,7 +311,9 @@ def test_video_process_reads_a_gpx_file_of_several_videos_once( assert len(descs) == 6, descs assert all("error" not in desc for desc in descs), descs - assert process.stderr.count("Found 2 tracks in the GPX file") == 1, process.stderr + assert process.stderr.count("Found 2 track segments in the GPX file") == 1, ( + process.stderr + ) def test_video_process_by_interval_with_a_video_gpx(setup_data: py.path.local): diff --git a/tests/unit/test_gpx_video_segment_gaps.py b/tests/unit/test_gpx_video_segment_gaps.py new file mode 100644 index 000000000..0716eef7c --- /dev/null +++ b/tests/unit/test_gpx_video_segment_gaps.py @@ -0,0 +1,273 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +""" +A GPS logger, such as that of the Mapillary apps, starts a new segment of its +GPX track where it lost the GPS. Process keeps such a gap inside a video in +its description (MAPGPSTrackGaps). +""" + +from __future__ import annotations + +import datetime +import typing as T +from pathlib import Path + +import pytest +from mapillary_tools import constants, exceptions, types +from mapillary_tools.geotag.video_extractors.gpx import GPXVideoExtractor +from mapillary_tools.geotag.video_extractors.native import NativeVideoExtractor +from mapillary_tools.serializer.description import ( + DescriptionJSONSerializer, + validate_video_desc, +) + +_DATA = Path(__file__).resolve().parent.parent.joinpath("data") + +# No GPS of its own, and 5.76 seconds long +NO_GPS_VIDEO = _DATA.joinpath("videos", "sample-5s.mp4") + +# GPS of its own, and 12.137125 seconds long +GPS_VIDEO = _DATA.joinpath("gopro_data", "max-360mode.mp4") + + +def _gps_video_start() -> float: + """The Unix time of the first frame of GPS_VIDEO, by its GPS clock""" + points = NativeVideoExtractor(GPS_VIDEO).extract().points + clock = GPXVideoExtractor._read_video_clock(points) + assert clock is not None + return clock.to_unix_time(0) + + +def _write_gpx( + path: Path, start: float, segments: T.Sequence[T.Sequence[float]] +) -> Path: + """ + A GPX track of a segment for each list of times (seconds from start), + heading north at 10 m/s + """ + + def trkpt(t: float) -> str: + time = datetime.datetime.fromtimestamp(start + t, datetime.timezone.utc) + return f'' + + trksegs = "".join( + f"{''.join(trkpt(t) for t in times)}" for times in segments + ) + path.write_text( + '\n' + '' + f"{trksegs}\n" + ) + return path + + +def _seconds(first: int, last: int) -> list[float]: + return [float(t) for t in range(first, last + 1)] + + +class TestClockPlacedTrack: + def _extract(self, tmp_path: Path, *segments, **kwargs) -> types.VideoMetadata: + gpx = _write_gpx(tmp_path / "track.gpx", _gps_video_start(), segments) + return GPXVideoExtractor( + GPS_VIDEO, gpx, **{"clip_to_video": True, **kwargs} + ).extract() + + def test_gap_between_segments_inside_the_video(self, tmp_path, caplog): + metadata = self._extract(tmp_path, _seconds(-2, 3), _seconds(10, 14)) + + assert metadata.track_gaps == [(pytest.approx(3.0), pytest.approx(10.0))] + assert ( + "Found 2 track segments in the GPX file " + f"{tmp_path / 'track.gpx'}. Will merge their points into one track by " + "time for interpolation, keeping a gap of more than 5 seconds between " + "two segments inside a video as a gap" + ) in caplog.text + # The times of the points on either side + before, after = metadata.track_gaps[0] + times = [p.time for p in metadata.points] + assert times[times.index(before) + 1] == after + + def test_segments_a_few_fixes_apart_leave_no_gap(self, tmp_path, monkeypatch): + metadata = self._extract(tmp_path, _seconds(-2, 3), _seconds(7, 14)) + assert metadata.track_gaps == [] + + monkeypatch.setattr(constants, "MAX_GPX_SEGMENT_GAP_SECONDS", 3) + metadata = self._extract(tmp_path, _seconds(-2, 3), _seconds(7, 14)) + assert metadata.track_gaps == [(pytest.approx(3.0), pytest.approx(7.0))] + + def test_gap_before_the_video_is_none_of_it(self, tmp_path): + metadata = self._extract(tmp_path, _seconds(-20, -10), _seconds(1, 14)) + + assert metadata.track_gaps == [] + + def test_gap_after_the_video_is_none_of_it(self, tmp_path): + metadata = self._extract(tmp_path, _seconds(-2, 11), _seconds(20, 30)) + + assert metadata.track_gaps == [] + + def test_overlapping_segments_leave_no_gap(self, tmp_path, monkeypatch): + # As the tracks of two loggers merged into one file, one of them in + # segments: neither ends where the other starts + monkeypatch.setattr(constants, "MAX_GPX_SEGMENT_GAP_SECONDS", 3) + metadata = self._extract( + tmp_path, _seconds(-2, 14), _seconds(1, 3), _seconds(10, 12) + ) + + assert metadata.track_gaps == [] + + def test_overlapping_segments_after_the_video_leave_the_gap( + self, tmp_path, monkeypatch + ): + metadata = self._extract( + tmp_path, + _seconds(-2, 3), + _seconds(10, 14), + _seconds(3000, 3010), + _seconds(3005, 3020), + ) + + assert metadata.track_gaps == [(pytest.approx(3.0), pytest.approx(10.0))] + + def test_segments_that_touch_leave_the_gap(self, tmp_path): + # The next segment starts with the last fix of the one before + metadata = self._extract( + tmp_path, _seconds(-2, 3), _seconds(10, 11), _seconds(11, 14) + ) + + assert metadata.track_gaps == [(pytest.approx(3.0), pytest.approx(10.0))] + + def test_segment_that_ends_with_a_repeated_fix(self, tmp_path): + metadata = self._extract(tmp_path, [*_seconds(-2, 3), 3.0], _seconds(10, 14)) + + assert metadata.track_gaps == [(pytest.approx(3.0), pytest.approx(10.0))] + + def test_segments_out_of_order(self, tmp_path): + metadata = self._extract(tmp_path, _seconds(10, 14), _seconds(-2, 3)) + + assert metadata.track_gaps == [(pytest.approx(3.0), pytest.approx(10.0))] + + def test_segment_of_one_point(self, tmp_path, monkeypatch): + monkeypatch.setattr(constants, "MAX_GPX_SEGMENT_GAP_SECONDS", 2) + # And out of order + metadata = self._extract(tmp_path, _seconds(10, 14), [6.0], _seconds(-2, 3)) + + assert metadata.track_gaps == [ + (pytest.approx(3.0), pytest.approx(6.0)), + (pytest.approx(6.0), pytest.approx(10.0)), + ] + + def test_gap_across_the_start_of_the_video(self, tmp_path): + metadata = self._extract(tmp_path, _seconds(-20, -3), _seconds(5, 20)) + + # Nothing is known of where the video was until the first fix after + # the gap: no position is interpolated across it + assert metadata.track_gaps == [] + assert metadata.points[0].time == pytest.approx(5.0) + assert metadata.points[-1].time == pytest.approx(12.137125) + + def test_gap_across_the_end_of_the_video(self, tmp_path): + metadata = self._extract(tmp_path, _seconds(-5, 8), _seconds(15, 30)) + + assert metadata.track_gaps == [] + assert metadata.points[0].time == pytest.approx(0.0) + assert metadata.points[-1].time == pytest.approx(8.0) + + def test_no_gap_for_a_limit_that_is_no_number(self, tmp_path, monkeypatch): + monkeypatch.setattr(constants, "MAX_GPX_SEGMENT_GAP_SECONDS", float("nan")) + metadata = self._extract(tmp_path, _seconds(-2, 3), _seconds(4, 14)) + + assert metadata.track_gaps == [] + + def test_gaps_on_the_points_of_the_description(self, tmp_path): + metadata = self._extract( + tmp_path, _seconds(-2, 3), _seconds(10, 11), [11.4, 11.5, 11.6, 12, 13] + ) + assert len(metadata.track_gaps) == 1 + + desc = DescriptionJSONSerializer.as_desc(metadata) + + # Each gap is between two points of the track, to the millisecond, as + # uploading the video splits its track at the gaps + times = [point[0] for point in desc["MAPGPSTrack"]] + assert [ + times.index(before) + 1 == times.index(after) + for before, after in desc["MAPGPSTrackGaps"] + ] == [True] + + def test_not_kept_for_sampling(self, tmp_path): + """Only process keeps the gaps: sampling is not changed here""" + metadata = self._extract( + tmp_path, _seconds(-2, 3), _seconds(10, 14), clip_to_video=False + ) + + assert metadata.track_gaps == [] + + +class TestTrackAssumedToStartWithTheVideo: + START = datetime.datetime(2025, 3, 14, 7, 0, 0, tzinfo=datetime.timezone.utc) + + @pytest.fixture(autouse=True) + def _short_gaps(self, monkeypatch): + # The video is only 5.76 seconds long + monkeypatch.setattr(constants, "MAX_GPX_SEGMENT_GAP_SECONDS", 1) + + def _extract(self, tmp_path: Path, *segments) -> types.VideoMetadata: + gpx = _write_gpx(tmp_path / "track.gpx", self.START.timestamp(), segments) + return GPXVideoExtractor(NO_GPS_VIDEO, gpx, clip_to_video=True).extract() + + def test_gap_between_segments_inside_the_video(self, tmp_path): + metadata = self._extract(tmp_path, _seconds(0, 2), [3.5, 4.5, 5.5]) + + assert metadata.track_gaps == [(2.0, 3.5)] + + def test_track_of_a_timelapse_leaves_no_gap(self, tmp_path): + # Twice as long as the video: its frames are paced along all of it + metadata = self._extract(tmp_path, _seconds(0, 2), [3.5 + t for t in range(10)]) + + assert metadata.track_gaps == [] + assert metadata.points[-1].time == 12.5 + + def test_gap_across_the_end_of_the_video(self, tmp_path): + # The track runs on past the end of the video, which is 5.76 seconds + # long, but not so far as that of a timelapse would + metadata = self._extract(tmp_path, _seconds(0, 4), _seconds(7, 9)) + + assert metadata.track_gaps == [] + assert [p.time for p in metadata.points] == _seconds(0, 4) + + +class TestDescription: + def _metadata(self, track_gaps: list[tuple[float, float]]) -> types.VideoMetadata: + metadata = GPXVideoExtractor( + NO_GPS_VIDEO, + _DATA.joinpath("gpx", "sf_30km_h.gpx"), + clip_to_video=True, + ).extract() + metadata.track_gaps = track_gaps + return metadata + + def test_gaps_in_milliseconds(self): + metadata = self._metadata([(1.5, 3.25)]) + + desc = DescriptionJSONSerializer.as_desc(metadata) + + assert desc["MAPGPSTrackGaps"] == [[1500, 3250]] + validate_video_desc(desc) + assert DescriptionJSONSerializer.from_desc(desc).track_gaps == [(1.5, 3.25)] + + def test_no_gaps_no_field(self): + desc = DescriptionJSONSerializer.as_desc(self._metadata([])) + + assert "MAPGPSTrackGaps" not in desc + assert DescriptionJSONSerializer.from_desc(desc).track_gaps == [] + + @pytest.mark.parametrize("gaps", [[[1500]], [[1500, 3250, 5000]], [["1500", 3250]]]) + def test_invalid_gaps(self, gaps): + desc = DescriptionJSONSerializer.as_desc(self._metadata([])) + desc["MAPGPSTrackGaps"] = gaps + + with pytest.raises(exceptions.MapillaryMetadataValidationError): + validate_video_desc(desc) diff --git a/tests/unit/test_read_track_files_once.py b/tests/unit/test_read_track_files_once.py index 28a6744c4..cd5a6aba7 100644 --- a/tests/unit/test_read_track_files_once.py +++ b/tests/unit/test_read_track_files_once.py @@ -299,7 +299,7 @@ def test_images_warn_of_the_tracks_once(tmp_path: Path, parses: list[int], caplo assert len(points) == 4 assert len(parses) == 1 - assert caplog.text.count("Found 2 tracks in the GPX file") == 1 + assert caplog.text.count("Found 2 track segments in the GPX file") == 1 def test_videos_warn_of_the_tracks_once(tmp_path: Path, parses: list[int], caplog): @@ -313,7 +313,7 @@ def test_videos_warn_of_the_tracks_once(tmp_path: Path, parses: list[int], caplo assert len(points) == 4 assert len(parses) == 1 - assert caplog.text.count("Found 2 tracks") == 1 + assert caplog.text.count("Found 2 track segments") == 1 def test_video_points_are_copies(tmp_path: Path, parses: list[int]):